prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SoftAACEncoder2::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (!mSentCodecSpecificData) {
if (outQueue.empty()) {
return;
}
if (AACENC_OK != aacEncEncode(mAACEncoder, NULL, NULL, NULL, NULL)) {
ALOGE("Unable to initialize encoder for profile / sample-rate / bit-rate / channels");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
OMX_U32 actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE);
if (mBitRate != actualBitRate) {
ALOGW("Requested bitrate %u unsupported, using %u", mBitRate, actualBitRate);
}
AACENC_InfoStruct encInfo;
if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) {
ALOGE("Failed to get AAC encoder info");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFilledLen = encInfo.confSize;
outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG;
uint8_t *out = outHeader->pBuffer + outHeader->nOffset;
memcpy(out, encInfo.confBuf, encInfo.confSize);
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
mSentCodecSpecificData = true;
}
size_t numBytesPerInputFrame =
mNumChannels * kNumSamplesPerFrame * sizeof(int16_t);
if (mAACProfile == OMX_AUDIO_AACObjectELD && numBytesPerInputFrame > 512) {
numBytesPerInputFrame = 512;
}
for (;;) {
while (mInputSize < numBytesPerInputFrame) {
if (mSawInputEOS || inQueue.empty()) {
return;
}
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
const void *inData = inHeader->pBuffer + inHeader->nOffset;
size_t copy = numBytesPerInputFrame - mInputSize;
if (copy > inHeader->nFilledLen) {
copy = inHeader->nFilledLen;
}
if (mInputFrame == NULL) {
mInputFrame = new int16_t[numBytesPerInputFrame / sizeof(int16_t)];
}
if (mInputSize == 0) {
mInputTimeUs = inHeader->nTimeStamp;
}
memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy);
mInputSize += copy;
inHeader->nOffset += copy;
inHeader->nFilledLen -= copy;
inHeader->nTimeStamp +=
(copy * 1000000ll / mSampleRate)
/ (mNumChannels * sizeof(int16_t));
if (inHeader->nFilledLen == 0) {
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEOS = true;
memset((uint8_t *)mInputFrame + mInputSize,
0,
numBytesPerInputFrame - mInputSize);
mInputSize = numBytesPerInputFrame;
}
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
inData = NULL;
inHeader = NULL;
inInfo = NULL;
}
}
if (outQueue.empty()) {
return;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset;
size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset;
AACENC_InArgs inargs;
AACENC_OutArgs outargs;
memset(&inargs, 0, sizeof(inargs));
memset(&outargs, 0, sizeof(outargs));
inargs.numInSamples = numBytesPerInputFrame / sizeof(int16_t);
void* inBuffer[] = { (unsigned char *)mInputFrame };
INT inBufferIds[] = { IN_AUDIO_DATA };
INT inBufferSize[] = { (INT)numBytesPerInputFrame };
INT inBufferElSize[] = { sizeof(int16_t) };
AACENC_BufDesc inBufDesc;
inBufDesc.numBufs = sizeof(inBuffer) / sizeof(void*);
inBufDesc.bufs = (void**)&inBuffer;
inBufDesc.bufferIdentifiers = inBufferIds;
inBufDesc.bufSizes = inBufferSize;
inBufDesc.bufElSizes = inBufferElSize;
void* outBuffer[] = { outPtr };
INT outBufferIds[] = { OUT_BITSTREAM_DATA };
INT outBufferSize[] = { 0 };
INT outBufferElSize[] = { sizeof(UCHAR) };
AACENC_BufDesc outBufDesc;
outBufDesc.numBufs = sizeof(outBuffer) / sizeof(void*);
outBufDesc.bufs = (void**)&outBuffer;
outBufDesc.bufferIdentifiers = outBufferIds;
outBufDesc.bufSizes = outBufferSize;
outBufDesc.bufElSizes = outBufferElSize;
AACENC_ERROR encoderErr = AACENC_OK;
size_t nOutputBytes = 0;
do {
memset(&outargs, 0, sizeof(outargs));
outBuffer[0] = outPtr;
outBufferSize[0] = outAvailable - nOutputBytes;
encoderErr = aacEncEncode(mAACEncoder,
&inBufDesc,
&outBufDesc,
&inargs,
&outargs);
if (encoderErr == AACENC_OK) {
outPtr += outargs.numOutBytes;
nOutputBytes += outargs.numOutBytes;
if (outargs.numInSamples > 0) {
int numRemainingSamples = inargs.numInSamples - outargs.numInSamples;
if (numRemainingSamples > 0) {
memmove(mInputFrame,
&mInputFrame[outargs.numInSamples],
sizeof(int16_t) * numRemainingSamples);
}
inargs.numInSamples -= outargs.numInSamples;
}
}
} while (encoderErr == AACENC_OK && inargs.numInSamples > 0);
outHeader->nFilledLen = nOutputBytes;
outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
if (mSawInputEOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
}
outHeader->nTimeStamp = mInputTimeUs;
#if 0
ALOGI("sending %d bytes of data (time = %lld us, flags = 0x%08lx)",
nOutputBytes, mInputTimeUs, outHeader->nFlags);
hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen);
#endif
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
outHeader = NULL;
outInfo = NULL;
mInputSize = 0;
}
}
Commit Message: Add bounds check in SoftAACEncoder2::onQueueFilled()
Original code blindly copied some header information into the
user-supplied buffer without checking for sufficient space.
The code does check when it gets to filling the data -- it's
just the header copies that weren't checked.
Bug: 34617444
Test: ran POC before/after
Change-Id: I6e80ec90616f6cd02bb8316cd2d6e309b7e4729d
(cherry picked from commit 6231243626b8b9c57593b1f0ee417f2c4af4c0aa)
CWE ID: CWE-120
Target: 1
Example 2:
Code: send_disable_carbons(void **state)
{
prof_input("/carbons on");
prof_connect();
prof_input("/carbons off");
assert_true(stbbr_received(
"<iq id='*' type='set'><disable xmlns='urn:xmpp:carbons:2'/></iq>"
));
}
Commit Message: Add carbons from check
CWE ID: CWE-346
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: entry_guard_obeys_restriction(const entry_guard_t *guard,
const entry_guard_restriction_t *rst)
{
tor_assert(guard);
if (! rst)
return 1; // No restriction? No problem.
return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
}
Commit Message: Consider the exit family when applying guard restrictions.
When the new path selection logic went into place, I accidentally
dropped the code that considered the _family_ of the exit node when
deciding if the guard was usable, and we didn't catch that during
code review.
This patch makes the guard_restriction_t code consider the exit
family as well, and adds some (hopefully redundant) checks for the
case where we lack a node_t for a guard but we have a bridge_info_t
for it.
Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006
and CVE-2017-0377.
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int blk_rq_map_user_iov(struct request_queue *q, struct request *rq,
struct rq_map_data *map_data,
const struct iov_iter *iter, gfp_t gfp_mask)
{
bool copy = false;
unsigned long align = q->dma_pad_mask | queue_dma_alignment(q);
struct bio *bio = NULL;
struct iov_iter i;
int ret;
if (map_data)
copy = true;
else if (iov_iter_alignment(iter) & align)
copy = true;
else if (queue_virt_boundary(q))
copy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);
i = *iter;
do {
ret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);
if (ret)
goto unmap_rq;
if (!bio)
bio = rq->bio;
} while (iov_iter_count(&i));
if (!bio_flagged(bio, BIO_USER_MAPPED))
rq->cmd_flags |= REQ_COPY_USER;
return 0;
unmap_rq:
__blk_rq_unmap_user(bio);
rq->bio = NULL;
return -EINVAL;
}
Commit Message: Don't feed anything but regular iovec's to blk_rq_map_user_iov
In theory we could map other things, but there's a reason that function
is called "user_iov". Using anything else (like splice can do) just
confuses it.
Reported-and-tested-by: Johannes Thumshirn <[email protected]>
Cc: Al Viro <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void qeth_clear_outq_buffers(struct qeth_qdio_out_q *q, int free)
{
int j;
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; ++j) {
if (!q->bufs[j])
continue;
qeth_cleanup_handled_pending(q, j, 1);
qeth_clear_output_buffer(q, q->bufs[j], QETH_QDIO_BUF_EMPTY);
if (free) {
kmem_cache_free(qeth_qdio_outbuf_cache, q->bufs[j]);
q->bufs[j] = NULL;
}
}
}
Commit Message: qeth: avoid buffer overflow in snmp ioctl
Check user-defined length in snmp ioctl request and allow request
only if it fits into a qeth command buffer.
Signed-off-by: Ursula Braun <[email protected]>
Signed-off-by: Frank Blaschka <[email protected]>
Reviewed-by: Heiko Carstens <[email protected]>
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Cc: <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: image_transform_png_set_strip_alpha_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int lsm_set_label_at(int procfd, int on_exec, char* lsm_label) {
int labelfd = -1;
int ret = 0;
const char* name;
char* command = NULL;
name = lsm_name();
if (strcmp(name, "nop") == 0)
goto out;
if (strcmp(name, "none") == 0)
goto out;
/* We don't support on-exec with AppArmor */
if (strcmp(name, "AppArmor") == 0)
on_exec = 0;
if (on_exec) {
labelfd = openat(procfd, "self/attr/exec", O_RDWR);
}
else {
labelfd = openat(procfd, "self/attr/current", O_RDWR);
}
if (labelfd < 0) {
SYSERROR("Unable to open LSM label");
ret = -1;
goto out;
}
if (strcmp(name, "AppArmor") == 0) {
int size;
command = malloc(strlen(lsm_label) + strlen("changeprofile ") + 1);
if (!command) {
SYSERROR("Failed to write apparmor profile");
ret = -1;
goto out;
}
size = sprintf(command, "changeprofile %s", lsm_label);
if (size < 0) {
SYSERROR("Failed to write apparmor profile");
ret = -1;
goto out;
}
if (write(labelfd, command, size + 1) < 0) {
SYSERROR("Unable to set LSM label");
ret = -1;
goto out;
}
}
else if (strcmp(name, "SELinux") == 0) {
if (write(labelfd, lsm_label, strlen(lsm_label) + 1) < 0) {
SYSERROR("Unable to set LSM label");
ret = -1;
goto out;
}
}
else {
ERROR("Unable to restore label for unknown LSM: %s", name);
ret = -1;
goto out;
}
out:
free(command);
if (labelfd != -1)
close(labelfd);
return ret;
}
Commit Message: attach: do not send procfd to attached process
So far, we opened a file descriptor refering to proc on the host inside the
host namespace and handed that fd to the attached process in
attach_child_main(). This was done to ensure that LSM labels were correctly
setup. However, by exploiting a potential kernel bug, ptrace could be used to
prevent the file descriptor from being closed which in turn could be used by an
unprivileged container to gain access to the host namespace. Aside from this
needing an upstream kernel fix, we should make sure that we don't pass the fd
for proc itself to the attached process. However, we cannot completely prevent
this, as the attached process needs to be able to change its apparmor profile
by writing to /proc/self/attr/exec or /proc/self/attr/current. To minimize the
attack surface, we only send the fd for /proc/self/attr/exec or
/proc/self/attr/current to the attached process. To do this we introduce a
little more IPC between the child and parent:
* IPC mechanism: (X is receiver)
* initial process intermediate attached
* X <--- send pid of
* attached proc,
* then exit
* send 0 ------------------------------------> X
* [do initialization]
* X <------------------------------------ send 1
* [add to cgroup, ...]
* send 2 ------------------------------------> X
* [set LXC_ATTACH_NO_NEW_PRIVS]
* X <------------------------------------ send 3
* [open LSM label fd]
* send 4 ------------------------------------> X
* [set LSM label]
* close socket close socket
* run program
The attached child tells the parent when it is ready to have its LSM labels set
up. The parent then opens an approriate fd for the child PID to
/proc/<pid>/attr/exec or /proc/<pid>/attr/current and sends it via SCM_RIGHTS
to the child. The child can then set its LSM laben. Both sides then close the
socket fds and the child execs the requested process.
Signed-off-by: Christian Brauner <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void midi_outc(int dev, unsigned char data)
{
/*
* NOTE! Calls sleep(). Don't call this from interrupt.
*/
int n;
unsigned long flags;
/*
* This routine sends one byte to the Midi channel.
* If the output FIFO is full, it waits until there
* is space in the queue
*/
n = 3 * HZ; /* Timeout */
spin_lock_irqsave(&lock,flags);
while (n && !midi_devs[dev]->outputc(dev, data)) {
interruptible_sleep_on_timeout(&seq_sleeper, HZ/25);
n--;
}
spin_unlock_irqrestore(&lock,flags);
}
Commit Message: sound/oss: remove offset from load_patch callbacks
Was: [PATCH] sound/oss/midi_synth: prevent underflow, use of
uninitialized value, and signedness issue
The offset passed to midi_synth_load_patch() can be essentially
arbitrary. If it's greater than the header length, this will result in
a copy_from_user(dst, src, negative_val). While this will just return
-EFAULT on x86, on other architectures this may cause memory corruption.
Additionally, the length field of the sysex_info structure may not be
initialized prior to its use. Finally, a signed comparison may result
in an unintentionally large loop.
On suggestion by Takashi Iwai, version two removes the offset argument
from the load_patch callbacks entirely, which also resolves similar
issues in opl3. Compile tested only.
v3 adjusts comments and hopefully gets copy offsets right.
Signed-off-by: Dan Rosenberg <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Compositor::~Compositor() {
TRACE_EVENT0("shutdown", "Compositor::destructor");
for (auto& observer : observer_list_)
observer.OnCompositingShuttingDown(this);
for (auto& observer : animation_observer_list_)
observer.OnCompositingShuttingDown(this);
if (root_layer_)
root_layer_->ResetCompositor();
if (animation_timeline_)
animation_host_->RemoveAnimationTimeline(animation_timeline_.get());
host_.reset();
context_factory_->RemoveCompositor(this);
if (context_factory_private_) {
auto* host_frame_sink_manager =
context_factory_private_->GetHostFrameSinkManager();
for (auto& client : child_frame_sinks_) {
DCHECK(client.is_valid());
host_frame_sink_manager->UnregisterFrameSinkHierarchy(frame_sink_id_,
client);
}
host_frame_sink_manager->InvalidateFrameSinkId(frame_sink_id_);
}
}
Commit Message: Fix PIP window being blank after minimize/show
DesktopWindowTreeHostX11::SetVisible only made the call into
OnNativeWidgetVisibilityChanged when transitioning from shown
to minimized and not vice versa. This is because this change
https://chromium-review.googlesource.com/c/chromium/src/+/1437263
considered IsVisible to be true when minimized, which made
IsVisible always true in this case. This caused layers to be hidden
but never shown again.
This is a reland of:
https://chromium-review.googlesource.com/c/chromium/src/+/1580103
Bug: 949199
Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617
Reviewed-by: Scott Violet <[email protected]>
Commit-Queue: enne <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654280}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto(
ContainerNode& insertion_point) {
HTMLElement::InsertedInto(insertion_point);
LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr);
if (!insertion_point.isConnected())
return kInsertionDone;
DCHECK(isConnected());
if (!ShouldLoadLink() && IsInShadowTree()) {
String message = "HTML element <link> is ignored in shadow tree.";
GetDocument().AddConsoleMessage(ConsoleMessage::Create(
kJSMessageSource, kWarningMessageLevel, message));
return kInsertionDone;
}
GetDocument().GetStyleEngine().AddStyleSheetCandidateNode(*this);
Process();
if (link_)
link_->OwnerInserted();
return kInsertionDone;
}
Commit Message: Avoid crash when setting rel=stylesheet on <link> in shadow root.
Link elements in shadow roots without rel=stylesheet are currently not
added as stylesheet candidates upon insertion. This causes a crash if
rel=stylesheet is set (and then loaded) later.
[email protected]
Bug: 886753
Change-Id: Ia0de2c1edf43407950f973982ee1c262a909d220
Reviewed-on: https://chromium-review.googlesource.com/1242463
Commit-Queue: Anders Ruud <[email protected]>
Reviewed-by: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#593907}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void BrowserChildProcessHostImpl::OnProcessLaunched() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
const base::Process& process = child_process_->GetProcess();
DCHECK(process.IsValid());
if (child_connection_)
child_connection_->SetProcessHandle(process.Handle());
#if defined(OS_WIN)
DCHECK(!early_exit_watcher_.GetWatchedObject());
early_exit_watcher_.StartWatchingOnce(process.Handle(), this);
#endif
data_.handle = process.Handle();
delegate_->OnProcessLaunched();
if (is_channel_connected_) {
ShareMetricsAllocatorToProcess();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&NotifyProcessLaunchedAndConnected, data_));
}
}
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 <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AppCacheUpdateJob::HandleMasterEntryFetchCompleted(
URLFetcher* fetcher) {
DCHECK(internal_state_ == NO_UPDATE || internal_state_ == DOWNLOADING);
net::URLRequest* request = fetcher->request();
const GURL& url = request->original_url();
master_entry_fetches_.erase(url);
++master_entries_completed_;
int response_code = request->status().is_success()
? request->GetResponseCode() : -1;
PendingMasters::iterator found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
if (response_code / 100 == 2) {
AppCache* cache = inprogress_cache_.get() ? inprogress_cache_.get()
: group_->newest_complete_cache();
DCHECK(fetcher->response_writer());
AppCacheEntry master_entry(AppCacheEntry::MASTER,
fetcher->response_writer()->response_id(),
fetcher->response_writer()->amount_written());
if (cache->AddOrModifyEntry(url, master_entry))
added_master_entries_.push_back(url);
else
duplicate_response_ids_.push_back(master_entry.response_id());
if (!inprogress_cache_.get()) {
DCHECK(cache == group_->newest_complete_cache());
for (PendingHosts::iterator host_it = hosts.begin();
host_it != hosts.end(); ++host_it) {
(*host_it)->AssociateCompleteCache(cache);
}
}
} else {
HostNotifier host_notifier;
for (PendingHosts::iterator host_it = hosts.begin();
host_it != hosts.end(); ++host_it) {
AppCacheHost* host = *host_it;
host_notifier.AddHost(host);
if (inprogress_cache_.get())
host->AssociateNoCache(GURL());
host->RemoveObserver(this);
}
hosts.clear();
const char* kFormatString = "Manifest fetch failed (%d) %s";
std::string message = FormatUrlErrorMessage(
kFormatString, request->url(), fetcher->result(), response_code);
host_notifier.SendErrorNotifications(
AppCacheErrorDetails(message,
APPCACHE_MANIFEST_ERROR,
request->url(),
response_code,
false /*is_cross_origin*/));
if (inprogress_cache_.get()) {
pending_master_entries_.erase(found);
--master_entries_completed_;
if (update_type_ == CACHE_ATTEMPT && pending_master_entries_.empty()) {
HandleCacheFailure(AppCacheErrorDetails(message,
APPCACHE_MANIFEST_ERROR,
request->url(),
response_code,
false /*is_cross_origin*/),
fetcher->result(),
GURL());
return;
}
}
}
DCHECK(internal_state_ != CACHE_FAILURE);
FetchMasterEntries();
MaybeCompleteUpdate();
}
Commit Message: AppCache: fix a browser crashing bug that can happen during updates.
BUG=558589
Review URL: https://codereview.chromium.org/1463463003
Cr-Commit-Position: refs/heads/master@{#360967}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GpuChannel::OnChannelConnected(int32 peer_pid) {
renderer_pid_ = peer_pid;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
{
struct bpf_verifier_state *parent = state->parent;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
}
}
Commit Message: bpf: fix branch pruning logic
when the verifier detects that register contains a runtime constant
and it's compared with another constant it will prune exploration
of the branch that is guaranteed not to be taken at runtime.
This is all correct, but malicious program may be constructed
in such a way that it always has a constant comparison and
the other branch is never taken under any conditions.
In this case such path through the program will not be explored
by the verifier. It won't be taken at run-time either, but since
all instructions are JITed the malicious program may cause JITs
to complain about using reserved fields, etc.
To fix the issue we have to track the instructions explored by
the verifier and sanitize instructions that are dead at run time
with NOPs. We cannot reject such dead code, since llvm generates
it for valid C code, since it doesn't do as much data flow
analysis as the verifier does.
Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)")
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
{
char *new_ifalias;
ASSERT_RTNL();
if (len >= IFALIASZ)
return -EINVAL;
if (!len) {
kfree(dev->ifalias);
dev->ifalias = NULL;
return 0;
}
new_ifalias = krealloc(dev->ifalias, len + 1, GFP_KERNEL);
if (!new_ifalias)
return -ENOMEM;
dev->ifalias = new_ifalias;
memcpy(dev->ifalias, alias, len);
dev->ifalias[len] = 0;
return len;
}
Commit Message: tun: call dev_get_valid_name() before register_netdevice()
register_netdevice() could fail early when we have an invalid
dev name, in which case ->ndo_uninit() is not called. For tun
device, this is a problem because a timer etc. are already
initialized and it expects ->ndo_uninit() to clean them up.
We could move these initializations into a ->ndo_init() so
that register_netdevice() knows better, however this is still
complicated due to the logic in tun_detach().
Therefore, I choose to just call dev_get_valid_name() before
register_netdevice(), which is quicker and much easier to audit.
And for this specific case, it is already enough.
Fixes: 96442e42429e ("tuntap: choose the txq based on rxq")
Reported-by: Dmitry Alexeev <[email protected]>
Cc: Jason Wang <[email protected]>
Cc: "Michael S. Tsirkin" <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct rds_connection *__rds_conn_create(struct net *net,
__be32 laddr, __be32 faddr,
struct rds_transport *trans, gfp_t gfp,
int is_outgoing)
{
struct rds_connection *conn, *parent = NULL;
struct hlist_head *head = rds_conn_bucket(laddr, faddr);
struct rds_transport *loop_trans;
unsigned long flags;
int ret;
struct rds_transport *otrans = trans;
if (!is_outgoing && otrans->t_type == RDS_TRANS_TCP)
goto new_conn;
rcu_read_lock();
conn = rds_conn_lookup(net, head, laddr, faddr, trans);
if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport &&
laddr == faddr && !is_outgoing) {
/* This is a looped back IB connection, and we're
* called by the code handling the incoming connect.
* We need a second connection object into which we
* can stick the other QP. */
parent = conn;
conn = parent->c_passive;
}
rcu_read_unlock();
if (conn)
goto out;
new_conn:
conn = kmem_cache_zalloc(rds_conn_slab, gfp);
if (!conn) {
conn = ERR_PTR(-ENOMEM);
goto out;
}
INIT_HLIST_NODE(&conn->c_hash_node);
conn->c_laddr = laddr;
conn->c_faddr = faddr;
spin_lock_init(&conn->c_lock);
conn->c_next_tx_seq = 1;
rds_conn_net_set(conn, net);
init_waitqueue_head(&conn->c_waitq);
INIT_LIST_HEAD(&conn->c_send_queue);
INIT_LIST_HEAD(&conn->c_retrans);
ret = rds_cong_get_maps(conn);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
/*
* This is where a connection becomes loopback. If *any* RDS sockets
* can bind to the destination address then we'd rather the messages
* flow through loopback rather than either transport.
*/
loop_trans = rds_trans_get_preferred(net, faddr);
if (loop_trans) {
rds_trans_put(loop_trans);
conn->c_loopback = 1;
if (is_outgoing && trans->t_prefer_loopback) {
/* "outgoing" connection - and the transport
* says it wants the connection handled by the
* loopback transport. This is what TCP does.
*/
trans = &rds_loop_transport;
}
}
conn->c_trans = trans;
ret = trans->conn_alloc(conn, gfp);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
atomic_set(&conn->c_state, RDS_CONN_DOWN);
conn->c_send_gen = 0;
conn->c_reconnect_jiffies = 0;
INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker);
INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker);
INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker);
INIT_WORK(&conn->c_down_w, rds_shutdown_worker);
mutex_init(&conn->c_cm_lock);
conn->c_flags = 0;
rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n",
conn, &laddr, &faddr,
trans->t_name ? trans->t_name : "[unknown]",
is_outgoing ? "(outgoing)" : "");
/*
* Since we ran without holding the conn lock, someone could
* have created the same conn (either normal or passive) in the
* interim. We check while holding the lock. If we won, we complete
* init and return our conn. If we lost, we rollback and return the
* other one.
*/
spin_lock_irqsave(&rds_conn_lock, flags);
if (parent) {
/* Creating passive conn */
if (parent->c_passive) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = parent->c_passive;
} else {
parent->c_passive = conn;
rds_cong_add_conn(conn);
rds_conn_count++;
}
} else {
/* Creating normal conn */
struct rds_connection *found;
if (!is_outgoing && otrans->t_type == RDS_TRANS_TCP)
found = NULL;
else
found = rds_conn_lookup(net, head, laddr, faddr, trans);
if (found) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = found;
} else {
if ((is_outgoing && otrans->t_type == RDS_TRANS_TCP) ||
(otrans->t_type != RDS_TRANS_TCP)) {
/* Only the active side should be added to
* reconnect list for TCP.
*/
hlist_add_head_rcu(&conn->c_hash_node, head);
}
rds_cong_add_conn(conn);
rds_conn_count++;
}
}
spin_unlock_irqrestore(&rds_conn_lock, flags);
out:
return conn;
}
Commit Message: RDS: verify the underlying transport exists before creating a connection
There was no verification that an underlying transport exists when creating
a connection, this would cause dereferencing a NULL ptr.
It might happen on sockets that weren't properly bound before attempting to
send a message, which will cause a NULL ptr deref:
[135546.047719] kasan: GPF could be caused by NULL-ptr deref or user memory accessgeneral protection fault: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC KASAN
[135546.051270] Modules linked in:
[135546.051781] CPU: 4 PID: 15650 Comm: trinity-c4 Not tainted 4.2.0-next-20150902-sasha-00041-gbaa1222-dirty #2527
[135546.053217] task: ffff8800835bc000 ti: ffff8800bc708000 task.ti: ffff8800bc708000
[135546.054291] RIP: __rds_conn_create (net/rds/connection.c:194)
[135546.055666] RSP: 0018:ffff8800bc70fab0 EFLAGS: 00010202
[135546.056457] RAX: dffffc0000000000 RBX: 0000000000000f2c RCX: ffff8800835bc000
[135546.057494] RDX: 0000000000000007 RSI: ffff8800835bccd8 RDI: 0000000000000038
[135546.058530] RBP: ffff8800bc70fb18 R08: 0000000000000001 R09: 0000000000000000
[135546.059556] R10: ffffed014d7a3a23 R11: ffffed014d7a3a21 R12: 0000000000000000
[135546.060614] R13: 0000000000000001 R14: ffff8801ec3d0000 R15: 0000000000000000
[135546.061668] FS: 00007faad4ffb700(0000) GS:ffff880252000000(0000) knlGS:0000000000000000
[135546.062836] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[135546.063682] CR2: 000000000000846a CR3: 000000009d137000 CR4: 00000000000006a0
[135546.064723] Stack:
[135546.065048] ffffffffafe2055c ffffffffafe23fc1 ffffed00493097bf ffff8801ec3d0008
[135546.066247] 0000000000000000 00000000000000d0 0000000000000000 ac194a24c0586342
[135546.067438] 1ffff100178e1f78 ffff880320581b00 ffff8800bc70fdd0 ffff880320581b00
[135546.068629] Call Trace:
[135546.069028] ? __rds_conn_create (include/linux/rcupdate.h:856 net/rds/connection.c:134)
[135546.069989] ? rds_message_copy_from_user (net/rds/message.c:298)
[135546.071021] rds_conn_create_outgoing (net/rds/connection.c:278)
[135546.071981] rds_sendmsg (net/rds/send.c:1058)
[135546.072858] ? perf_trace_lock (include/trace/events/lock.h:38)
[135546.073744] ? lockdep_init (kernel/locking/lockdep.c:3298)
[135546.074577] ? rds_send_drop_to (net/rds/send.c:976)
[135546.075508] ? __might_fault (./arch/x86/include/asm/current.h:14 mm/memory.c:3795)
[135546.076349] ? __might_fault (mm/memory.c:3795)
[135546.077179] ? rds_send_drop_to (net/rds/send.c:976)
[135546.078114] sock_sendmsg (net/socket.c:611 net/socket.c:620)
[135546.078856] SYSC_sendto (net/socket.c:1657)
[135546.079596] ? SYSC_connect (net/socket.c:1628)
[135546.080510] ? trace_dump_stack (kernel/trace/trace.c:1926)
[135546.081397] ? ring_buffer_unlock_commit (kernel/trace/ring_buffer.c:2479 kernel/trace/ring_buffer.c:2558 kernel/trace/ring_buffer.c:2674)
[135546.082390] ? trace_buffer_unlock_commit (kernel/trace/trace.c:1749)
[135546.083410] ? trace_event_raw_event_sys_enter (include/trace/events/syscalls.h:16)
[135546.084481] ? do_audit_syscall_entry (include/trace/events/syscalls.h:16)
[135546.085438] ? trace_buffer_unlock_commit (kernel/trace/trace.c:1749)
[135546.085515] rds_ib_laddr_check(): addr 36.74.25.172 ret -99 node type -1
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: Sasha Levin <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 1
Example 2:
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) {
#if !defined(OS_MACOSX) && defined(USE_TCMALLOC)
MallocExtension::instance()->ReleaseFreeMemory();
#endif
if (v8::V8::IdleNotification(idle_hint)) {
new_delay_ms = kLongIdleHandlerDelayMs;
}
}
}
ScheduleIdleHandler(new_delay_ms);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostImpl::WindowSnapshotReachedScreen(int snapshot_id) {
DCHECK(base::MessageLoopForUI::IsCurrent());
if (!pending_surface_browser_snapshots_.empty()) {
GetView()->CopyFromSurface(
gfx::Rect(), gfx::Size(),
base::BindOnce(&RenderWidgetHostImpl::OnSnapshotFromSurfaceReceived,
weak_factory_.GetWeakPtr(), snapshot_id, 0));
}
if (!pending_browser_snapshots_.empty()) {
#if defined(OS_ANDROID)
gfx::Rect snapshot_bounds(GetView()->GetViewBounds());
snapshot_bounds.Offset(0, GetView()->GetNativeView()->content_offset());
#else
gfx::Rect snapshot_bounds(GetView()->GetViewBounds().size());
#endif
gfx::Image image;
if (ui::GrabViewSnapshot(GetView()->GetNativeView(), snapshot_bounds,
&image)) {
OnSnapshotReceived(snapshot_id, image);
return;
}
ui::GrabViewSnapshotAsync(
GetView()->GetNativeView(), snapshot_bounds,
base::Bind(&RenderWidgetHostImpl::OnSnapshotReceived,
weak_factory_.GetWeakPtr(), snapshot_id));
}
}
Commit Message: Start rendering timer after first navigation
Currently the new content rendering timer in the browser process,
which clears an old page's contents 4 seconds after a navigation if the
new page doesn't draw in that time, is not set on the first navigation
for a top-level frame.
This is problematic because content can exist before the first
navigation, for instance if it was created by a javascript: URL.
This CL removes the code that skips the timer activation on the first
navigation.
Bug: 844881
Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584
Reviewed-on: https://chromium-review.googlesource.com/1188589
Reviewed-by: Fady Samuel <[email protected]>
Reviewed-by: ccameron <[email protected]>
Commit-Queue: Ken Buchanan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586913}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: spnego_gss_export_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 ret;
ret = gss_export_sec_context(minor_status,
context_handle,
interprocess_token);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18
Target: 1
Example 2:
Code: BackFramebuffer::~BackFramebuffer() {
DCHECK_EQ(id_, 0u);
}
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
[email protected],[email protected]
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void writeObject(uint32_t numProperties)
{
append(ObjectTag);
doWriteUint32(numProperties);
}
Commit Message: Replace further questionable HashMap::add usages in bindings
BUG=390928
[email protected]
Review URL: https://codereview.chromium.org/411273002
git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static char *lxclock_name(const char *p, const char *n)
{
int ret;
int len;
char *dest;
char *rundir;
/* lockfile will be:
* "/run" + "/lock/lxc/$lxcpath/$lxcname + '\0' if root
* or
* $XDG_RUNTIME_DIR + "/lock/lxc/$lxcpath/$lxcname + '\0' if non-root
*/
/* length of "/lock/lxc/" + $lxcpath + "/" + "." + $lxcname + '\0' */
len = strlen("/lock/lxc/") + strlen(n) + strlen(p) + 3;
rundir = get_rundir();
if (!rundir)
return NULL;
len += strlen(rundir);
if ((dest = malloc(len)) == NULL) {
free(rundir);
return NULL;
}
ret = snprintf(dest, len, "%s/lock/lxc/%s", rundir, p);
if (ret < 0 || ret >= len) {
free(dest);
free(rundir);
return NULL;
}
ret = mkdir_p(dest, 0755);
if (ret < 0) {
/* fall back to "/tmp/" + $(id -u) + "/lxc" + $lxcpath + "/" + "." + $lxcname + '\0'
* * maximum length of $(id -u) is 10 calculated by (log (2 ** (sizeof(uid_t) * 8) - 1) / log 10 + 1)
* * lxcpath always starts with '/'
*/
int l2 = 22 + strlen(n) + strlen(p);
if (l2 > len) {
char *d;
d = realloc(dest, l2);
if (!d) {
free(dest);
free(rundir);
return NULL;
}
len = l2;
dest = d;
}
ret = snprintf(dest, len, "/tmp/%d/lxc%s", geteuid(), p);
if (ret < 0 || ret >= len) {
free(dest);
free(rundir);
return NULL;
}
ret = mkdir_p(dest, 0755);
if (ret < 0) {
free(dest);
free(rundir);
return NULL;
}
ret = snprintf(dest, len, "/tmp/%d/lxc%s/.%s", geteuid(), p, n);
} else
ret = snprintf(dest, len, "%s/lock/lxc/%s/.%s", rundir, p, n);
free(rundir);
if (ret < 0 || ret >= len) {
free(dest);
return NULL;
}
return dest;
}
Commit Message: CVE-2015-1331: lxclock: use /run/lxc/lock rather than /run/lock/lxc
This prevents an unprivileged user to use LXC to create arbitrary file
on the filesystem.
Signed-off-by: Serge Hallyn <[email protected]>
Signed-off-by: Tyler Hicks <[email protected]>
Acked-by: Stéphane Graber <[email protected]>
CWE ID: CWE-59
Target: 1
Example 2:
Code: force_sigsegv(int sig, struct task_struct *p)
{
if (sig == SIGSEGV) {
unsigned long flags;
spin_lock_irqsave(&p->sighand->siglock, flags);
p->sighand->action[sig - 1].sa.sa_handler = SIG_DFL;
spin_unlock_irqrestore(&p->sighand->siglock, flags);
}
force_sig(SIGSEGV, p);
return 0;
}
Commit Message: kernel/signal.c: stop info leak via the tkill and the tgkill syscalls
This fixes a kernel memory contents leak via the tkill and tgkill syscalls
for compat processes.
This is visible in the siginfo_t->_sifields._rt.si_sigval.sival_ptr field
when handling signals delivered from tkill.
The place of the infoleak:
int copy_siginfo_to_user32(compat_siginfo_t __user *to, siginfo_t *from)
{
...
put_user_ex(ptr_to_compat(from->si_ptr), &to->si_ptr);
...
}
Signed-off-by: Emese Revfy <[email protected]>
Reviewed-by: PaX Team <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void sas_eh_finish_cmd(struct scsi_cmnd *cmd)
{
struct sas_ha_struct *sas_ha = SHOST_TO_SAS_HA(cmd->device->host);
struct sas_task *task = TO_SAS_TASK(cmd);
/* At this point, we only get called following an actual abort
* of the task, so we should be guaranteed not to be racing with
* any completions from the LLD. Task is freed after this.
*/
sas_end_task(cmd, task);
/* now finish the command and move it on to the error
* handler done list, this also takes it off the
* error handler pending list.
*/
scsi_eh_finish_cmd(cmd, &sas_ha->eh_done_q);
}
Commit Message: scsi: libsas: defer ata device eh commands to libata
When ata device doing EH, some commands still attached with tasks are
not passed to libata when abort failed or recover failed, so libata did
not handle these commands. After these commands done, sas task is freed,
but ata qc is not freed. This will cause ata qc leak and trigger a
warning like below:
WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037
ata_eh_finish+0xb4/0xcc
CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1
......
Call trace:
[<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc
[<ffff0000088b8420>] ata_do_eh+0xc4/0xd8
[<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c
[<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694
[<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80
[<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170
[<ffff0000080ebd70>] process_one_work+0x144/0x390
[<ffff0000080ec100>] worker_thread+0x144/0x418
[<ffff0000080f2c98>] kthread+0x10c/0x138
[<ffff0000080855dc>] ret_from_fork+0x10/0x18
If ata qc leaked too many, ata tag allocation will fail and io blocked
for ever.
As suggested by Dan Williams, defer ata device commands to libata and
merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle
ata qcs correctly after this.
Signed-off-by: Jason Yan <[email protected]>
CC: Xiaofei Tan <[email protected]>
CC: John Garry <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Dan Williams <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GDataCacheMetadataMap::Initialize(
const std::vector<FilePath>& cache_paths) {
AssertOnSequencedWorkerPool();
if (cache_paths.size() < GDataCache::NUM_CACHE_TYPES) {
LOG(ERROR) << "Size of cache_paths is invalid.";
return;
}
if (!GDataCache::CreateCacheDirectories(cache_paths))
return;
if (!ChangeFilePermissions(cache_paths[GDataCache::CACHE_TYPE_PERSISTENT],
S_IRWXU | S_IXGRP | S_IXOTH))
return;
DVLOG(1) << "Scanning directories";
ResourceIdToFilePathMap persistent_file_map;
ScanCacheDirectory(cache_paths,
GDataCache::CACHE_TYPE_PERSISTENT,
&cache_map_,
&persistent_file_map);
ResourceIdToFilePathMap tmp_file_map;
ScanCacheDirectory(cache_paths,
GDataCache::CACHE_TYPE_TMP,
&cache_map_,
&tmp_file_map);
ResourceIdToFilePathMap pinned_file_map;
ScanCacheDirectory(cache_paths,
GDataCache::CACHE_TYPE_PINNED,
&cache_map_,
&pinned_file_map);
ResourceIdToFilePathMap outgoing_file_map;
ScanCacheDirectory(cache_paths,
GDataCache::CACHE_TYPE_OUTGOING,
&cache_map_,
&outgoing_file_map);
RemoveInvalidFilesFromPersistentDirectory(persistent_file_map,
outgoing_file_map,
&cache_map_);
DVLOG(1) << "Directory scan finished";
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ChromePluginServiceFilter::OverridePluginForTab(
int render_process_id,
int render_view_id,
const GURL& url,
const webkit::WebPluginInfo& plugin) {
base::AutoLock auto_lock(lock_);
ProcessDetails* details = GetOrRegisterProcess(render_process_id);
OverriddenPlugin overridden_plugin;
overridden_plugin.render_view_id = render_view_id;
overridden_plugin.url = url;
overridden_plugin.plugin = plugin;
details->overridden_plugins.push_back(overridden_plugin);
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
{
}
Commit Message: ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl
Some ARM KVM VCPU ioctls require the vCPU to be properly initialized
with the KVM_ARM_VCPU_INIT ioctl before being used with further
requests. KVM_RUN checks whether this initialization has been
done, but other ioctls do not.
Namely KVM_GET_REG_LIST will dereference an array with index -1
without initialization and thus leads to a kernel oops.
Fix this by adding checks before executing the ioctl handlers.
[ Removed superflous comment from static function - Christoffer ]
Changes from v1:
* moved check into a static function with a meaningful name
Signed-off-by: Andre Przywara <[email protected]>
Signed-off-by: Christoffer Dall <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void UserSelectionScreen::OnBeforeUserRemoved(const AccountId& account_id) {
for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();
++it) {
if ((*it)->GetAccountId() == account_id) {
users_.erase(it);
break;
}
}
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID:
Target: 1
Example 2:
Code: void V8ValueConverterImpl::SetDateAllowed(bool val) {
date_allowed_ = val;
}
Commit Message: V8ValueConverter::ToV8Value should not trigger setters
BUG=606390
Review URL: https://codereview.chromium.org/1918793003
Cr-Commit-Position: refs/heads/master@{#390045}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
mpeg4_decode_profile_level(s, gb);
if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(s->avctx->level > 0 && s->avctx->level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
}
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
Commit Message: avcodec/mpeg4videodec: Check read profile before setting it
Fixes: null pointer dereference
Fixes: ffmpeg_crash_7.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int misaligned_load(struct pt_regs *regs,
__u32 opcode,
int displacement_not_indexed,
int width_shift,
int do_sign_extend)
{
/* Return -1 for a fault, 0 for OK */
int error;
int destreg;
__u64 address;
error = generate_and_check_address(regs, opcode,
displacement_not_indexed, width_shift, &address);
if (error < 0) {
return error;
}
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, address);
destreg = (opcode >> 4) & 0x3f;
if (user_mode(regs)) {
__u64 buffer;
if (!access_ok(VERIFY_READ, (unsigned long) address, 1UL<<width_shift)) {
return -1;
}
if (__copy_user(&buffer, (const void *)(int)address, (1 << width_shift)) > 0) {
return -1; /* fault */
}
switch (width_shift) {
case 1:
if (do_sign_extend) {
regs->regs[destreg] = (__u64)(__s64) *(__s16 *) &buffer;
} else {
regs->regs[destreg] = (__u64) *(__u16 *) &buffer;
}
break;
case 2:
regs->regs[destreg] = (__u64)(__s64) *(__s32 *) &buffer;
break;
case 3:
regs->regs[destreg] = buffer;
break;
default:
printk("Unexpected width_shift %d in misaligned_load, PC=%08lx\n",
width_shift, (unsigned long) regs->pc);
break;
}
} else {
/* kernel mode - we can take short cuts since if we fault, it's a genuine bug */
__u64 lo, hi;
switch (width_shift) {
case 1:
misaligned_kernel_word_load(address, do_sign_extend, ®s->regs[destreg]);
break;
case 2:
asm ("ldlo.l %1, 0, %0" : "=r" (lo) : "r" (address));
asm ("ldhi.l %1, 3, %0" : "=r" (hi) : "r" (address));
regs->regs[destreg] = lo | hi;
break;
case 3:
asm ("ldlo.q %1, 0, %0" : "=r" (lo) : "r" (address));
asm ("ldhi.q %1, 7, %0" : "=r" (hi) : "r" (address));
regs->regs[destreg] = lo | hi;
break;
default:
printk("Unexpected width_shift %d in misaligned_load, PC=%08lx\n",
width_shift, (unsigned long) regs->pc);
break;
}
}
return 0;
}
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 <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: static inline int preempt_count_equals(int preempt_offset)
{
int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
return (nested == preempt_offset);
}
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 <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct key *key_alloc(struct key_type *type, const char *desc,
kuid_t uid, kgid_t gid, const struct cred *cred,
key_perm_t perm, unsigned long flags,
int (*restrict_link)(struct key *,
const struct key_type *,
const union key_payload *))
{
struct key_user *user = NULL;
struct key *key;
size_t desclen, quotalen;
int ret;
key = ERR_PTR(-EINVAL);
if (!desc || !*desc)
goto error;
if (type->vet_description) {
ret = type->vet_description(desc);
if (ret < 0) {
key = ERR_PTR(ret);
goto error;
}
}
desclen = strlen(desc);
quotalen = desclen + 1 + type->def_datalen;
/* get hold of the key tracking for this user */
user = key_user_lookup(uid);
if (!user)
goto no_memory_1;
/* check that the user's quota permits allocation of another key and
* its description */
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxkeys : key_quota_maxkeys;
unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ?
key_quota_root_maxbytes : key_quota_maxbytes;
spin_lock(&user->lock);
if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) {
if (user->qnkeys + 1 >= maxkeys ||
user->qnbytes + quotalen >= maxbytes ||
user->qnbytes + quotalen < user->qnbytes)
goto no_quota;
}
user->qnkeys++;
user->qnbytes += quotalen;
spin_unlock(&user->lock);
}
/* allocate and initialise the key and its description */
key = kmem_cache_zalloc(key_jar, GFP_KERNEL);
if (!key)
goto no_memory_2;
key->index_key.desc_len = desclen;
key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL);
if (!key->index_key.description)
goto no_memory_3;
atomic_set(&key->usage, 1);
init_rwsem(&key->sem);
lockdep_set_class(&key->sem, &type->lock_class);
key->index_key.type = type;
key->user = user;
key->quotalen = quotalen;
key->datalen = type->def_datalen;
key->uid = uid;
key->gid = gid;
key->perm = perm;
key->restrict_link = restrict_link;
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA))
key->flags |= 1 << KEY_FLAG_IN_QUOTA;
if (flags & KEY_ALLOC_BUILT_IN)
key->flags |= 1 << KEY_FLAG_BUILTIN;
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC;
#endif
/* let the security module know about the key */
ret = security_key_alloc(key, cred, flags);
if (ret < 0)
goto security_error;
/* publish the key by giving it a serial number */
atomic_inc(&user->nkeys);
key_alloc_serial(key);
error:
return key;
security_error:
kfree(key->description);
kmem_cache_free(key_jar, key);
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
spin_lock(&user->lock);
user->qnkeys--;
user->qnbytes -= quotalen;
spin_unlock(&user->lock);
}
key_user_put(user);
key = ERR_PTR(ret);
goto error;
no_memory_3:
kmem_cache_free(key_jar, key);
no_memory_2:
if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) {
spin_lock(&user->lock);
user->qnkeys--;
user->qnbytes -= quotalen;
spin_unlock(&user->lock);
}
key_user_put(user);
no_memory_1:
key = ERR_PTR(-ENOMEM);
goto error;
no_quota:
spin_unlock(&user->lock);
key_user_put(user);
key = ERR_PTR(-EDQUOT);
goto error;
}
Commit Message: KEYS: potential uninitialized variable
If __key_link_begin() failed then "edit" would be uninitialized. I've
added a check to fix that.
This allows a random user to crash the kernel, though it's quite
difficult to achieve. There are three ways it can be done as the user
would have to cause an error to occur in __key_link():
(1) Cause the kernel to run out of memory. In practice, this is difficult
to achieve without ENOMEM cropping up elsewhere and aborting the
attempt.
(2) Revoke the destination keyring between the keyring ID being looked up
and it being tested for revocation. In practice, this is difficult to
time correctly because the KEYCTL_REJECT function can only be used
from the request-key upcall process. Further, users can only make use
of what's in /sbin/request-key.conf, though this does including a
rejection debugging test - which means that the destination keyring
has to be the caller's session keyring in practice.
(3) Have just enough key quota available to create a key, a new session
keyring for the upcall and a link in the session keyring, but not then
sufficient quota to create a link in the nominated destination keyring
so that it fails with EDQUOT.
The bug can be triggered using option (3) above using something like the
following:
echo 80 >/proc/sys/kernel/keys/root_maxbytes
keyctl request2 user debug:fred negate @t
The above sets the quota to something much lower (80) to make the bug
easier to trigger, but this is dependent on the system. Note also that
the name of the keyring created contains a random number that may be
between 1 and 10 characters in size, so may throw the test off by
changing the amount of quota used.
Assuming the failure occurs, something like the following will be seen:
kfree_debugcheck: out of range ptr 6b6b6b6b6b6b6b68h
------------[ cut here ]------------
kernel BUG at ../mm/slab.c:2821!
...
RIP: 0010:[<ffffffff811600f9>] kfree_debugcheck+0x20/0x25
RSP: 0018:ffff8804014a7de8 EFLAGS: 00010092
RAX: 0000000000000034 RBX: 6b6b6b6b6b6b6b68 RCX: 0000000000000000
RDX: 0000000000040001 RSI: 00000000000000f6 RDI: 0000000000000300
RBP: ffff8804014a7df0 R08: 0000000000000001 R09: 0000000000000000
R10: ffff8804014a7e68 R11: 0000000000000054 R12: 0000000000000202
R13: ffffffff81318a66 R14: 0000000000000000 R15: 0000000000000001
...
Call Trace:
kfree+0xde/0x1bc
assoc_array_cancel_edit+0x1f/0x36
__key_link_end+0x55/0x63
key_reject_and_link+0x124/0x155
keyctl_reject_key+0xb6/0xe0
keyctl_negate_key+0x10/0x12
SyS_keyctl+0x9f/0xe7
do_syscall_64+0x63/0x13a
entry_SYSCALL64_slow_path+0x25/0x25
Fixes: f70e2e06196a ('KEYS: Do preallocation for __key_link()')
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: David Howells <[email protected]>
cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ptrace_setxregs(struct task_struct *child, void __user *uregs)
{
struct thread_info *ti = task_thread_info(child);
struct pt_regs *regs = task_pt_regs(child);
elf_xtregs_t *xtregs = uregs;
int ret = 0;
#if XTENSA_HAVE_COPROCESSORS
/* Flush all coprocessors before we overwrite them. */
coprocessor_flush_all(ti);
coprocessor_release_all(ti);
ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0,
sizeof(xtregs_coprocessor_t));
#endif
ret |= __copy_from_user(®s->xtregs_opt, &xtregs->opt,
sizeof(xtregs->opt));
ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user,
sizeof(xtregs->user));
return ret ? -EFAULT : 0;
}
Commit Message: xtensa: prevent arbitrary read in ptrace
Prevent an arbitrary kernel read. Check the user pointer with access_ok()
before copying data in.
[[email protected]: s/EIO/EFAULT/]
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: Christian Zankel <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool reqsk_queue_unlink(struct request_sock_queue *queue,
struct request_sock *req)
{
struct inet_hashinfo *hashinfo = req_to_sk(req)->sk_prot->h.hashinfo;
bool found = false;
if (sk_hashed(req_to_sk(req))) {
spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
spin_lock(lock);
found = __sk_nulls_del_node_init_rcu(req_to_sk(req));
spin_unlock(lock);
}
if (timer_pending(&req->rsk_timer) && del_timer_sync(&req->rsk_timer))
reqsk_put(req);
return found;
}
Commit Message: dccp/tcp: do not inherit mc_list from parent
syzkaller found a way to trigger double frees from ip_mc_drop_socket()
It turns out that leave a copy of parent mc_list at accept() time,
which is very bad.
Very similar to commit 8b485ce69876 ("tcp: do not inherit
fastopen_req from parent")
Initial report from Pray3r, completed by Andrey one.
Thanks a lot to them !
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Pray3r <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-415
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PixelBufferRasterWorkerPool::OnRasterTasksRequiredForActivationFinished() {
if (!should_notify_client_if_no_tasks_required_for_activation_are_pending_)
return;
CheckForCompletedRasterTasks();
}
Commit Message: cc: Simplify raster task completion notification logic
(Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/)
Previously the pixel buffer raster worker pool used a combination of
polling and explicit notifications from the raster worker pool to decide
when to tell the client about the completion of 1) all tasks or 2) the
subset of tasks required for activation. This patch simplifies the logic
by only triggering the notification based on the OnRasterTasksFinished
and OnRasterTasksRequiredForActivationFinished calls from the worker
pool.
BUG=307841,331534
Review URL: https://codereview.chromium.org/99873007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: apprentice_load(struct magic_set *ms, const char *fn, int action)
{
int errs = 0;
uint32_t i, j;
size_t files = 0, maxfiles = 0;
char **filearr = NULL;
struct stat st;
struct magic_map *map;
struct magic_entry_set mset[MAGIC_SETS];
php_stream *dir;
php_stream_dirent d;
TSRMLS_FETCH();
memset(mset, 0, sizeof(mset));
ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)
{
file_oomem(ms, sizeof(*map));
return NULL;
}
/* print silly verbose header for USG compat. */
if (action == FILE_CHECK)
(void)fprintf(stderr, "%s\n", usg_hdr);
/* load directory or file */
/* FIXME: Read file names and sort them to prevent
non-determinism. See Debian bug #488562. */
if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
int mflen;
char mfn[MAXPATHLEN];
dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);
if (!dir) {
errs++;
goto out;
}
while (php_stream_readdir(dir, &d)) {
if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) {
file_oomem(ms,
strlen(fn) + strlen(d.d_name) + 2);
errs++;
php_stream_closedir(dir);
goto out;
}
if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
continue;
}
if (files >= maxfiles) {
size_t mlen;
maxfiles = (maxfiles + 1) * 2;
mlen = maxfiles * sizeof(*filearr);
if ((filearr = CAST(char **,
erealloc(filearr, mlen))) == NULL) {
file_oomem(ms, mlen);
efree(mfn);
php_stream_closedir(dir);
errs++;
goto out;
goto out;
}
}
filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);
}
php_stream_closedir(dir);
qsort(filearr, files, sizeof(*filearr), cmpstrp);
for (i = 0; i < files; i++) {
load_1(ms, action, filearr[i], &errs, mset);
efree(filearr[i]);
}
efree(filearr);
} else
load_1(ms, action, fn, &errs, mset);
if (errs)
goto out;
for (j = 0; j < MAGIC_SETS; j++) {
/* Set types of tests */
for (i = 0; i < mset[j].count; ) {
if (mset[j].me[i].mp->cont_level != 0) {
i++;
continue;
}
i = set_text_binary(ms, mset[j].me, mset[j].count, i);
}
qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
apprentice_sort);
/*
* Make sure that any level 0 "default" line is last
* (if one exists).
*/
set_last_default(ms, mset[j].me, mset[j].count);
/* coalesce per file arrays into a single one */
if (coalesce_entries(ms, mset[j].me, mset[j].count,
&map->magic[j], &map->nmagic[j]) == -1) {
errs++;
goto out;
}
}
out:
for (j = 0; j < MAGIC_SETS; j++)
magic_entry_free(mset[j].me, mset[j].count);
if (errs) {
for (j = 0; j < MAGIC_SETS; j++) {
if (map->magic[j])
efree(map->magic[j]);
}
efree(map);
return NULL;
}
return map;
}
Commit Message:
CWE ID: CWE-17
Target: 1
Example 2:
Code: static struct page *kvm_pfn_to_page(pfn_t pfn)
{
if (is_error_pfn(pfn))
return KVM_ERR_PTR_BAD_PAGE;
if (kvm_is_mmio_pfn(pfn)) {
WARN_ON(1);
return KVM_ERR_PTR_BAD_PAGE;
}
return pfn_to_page(pfn);
}
Commit Message: KVM: perform an invalid memslot step for gpa base change
PPC must flush all translations before the new memory slot
is visible.
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: HostCache::HostCache(size_t max_entries)
: max_entries_(max_entries), network_changes_(0) {}
Commit Message: Add PersistenceDelegate to HostCache
PersistenceDelegate is a new interface for persisting the contents of
the HostCache. This commit includes the interface itself, the logic in
HostCache for interacting with it, and a mock implementation of the
interface for testing. It does not include support for immediate data
removal since that won't be needed for the currently planned use case.
BUG=605149
Review-Url: https://codereview.chromium.org/2943143002
Cr-Commit-Position: refs/heads/master@{#481015}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: print_attr_string(netdissect_options *ndo,
register const u_char *data, u_int length, u_short attr_code)
{
register u_int i;
ND_TCHECK2(data[0],length);
switch(attr_code)
{
case TUNNEL_PASS:
if (length < 3)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (*data && (*data <=0x1F) )
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
ND_PRINT((ndo, "Salt %u ", EXTRACT_16BITS(data)));
data+=2;
length-=2;
break;
case TUNNEL_CLIENT_END:
case TUNNEL_SERVER_END:
case TUNNEL_PRIV_GROUP:
case TUNNEL_ASSIGN_ID:
case TUNNEL_CLIENT_AUTH:
case TUNNEL_SERVER_AUTH:
if (*data <= 0x1F)
{
if (length < 1)
{
ND_PRINT((ndo, "%s", tstr));
return;
}
if (*data)
ND_PRINT((ndo, "Tag[%u] ", *data));
else
ND_PRINT((ndo, "Tag[Unused] "));
data++;
length--;
}
break;
case EGRESS_VLAN_NAME:
ND_PRINT((ndo, "%s (0x%02x) ",
tok2str(rfc4675_tagged,"Unknown tag",*data),
*data));
data++;
length--;
break;
}
for (i=0; *data && i < length ; i++, data++)
ND_PRINT((ndo, "%c", (*data < 32 || *data > 126) ? '.' : *data));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-13032/RADIUS: Check whether a byte exists before testing its value.
Reverse the test in a for loop to test the length before testing whether
we have a null byte.
This fixes a buffer over-read discovered by Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Clean up other length tests while we're at it.
CWE ID: CWE-125
Target: 1
Example 2:
Code: void RenderProcessHostImpl::RemoveFrameWithSite(
BrowserContext* browser_context,
RenderProcessHost* render_process_host,
const GURL& site_url) {
if (!ShouldTrackProcessForSite(browser_context, render_process_host,
site_url))
return;
SiteProcessCountTracker* tracker = static_cast<SiteProcessCountTracker*>(
browser_context->GetUserData(kCommittedSiteProcessCountTrackerKey));
if (!tracker) {
tracker = new SiteProcessCountTracker();
browser_context->SetUserData(kCommittedSiteProcessCountTrackerKey,
base::WrapUnique(tracker));
}
tracker->DecrementSiteProcessCount(site_url, render_process_host->GetID());
}
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 <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline unsigned int get_next_char(
enum entity_charset charset,
const unsigned char *str,
size_t str_len,
size_t *cursor,
int *status)
{
size_t pos = *cursor;
unsigned int this_char = 0;
*status = SUCCESS;
assert(pos <= str_len);
if (!CHECK_LEN(pos, 1))
MB_FAILURE(pos, 1);
switch (charset) {
case cs_utf_8:
{
/* We'll follow strategy 2. from section 3.6.1 of UTR #36:
* "In a reported illegal byte sequence, do not include any
* non-initial byte that encodes a valid character or is a leading
* byte for a valid sequence." */
unsigned char c;
c = str[pos];
if (c < 0x80) {
this_char = c;
pos++;
} else if (c < 0xc2) {
MB_FAILURE(pos, 1);
} else if (c < 0xe0) {
if (!CHECK_LEN(pos, 2))
MB_FAILURE(pos, 1);
if (!utf8_trail(str[pos + 1])) {
MB_FAILURE(pos, utf8_lead(str[pos + 1]) ? 1 : 2);
}
this_char = ((c & 0x1f) << 6) | (str[pos + 1] & 0x3f);
if (this_char < 0x80) { /* non-shortest form */
MB_FAILURE(pos, 2);
}
pos += 2;
} else if (c < 0xf0) {
size_t avail = str_len - pos;
if (avail < 3 ||
!utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2])) {
if (avail < 2 || utf8_lead(str[pos + 1]))
MB_FAILURE(pos, 1);
else if (avail < 3 || utf8_lead(str[pos + 2]))
MB_FAILURE(pos, 2);
else
MB_FAILURE(pos, 3);
}
this_char = ((c & 0x0f) << 12) | ((str[pos + 1] & 0x3f) << 6) | (str[pos + 2] & 0x3f);
if (this_char < 0x800) { /* non-shortest form */
MB_FAILURE(pos, 3);
} else if (this_char >= 0xd800 && this_char <= 0xdfff) { /* surrogate */
MB_FAILURE(pos, 3);
}
pos += 3;
} else if (c < 0xf5) {
size_t avail = str_len - pos;
if (avail < 4 ||
!utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2]) ||
!utf8_trail(str[pos + 3])) {
if (avail < 2 || utf8_lead(str[pos + 1]))
MB_FAILURE(pos, 1);
else if (avail < 3 || utf8_lead(str[pos + 2]))
MB_FAILURE(pos, 2);
else if (avail < 4 || utf8_lead(str[pos + 3]))
MB_FAILURE(pos, 3);
else
MB_FAILURE(pos, 4);
}
this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f);
if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */
MB_FAILURE(pos, 4);
}
pos += 4;
} else {
MB_FAILURE(pos, 1);
}
}
break;
case cs_big5:
/* reference http://demo.icu-project.org/icu-bin/convexp?conv=big5 */
{
unsigned char c = str[pos];
if (c >= 0x81 && c <= 0xFE) {
unsigned char next;
if (!CHECK_LEN(pos, 2))
MB_FAILURE(pos, 1);
next = str[pos + 1];
if ((next >= 0x40 && next <= 0x7E) ||
(next >= 0xA1 && next <= 0xFE)) {
this_char = (c << 8) | next;
} else {
MB_FAILURE(pos, 1);
}
pos += 2;
} else {
this_char = c;
pos += 1;
}
}
break;
case cs_big5hkscs:
{
unsigned char c = str[pos];
if (c >= 0x81 && c <= 0xFE) {
unsigned char next;
if (!CHECK_LEN(pos, 2))
MB_FAILURE(pos, 1);
next = str[pos + 1];
if ((next >= 0x40 && next <= 0x7E) ||
(next >= 0xA1 && next <= 0xFE)) {
this_char = (c << 8) | next;
} else if (next != 0x80 && next != 0xFF) {
MB_FAILURE(pos, 1);
} else {
MB_FAILURE(pos, 2);
}
pos += 2;
} else {
this_char = c;
pos += 1;
}
}
break;
case cs_gb2312: /* EUC-CN */
{
unsigned char c = str[pos];
if (c >= 0xA1 && c <= 0xFE) {
unsigned char next;
if (!CHECK_LEN(pos, 2))
MB_FAILURE(pos, 1);
next = str[pos + 1];
if (gb2312_trail(next)) {
this_char = (c << 8) | next;
} else if (gb2312_lead(next)) {
MB_FAILURE(pos, 1);
} else {
MB_FAILURE(pos, 2);
}
pos += 2;
} else if (gb2312_lead(c)) {
this_char = c;
pos += 1;
} else {
MB_FAILURE(pos, 1);
}
}
break;
case cs_sjis:
{
unsigned char c = str[pos];
if ((c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC)) {
unsigned char next;
if (!CHECK_LEN(pos, 2))
MB_FAILURE(pos, 1);
next = str[pos + 1];
if (sjis_trail(next)) {
this_char = (c << 8) | next;
} else if (sjis_lead(next)) {
MB_FAILURE(pos, 1);
} else {
MB_FAILURE(pos, 2);
}
pos += 2;
} else if (c < 0x80 || (c >= 0xA1 && c <= 0xDF)) {
this_char = c;
pos += 1;
} else {
MB_FAILURE(pos, 1);
}
}
break;
case cs_eucjp:
{
unsigned char c = str[pos];
if (c >= 0xA1 && c <= 0xFE) {
unsigned next;
if (!CHECK_LEN(pos, 2))
MB_FAILURE(pos, 1);
next = str[pos + 1];
if (next >= 0xA1 && next <= 0xFE) {
/* this a jis kanji char */
this_char = (c << 8) | next;
} else {
MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2);
}
pos += 2;
} else if (c == 0x8E) {
unsigned next;
if (!CHECK_LEN(pos, 2))
MB_FAILURE(pos, 1);
next = str[pos + 1];
if (next >= 0xA1 && next <= 0xDF) {
/* JIS X 0201 kana */
this_char = (c << 8) | next;
} else {
MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2);
}
pos += 2;
} else if (c == 0x8F) {
size_t avail = str_len - pos;
if (avail < 3 || !(str[pos + 1] >= 0xA1 && str[pos + 1] <= 0xFE) ||
!(str[pos + 2] >= 0xA1 && str[pos + 2] <= 0xFE)) {
if (avail < 2 || (str[pos + 1] != 0xA0 && str[pos + 1] != 0xFF))
MB_FAILURE(pos, 1);
else if (avail < 3 || (str[pos + 2] != 0xA0 && str[pos + 2] != 0xFF))
MB_FAILURE(pos, 2);
else
MB_FAILURE(pos, 3);
} else {
/* JIS X 0212 hojo-kanji */
this_char = (c << 16) | (str[pos + 1] << 8) | str[pos + 2];
}
pos += 3;
} else if (c != 0xA0 && c != 0xFF) {
/* character encoded in 1 code unit */
this_char = c;
pos += 1;
} else {
MB_FAILURE(pos, 1);
}
}
break;
default:
/* single-byte charsets */
this_char = str[pos++];
break;
}
*cursor = pos;
return this_char;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PlatformSensorProviderAndroid::CreateSensorInternal(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
JNIEnv* env = AttachCurrentThread();
switch (type) {
case mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES:
CreateAbsoluteOrientationEulerAnglesSensor(env, std::move(mapping),
callback);
break;
case mojom::SensorType::ABSOLUTE_ORIENTATION_QUATERNION:
CreateAbsoluteOrientationQuaternionSensor(env, std::move(mapping),
callback);
break;
case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES:
CreateRelativeOrientationEulerAnglesSensor(env, std::move(mapping),
callback);
break;
default: {
ScopedJavaLocalRef<jobject> sensor =
Java_PlatformSensorProvider_createSensor(env, j_object_,
static_cast<jint>(type));
if (!sensor.obj()) {
callback.Run(nullptr);
return;
}
auto concrete_sensor = base::MakeRefCounted<PlatformSensorAndroid>(
type, std::move(mapping), this, sensor);
callback.Run(concrete_sensor);
break;
}
}
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732
Target: 1
Example 2:
Code: void Textfield::WriteDragDataForView(View* sender,
const gfx::Point& press_pt,
OSExchangeData* data) {
const base::string16& selected_text(GetSelectedText());
data->SetString(selected_text);
Label label(selected_text, {GetFontList()});
label.SetBackgroundColor(GetBackgroundColor());
label.SetSubpixelRenderingEnabled(false);
gfx::Size size(label.GetPreferredSize());
gfx::NativeView native_view = GetWidget()->GetNativeView();
display::Display display =
display::Screen::GetScreen()->GetDisplayNearestView(native_view);
size.SetToMin(gfx::Size(display.size().width(), height()));
label.SetBoundsRect(gfx::Rect(size));
label.SetEnabledColor(GetTextColor());
SkBitmap bitmap;
float raster_scale = ScaleFactorForDragFromWidget(GetWidget());
SkColor color = SK_ColorTRANSPARENT;
#if defined(USE_X11)
if (!ui::XVisualManager::GetInstance()->ArgbVisualAvailable())
color = GetBackgroundColor();
#endif
label.Paint(PaintInfo::CreateRootPaintInfo(
ui::CanvasPainter(&bitmap, label.size(), raster_scale, color,
GetWidget()->GetCompositor()->is_pixel_canvas())
.context(),
label.size()));
const gfx::Vector2d kOffset(-15, 0);
gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, raster_scale));
data->provider().SetDragImage(image, kOffset);
if (controller_)
controller_->OnWriteDragData(data);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DataReductionProxyIOData::UpdateThrottleConfig() {
if (drp_throttle_config_observers_.empty())
return;
auto config = CreateThrottleConfig();
drp_throttle_config_observers_.ForAllPtrs(
[&config](mojom::DataReductionProxyThrottleConfigObserver* observer) {
observer->OnThrottleConfigChanged(config->Clone());
});
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AXARIAGridCell::isAriaRowHeader() const {
const AtomicString& role = getAttribute(HTMLNames::roleAttr);
return equalIgnoringCase(role, "rowheader");
}
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
Target: 1
Example 2:
Code: void AwContents::HideGeolocationPrompt(const GURL& origin) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
bool removed_current_outstanding_callback = false;
std::list<OriginCallback>::iterator it = pending_geolocation_prompts_.begin();
while (it != pending_geolocation_prompts_.end()) {
if ((*it).first == origin.GetOrigin()) {
if (it == pending_geolocation_prompts_.begin()) {
removed_current_outstanding_callback = true;
}
it = pending_geolocation_prompts_.erase(it);
} else {
++it;
}
}
if (removed_current_outstanding_callback) {
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> j_ref = java_ref_.get(env);
if (j_ref.obj()) {
devtools_instrumentation::ScopedEmbedderCallbackTask embedder_callback(
"onGeolocationPermissionsHidePrompt");
Java_AwContents_onGeolocationPermissionsHidePrompt(env, j_ref.obj());
}
if (!pending_geolocation_prompts_.empty()) {
ShowGeolocationPromptHelper(java_ref_,
pending_geolocation_prompts_.front().first);
}
}
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGL2RenderingContextBase::bindVertexArray(
WebGLVertexArrayObject* vertex_array) {
if (isContextLost())
return;
if (vertex_array &&
(vertex_array->IsDeleted() || !vertex_array->Validate(nullptr, this))) {
SynthesizeGLError(GL_INVALID_OPERATION, "bindVertexArray",
"invalid vertexArray");
return;
}
if (vertex_array && !vertex_array->IsDefaultObject() &&
vertex_array->Object()) {
ContextGL()->BindVertexArrayOES(ObjectOrZero(vertex_array));
vertex_array->SetHasEverBeenBound();
SetBoundVertexArrayObject(vertex_array);
} else {
ContextGL()->BindVertexArrayOES(0);
SetBoundVertexArrayObject(nullptr);
}
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int setup_dev_console(const struct lxc_rootfs *rootfs,
const struct lxc_console *console)
{
char path[MAXPATHLEN];
struct stat s;
int ret;
ret = snprintf(path, sizeof(path), "%s/dev/console", rootfs->mount);
if (ret >= sizeof(path)) {
ERROR("console path too long");
return -1;
}
if (access(path, F_OK)) {
WARN("rootfs specified but no console found at '%s'", path);
return 0;
}
if (console->master < 0) {
INFO("no console");
return 0;
}
if (stat(path, &s)) {
SYSERROR("failed to stat '%s'", path);
return -1;
}
if (chmod(console->name, s.st_mode)) {
SYSERROR("failed to set mode '0%o' to '%s'",
s.st_mode, console->name);
return -1;
}
if (mount(console->name, path, "none", MS_BIND, 0)) {
ERROR("failed to mount '%s' on '%s'", console->name, path);
return -1;
}
INFO("console has been setup");
return 0;
}
Commit Message: CVE-2015-1335: Protect container mounts against symlinks
When a container starts up, lxc sets up the container's inital fstree
by doing a bunch of mounting, guided by the container configuration
file. The container config is owned by the admin or user on the host,
so we do not try to guard against bad entries. However, since the
mount target is in the container, it's possible that the container admin
could divert the mount with symbolic links. This could bypass proper
container startup (i.e. confinement of a root-owned container by the
restrictive apparmor policy, by diverting the required write to
/proc/self/attr/current), or bypass the (path-based) apparmor policy
by diverting, say, /proc to /mnt in the container.
To prevent this,
1. do not allow mounts to paths containing symbolic links
2. do not allow bind mounts from relative paths containing symbolic
links.
Details:
Define safe_mount which ensures that the container has not inserted any
symbolic links into any mount targets for mounts to be done during
container setup.
The host's mount path may contain symbolic links. As it is under the
control of the administrator, that's ok. So safe_mount begins the check
for symbolic links after the rootfs->mount, by opening that directory.
It opens each directory along the path using openat() relative to the
parent directory using O_NOFOLLOW. When the target is reached, it
mounts onto /proc/self/fd/<targetfd>.
Use safe_mount() in mount_entry(), when mounting container proc,
and when needed. In particular, safe_mount() need not be used in
any case where:
1. the mount is done in the container's namespace
2. the mount is for the container's rootfs
3. the mount is relative to a tmpfs or proc/sysfs which we have
just safe_mount()ed ourselves
Since we were using proc/net as a temporary placeholder for /proc/sys/net
during container startup, and proc/net is a symbolic link, use proc/tty
instead.
Update the lxc.container.conf manpage with details about the new
restrictions.
Finally, add a testcase to test some symbolic link possibilities.
Reported-by: Roman Fiedler
Signed-off-by: Serge Hallyn <[email protected]>
Acked-by: Stéphane Graber <[email protected]>
CWE ID: CWE-59
Target: 1
Example 2:
Code: tgs_check_authenticator(krb5_context context,
krb5_kdc_configuration *config,
krb5_auth_context ac,
KDC_REQ_BODY *b,
const char **e_text,
krb5_keyblock *key)
{
krb5_authenticator auth;
size_t len = 0;
unsigned char *buf;
size_t buf_size;
krb5_error_code ret;
krb5_crypto crypto;
krb5_auth_con_getauthenticator(context, ac, &auth);
if(auth->cksum == NULL){
kdc_log(context, config, 0, "No authenticator in request");
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
/*
* according to RFC1510 it doesn't need to be keyed,
* but according to the latest draft it needs to.
*/
if (
#if 0
!krb5_checksum_is_keyed(context, auth->cksum->cksumtype)
||
#endif
!krb5_checksum_is_collision_proof(context, auth->cksum->cksumtype)) {
kdc_log(context, config, 0, "Bad checksum type in authenticator: %d",
auth->cksum->cksumtype);
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
/* XXX should not re-encode this */
ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, b, &len, ret);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "Failed to encode KDC-REQ-BODY: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
if(buf_size != len) {
free(buf);
kdc_log(context, config, 0, "Internal error in ASN.1 encoder");
*e_text = "KDC internal error";
ret = KRB5KRB_ERR_GENERIC;
goto out;
}
ret = krb5_crypto_init(context, key, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free(buf);
kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = krb5_verify_checksum(context,
crypto,
KRB5_KU_TGS_REQ_AUTH_CKSUM,
buf,
len,
auth->cksum);
free(buf);
krb5_crypto_destroy(context, crypto);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Failed to verify authenticator checksum: %s", msg);
krb5_free_error_message(context, msg);
}
out:
free_Authenticator(auth);
free(auth);
return ret;
}
Commit Message: Fix transit path validation CVE-2017-6594
Commit f469fc6 (2010-10-02) inadvertently caused the previous hop realm
to not be added to the transit path of issued tickets. This may, in
some cases, enable bypass of capath policy in Heimdal versions 1.5
through 7.2.
Note, this may break sites that rely on the bug. With the bug some
incomplete [capaths] worked, that should not have. These may now break
authentication in some cross-realm configurations.
CWE ID: CWE-295
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool SubsetterImpl::LoadFont(const char* font_name,
const unsigned char* original_font,
size_t font_size) {
ByteArrayPtr raw_font =
new MemoryByteArray((byte_t*)original_font, font_size);
if (factory_ == NULL) {
factory_.Attach(FontFactory::GetInstance());
}
FontArray font_array;
factory_->LoadFonts(raw_font, &font_array);
font_ = FindFont(font_name, font_array);
if (font_ == NULL) {
return false;
}
return true;
}
Commit Message: Fix compile warning.
BUG=none
TEST=none
Review URL: http://codereview.chromium.org/7572039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95563 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
: content::RenderViewObserver(render_view),
content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
print_web_view_(NULL),
is_preview_enabled_(IsPrintPreviewEnabled()),
is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()),
is_print_ready_metafile_sent_(false),
ignore_css_margins_(false),
user_cancelled_scripted_print_count_(0),
is_scripted_printing_blocked_(false),
notify_browser_of_print_failure_(true),
print_for_preview_(false) {
}
Commit Message: Guard against the same PrintWebViewHelper being re-entered.
BUG=159165
Review URL: https://chromiumcodereview.appspot.com/11367076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int coolkey_final_iterator(list_t *list)
{
list_iterator_stop(list);
return SC_SUCCESS;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DiscardAndExplicitlyReloadTest(DiscardReason reason) {
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true));
background_lifecycle_unit->Discard(reason);
testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false));
tab_strip_model_->GetWebContentsAt(0)->GetController().Reload(
content::ReloadType::NORMAL, false);
testing::Mock::VerifyAndClear(&tab_observer_);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AudioRendererAlgorithm::OutputFasterPlayback(uint8* dest) {
DCHECK_LT(index_into_window_, window_size_);
DCHECK_GT(playback_rate_, 1.0);
if (audio_buffer_.forward_bytes() < bytes_per_frame_)
return false;
int input_step = window_size_;
int output_step = ceil(window_size_ / playback_rate_);
AlignToFrameBoundary(&output_step);
DCHECK_GT(input_step, output_step);
int bytes_to_crossfade = bytes_in_crossfade_;
if (muted_ || bytes_to_crossfade > output_step)
bytes_to_crossfade = 0;
int outtro_crossfade_begin = output_step - bytes_to_crossfade;
int outtro_crossfade_end = output_step;
int intro_crossfade_begin = input_step - bytes_to_crossfade;
if (index_into_window_ < outtro_crossfade_begin) {
CopyWithAdvance(dest);
index_into_window_ += bytes_per_frame_;
return true;
}
while (index_into_window_ < outtro_crossfade_end) {
if (audio_buffer_.forward_bytes() < bytes_per_frame_)
return false;
DCHECK_GT(bytes_to_crossfade, 0);
uint8* place_to_copy = crossfade_buffer_.get() +
(index_into_window_ - outtro_crossfade_begin);
CopyWithAdvance(place_to_copy);
index_into_window_ += bytes_per_frame_;
}
while (index_into_window_ < intro_crossfade_begin) {
if (audio_buffer_.forward_bytes() < bytes_per_frame_)
return false;
DropFrame();
index_into_window_ += bytes_per_frame_;
}
if (audio_buffer_.forward_bytes() < bytes_per_frame_)
return false;
if (bytes_to_crossfade == 0) {
DCHECK_EQ(index_into_window_, window_size_);
return false;
}
DCHECK_LT(index_into_window_, window_size_);
int offset_into_buffer = index_into_window_ - intro_crossfade_begin;
memcpy(dest, crossfade_buffer_.get() + offset_into_buffer,
bytes_per_frame_);
scoped_array<uint8> intro_frame_ptr(new uint8[bytes_per_frame_]);
audio_buffer_.Read(intro_frame_ptr.get(), bytes_per_frame_);
OutputCrossfadedFrame(dest, intro_frame_ptr.get());
index_into_window_ += bytes_per_frame_;
return true;
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: void SoundTriggerHwService::sendServiceStateEvent_l(sound_trigger_service_state_t state,
Module *module)
{
sp<IMemory> eventMemory = prepareServiceStateEvent_l(state);
if (eventMemory == 0) {
return;
}
sp<Module> strongModule;
for (size_t i = 0; i < mModules.size(); i++) {
if (mModules.valueAt(i).get() == module) {
strongModule = mModules.valueAt(i);
break;
}
}
if (strongModule == 0) {
return;
}
sendCallbackEvent_l(new CallbackEvent(CallbackEvent::TYPE_SERVICE_STATE,
eventMemory, strongModule));
}
Commit Message: soundtrigger: add size check on sound model and recogntion data
Bug: 30148546
Change-Id: I082f535a853c96571887eeea37c6d41ecee7d8c0
(cherry picked from commit bb00d8f139ff51336ab3c810d35685003949bcf8)
(cherry picked from commit ef0c91518446e65533ca8bab6726a845f27c73fd)
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: unsigned int inet_addr_type_table(struct net *net, __be32 addr, u32 tb_id)
{
return __inet_dev_addr_type(net, NULL, addr, tb_id);
}
Commit Message: ipv4: Don't do expensive useless work during inetdev destroy.
When an inetdev is destroyed, every address assigned to the interface
is removed. And in this scenerio we do two pointless things which can
be very expensive if the number of assigned interfaces is large:
1) Address promotion. We are deleting all addresses, so there is no
point in doing this.
2) A full nf conntrack table purge for every address. We only need to
do this once, as is already caught by the existing
masq_dev_notifier so masq_inet_event() can skip this.
Reported-by: Solar Designer <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
Tested-by: Cyrill Gorcunov <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PermissionsData::CanRunOnPage(const Extension* extension,
const GURL& document_url,
const GURL& top_frame_url,
int tab_id,
int process_id,
const URLPatternSet& permitted_url_patterns,
std::string* error) const {
if (g_policy_delegate &&
!g_policy_delegate->CanExecuteScriptOnPage(
extension, document_url, top_frame_url, tab_id, process_id, error)) {
return false;
}
bool can_execute_everywhere = CanExecuteScriptEverywhere(extension);
if (!can_execute_everywhere &&
!ExtensionsClient::Get()->IsScriptableURL(document_url, error)) {
return false;
}
if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kExtensionsOnChromeURLs)) {
if (document_url.SchemeIs(content::kChromeUIScheme) &&
!can_execute_everywhere) {
if (error)
*error = manifest_errors::kCannotAccessChromeUrl;
return false;
}
}
if (top_frame_url.SchemeIs(kExtensionScheme) &&
top_frame_url.GetOrigin() !=
Extension::GetBaseURLFromExtensionId(extension->id()).GetOrigin() &&
!can_execute_everywhere) {
if (error)
*error = manifest_errors::kCannotAccessExtensionUrl;
return false;
}
if (HasTabSpecificPermissionToExecuteScript(tab_id, top_frame_url))
return true;
bool can_access = permitted_url_patterns.MatchesURL(document_url);
if (!can_access && error) {
*error = ErrorUtils::FormatErrorMessage(manifest_errors::kCannotAccessPage,
document_url.spec());
}
return can_access;
}
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 1
Example 2:
Code: void IRCView::dragEnterEvent(QDragEnterEvent* e)
{
if (e->mimeData()->hasUrls())
e->acceptProposedAction();
else
e->ignore();
}
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitSlice(
const H264PPS* pps,
const H264SliceHeader* slice_hdr,
const H264Picture::Vector& ref_pic_list0,
const H264Picture::Vector& ref_pic_list1,
const scoped_refptr<H264Picture>& pic,
const uint8_t* data,
size_t size) {
VASliceParameterBufferH264 slice_param;
memset(&slice_param, 0, sizeof(slice_param));
slice_param.slice_data_size = slice_hdr->nalu_size;
slice_param.slice_data_offset = 0;
slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL;
slice_param.slice_data_bit_offset = slice_hdr->header_bit_size;
#define SHDRToSP(a) slice_param.a = slice_hdr->a
SHDRToSP(first_mb_in_slice);
slice_param.slice_type = slice_hdr->slice_type % 5;
SHDRToSP(direct_spatial_mv_pred_flag);
SHDRToSP(num_ref_idx_l0_active_minus1);
SHDRToSP(num_ref_idx_l1_active_minus1);
SHDRToSP(cabac_init_idc);
SHDRToSP(slice_qp_delta);
SHDRToSP(disable_deblocking_filter_idc);
SHDRToSP(slice_alpha_c0_offset_div2);
SHDRToSP(slice_beta_offset_div2);
if (((slice_hdr->IsPSlice() || slice_hdr->IsSPSlice()) &&
pps->weighted_pred_flag) ||
(slice_hdr->IsBSlice() && pps->weighted_bipred_idc == 1)) {
SHDRToSP(luma_log2_weight_denom);
SHDRToSP(chroma_log2_weight_denom);
SHDRToSP(luma_weight_l0_flag);
SHDRToSP(luma_weight_l1_flag);
SHDRToSP(chroma_weight_l0_flag);
SHDRToSP(chroma_weight_l1_flag);
for (int i = 0; i <= slice_param.num_ref_idx_l0_active_minus1; ++i) {
slice_param.luma_weight_l0[i] =
slice_hdr->pred_weight_table_l0.luma_weight[i];
slice_param.luma_offset_l0[i] =
slice_hdr->pred_weight_table_l0.luma_offset[i];
for (int j = 0; j < 2; ++j) {
slice_param.chroma_weight_l0[i][j] =
slice_hdr->pred_weight_table_l0.chroma_weight[i][j];
slice_param.chroma_offset_l0[i][j] =
slice_hdr->pred_weight_table_l0.chroma_offset[i][j];
}
}
if (slice_hdr->IsBSlice()) {
for (int i = 0; i <= slice_param.num_ref_idx_l1_active_minus1; ++i) {
slice_param.luma_weight_l1[i] =
slice_hdr->pred_weight_table_l1.luma_weight[i];
slice_param.luma_offset_l1[i] =
slice_hdr->pred_weight_table_l1.luma_offset[i];
for (int j = 0; j < 2; ++j) {
slice_param.chroma_weight_l1[i][j] =
slice_hdr->pred_weight_table_l1.chroma_weight[i][j];
slice_param.chroma_offset_l1[i][j] =
slice_hdr->pred_weight_table_l1.chroma_offset[i][j];
}
}
}
}
static_assert(
arraysize(slice_param.RefPicList0) == arraysize(slice_param.RefPicList1),
"Invalid RefPicList sizes");
for (size_t i = 0; i < arraysize(slice_param.RefPicList0); ++i) {
InitVAPicture(&slice_param.RefPicList0[i]);
InitVAPicture(&slice_param.RefPicList1[i]);
}
for (size_t i = 0;
i < ref_pic_list0.size() && i < arraysize(slice_param.RefPicList0);
++i) {
if (ref_pic_list0[i])
FillVAPicture(&slice_param.RefPicList0[i], ref_pic_list0[i]);
}
for (size_t i = 0;
i < ref_pic_list1.size() && i < arraysize(slice_param.RefPicList1);
++i) {
if (ref_pic_list1[i])
FillVAPicture(&slice_param.RefPicList1[i], ref_pic_list1[i]);
}
if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType,
sizeof(slice_param), &slice_param))
return false;
void* non_const_ptr = const_cast<uint8_t*>(data);
return vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, size,
non_const_ptr);
}
Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup()
This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and
posts the destruction of those objects to the appropriate thread on
Cleanup().
Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@
comment in
https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f
TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build
unstripped, let video play for a few seconds then navigate back; no
crashes. Unittests as before:
video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12
video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11
video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1
Bug: 789160
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: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2
Reviewed-on: https://chromium-review.googlesource.com/794091
Reviewed-by: Pawel Osciak <[email protected]>
Commit-Queue: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#523372}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ModuleExport size_t RegisterPNGImage(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
static const char
*PNGNote=
{
"See http://www.libpng.org/ for details about the PNG format."
},
*JNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the JNG\n"
"format."
},
*MNGNote=
{
"See http://www.libpng.org/pub/mng/ for details about the MNG\n"
"format."
};
*version='\0';
#if defined(PNG_LIBPNG_VER_STRING)
(void) ConcatenateMagickString(version,"libpng ",MaxTextExtent);
(void) ConcatenateMagickString(version,PNG_LIBPNG_VER_STRING,MaxTextExtent);
if (LocaleCompare(PNG_LIBPNG_VER_STRING,png_get_header_ver(NULL)) != 0)
{
(void) ConcatenateMagickString(version,",",MaxTextExtent);
(void) ConcatenateMagickString(version,png_get_libpng_ver(NULL),
MaxTextExtent);
}
#endif
entry=SetMagickInfo("MNG");
entry->seekable_stream=MagickTrue; /* To do: eliminate this. */
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadMNGImage;
entry->encoder=(EncodeImageHandler *) WriteMNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsMNG;
entry->description=ConstantString("Multiple-image Network Graphics");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("video/x-mng");
entry->module=ConstantString("PNG");
entry->note=ConstantString(MNGNote);
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Portable Network Graphics");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
if (*version != '\0')
entry->version=ConstantString(version);
entry->note=ConstantString(PNGNote);
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG8");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"8-bit indexed with optional binary transparency");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG24");
*version='\0';
#if defined(ZLIB_VERSION)
(void) ConcatenateMagickString(version,"zlib ",MaxTextExtent);
(void) ConcatenateMagickString(version,ZLIB_VERSION,MaxTextExtent);
if (LocaleCompare(ZLIB_VERSION,zlib_version) != 0)
{
(void) ConcatenateMagickString(version,",",MaxTextExtent);
(void) ConcatenateMagickString(version,zlib_version,MaxTextExtent);
}
#endif
if (*version != '\0')
entry->version=ConstantString(version);
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or binary transparent 24-bit RGB");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG32");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or transparent 32-bit RGBA");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG48");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or binary transparent 48-bit RGB");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG64");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->adjoin=MagickFalse;
entry->description=ConstantString("opaque or transparent 64-bit RGBA");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PNG00");
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadPNGImage;
entry->encoder=(EncodeImageHandler *) WritePNGImage;
#endif
entry->magick=(IsImageFormatHandler *) IsPNG;
entry->adjoin=MagickFalse;
entry->description=ConstantString(
"PNG inheriting bit-depth, color-type from original if possible");
entry->mime_type=ConstantString("image/png");
entry->module=ConstantString("PNG");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JNG");
#if defined(JNG_SUPPORTED)
#if defined(MAGICKCORE_PNG_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJNGImage;
entry->encoder=(EncodeImageHandler *) WriteJNGImage;
#endif
#endif
entry->magick=(IsImageFormatHandler *) IsJNG;
entry->adjoin=MagickFalse;
entry->description=ConstantString("JPEG Network Graphics");
entry->mime_type=ConstantString("image/x-jng");
entry->module=ConstantString("PNG");
entry->note=ConstantString(JNGNote);
(void) RegisterMagickInfo(entry);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
ping_semaphore=AllocateSemaphoreInfo();
#endif
return(MagickImageCoderSignature);
}
Commit Message: ...
CWE ID: CWE-754
Target: 1
Example 2:
Code: void ArcVoiceInteractionFrameworkService::StartSessionFromUserInteraction(
const gfx::Rect& rect) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!InitiateUserInteraction(false /* is_toggle */))
return;
if (rect.IsEmpty()) {
mojom::VoiceInteractionFrameworkInstance* framework_instance =
ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->voice_interaction_framework(),
StartVoiceInteractionSession);
DCHECK(framework_instance);
framework_instance->StartVoiceInteractionSession(IsHomescreenActive());
} else {
mojom::VoiceInteractionFrameworkInstance* framework_instance =
ARC_GET_INSTANCE_FOR_METHOD(
arc_bridge_service_->voice_interaction_framework(),
StartVoiceInteractionSessionForRegion);
DCHECK(framework_instance);
framework_instance->StartVoiceInteractionSessionForRegion(rect);
}
VLOG(1) << "Sent voice interaction request.";
}
Commit Message: arc: add test for blocking incognito windows in screenshot
BUG=778852
TEST=ArcVoiceInteractionFrameworkServiceUnittest.
CapturingScreenshotBlocksIncognitoWindows
Change-Id: I0bfa5a486759783d7c8926a309c6b5da9b02dcc6
Reviewed-on: https://chromium-review.googlesource.com/914983
Commit-Queue: Muyuan Li <[email protected]>
Reviewed-by: Luis Hector Chavez <[email protected]>
Cr-Commit-Position: refs/heads/master@{#536438}
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SpdyProxyClientSocket::LogBlockedTunnelResponse() const {
ProxyClientSocket::LogBlockedTunnelResponse(
response_.headers->response_code(),
request_.url,
/* is_https_proxy = */ true);
}
Commit Message: Sanitize headers in Proxy Authentication Required responses
BUG=431504
Review URL: https://codereview.chromium.org/769043003
Cr-Commit-Position: refs/heads/master@{#310014}
CWE ID: CWE-19
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AppListControllerDelegateImpl::DoCreateShortcutsFlow(
Profile* profile,
const std::string& extension_id) {
DCHECK(CanDoCreateShortcutsFlow());
ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
DCHECK(service);
const extensions::Extension* extension = service->GetInstalledExtension(
extension_id);
DCHECK(extension);
gfx::NativeWindow parent_window = GetAppListWindow();
if (!parent_window)
return;
OnShowChildDialog();
chrome::ShowCreateChromeAppShortcutsDialog(
parent_window, profile, extension,
base::Bind(&AppListControllerDelegateImpl::OnCloseCreateShortcutsPrompt,
base::Unretained(this)));
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID:
Target: 1
Example 2:
Code: void SoftOpus::onQueueFilled(OMX_U32 portIndex) {
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (mOutputPortSettingsChange != NONE) {
return;
}
if (portIndex == 0 && mInputBufferCount < 3) {
BufferInfo *info = *inQueue.begin();
OMX_BUFFERHEADERTYPE *header = info->mHeader;
const uint8_t *data = header->pBuffer + header->nOffset;
size_t size = header->nFilledLen;
if (mInputBufferCount == 0) {
CHECK(mHeader == NULL);
mHeader = new OpusHeader();
memset(mHeader, 0, sizeof(*mHeader));
if (!ParseOpusHeader(data, size, mHeader)) {
ALOGV("Parsing Opus Header failed.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
uint8_t channel_mapping[kMaxChannels] = {0};
if (mHeader->channels <= kMaxChannelsWithDefaultLayout) {
memcpy(&channel_mapping,
kDefaultOpusChannelLayout,
kMaxChannelsWithDefaultLayout);
} else {
memcpy(&channel_mapping,
mHeader->stream_map,
mHeader->channels);
}
int status = OPUS_INVALID_STATE;
mDecoder = opus_multistream_decoder_create(kRate,
mHeader->channels,
mHeader->num_streams,
mHeader->num_coupled,
channel_mapping,
&status);
if (!mDecoder || status != OPUS_OK) {
ALOGV("opus_multistream_decoder_create failed status=%s",
opus_strerror(status));
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
status =
opus_multistream_decoder_ctl(mDecoder,
OPUS_SET_GAIN(mHeader->gain_db));
if (status != OPUS_OK) {
ALOGV("Failed to set OPUS header gain; status=%s",
opus_strerror(status));
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
} else if (mInputBufferCount == 1) {
mCodecDelay = ns_to_samples(
*(reinterpret_cast<int64_t*>(header->pBuffer +
header->nOffset)),
kRate);
mSamplesToDiscard = mCodecDelay;
} else {
mSeekPreRoll = ns_to_samples(
*(reinterpret_cast<int64_t*>(header->pBuffer +
header->nOffset)),
kRate);
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
}
inQueue.erase(inQueue.begin());
info->mOwnedByUs = false;
notifyEmptyBufferDone(header);
++mInputBufferCount;
return;
}
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
return;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nOffset == 0) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nTimeStamp == 0) {
mSamplesToDiscard = mCodecDelay;
}
const uint8_t *data = inHeader->pBuffer + inHeader->nOffset;
const uint32_t size = inHeader->nFilledLen;
int numFrames = opus_multistream_decode(mDecoder,
data,
size,
(int16_t *)outHeader->pBuffer,
kMaxOpusOutputPacketSizeSamples,
0);
if (numFrames < 0) {
ALOGE("opus_multistream_decode returned %d", numFrames);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
outHeader->nOffset = 0;
if (mSamplesToDiscard > 0) {
if (mSamplesToDiscard > numFrames) {
mSamplesToDiscard -= numFrames;
numFrames = 0;
} else {
numFrames -= mSamplesToDiscard;
outHeader->nOffset = mSamplesToDiscard * sizeof(int16_t) *
mHeader->channels;
mSamplesToDiscard = 0;
}
}
outHeader->nFilledLen = numFrames * sizeof(int16_t) * mHeader->channels;
outHeader->nFlags = 0;
outHeader->nTimeStamp = mAnchorTimeUs +
(mNumFramesOutput * 1000000ll) /
kRate;
mNumFramesOutput += numFrames;
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mInputBufferCount;
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::unique_ptr<SymmetricKey> CopyDefaultPaddingKey() {
return SymmetricKey::Import(kPaddingKeyAlgorithm, (*GetPaddingKey())->key());
}
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 <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> 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 <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void IBusBusGlobalEngineChangedCallback(
IBusBus* bus, const gchar* engine_name, gpointer user_data) {
DCHECK(engine_name);
DLOG(INFO) << "Global engine is changed to " << engine_name;
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->UpdateUI(engine_name);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int yam_close(struct net_device *dev)
{
struct sk_buff *skb;
struct yam_port *yp = netdev_priv(dev);
if (!dev)
return -EINVAL;
/*
* disable interrupts
*/
outb(0, IER(dev->base_addr));
outb(1, MCR(dev->base_addr));
/* Remove IRQ handler if last */
free_irq(dev->irq,dev);
release_region(dev->base_addr, YAM_EXTENT);
netif_stop_queue(dev);
while ((skb = skb_dequeue(&yp->send_queue)))
dev_kfree_skb(skb);
printk(KERN_INFO "%s: close yam at iobase 0x%lx irq %u\n",
yam_drvname, dev->base_addr, dev->irq);
return 0;
}
Commit Message: hamradio/yam: fix info leak in ioctl
The yam_ioctl() code fails to initialise the cmd field
of the struct yamdrv_ioctl_cfg. Add an explicit memset(0)
before filling the structure to avoid the 4-byte info leak.
Signed-off-by: Salva Peiró <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ExtensionPrefs::GetGrantedPermissions(
const std::string& extension_id,
bool* full_access,
std::set<std::string>* api_permissions,
URLPatternSet* host_extent) {
CHECK(Extension::IdIsValid(extension_id));
const DictionaryValue* ext = GetExtensionPref(extension_id);
if (!ext || !ext->GetBoolean(kPrefGrantedPermissionsAll, full_access))
return false;
ReadExtensionPrefStringSet(
extension_id, kPrefGrantedPermissionsAPI, api_permissions);
std::set<std::string> host_permissions;
ReadExtensionPrefStringSet(
extension_id, kPrefGrantedPermissionsHost, &host_permissions);
bool allow_file_access = AllowFileAccess(extension_id);
for (std::set<std::string>::iterator i = host_permissions.begin();
i != host_permissions.end(); ++i) {
URLPattern pattern(
Extension::kValidHostPermissionSchemes |
UserScript::kValidUserScriptSchemes);
if (URLPattern::PARSE_SUCCESS != pattern.Parse(
*i, URLPattern::PARSE_LENIENT)) {
NOTREACHED(); // Corrupt prefs? Hand editing?
} else {
if (!allow_file_access && pattern.MatchesScheme(chrome::kFileScheme)) {
pattern.set_valid_schemes(
pattern.valid_schemes() & ~URLPattern::SCHEME_FILE);
}
host_extent->AddPattern(pattern);
}
}
return true;
}
Commit Message: Coverity: Add a missing NULL check.
BUG=none
TEST=none
CID=16813
Review URL: http://codereview.chromium.org/7216034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89991 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: image_transform_png_set_expand_16_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* expand_16 does something unless the bit depth is already 16. */
return bit_depth < 16;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: SYSCALL_DEFINE2(osf_utimes, const char __user *, filename,
struct timeval32 __user *, tvs)
{
struct timespec tv[2];
if (tvs) {
struct timeval ktvs[2];
if (get_tv32(&ktvs[0], &tvs[0]) ||
get_tv32(&ktvs[1], &tvs[1]))
return -EFAULT;
if (ktvs[0].tv_usec < 0 || ktvs[0].tv_usec >= 1000000 ||
ktvs[1].tv_usec < 0 || ktvs[1].tv_usec >= 1000000)
return -EINVAL;
tv[0].tv_sec = ktvs[0].tv_sec;
tv[0].tv_nsec = 1000 * ktvs[0].tv_usec;
tv[1].tv_sec = ktvs[1].tv_sec;
tv[1].tv_nsec = 1000 * ktvs[1].tv_usec;
}
return do_utimes(AT_FDCWD, filename, tvs ? tv : NULL, 0);
}
Commit Message: alpha: fix several security issues
Fix several security issues in Alpha-specific syscalls. Untested, but
mostly trivial.
1. Signedness issue in osf_getdomainname allows copying out-of-bounds
kernel memory to userland.
2. Signedness issue in osf_sysinfo allows copying large amounts of
kernel memory to userland.
3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy
size, allowing copying large amounts of kernel memory to userland.
4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows
privilege escalation via writing return value of sys_wait4 to kernel
memory.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: Richard Henderson <[email protected]>
Cc: Ivan Kokshaysky <[email protected]>
Cc: Matt Turner <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void activityLoggingGetterForIsolatedWorldsPerWorldBindingsLongAttributeAttributeSetterForMainWorld(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
ExceptionState exceptionState(ExceptionState::SetterContext, "activityLoggingGetterForIsolatedWorldsPerWorldBindingsLongAttribute", "TestObjectPython", info.Holder(), info.GetIsolate());
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
V8TRYCATCH_EXCEPTION_VOID(int, cppValue, toInt32(jsValue, exceptionState), exceptionState);
imp->setActivityLoggingGetterForIsolatedWorldsPerWorldBindingsLongAttribute(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AppControllerImpl::GetArcAndroidId(
mojom::AppController::GetArcAndroidIdCallback callback) {
arc::GetAndroidId(base::BindOnce(
[](mojom::AppController::GetArcAndroidIdCallback callback, bool success,
int64_t android_id) {
std::move(callback).Run(success, base::NumberToString(android_id));
},
std::move(callback)));
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void SignalDone() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!is_removing_)
return;
is_removing_ = false;
event_->Signal();
}
Commit Message: Do not attempt to open a channel to a plugin in Plugin Data Remover if there are no plugins available.
BUG=485886
Review URL: https://codereview.chromium.org/1144353003
Cr-Commit-Position: refs/heads/master@{#331168}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long Segment::ParseNext(
const Cluster* pCurr,
const Cluster*& pResult,
long long& pos,
long& len)
{
assert(pCurr);
assert(!pCurr->EOS());
assert(m_clusters);
pResult = 0;
if (pCurr->m_index >= 0) //loaded (not merely preloaded)
{
assert(m_clusters[pCurr->m_index] == pCurr);
const long next_idx = pCurr->m_index + 1;
if (next_idx < m_clusterCount)
{
pResult = m_clusters[next_idx];
return 0; //success
}
const long result = LoadCluster(pos, len);
if (result < 0) //error or underflow
return result;
if (result > 0) //no more clusters
{
return 1;
}
pResult = GetLast();
return 0; //success
}
assert(m_pos > 0);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
pos = pCurr->m_element_start;
if (pCurr->m_element_size >= 0)
pos += pCurr->m_element_size;
else
{
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(m_pReader, pos, len);
if (id != 0x0F43B675) //weird: not Cluster ID
return -1;
pos += len; //consume ID
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size) //TODO: should never happen
return E_FILE_FORMAT_INVALID; //TODO: resolve this
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload (that is, the current cluster)
assert((segment_stop < 0) || (pos <= segment_stop));
}
for (;;)
{
const long status = DoParseNext(pResult, pos, len);
if (status <= 1)
return status;
}
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline ulong encode_twos_comp(long n, int prec)
{
ulong result;
assert(prec >= 2);
jas_eprintf("warning: support for signed data is untested\n");
if (n < 0) {
result = -n;
result = (result ^ 0xffffffffUL) + 1;
result &= (1 << prec) - 1;
} else {
result = n;
}
return result;
}
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
Target: 1
Example 2:
Code: f2flac16_clip_array (const float *src, int32_t *dest, int count, int normalize)
{ float normfact, scaled_value ;
normfact = normalize ? (8.0 * 0x1000) : 1.0 ;
while (--count >= 0)
{ scaled_value = src [count] * normfact ;
if (CPU_CLIPS_POSITIVE == 0 && scaled_value >= (1.0 * 0x7FFF))
{ dest [count] = 0x7FFF ;
continue ;
} ;
if (CPU_CLIPS_NEGATIVE == 0 && scaled_value <= (-8.0 * 0x1000))
{ dest [count] = 0x8000 ;
continue ;
} ;
dest [count] = lrintf (scaled_value) ;
} ;
} /* f2flac16_clip_array */
Commit Message: src/flac.c: Improve error handling
Especially when dealing with corrupt or malicious files.
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: 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: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static long ioctl_file_dedupe_range(struct file *file, void __user *arg)
{
struct file_dedupe_range __user *argp = arg;
struct file_dedupe_range *same = NULL;
int ret;
unsigned long size;
u16 count;
if (get_user(count, &argp->dest_count)) {
ret = -EFAULT;
goto out;
}
size = offsetof(struct file_dedupe_range __user, info[count]);
same = memdup_user(argp, size);
if (IS_ERR(same)) {
ret = PTR_ERR(same);
same = NULL;
goto out;
}
ret = vfs_dedupe_file_range(file, same);
if (ret)
goto out;
ret = copy_to_user(argp, same, size);
if (ret)
ret = -EFAULT;
out:
kfree(same);
return ret;
}
Commit Message: vfs: ioctl: prevent double-fetch in dedupe ioctl
This prevents a double-fetch from user space that can lead to to an
undersized allocation and heap overflow.
Fixes: 54dbc1517237 ("vfs: hoist the btrfs deduplication ioctl to the vfs")
Signed-off-by: Scott Bauer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ssl_security_cert_sig(SSL *s, SSL_CTX *ctx, X509 *x, int op)
{
/* Lookup signature algorithm digest */
int secbits = -1, md_nid = NID_undef, sig_nid;
sig_nid = X509_get_signature_nid(x);
if (sig_nid && OBJ_find_sigid_algs(sig_nid, &md_nid, NULL))
{
const EVP_MD *md;
if (md_nid && (md = EVP_get_digestbynid(md_nid)))
secbits = EVP_MD_size(md) * 4;
}
if (s)
return ssl_security(s, op, secbits, md_nid, x);
else
return ssl_ctx_security(ctx, op, secbits, md_nid, x);
}
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void tcp_cwnd_reduction(struct sock *sk, const int prior_unsacked,
int fast_rexmit, int flag)
{
struct tcp_sock *tp = tcp_sk(sk);
int sndcnt = 0;
int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
int newly_acked_sacked = prior_unsacked -
(tp->packets_out - tp->sacked_out);
tp->prr_delivered += newly_acked_sacked;
if (delta < 0) {
u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
tp->prior_cwnd - 1;
sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
} else if ((flag & FLAG_RETRANS_DATA_ACKED) &&
!(flag & FLAG_LOST_RETRANS)) {
sndcnt = min_t(int, delta,
max_t(int, tp->prr_delivered - tp->prr_out,
newly_acked_sacked) + 1);
} else {
sndcnt = min(delta, newly_acked_sacked);
}
sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0));
tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
}
Commit Message: tcp: fix zero cwnd in tcp_cwnd_reduction
Patch 3759824da87b ("tcp: PRR uses CRB mode by default and SS mode
conditionally") introduced a bug that cwnd may become 0 when both
inflight and sndcnt are 0 (cwnd = inflight + sndcnt). This may lead
to a div-by-zero if the connection starts another cwnd reduction
phase by setting tp->prior_cwnd to the current cwnd (0) in
tcp_init_cwnd_reduction().
To prevent this we skip PRR operation when nothing is acked or
sacked. Then cwnd must be positive in all cases as long as ssthresh
is positive:
1) The proportional reduction mode
inflight > ssthresh > 0
2) The reduction bound mode
a) inflight == ssthresh > 0
b) inflight < ssthresh
sndcnt > 0 since newly_acked_sacked > 0 and inflight < ssthresh
Therefore in all cases inflight and sndcnt can not both be 0.
We check invalid tp->prior_cwnd to avoid potential div0 bugs.
In reality this bug is triggered only with a sequence of less common
events. For example, the connection is terminating an ECN-triggered
cwnd reduction with an inflight 0, then it receives reordered/old
ACKs or DSACKs from prior transmission (which acks nothing). Or the
connection is in fast recovery stage that marks everything lost,
but fails to retransmit due to local issues, then receives data
packets from other end which acks nothing.
Fixes: 3759824da87b ("tcp: PRR uses CRB mode by default and SS mode conditionally")
Reported-by: Oleksandr Natalenko <[email protected]>
Signed-off-by: Yuchung Cheng <[email protected]>
Signed-off-by: Neal Cardwell <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: foreach_nfs_shareopt(const char *shareopts,
nfs_shareopt_callback_t callback, void *cookie)
{
char *shareopts_dup, *opt, *cur, *value;
int was_nul, rc;
if (shareopts == NULL)
return (SA_OK);
shareopts_dup = strdup(shareopts);
if (shareopts_dup == NULL)
return (SA_NO_MEMORY);
opt = shareopts_dup;
was_nul = 0;
while (1) {
cur = opt;
while (*cur != ',' && *cur != '\0')
cur++;
if (*cur == '\0')
was_nul = 1;
*cur = '\0';
if (cur > opt) {
value = strchr(opt, '=');
if (value != NULL) {
*value = '\0';
value++;
}
rc = callback(opt, value, cookie);
if (rc != SA_OK) {
free(shareopts_dup);
return (rc);
}
}
opt = cur + 1;
if (was_nul)
break;
}
free(shareopts_dup);
return (0);
}
Commit Message: Move nfs.c:foreach_nfs_shareopt() to libshare.c:foreach_shareopt()
so that it can be (re)used in other parts of libshare.
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
{
num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
return num ? num : -EDOM;
}
Commit Message: usb: gadget: f_fs: Fix use-after-free
When using asynchronous read or write operations on the USB endpoints the
issuer of the IO request is notified by calling the ki_complete() callback
of the submitted kiocb when the URB has been completed.
Calling this ki_complete() callback will free kiocb. Make sure that the
structure is no longer accessed beyond that point, otherwise undefined
behaviour might occur.
Fixes: 2e4c7553cd6f ("usb: gadget: f_fs: add aio support")
Cc: <[email protected]> # v3.15+
Signed-off-by: Lars-Peter Clausen <[email protected]>
Signed-off-by: Felipe Balbi <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Document::UpdateStyleAndLayoutTree() {
DCHECK(IsMainThread());
ScriptForbiddenScope forbid_script;
PluginScriptForbiddenScope plugin_forbid_script;
if (!View() || !IsActive())
return;
if (View()->ShouldThrottleRendering())
return;
if (!NeedsLayoutTreeUpdate()) {
if (Lifecycle().GetState() < DocumentLifecycle::kStyleClean) {
Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
Lifecycle().AdvanceTo(DocumentLifecycle::kStyleClean);
}
return;
}
if (InStyleRecalc())
return;
CHECK(Lifecycle().StateAllowsTreeMutations());
TRACE_EVENT_BEGIN1("blink,devtools.timeline", "UpdateLayoutTree", "beginData",
InspectorRecalculateStylesEvent::Data(GetFrame()));
unsigned start_element_count = GetStyleEngine().StyleForElementCount();
probe::RecalculateStyle recalculate_style_scope(this);
DocumentAnimations::UpdateAnimationTimingIfNeeded(*this);
EvaluateMediaQueryListIfNeeded();
UpdateUseShadowTreesIfNeeded();
UpdateDistribution();
UpdateActiveStyle();
UpdateStyleInvalidationIfNeeded();
UpdateStyle();
NotifyLayoutTreeOfSubtreeChanges();
if (HoverElement() && !HoverElement()->GetLayoutObject() && GetFrame()) {
GetFrame()->GetEventHandler().DispatchFakeMouseMoveEventSoon(
MouseEventManager::FakeMouseMoveReason::kPerFrame);
}
if (focused_element_ && !focused_element_->IsFocusable())
ClearFocusedElementSoon();
GetLayoutViewItem().ClearHitTestCache();
DCHECK(!DocumentAnimations::NeedsAnimationTimingUpdate(*this));
unsigned element_count =
GetStyleEngine().StyleForElementCount() - start_element_count;
TRACE_EVENT_END1("blink,devtools.timeline", "UpdateLayoutTree",
"elementCount", element_count);
#if DCHECK_IS_ON()
AssertLayoutTreeUpdated(*this);
#endif
}
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 <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void *atomic_thread_inc_dec(void *context) {
struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
for (int i = 0; i < at->max_val; i++) {
usleep(1);
atomic_inc_prefix_s32(&at->data[i]);
usleep(1);
atomic_dec_prefix_s32(&at->data[i]);
}
return NULL;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Target: 1
Example 2:
Code: rds_send_pong(struct rds_connection *conn, __be16 dport)
{
struct rds_message *rm;
unsigned long flags;
int ret = 0;
rm = rds_message_alloc(0, GFP_ATOMIC);
if (!rm) {
ret = -ENOMEM;
goto out;
}
rm->m_daddr = conn->c_faddr;
rm->data.op_active = 1;
rds_conn_connect_if_down(conn);
ret = rds_cong_wait(conn->c_fcong, dport, 1, NULL);
if (ret)
goto out;
spin_lock_irqsave(&conn->c_lock, flags);
list_add_tail(&rm->m_conn_item, &conn->c_send_queue);
set_bit(RDS_MSG_ON_CONN, &rm->m_flags);
rds_message_addref(rm);
rm->m_inc.i_conn = conn;
rds_message_populate_header(&rm->m_inc.i_hdr, 0, dport,
conn->c_next_tx_seq);
conn->c_next_tx_seq++;
spin_unlock_irqrestore(&conn->c_lock, flags);
rds_stats_inc(s_send_queued);
rds_stats_inc(s_send_pong);
/* schedule the send work on rds_wq */
queue_delayed_work(rds_wq, &conn->c_send_w, 1);
rds_message_put(rm);
return 0;
out:
if (rm)
rds_message_put(rm);
return ret;
}
Commit Message: RDS: fix race condition when sending a message on unbound socket
Sasha's found a NULL pointer dereference in the RDS connection code when
sending a message to an apparently unbound socket. The problem is caused
by the code checking if the socket is bound in rds_sendmsg(), which checks
the rs_bound_addr field without taking a lock on the socket. This opens a
race where rs_bound_addr is temporarily set but where the transport is not
in rds_bind(), leading to a NULL pointer dereference when trying to
dereference 'trans' in __rds_conn_create().
Vegard wrote a reproducer for this issue, so kindly ask him to share if
you're interested.
I cannot reproduce the NULL pointer dereference using Vegard's reproducer
with this patch, whereas I could without.
Complete earlier incomplete fix to CVE-2015-6937:
74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection")
Cc: David S. Miller <[email protected]>
Cc: [email protected]
Reviewed-by: Vegard Nossum <[email protected]>
Reviewed-by: Sasha Levin <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void UDPSocketWin::Core::WatchForWrite() {
AddRef();
write_watcher_.StartWatching(write_overlapped_.hEvent, &writer_);
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst, UINT16 proto, const char* buf,
UINT16 len, BOOLEAN ext, BOOLEAN forward)
{
UNUSED(ext);
UNUSED(forward);
if (tap_fd != INVALID_FD)
{
tETH_HDR eth_hdr;
memcpy(ð_hdr.h_dest, dst, ETH_ADDR_LEN);
memcpy(ð_hdr.h_src, src, ETH_ADDR_LEN);
eth_hdr.h_proto = htons(proto);
char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)];
memcpy(packet, ð_hdr, sizeof(tETH_HDR));
if (len > TAP_MAX_PKT_WRITE_LEN)
{
LOG_ERROR("btpan_tap_send eth packet size:%d is exceeded limit!", len);
return -1;
}
memcpy(packet + sizeof(tETH_HDR), buf, len);
/* Send data to network interface */
int ret = write(tap_fd, packet, len + sizeof(tETH_HDR));
BTIF_TRACE_DEBUG("ret:%d", ret);
return ret;
}
return -1;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Target: 1
Example 2:
Code: void RenderFrameHostImpl::GetAudioContextManager(
blink::mojom::AudioContextManagerRequest request) {
AudioContextManagerImpl::Create(this, std::move(request));
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void tcp_mtup_probe_success(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
/* FIXME: breaks with very large cwnd */
tp->prior_ssthresh = tcp_current_ssthresh(sk);
tp->snd_cwnd = tp->snd_cwnd *
tcp_mss_to_mtu(sk, tp->mss_cache) /
icsk->icsk_mtup.probe_size;
tp->snd_cwnd_cnt = 0;
tp->snd_cwnd_stamp = tcp_time_stamp;
tp->snd_ssthresh = tcp_current_ssthresh(sk);
icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
icsk->icsk_mtup.probe_size = 0;
tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPMTUPSUCCESS);
}
Commit Message: tcp: fix zero cwnd in tcp_cwnd_reduction
Patch 3759824da87b ("tcp: PRR uses CRB mode by default and SS mode
conditionally") introduced a bug that cwnd may become 0 when both
inflight and sndcnt are 0 (cwnd = inflight + sndcnt). This may lead
to a div-by-zero if the connection starts another cwnd reduction
phase by setting tp->prior_cwnd to the current cwnd (0) in
tcp_init_cwnd_reduction().
To prevent this we skip PRR operation when nothing is acked or
sacked. Then cwnd must be positive in all cases as long as ssthresh
is positive:
1) The proportional reduction mode
inflight > ssthresh > 0
2) The reduction bound mode
a) inflight == ssthresh > 0
b) inflight < ssthresh
sndcnt > 0 since newly_acked_sacked > 0 and inflight < ssthresh
Therefore in all cases inflight and sndcnt can not both be 0.
We check invalid tp->prior_cwnd to avoid potential div0 bugs.
In reality this bug is triggered only with a sequence of less common
events. For example, the connection is terminating an ECN-triggered
cwnd reduction with an inflight 0, then it receives reordered/old
ACKs or DSACKs from prior transmission (which acks nothing). Or the
connection is in fast recovery stage that marks everything lost,
but fails to retransmit due to local issues, then receives data
packets from other end which acks nothing.
Fixes: 3759824da87b ("tcp: PRR uses CRB mode by default and SS mode conditionally")
Reported-by: Oleksandr Natalenko <[email protected]>
Signed-off-by: Yuchung Cheng <[email protected]>
Signed-off-by: Neal Cardwell <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
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) {
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 info leak via msg_name in nr_recvmsg()
In case msg_name is set the sockaddr info gets filled out, as
requested, but the code fails to initialize the padding bytes of
struct sockaddr_ax25 inserted by the compiler for alignment. Also
the sax25_ndigis member does not get assigned, leaking four more
bytes.
Both issues lead to the fact that the code will leak uninitialized
kernel stack bytes in net/socket.c.
Fix both issues by initializing the memory with memset(0).
Cc: Ralf Baechle <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: identity_sign(struct identity *id, u_char **sigp, size_t *lenp,
const u_char *data, size_t datalen, u_int compat)
{
Key *prv;
int ret;
const char *alg;
alg = identity_sign_encode(id);
/* the agent supports this key */
if (id->agent_fd != -1)
return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp,
data, datalen, alg, compat);
/*
* we have already loaded the private key or
* the private key is stored in external hardware
*/
if (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))
return (sshkey_sign(id->key, sigp, lenp, data, datalen, alg,
compat));
/* load the private key from the file */
if ((prv = load_identity_file(id)) == NULL)
return SSH_ERR_KEY_NOT_FOUND;
ret = sshkey_sign(prv, sigp, lenp, data, datalen, alg, compat);
sshkey_free(prv);
return (ret);
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
SyncCredentials credentials;
credentials.email = "[email protected]";
credentials.sync_token = "sometoken";
sync_notifier_mock_ = new StrictMock<SyncNotifierMock>();
EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver));
EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_));
EXPECT_CALL(*sync_notifier_mock_, SetState(""));
EXPECT_CALL(*sync_notifier_mock_,
UpdateCredentials(credentials.email, credentials.sync_token));
EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)).
Times(AtLeast(1)).
WillRepeatedly(
Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes));
EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver));
sync_manager_.AddObserver(&observer_);
EXPECT_CALL(observer_, OnInitializationComplete(_, _)).
WillOnce(SaveArg<0>(&js_backend_));
EXPECT_FALSE(sync_notifier_observer_);
EXPECT_FALSE(js_backend_.IsInitialized());
sync_manager_.Init(temp_dir_.path(),
WeakHandle<JsEventHandler>(),
"bogus", 0, false,
base::MessageLoopProxy::current(),
new TestHttpPostProviderFactory(), this,
&extensions_activity_monitor_, this, "bogus",
credentials,
false /* enable_sync_tabs_for_other_clients */,
sync_notifier_mock_, "",
sync_api::SyncManager::TEST_IN_MEMORY,
&encryptor_,
&handler_,
NULL);
EXPECT_TRUE(sync_notifier_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(1, update_enabled_types_call_count_);
ModelSafeRoutingInfo routes;
GetModelSafeRoutingInfo(&routes);
for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end();
++i) {
type_roots_[i->first] = MakeServerNodeForType(
sync_manager_.GetUserShare(), i->first);
}
PumpLoop();
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ConvolveFunctions(convolve_fn_t h8, convolve_fn_t h8_avg,
convolve_fn_t v8, convolve_fn_t v8_avg,
convolve_fn_t hv8, convolve_fn_t hv8_avg)
: h8_(h8), v8_(v8), hv8_(hv8), h8_avg_(h8_avg), v8_avg_(v8_avg),
hv8_avg_(hv8_avg) {}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 1
Example 2:
Code: slow_search(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *t, *p, *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s += enclen(enc, s);
}
return (UChar* )NULL;
}
Commit Message: fix #59 : access to invalid address by reg->dmax value
CWE ID: CWE-476
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderFrameDevToolsAgentHost::UpdateFrameHost(
RenderFrameHostImpl* frame_host) {
if (frame_host == frame_host_) {
if (frame_host && !render_frame_alive_) {
render_frame_alive_ = true;
for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
inspector->TargetReloadedAfterCrash();
UpdateRendererChannel(IsAttached());
}
return;
}
if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) {
DestroyOnRenderFrameGone();
return;
}
if (IsAttached())
RevokePolicy();
frame_host_ = frame_host;
std::vector<DevToolsSession*> restricted_sessions;
for (DevToolsSession* session : sessions()) {
if (!ShouldAllowSession(session))
restricted_sessions.push_back(session);
}
if (!restricted_sessions.empty())
ForceDetachRestrictedSessions(restricted_sessions);
if (!render_frame_alive_) {
render_frame_alive_ = true;
for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this))
inspector->TargetReloadedAfterCrash();
}
if (IsAttached())
GrantPolicy();
UpdateRendererChannel(IsAttached());
}
Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions
Bug: 866426
Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4
Reviewed-on: https://chromium-review.googlesource.com/c/1270007
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598004}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: omx_vdec::omx_vdec(): m_error_propogated(false),
m_state(OMX_StateInvalid),
m_app_data(NULL),
m_inp_mem_ptr(NULL),
m_out_mem_ptr(NULL),
input_flush_progress (false),
output_flush_progress (false),
input_use_buffer (false),
output_use_buffer (false),
ouput_egl_buffers(false),
m_use_output_pmem(OMX_FALSE),
m_out_mem_region_smi(OMX_FALSE),
m_out_pvt_entry_pmem(OMX_FALSE),
pending_input_buffers(0),
pending_output_buffers(0),
m_out_bm_count(0),
m_inp_bm_count(0),
m_inp_bPopulated(OMX_FALSE),
m_out_bPopulated(OMX_FALSE),
m_flags(0),
#ifdef _ANDROID_
m_heap_ptr(NULL),
#endif
m_inp_bEnabled(OMX_TRUE),
m_out_bEnabled(OMX_TRUE),
m_in_alloc_cnt(0),
m_platform_list(NULL),
m_platform_entry(NULL),
m_pmem_info(NULL),
h264_parser(NULL),
arbitrary_bytes (true),
psource_frame (NULL),
pdest_frame (NULL),
m_inp_heap_ptr (NULL),
m_phdr_pmem_ptr(NULL),
m_heap_inp_bm_count (0),
codec_type_parse ((codec_type)0),
first_frame_meta (true),
frame_count (0),
nal_count (0),
nal_length(0),
look_ahead_nal (false),
first_frame(0),
first_buffer(NULL),
first_frame_size (0),
m_device_file_ptr(NULL),
m_vc1_profile((vc1_profile_type)0),
h264_last_au_ts(LLONG_MAX),
h264_last_au_flags(0),
m_disp_hor_size(0),
m_disp_vert_size(0),
prev_ts(LLONG_MAX),
rst_prev_ts(true),
frm_int(0),
in_reconfig(false),
m_display_id(NULL),
client_extradata(0),
m_reject_avc_1080p_mp (0),
#ifdef _ANDROID_
m_enable_android_native_buffers(OMX_FALSE),
m_use_android_native_buffers(OMX_FALSE),
iDivXDrmDecrypt(NULL),
#endif
m_desc_buffer_ptr(NULL),
secure_mode(false),
m_other_extradata(NULL),
m_profile(0),
client_set_fps(false),
m_last_rendered_TS(-1),
m_queued_codec_config_count(0),
secure_scaling_to_non_secure_opb(false)
{
/* Assumption is that , to begin with , we have all the frames with decoder */
DEBUG_PRINT_HIGH("In %u bit OMX vdec Constructor", (unsigned int)sizeof(long) * 8);
memset(&m_debug,0,sizeof(m_debug));
#ifdef _ANDROID_
char property_value[PROPERTY_VALUE_MAX] = {0};
property_get("vidc.debug.level", property_value, "1");
debug_level = atoi(property_value);
property_value[0] = '\0';
DEBUG_PRINT_HIGH("In OMX vdec Constructor");
property_get("vidc.dec.debug.perf", property_value, "0");
perf_flag = atoi(property_value);
if (perf_flag) {
DEBUG_PRINT_HIGH("vidc.dec.debug.perf is %d", perf_flag);
dec_time.start();
proc_frms = latency = 0;
}
prev_n_filled_len = 0;
property_value[0] = '\0';
property_get("vidc.dec.debug.ts", property_value, "0");
m_debug_timestamp = atoi(property_value);
DEBUG_PRINT_HIGH("vidc.dec.debug.ts value is %d",m_debug_timestamp);
if (m_debug_timestamp) {
time_stamp_dts.set_timestamp_reorder_mode(true);
time_stamp_dts.enable_debug_print(true);
}
property_value[0] = '\0';
property_get("vidc.dec.debug.concealedmb", property_value, "0");
m_debug_concealedmb = atoi(property_value);
DEBUG_PRINT_HIGH("vidc.dec.debug.concealedmb value is %d",m_debug_concealedmb);
property_value[0] = '\0';
property_get("vidc.dec.profile.check", property_value, "0");
m_reject_avc_1080p_mp = atoi(property_value);
DEBUG_PRINT_HIGH("vidc.dec.profile.check value is %d",m_reject_avc_1080p_mp);
property_value[0] = '\0';
property_get("vidc.dec.log.in", property_value, "0");
m_debug.in_buffer_log = atoi(property_value);
property_value[0] = '\0';
property_get("vidc.dec.log.out", property_value, "0");
m_debug.out_buffer_log = atoi(property_value);
sprintf(m_debug.log_loc, "%s", BUFFER_LOG_LOC);
property_value[0] = '\0';
property_get("vidc.log.loc", property_value, "");
if (*property_value)
strlcpy(m_debug.log_loc, property_value, PROPERTY_VALUE_MAX);
property_value[0] = '\0';
property_get("vidc.dec.120fps.enabled", property_value, "0");
if(atoi(property_value)) {
DEBUG_PRINT_LOW("feature 120 FPS decode enabled");
m_last_rendered_TS = 0;
}
property_value[0] = '\0';
property_get("vidc.dec.debug.dyn.disabled", property_value, "0");
m_disable_dynamic_buf_mode = atoi(property_value);
DEBUG_PRINT_HIGH("vidc.dec.debug.dyn.disabled value is %d",m_disable_dynamic_buf_mode);
#endif
memset(&m_cmp,0,sizeof(m_cmp));
memset(&m_cb,0,sizeof(m_cb));
memset (&drv_ctx,0,sizeof(drv_ctx));
memset (&h264_scratch,0,sizeof (OMX_BUFFERHEADERTYPE));
memset (m_hwdevice_name,0,sizeof(m_hwdevice_name));
memset(m_demux_offsets, 0, ( sizeof(OMX_U32) * 8192) );
memset(&m_custom_buffersize, 0, sizeof(m_custom_buffersize));
m_demux_entries = 0;
msg_thread_id = 0;
async_thread_id = 0;
msg_thread_created = false;
async_thread_created = false;
#ifdef _ANDROID_ICS_
memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS));
#endif
memset(&drv_ctx.extradata_info, 0, sizeof(drv_ctx.extradata_info));
/* invalidate m_frame_pack_arrangement */
memset(&m_frame_pack_arrangement, 0, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT));
m_frame_pack_arrangement.cancel_flag = 1;
drv_ctx.timestamp_adjust = false;
drv_ctx.video_driver_fd = -1;
m_vendor_config.pData = NULL;
pthread_mutex_init(&m_lock, NULL);
pthread_mutex_init(&c_lock, NULL);
sem_init(&m_cmd_lock,0,0);
sem_init(&m_safe_flush, 0, 0);
streaming[CAPTURE_PORT] =
streaming[OUTPUT_PORT] = false;
#ifdef _ANDROID_
char extradata_value[PROPERTY_VALUE_MAX] = {0};
property_get("vidc.dec.debug.extradata", extradata_value, "0");
m_debug_extradata = atoi(extradata_value);
DEBUG_PRINT_HIGH("vidc.dec.debug.extradata value is %d",m_debug_extradata);
#endif
m_fill_output_msg = OMX_COMPONENT_GENERATE_FTB;
client_buffers.set_vdec_client(this);
dynamic_buf_mode = false;
out_dynamic_list = NULL;
is_down_scalar_enabled = false;
m_smoothstreaming_mode = false;
m_smoothstreaming_width = 0;
m_smoothstreaming_height = 0;
is_q6_platform = false;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID:
Target: 1
Example 2:
Code: void HTMLScriptRunner::requestDeferredScript(Element* element)
{
PendingScript pendingScript;
if (!requestPendingScript(pendingScript, element))
return;
if (m_document->frame() && !pendingScript.isReady())
ScriptStreamer::startStreaming(pendingScript, PendingScript::Deferred, m_document->frame()->settings(), ScriptState::forMainWorld(m_document->frame()));
ASSERT(pendingScript.resource());
m_scriptsToExecuteAfterParsing.append(pendingScript);
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WrapInMultipleItemsCallback(const MultipleOfflineIdCallback& callback,
const MultipleOfflinePageItemResult& pages) {
std::vector<int64_t> results;
for (const auto& page : pages)
results.push_back(page.offline_id);
callback.Run(results);
}
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 <[email protected]>
Commit-Queue: Jian Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#524232}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void usb_xhci_exit(PCIDevice *dev)
{
int i;
XHCIState *xhci = XHCI(dev);
trace_usb_xhci_exit();
for (i = 0; i < xhci->numslots; i++) {
xhci_disable_slot(xhci, i + 1);
}
if (xhci->mfwrap_timer) {
timer_del(xhci->mfwrap_timer);
timer_free(xhci->mfwrap_timer);
xhci->mfwrap_timer = NULL;
}
memory_region_del_subregion(&xhci->mem, &xhci->mem_cap);
memory_region_del_subregion(&xhci->mem, &xhci->mem_oper);
memory_region_del_subregion(&xhci->mem, &xhci->mem_runtime);
memory_region_del_subregion(&xhci->mem, &xhci->mem_doorbell);
for (i = 0; i < xhci->numports; i++) {
XHCIPort *port = &xhci->ports[i];
memory_region_del_subregion(&xhci->mem, &port->mem);
}
/* destroy msix memory region */
if (dev->msix_table && dev->msix_pba
&& dev->msix_entry_used) {
memory_region_del_subregion(&xhci->mem, &dev->msix_table_mmio);
memory_region_del_subregion(&xhci->mem, &dev->msix_pba_mmio);
}
usb_bus_release(&xhci->bus);
usb_bus_release(&xhci->bus);
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int cxusb_fmd1216me_tuner_attach(struct dvb_usb_adapter *adap)
{
dvb_attach(simple_tuner_attach, adap->fe_adap[0].fe,
&adap->dev->i2c_adap, 0x61,
TUNER_PHILIPS_FMD1216ME_MK3);
return 0;
}
Commit Message: [media] cxusb: Use a dma capable buffer also for reading
Commit 17ce039b4e54 ("[media] cxusb: don't do DMA on stack")
added a kmalloc'ed bounce buffer for writes, but missed to do the same
for reads. As the read only happens after the write is finished, we can
reuse the same buffer.
As dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling
it using the dvb_usb_generic_read wrapper function.
Signed-off-by: Stefan Brüns <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void SVGProcessingInstructions(void *context,const xmlChar *target,
const xmlChar *data)
{
SVGInfo
*svg_info;
/*
A processing instruction has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.processingInstruction(%s, %s)",target,data);
svg_info=(SVGInfo *) context;
(void) svg_info;
}
Commit Message:
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)
{
int i;
int j;
if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=
mat1->numcols_) {
return 1;
}
for (i = 0; i < mat0->numrows_; i++) {
for (j = 0; j < mat0->numcols_; j++) {
if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {
return 1;
}
}
}
return 0;
}
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
Target: 1
Example 2:
Code: void PutARGBImage(Display* display,
void* visual, int depth,
XID pixmap, void* pixmap_gc,
const uint8* data,
int width, int height) {
PutARGBImage(display,
visual, depth,
pixmap, pixmap_gc,
data, width, height,
0, 0, // src_x, src_y
0, 0, // dst_x, dst_y
width, height);
}
Commit Message: Make shared memory segments writable only by their rightful owners.
BUG=143859
TEST=Chrome's UI still works on Linux and Chrome OS
Review URL: https://chromiumcodereview.appspot.com/10854242
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const char* WebGL2RenderingContextBase::ValidateGetBufferSubDataBounds(
const char* function_name,
WebGLBuffer* source_buffer,
GLintptr source_byte_offset,
long long destination_byte_length) {
CheckedNumeric<long long> src_end = source_byte_offset;
src_end += destination_byte_length;
if (!src_end.IsValid() || src_end.ValueOrDie() > source_buffer->GetSize()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name,
"overflow of bound buffer");
return "Invalid value: overflow of bound buffer";
}
return nullptr;
}
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
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static __u8 *nci_extract_rf_params_nfca_passive_poll(struct nci_dev *ndev,
struct rf_tech_specific_params_nfca_poll *nfca_poll,
__u8 *data)
{
nfca_poll->sens_res = __le16_to_cpu(*((__u16 *)data));
data += 2;
nfca_poll->nfcid1_len = *data++;
pr_debug("sens_res 0x%x, nfcid1_len %d\n",
nfca_poll->sens_res, nfca_poll->nfcid1_len);
memcpy(nfca_poll->nfcid1, data, nfca_poll->nfcid1_len);
data += nfca_poll->nfcid1_len;
nfca_poll->sel_res_len = *data++;
if (nfca_poll->sel_res_len != 0)
nfca_poll->sel_res = *data++;
pr_debug("sel_res_len %d, sel_res 0x%x\n",
nfca_poll->sel_res_len,
nfca_poll->sel_res);
return data;
}
Commit Message: NFC: Prevent multiple buffer overflows in NCI
Fix multiple remotely-exploitable stack-based buffer overflows due to
the NCI code pulling length fields directly from incoming frames and
copying too much data into statically-sized arrays.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: Lauro Ramos Venancio <[email protected]>
Cc: Aloisio Almeida Jr <[email protected]>
Cc: Samuel Ortiz <[email protected]>
Cc: David S. Miller <[email protected]>
Acked-by: Ilan Elias <[email protected]>
Signed-off-by: Samuel Ortiz <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
int vector)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (is_guest_mode(vcpu) &&
vector == vmx->nested.posted_intr_nv) {
/*
* If a posted intr is not recognized by hardware,
* we will accomplish it in the next vmentry.
*/
vmx->nested.pi_pending = true;
kvm_make_request(KVM_REQ_EVENT, vcpu);
/* the PIR and ON have been set by L1. */
if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
kvm_vcpu_kick(vcpu);
return 0;
}
return -1;
}
Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions
VMX instructions executed inside a L1 VM will always trigger a VM exit
even when executed with cpl 3. This means we must perform the
privilege check in software.
Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks")
Cc: [email protected]
Signed-off-by: Felix Wilhelm <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int mem_resize(jas_stream_memobj_t *m, int bufsize)
{
unsigned char *buf;
assert(bufsize >= 0);
JAS_DBGLOG(100, ("mem_resize(%p, %d)\n", m, bufsize));
if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) &&
bufsize) {
JAS_DBGLOG(100, ("mem_resize realloc failed\n"));
return -1;
}
JAS_DBGLOG(100, ("mem_resize realloc succeeded\n"));
m->buf_ = buf;
m->bufsize_ = bufsize;
return 0;
}
Commit Message: Made some changes to the I/O stream library for memory streams.
There were a number of potential problems due to the possibility
of integer overflow.
Changed some integral types to the larger types size_t or ssize_t.
For example, the function mem_resize now takes the buffer size parameter
as a size_t.
Added a new function jas_stream_memopen2, which takes a
buffer size specified as a size_t instead of an int.
This can be used in jas_image_cmpt_create to avoid potential
overflow problems.
Added a new function jas_deprecated to warn about reliance on
deprecated library behavior.
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
{
int ret;
gpa_t gpa;
gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
if (!kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
skip_emulated_instruction(vcpu);
trace_kvm_fast_mmio(gpa);
return 1;
}
ret = handle_mmio_page_fault(vcpu, gpa, true);
if (likely(ret == RET_MMIO_PF_EMULATE))
return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
EMULATE_DONE;
if (unlikely(ret == RET_MMIO_PF_INVALID))
return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
if (unlikely(ret == RET_MMIO_PF_RETRY))
return 1;
/* It is the real ept misconfig */
WARN_ON(1);
vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
return 0;
}
Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered
It was found that a guest can DoS a host by triggering an infinite
stream of "alignment check" (#AC) exceptions. This causes the
microcode to enter an infinite loop where the core never receives
another interrupt. The host kernel panics pretty quickly due to the
effects (CVE-2015-5307).
Signed-off-by: Eric Northup <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MagickExport void *DetachBlob(BlobInfo *blob_info)
{
void
*data;
assert(blob_info != (BlobInfo *) NULL);
if (blob_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (blob_info->mapped != MagickFalse)
{
(void) UnmapBlob(blob_info->data,blob_info->length);
RelinquishMagickResource(MapResource,blob_info->length);
}
blob_info->mapped=MagickFalse;
blob_info->length=0;
blob_info->offset=0;
blob_info->eof=MagickFalse;
blob_info->error=0;
blob_info->exempt=MagickFalse;
blob_info->type=UndefinedStream;
blob_info->file_info.file=(FILE *) NULL;
data=blob_info->data;
blob_info->data=(unsigned char *) NULL;
blob_info->stream=(StreamHandler) NULL;
blob_info->custom_stream=(CustomStreamInfo *) NULL;
return(data);
}
Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline const unsigned char *ReadResourceLong(const unsigned char *p,
unsigned int *quantum)
{
*quantum=(size_t) (*p++ << 24);
*quantum|=(size_t) (*p++ << 16);
*quantum|=(size_t) (*p++ << 8);
*quantum|=(size_t) (*p++ << 0);
return(p);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
Target: 1
Example 2:
Code: void RenderView::didExecuteCommand(const WebString& command_name) {
const std::string& name = UTF16ToUTF8(command_name);
if (StartsWithASCII(name, "Move", true) ||
StartsWithASCII(name, "Insert", true) ||
StartsWithASCII(name, "Delete", true))
return;
RenderThread::current()->Send(
new ViewHostMsg_UserMetricsRecordAction(name));
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void usb_serial_console_disconnect(struct usb_serial *serial)
{
if (serial->port[0] == usbcons_info.port) {
usb_serial_console_exit();
usb_serial_put(serial);
}
}
Commit Message: USB: serial: console: fix use-after-free on disconnect
A clean-up patch removing two redundant NULL-checks from the console
disconnect handler inadvertently also removed a third check. This could
lead to the struct usb_serial being prematurely freed by the console
code when a driver accepts but does not register any ports for an
interface which also lacks endpoint descriptors.
Fixes: 0e517c93dc02 ("USB: serial: console: clean up sanity checks")
Cc: stable <[email protected]> # 4.11
Reported-by: Andrey Konovalov <[email protected]>
Acked-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int32 CommandBufferProxyImpl::RegisterTransferBuffer(
base::SharedMemory* shared_memory,
size_t size,
int32 id_request) {
if (last_state_.error != gpu::error::kNoError)
return -1;
int32 id;
if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(
route_id_,
shared_memory->handle(), // Returns FileDescriptor with auto_close off.
size,
id_request,
&id))) {
return -1;
}
return id;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: void sas_porte_broadcast_rcvd(struct work_struct *work)
{
struct asd_sas_event *ev = to_asd_sas_event(work);
struct asd_sas_phy *phy = ev->phy;
unsigned long flags;
u32 prim;
spin_lock_irqsave(&phy->sas_prim_lock, flags);
prim = phy->sas_prim;
spin_unlock_irqrestore(&phy->sas_prim_lock, flags);
SAS_DPRINTK("broadcast received: %d\n", prim);
sas_discover_event(phy->port, DISCE_REVALIDATE_DOMAIN);
if (phy->port)
flush_workqueue(phy->port->ha->disco_q);
}
Commit Message: scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, char **error TSRMLS_DC) /* {{{ */
{
phar_zip_dir_end locator;
char buf[sizeof(locator) + 65536];
long size;
php_uint16 i;
phar_archive_data *mydata = NULL;
phar_entry_info entry = {0};
char *p = buf, *ext, *actual_alias = NULL;
char *metadata = NULL;
size = php_stream_tell(fp);
if (size > sizeof(locator) + 65536) {
/* seek to max comment length + end of central directory record */
size = sizeof(locator) + 65536;
if (FAILURE == php_stream_seek(fp, -size, SEEK_END)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
} else {
php_stream_seek(fp, 0, SEEK_SET);
}
if (!php_stream_read(fp, buf, size)) {
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: unable to read in data to search for end of central directory in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) {
if (!memcmp(p + 1, "K\5\6", 3)) {
memcpy((void *)&locator, (void *) p, sizeof(locator));
if (PHAR_GET_16(locator.centraldisk) != 0 || PHAR_GET_16(locator.disknumber) != 0) {
/* split archives not handled */
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: split archives spanning multiple zips cannot be processed in zip-based phar \"%s\"", fname);
}
return FAILURE;
}
if (PHAR_GET_16(locator.counthere) != PHAR_GET_16(locator.count)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, conflicting file count in end of central directory record in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
return FAILURE;
}
mydata = pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist));
mydata->is_persistent = PHAR_G(persist);
/* read in archive comment, if any */
if (PHAR_GET_16(locator.comment_len)) {
metadata = p + sizeof(locator);
if (PHAR_GET_16(locator.comment_len) != size - (metadata - buf)) {
if (error) {
spprintf(error, 4096, "phar error: corrupt zip archive, zip file comment truncated in zip-based phar \"%s\"", fname);
}
php_stream_close(fp);
pefree(mydata, mydata->is_persistent);
return FAILURE;
}
mydata->metadata_len = PHAR_GET_16(locator.comment_len);
if (phar_parse_metadata(&metadata, &mydata->metadata, PHAR_GET_16(locator.comment_len) TSRMLS_CC) == FAILURE) {
mydata->metadata_len = 0;
/* if not valid serialized data, it is a regular string */
if (entry.is_persistent) {
ALLOC_PERMANENT_ZVAL(mydata->metadata);
} else {
ALLOC_ZVAL(mydata->metadata);
}
INIT_ZVAL(*mydata->metadata);
metadata = pestrndup(metadata, PHAR_GET_16(locator.comment_len), mydata->is_persistent);
ZVAL_STRINGL(mydata->metadata, metadata, PHAR_GET_16(locator.comment_len), 0);
}
} else {
mydata->metadata = NULL;
}
goto foundit;
}
}
php_stream_close(fp);
if (error) {
spprintf(error, 4096, "phar error: end of central directory not found in zip-based phar \"%s\"", fname);
}
return FAILURE;
foundit:
mydata->fname = pestrndup(fname, fname_len, mydata->is_persistent);
#ifdef PHP_WIN32
phar_unixify_path_separators(mydata->fname, fname_len);
#endif
mydata->is_zip = 1;
mydata->fname_len = fname_len;
ext = strrchr(mydata->fname, '/');
if (ext) {
mydata->ext = memchr(ext, '.', (mydata->fname + fname_len) - ext);
if (mydata->ext == ext) {
mydata->ext = memchr(ext + 1, '.', (mydata->fname + fname_len) - ext - 1);
}
if (mydata->ext) {
mydata->ext_len = (mydata->fname + fname_len) - mydata->ext;
}
}
/* clean up on big-endian systems */
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* read in central directory */
zend_hash_init(&mydata->manifest, PHAR_GET_16(locator.count),
zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->mounted_dirs, 5,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
zend_hash_init(&mydata->virtual_dirs, PHAR_GET_16(locator.count) * 2,
zend_get_hash_value, NULL, (zend_bool)mydata->is_persistent);
entry.phar = mydata;
entry.is_zip = 1;
entry.fp_type = PHAR_FP;
entry.is_persistent = mydata->is_persistent;
#define PHAR_ZIP_FAIL_FREE(errmsg, save) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.arBuckets = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.arBuckets = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.arBuckets = 0; \
php_stream_close(fp); \
if (mydata->metadata) { \
zval_dtor(mydata->metadata); \
} \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
efree(save); \
return FAILURE;
#define PHAR_ZIP_FAIL(errmsg) \
zend_hash_destroy(&mydata->manifest); \
mydata->manifest.arBuckets = 0; \
zend_hash_destroy(&mydata->mounted_dirs); \
mydata->mounted_dirs.arBuckets = 0; \
zend_hash_destroy(&mydata->virtual_dirs); \
mydata->virtual_dirs.arBuckets = 0; \
php_stream_close(fp); \
if (mydata->metadata) { \
zval_dtor(mydata->metadata); \
} \
if (mydata->signature) { \
efree(mydata->signature); \
} \
if (error) { \
spprintf(error, 4096, "phar error: %s in zip-based phar \"%s\"", errmsg, mydata->fname); \
} \
pefree(mydata->fname, mydata->is_persistent); \
if (mydata->alias) { \
pefree(mydata->alias, mydata->is_persistent); \
} \
pefree(mydata, mydata->is_persistent); \
return FAILURE;
/* add each central directory item to the manifest */
for (i = 0; i < PHAR_GET_16(locator.count); ++i) {
phar_zip_central_dir_file zipentry;
off_t beforeus = php_stream_tell(fp);
if (sizeof(zipentry) != php_stream_read(fp, (char *) &zipentry, sizeof(zipentry))) {
PHAR_ZIP_FAIL("unable to read central directory entry, truncated");
}
/* clean up for bigendian systems */
if (memcmp("PK\1\2", zipentry.signature, 4)) {
/* corrupted entry */
PHAR_ZIP_FAIL("corrupted central directory entry, no magic signature");
}
if (entry.is_persistent) {
entry.manifest_pos = i;
}
entry.compressed_filesize = PHAR_GET_32(zipentry.compsize);
entry.uncompressed_filesize = PHAR_GET_32(zipentry.uncompsize);
entry.crc32 = PHAR_GET_32(zipentry.crc32);
/* do not PHAR_GET_16 either on the next line */
entry.timestamp = phar_zip_d2u_time(zipentry.timestamp, zipentry.datestamp);
entry.flags = PHAR_ENT_PERM_DEF_FILE;
entry.header_offset = PHAR_GET_32(zipentry.offset);
entry.offset = entry.offset_abs = PHAR_GET_32(zipentry.offset) + sizeof(phar_zip_file_header) + PHAR_GET_16(zipentry.filename_len) +
PHAR_GET_16(zipentry.extra_len);
if (PHAR_GET_16(zipentry.flags) & PHAR_ZIP_FLAG_ENCRYPTED) {
PHAR_ZIP_FAIL("Cannot process encrypted zip files");
}
if (!PHAR_GET_16(zipentry.filename_len)) {
PHAR_ZIP_FAIL("Cannot process zips created from stdin (zero-length filename)");
}
entry.filename_len = PHAR_GET_16(zipentry.filename_len);
entry.filename = (char *) pemalloc(entry.filename_len + 1, entry.is_persistent);
if (entry.filename_len != php_stream_read(fp, entry.filename, entry.filename_len)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in filename from central directory, truncated");
}
entry.filename[entry.filename_len] = '\0';
if (entry.filename[entry.filename_len - 1] == '/') {
entry.is_dir = 1;
if(entry.filename_len > 1) {
entry.filename_len--;
}
entry.flags |= PHAR_ENT_PERM_DEF_DIR;
} else {
entry.is_dir = 0;
}
if (entry.filename_len == sizeof(".phar/signature.bin")-1 && !strncmp(entry.filename, ".phar/signature.bin", sizeof(".phar/signature.bin")-1)) {
size_t read;
php_stream *sigfile;
off_t now;
char *sig;
now = php_stream_tell(fp);
pefree(entry.filename, entry.is_persistent);
sigfile = php_stream_fopen_tmpfile();
if (!sigfile) {
PHAR_ZIP_FAIL("couldn't open temporary file");
}
php_stream_seek(fp, 0, SEEK_SET);
/* copy file contents + local headers and zip comment, if any, to be hashed for signature */
phar_stream_copy_to_stream(fp, sigfile, entry.header_offset, NULL);
/* seek to central directory */
php_stream_seek(fp, PHAR_GET_32(locator.cdir_offset), SEEK_SET);
/* copy central directory header */
phar_stream_copy_to_stream(fp, sigfile, beforeus - PHAR_GET_32(locator.cdir_offset), NULL);
if (metadata) {
php_stream_write(sigfile, metadata, PHAR_GET_16(locator.comment_len));
}
php_stream_seek(fp, sizeof(phar_zip_file_header) + entry.header_offset + entry.filename_len + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
sig = (char *) emalloc(entry.uncompressed_filesize);
read = php_stream_read(fp, sig, entry.uncompressed_filesize);
if (read != entry.uncompressed_filesize) {
php_stream_close(sigfile);
efree(sig);
PHAR_ZIP_FAIL("signature cannot be read");
}
mydata->sig_flags = PHAR_GET_32(sig);
if (FAILURE == phar_verify_signature(sigfile, php_stream_tell(sigfile), mydata->sig_flags, sig + 8, entry.uncompressed_filesize - 8, fname, &mydata->signature, &mydata->sig_len, error TSRMLS_CC)) {
efree(sig);
if (error) {
char *save;
php_stream_close(sigfile);
spprintf(&save, 4096, "signature cannot be verified: %s", *error);
efree(*error);
PHAR_ZIP_FAIL_FREE(save, save);
} else {
php_stream_close(sigfile);
PHAR_ZIP_FAIL("signature cannot be verified");
}
}
php_stream_close(sigfile);
efree(sig);
/* signature checked out, let's ensure this is the last file in the phar */
if (i != PHAR_GET_16(locator.count) - 1) {
PHAR_ZIP_FAIL("entries exist after signature, invalid phar");
}
continue;
}
phar_add_virtual_dirs(mydata, entry.filename, entry.filename_len TSRMLS_CC);
if (PHAR_GET_16(zipentry.extra_len)) {
off_t loc = php_stream_tell(fp);
if (FAILURE == phar_zip_process_extra(fp, &entry, PHAR_GET_16(zipentry.extra_len) TSRMLS_CC)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("Unable to process extra field header for file in central directory");
}
php_stream_seek(fp, loc + PHAR_GET_16(zipentry.extra_len), SEEK_SET);
}
switch (PHAR_GET_16(zipentry.compressed)) {
case PHAR_ZIP_COMP_NONE :
/* compression flag already set */
break;
case PHAR_ZIP_COMP_DEFLATE :
entry.flags |= PHAR_ENT_COMPRESSED_GZ;
if (!PHAR_G(has_zlib)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("zlib extension is required");
}
break;
case PHAR_ZIP_COMP_BZIP2 :
entry.flags |= PHAR_ENT_COMPRESSED_BZ2;
if (!PHAR_G(has_bz2)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("bzip2 extension is required");
}
break;
case 1 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Shrunk) used in this zip");
case 2 :
case 3 :
case 4 :
case 5 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Reduce) used in this zip");
case 6 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Implode) used in this zip");
case 7 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Tokenize) used in this zip");
case 9 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (Deflate64) used in this zip");
case 10 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PKWare Implode/old IBM TERSE) used in this zip");
case 14 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (LZMA) used in this zip");
case 18 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM TERSE) used in this zip");
case 19 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (IBM LZ77) used in this zip");
case 97 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (WavPack) used in this zip");
case 98 :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (PPMd) used in this zip");
default :
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unsupported compression method (unknown) used in this zip");
}
/* get file metadata */
if (PHAR_GET_16(zipentry.comment_len)) {
if (PHAR_GET_16(zipentry.comment_len) != php_stream_read(fp, buf, PHAR_GET_16(zipentry.comment_len))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in file comment, truncated");
}
p = buf;
entry.metadata_len = PHAR_GET_16(zipentry.comment_len);
if (phar_parse_metadata(&p, &(entry.metadata), PHAR_GET_16(zipentry.comment_len) TSRMLS_CC) == FAILURE) {
entry.metadata_len = 0;
/* if not valid serialized data, it is a regular string */
if (entry.is_persistent) {
ALLOC_PERMANENT_ZVAL(entry.metadata);
} else {
ALLOC_ZVAL(entry.metadata);
}
INIT_ZVAL(*entry.metadata);
ZVAL_STRINGL(entry.metadata, pestrndup(buf, PHAR_GET_16(zipentry.comment_len), entry.is_persistent), PHAR_GET_16(zipentry.comment_len), 0);
}
} else {
entry.metadata = NULL;
}
if (!actual_alias && entry.filename_len == sizeof(".phar/alias.txt")-1 && !strncmp(entry.filename, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
php_stream_filter *filter;
off_t saveloc;
/* verify local file header */
phar_zip_file_header local;
/* archive alias found */
saveloc = php_stream_tell(fp);
php_stream_seek(fp, PHAR_GET_32(zipentry.offset), SEEK_SET);
if (sizeof(local) != php_stream_read(fp, (char *) &local, sizeof(local))) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (cannot read local file header for alias)");
}
/* verify local header */
if (entry.filename_len != PHAR_GET_16(local.filename_len) || entry.crc32 != PHAR_GET_32(local.crc32) || entry.uncompressed_filesize != PHAR_GET_32(local.uncompsize) || entry.compressed_filesize != PHAR_GET_32(local.compsize)) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("phar error: internal corruption of zip-based phar (local header of alias does not match central directory)");
}
/* construct actual offset to file start - local extra_len can be different from central extra_len */
entry.offset = entry.offset_abs =
sizeof(local) + entry.header_offset + PHAR_GET_16(local.filename_len) + PHAR_GET_16(local.extra_len);
php_stream_seek(fp, entry.offset, SEEK_SET);
/* these next lines should be for php < 5.2.6 after 5.3 filters are fixed */
fp->writepos = 0;
fp->readpos = 0;
php_stream_seek(fp, entry.offset, SEEK_SET);
fp->writepos = 0;
fp->readpos = 0;
/* the above lines should be for php < 5.2.6 after 5.3 filters are fixed */
mydata->alias_len = entry.uncompressed_filesize;
if (entry.flags & PHAR_ENT_COMPRESSED_GZ) {
filter = php_stream_filter_create("zlib.inflate", NULL, php_stream_is_persistent(fp) TSRMLS_CC);
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to decompress alias, zlib filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
} else if (entry.flags & PHAR_ENT_COMPRESSED_BZ2) {
filter = php_stream_filter_create("bzip2.decompress", NULL, php_stream_is_persistent(fp) TSRMLS_CC);
if (!filter) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, bzip2 filter creation failed");
}
php_stream_filter_append(&fp->readfilters, filter);
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
php_stream_filter_flush(filter, 1);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
} else {
if (!(entry.uncompressed_filesize = php_stream_copy_to_mem(fp, &actual_alias, entry.uncompressed_filesize, 0)) || !actual_alias) {
pefree(entry.filename, entry.is_persistent);
PHAR_ZIP_FAIL("unable to read in alias, truncated");
}
}
/* return to central directory parsing */
php_stream_seek(fp, saveloc, SEEK_SET);
}
phar_set_inode(&entry TSRMLS_CC);
zend_hash_add(&mydata->manifest, entry.filename, entry.filename_len, (void *)&entry,sizeof(phar_entry_info), NULL);
}
mydata->fp = fp;
if (zend_hash_exists(&(mydata->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
mydata->is_data = 0;
} else {
mydata->is_data = 1;
}
zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
if (actual_alias) {
phar_archive_data **fd_ptr;
if (!phar_validate_alias(actual_alias, mydata->alias_len)) {
if (error) {
spprintf(error, 4096, "phar error: invalid alias \"%s\" in zip-based phar \"%s\"", actual_alias, fname);
}
efree(actual_alias);
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
return FAILURE;
}
mydata->is_temporary_alias = 0;
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, mydata->alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with implicit alias, alias is already in use", fname);
}
efree(actual_alias);
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
return FAILURE;
}
}
mydata->alias = entry.is_persistent ? pestrndup(actual_alias, mydata->alias_len, 1) : actual_alias;
if (entry.is_persistent) {
efree(actual_alias);
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
} else {
phar_archive_data **fd_ptr;
if (alias_len) {
if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) {
if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) {
if (error) {
spprintf(error, 4096, "phar error: Unable to add zip-based phar \"%s\" with explicit alias, alias is already in use", fname);
}
zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), mydata->fname, fname_len);
return FAILURE;
}
}
zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, mydata->alias_len, (void*)&mydata, sizeof(phar_archive_data*), NULL);
mydata->alias = pestrndup(alias, alias_len, mydata->is_persistent);
mydata->alias_len = alias_len;
} else {
mydata->alias = pestrndup(mydata->fname, fname_len, mydata->is_persistent);
mydata->alias_len = fname_len;
}
mydata->is_temporary_alias = 1;
}
if (pphar) {
*pphar = mydata;
}
return SUCCESS;
}
/* }}} */
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderWidgetHostViewAura::OnCompositingDidCommit(
ui::Compositor* compositor) {
if (can_lock_compositor_ == NO_PENDING_COMMIT) {
can_lock_compositor_ = YES;
for (ResizeLockList::iterator it = resize_locks_.begin();
it != resize_locks_.end(); ++it)
if ((*it)->GrabDeferredLock())
can_lock_compositor_ = YES_DID_LOCK;
}
RunCompositingDidCommitCallbacks(compositor);
locks_pending_commit_.clear();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: static inline struct virtio_net_hdr_mrg_rxbuf *skb_vnet_hdr(struct sk_buff *skb)
{
return (struct virtio_net_hdr_mrg_rxbuf *)skb->cb;
}
Commit Message: virtio-net: drop NETIF_F_FRAGLIST
virtio declares support for NETIF_F_FRAGLIST, but assumes
that there are at most MAX_SKB_FRAGS + 2 fragments which isn't
always true with a fraglist.
A longer fraglist in the skb will make the call to skb_to_sgvec overflow
the sg array, leading to memory corruption.
Drop NETIF_F_FRAGLIST so we only get what we can handle.
Cc: Michael S. Tsirkin <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
Acked-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PpapiPluginProcessHost::DidDeleteOutOfProcessInstance(
int plugin_process_id,
int32 pp_instance) {
for (PpapiPluginProcessHostIterator iter; !iter.Done(); ++iter) {
if (iter->process_.get() &&
iter->process_->GetData().id == plugin_process_id) {
iter->host_impl_->DeleteInstanceForView(pp_instance);
return;
}
}
}
Commit Message: Handle crashing Pepper plug-ins the same as crashing NPAPI plug-ins.
BUG=151895
Review URL: https://chromiumcodereview.appspot.com/10956065
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158364 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv_len, size_t le_tlv_len,
unsigned char *mac_tlv, size_t * mac_tlv_len, const unsigned char key_type)
{
size_t block_size = (KEY_TYPE_AES == key_type ? 16 : 8);
unsigned char mac[4096] = { 0 };
size_t mac_len;
unsigned char icv[16] = { 0 };
int i = (KEY_TYPE_AES == key_type ? 15 : 7);
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
if (0 == data_tlv_len && 0 == le_tlv_len) {
mac_len = block_size;
}
else {
/* padding */
*(apdu_buf + block_size + data_tlv_len + le_tlv_len) = 0x80;
if ((data_tlv_len + le_tlv_len + 1) % block_size)
mac_len = (((data_tlv_len + le_tlv_len + 1) / block_size) +
1) * block_size + block_size;
else
mac_len = data_tlv_len + le_tlv_len + 1 + block_size;
memset((apdu_buf + block_size + data_tlv_len + le_tlv_len + 1),
0, (mac_len - (data_tlv_len + le_tlv_len + 1)));
}
/* increase icv */
for (; i >= 0; i--) {
if (exdata->icv_mac[i] == 0xff) {
exdata->icv_mac[i] = 0;
}
else {
exdata->icv_mac[i]++;
break;
}
}
/* calculate MAC */
memset(icv, 0, sizeof(icv));
memcpy(icv, exdata->icv_mac, 16);
if (KEY_TYPE_AES == key_type) {
aes128_encrypt_cbc(exdata->sk_mac, 16, icv, apdu_buf, mac_len, mac);
memcpy(mac_tlv + 2, &mac[mac_len - 16], 8);
}
else {
unsigned char iv[8] = { 0 };
unsigned char tmp[8] = { 0 };
des_encrypt_cbc(exdata->sk_mac, 8, icv, apdu_buf, mac_len, mac);
des_decrypt_cbc(&exdata->sk_mac[8], 8, iv, &mac[mac_len - 8], 8, tmp);
memset(iv, 0x00, 8);
des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2);
}
*mac_tlv_len = 2 + 8;
return 0;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
Image *image)
{
const char
*value;
value=GetImageArtifact(image,"tiff:document");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
value=GetImageArtifact(image,"tiff:hostcomputer");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
value=GetImageArtifact(image,"tiff:artist");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
value=GetImageArtifact(image,"tiff:timestamp");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
value=GetImageArtifact(image,"tiff:make");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
value=GetImageArtifact(image,"tiff:model");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
value=GetImageArtifact(image,"tiff:software");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
value=GetImageArtifact(image,"tiff:copyright");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
value=GetImageArtifact(image,"kodak-33423");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,33423,value);
value=GetImageArtifact(image,"kodak-36867");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,36867,value);
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
value=GetImageArtifact(image,"tiff:subfiletype");
if (value != (const char *) NULL)
{
if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
else
if (LocaleCompare(value,"PAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
else
if (LocaleCompare(value,"MASK") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
}
else
{
uint16
page,
pages;
page=(uint16) image->scene;
pages=(uint16) GetImageListLength(image);
if ((image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
}
Commit Message: https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31161
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PromoResourceService::PromoResourceService(Profile* profile)
: WebResourceService(profile->GetPrefs(),
GetPromoResourceURL(),
true, // append locale to URL
prefs::kNtpPromoResourceCacheUpdate,
kStartResourceFetchDelay,
GetCacheUpdateDelay()),
profile_(profile),
ALLOW_THIS_IN_INITIALIZER_LIST(
weak_ptr_factory_(this)),
web_resource_update_scheduled_(false) {
ScheduleNotificationOnInit();
}
Commit Message: Refresh promo notifications as they're fetched
The "guard" existed for notification scheduling was preventing
"turn-off a promo" and "update a promo" scenarios.
Yet I do not believe it was adding any actual safety: if things
on a server backend go wrong, the clients will be affected one
way or the other, and it is better to have an option to shut
the malformed promo down "as quickly as possible" (~in 12-24 hours).
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10696204
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool DeleteSymlink(const FilePath& file_path) {
const bool deleted = HANDLE_EINTR(unlink(file_path.value().c_str())) == 0;
return deleted;
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: request_set_header (struct request *req, const char *name, const char *value,
enum rp release_policy)
{
struct request_header *hdr;
int i;
if (!value)
{
/* A NULL value is a no-op; if freeing the name is requested,
free it now to avoid leaks. */
if (release_policy == rel_name || release_policy == rel_both)
xfree (name);
return;
}
for (i = 0; i < req->hcount; i++)
{
hdr = &req->headers[i];
if (0 == c_strcasecmp (name, hdr->name))
{
/* Replace existing header. */
release_header (hdr);
hdr->name = (void *)name;
hdr->value = (void *)value;
hdr->release_policy = release_policy;
return;
}
}
/* Install new header. */
if (req->hcount >= req->hcapacity)
{
req->hcapacity <<= 1;
req->headers = xrealloc (req->headers, req->hcapacity * sizeof (*hdr));
}
hdr = &req->headers[req->hcount++];
hdr->name = (void *)name;
hdr->value = (void *)value;
hdr->release_policy = release_policy;
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Textfield::OnFocus() {
GetRenderText()->set_focused(true);
if (ShouldShowCursor()) {
UpdateCursorViewPosition();
cursor_view_.SetVisible(true);
}
if (GetInputMethod())
GetInputMethod()->SetFocusedTextInputClient(this);
OnCaretBoundsChanged();
if (ShouldBlinkCursor())
StartBlinkingCursor();
if (use_focus_ring_) {
FocusRing::Install(this, invalid_
? ui::NativeTheme::kColorId_AlertSeverityHigh
: ui::NativeTheme::kColorId_NumColors);
}
SchedulePaint();
View::OnFocus();
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ContentEncoding::ContentCompression::ContentCompression()
: algo(0),
settings(NULL),
settings_len(0) {
}
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
Target: 1
Example 2:
Code: bool ScriptLoader::ignoresLoadRequest() const
{
return m_alreadyStarted || m_isExternalScript || m_parserInserted || !element() || !element()->inDocument();
}
Commit Message: Apply 'x-content-type-options' check to dynamically inserted script.
BUG=348581
Review URL: https://codereview.chromium.org/185593011
git-svn-id: svn://svn.chromium.org/blink/trunk@168570 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void pmcraid_worker_function(struct work_struct *workp)
{
struct pmcraid_instance *pinstance;
struct pmcraid_resource_entry *res;
struct pmcraid_resource_entry *temp;
struct scsi_device *sdev;
unsigned long lock_flags;
unsigned long host_lock_flags;
u16 fw_version;
u8 bus, target, lun;
pinstance = container_of(workp, struct pmcraid_instance, worker_q);
/* add resources only after host is added into system */
if (!atomic_read(&pinstance->expose_resources))
return;
fw_version = be16_to_cpu(pinstance->inq_data->fw_version);
spin_lock_irqsave(&pinstance->resource_lock, lock_flags);
list_for_each_entry_safe(res, temp, &pinstance->used_res_q, queue) {
if (res->change_detected == RES_CHANGE_DEL && res->scsi_dev) {
sdev = res->scsi_dev;
/* host_lock must be held before calling
* scsi_device_get
*/
spin_lock_irqsave(pinstance->host->host_lock,
host_lock_flags);
if (!scsi_device_get(sdev)) {
spin_unlock_irqrestore(
pinstance->host->host_lock,
host_lock_flags);
pmcraid_info("deleting %x from midlayer\n",
res->cfg_entry.resource_address);
list_move_tail(&res->queue,
&pinstance->free_res_q);
spin_unlock_irqrestore(
&pinstance->resource_lock,
lock_flags);
scsi_remove_device(sdev);
scsi_device_put(sdev);
spin_lock_irqsave(&pinstance->resource_lock,
lock_flags);
res->change_detected = 0;
} else {
spin_unlock_irqrestore(
pinstance->host->host_lock,
host_lock_flags);
}
}
}
list_for_each_entry(res, &pinstance->used_res_q, queue) {
if (res->change_detected == RES_CHANGE_ADD) {
if (!pmcraid_expose_resource(fw_version,
&res->cfg_entry))
continue;
if (RES_IS_VSET(res->cfg_entry)) {
bus = PMCRAID_VSET_BUS_ID;
if (fw_version <= PMCRAID_FW_VERSION_1)
target = res->cfg_entry.unique_flags1;
else
target = res->cfg_entry.array_id & 0xFF;
lun = PMCRAID_VSET_LUN_ID;
} else {
bus = PMCRAID_PHYS_BUS_ID;
target =
RES_TARGET(
res->cfg_entry.resource_address);
lun = RES_LUN(res->cfg_entry.resource_address);
}
res->change_detected = 0;
spin_unlock_irqrestore(&pinstance->resource_lock,
lock_flags);
scsi_add_device(pinstance->host, bus, target, lun);
spin_lock_irqsave(&pinstance->resource_lock,
lock_flags);
}
}
spin_unlock_irqrestore(&pinstance->resource_lock, lock_flags);
}
Commit Message: [SCSI] pmcraid: reject negative request size
There's a code path in pmcraid that can be reached via device ioctl that
causes all sorts of ugliness, including heap corruption or triggering the
OOM killer due to consecutive allocation of large numbers of pages.
First, the user can call pmcraid_chr_ioctl(), with a type
PMCRAID_PASSTHROUGH_IOCTL. This calls through to
pmcraid_ioctl_passthrough(). Next, a pmcraid_passthrough_ioctl_buffer
is copied in, and the request_size variable is set to
buffer->ioarcb.data_transfer_length, which is an arbitrary 32-bit
signed value provided by the user. If a negative value is provided
here, bad things can happen. For example,
pmcraid_build_passthrough_ioadls() is called with this request_size,
which immediately calls pmcraid_alloc_sglist() with a negative size.
The resulting math on allocating a scatter list can result in an
overflow in the kzalloc() call (if num_elem is 0, the sglist will be
smaller than expected), or if num_elem is unexpectedly large the
subsequent loop will call alloc_pages() repeatedly, a high number of
pages will be allocated and the OOM killer might be invoked.
It looks like preventing this value from being negative in
pmcraid_ioctl_passthrough() would be sufficient.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: James Bottomley <[email protected]>
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: LogoService::LogoService(
const base::FilePath& cache_directory,
TemplateURLService* template_url_service,
std::unique_ptr<image_fetcher::ImageDecoder> image_decoder,
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
bool use_gray_background)
: cache_directory_(cache_directory),
template_url_service_(template_url_service),
request_context_getter_(request_context_getter),
use_gray_background_(use_gray_background),
image_decoder_(std::move(image_decoder)) {}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map, int flags)
{
struct ext4_ext_path *path = NULL;
struct ext4_extent newex, *ex, *ex2;
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
ext4_fsblk_t newblock = 0;
int free_on_err = 0, err = 0, depth, ret;
unsigned int allocated = 0, offset = 0;
unsigned int allocated_clusters = 0;
struct ext4_allocation_request ar;
ext4_lblk_t cluster_offset;
bool map_from_cluster = false;
ext_debug("blocks %u/%u requested for inode %lu\n",
map->m_lblk, map->m_len, inode->i_ino);
trace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);
/* find extent for this block */
path = ext4_find_extent(inode, map->m_lblk, NULL, 0);
if (IS_ERR(path)) {
err = PTR_ERR(path);
path = NULL;
goto out2;
}
depth = ext_depth(inode);
/*
* consistent leaf must not be empty;
* this situation is possible, though, _during_ tree modification;
* this is why assert can't be put in ext4_find_extent()
*/
if (unlikely(path[depth].p_ext == NULL && depth != 0)) {
EXT4_ERROR_INODE(inode, "bad extent address "
"lblock: %lu, depth: %d pblock %lld",
(unsigned long) map->m_lblk, depth,
path[depth].p_block);
err = -EFSCORRUPTED;
goto out2;
}
ex = path[depth].p_ext;
if (ex) {
ext4_lblk_t ee_block = le32_to_cpu(ex->ee_block);
ext4_fsblk_t ee_start = ext4_ext_pblock(ex);
unsigned short ee_len;
/*
* unwritten extents are treated as holes, except that
* we split out initialized portions during a write.
*/
ee_len = ext4_ext_get_actual_len(ex);
trace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);
/* if found extent covers block, simply return it */
if (in_range(map->m_lblk, ee_block, ee_len)) {
newblock = map->m_lblk - ee_block + ee_start;
/* number of remaining blocks in the extent */
allocated = ee_len - (map->m_lblk - ee_block);
ext_debug("%u fit into %u:%d -> %llu\n", map->m_lblk,
ee_block, ee_len, newblock);
/*
* If the extent is initialized check whether the
* caller wants to convert it to unwritten.
*/
if ((!ext4_ext_is_unwritten(ex)) &&
(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) {
allocated = convert_initialized_extent(
handle, inode, map, &path,
allocated);
goto out2;
} else if (!ext4_ext_is_unwritten(ex))
goto out;
ret = ext4_ext_handle_unwritten_extents(
handle, inode, map, &path, flags,
allocated, newblock);
if (ret < 0)
err = ret;
else
allocated = ret;
goto out2;
}
}
/*
* requested block isn't allocated yet;
* we couldn't try to create block if create flag is zero
*/
if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {
ext4_lblk_t hole_start, hole_len;
hole_start = map->m_lblk;
hole_len = ext4_ext_determine_hole(inode, path, &hole_start);
/*
* put just found gap into cache to speed up
* subsequent requests
*/
ext4_ext_put_gap_in_cache(inode, hole_start, hole_len);
/* Update hole_len to reflect hole size after map->m_lblk */
if (hole_start != map->m_lblk)
hole_len -= map->m_lblk - hole_start;
map->m_pblk = 0;
map->m_len = min_t(unsigned int, map->m_len, hole_len);
goto out2;
}
/*
* Okay, we need to do block allocation.
*/
newex.ee_block = cpu_to_le32(map->m_lblk);
cluster_offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
/*
* If we are doing bigalloc, check to see if the extent returned
* by ext4_find_extent() implies a cluster we can use.
*/
if (cluster_offset && ex &&
get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {
ar.len = allocated = map->m_len;
newblock = map->m_pblk;
map_from_cluster = true;
goto got_allocated_blocks;
}
/* find neighbour allocated blocks */
ar.lleft = map->m_lblk;
err = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
if (err)
goto out2;
ar.lright = map->m_lblk;
ex2 = NULL;
err = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);
if (err)
goto out2;
/* Check if the extent after searching to the right implies a
* cluster we can use. */
if ((sbi->s_cluster_ratio > 1) && ex2 &&
get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {
ar.len = allocated = map->m_len;
newblock = map->m_pblk;
map_from_cluster = true;
goto got_allocated_blocks;
}
/*
* See if request is beyond maximum number of blocks we can have in
* a single extent. For an initialized extent this limit is
* EXT_INIT_MAX_LEN and for an unwritten extent this limit is
* EXT_UNWRITTEN_MAX_LEN.
*/
if (map->m_len > EXT_INIT_MAX_LEN &&
!(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
map->m_len = EXT_INIT_MAX_LEN;
else if (map->m_len > EXT_UNWRITTEN_MAX_LEN &&
(flags & EXT4_GET_BLOCKS_UNWRIT_EXT))
map->m_len = EXT_UNWRITTEN_MAX_LEN;
/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */
newex.ee_len = cpu_to_le16(map->m_len);
err = ext4_ext_check_overlap(sbi, inode, &newex, path);
if (err)
allocated = ext4_ext_get_actual_len(&newex);
else
allocated = map->m_len;
/* allocate new block */
ar.inode = inode;
ar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);
ar.logical = map->m_lblk;
/*
* We calculate the offset from the beginning of the cluster
* for the logical block number, since when we allocate a
* physical cluster, the physical block should start at the
* same offset from the beginning of the cluster. This is
* needed so that future calls to get_implied_cluster_alloc()
* work correctly.
*/
offset = EXT4_LBLK_COFF(sbi, map->m_lblk);
ar.len = EXT4_NUM_B2C(sbi, offset+allocated);
ar.goal -= offset;
ar.logical -= offset;
if (S_ISREG(inode->i_mode))
ar.flags = EXT4_MB_HINT_DATA;
else
/* disable in-core preallocation for non-regular files */
ar.flags = 0;
if (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)
ar.flags |= EXT4_MB_HINT_NOPREALLOC;
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
ar.flags |= EXT4_MB_DELALLOC_RESERVED;
if (flags & EXT4_GET_BLOCKS_METADATA_NOFAIL)
ar.flags |= EXT4_MB_USE_RESERVED;
newblock = ext4_mb_new_blocks(handle, &ar, &err);
if (!newblock)
goto out2;
ext_debug("allocate new block: goal %llu, found %llu/%u\n",
ar.goal, newblock, allocated);
free_on_err = 1;
allocated_clusters = ar.len;
ar.len = EXT4_C2B(sbi, ar.len) - offset;
if (ar.len > allocated)
ar.len = allocated;
got_allocated_blocks:
/* try to insert new extent into found leaf and return */
ext4_ext_store_pblock(&newex, newblock + offset);
newex.ee_len = cpu_to_le16(ar.len);
/* Mark unwritten */
if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT){
ext4_ext_mark_unwritten(&newex);
map->m_flags |= EXT4_MAP_UNWRITTEN;
}
err = 0;
if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)
err = check_eofblocks_fl(handle, inode, map->m_lblk,
path, ar.len);
if (!err)
err = ext4_ext_insert_extent(handle, inode, &path,
&newex, flags);
if (err && free_on_err) {
int fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?
EXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;
/* free data blocks we just allocated */
/* not a good idea to call discard here directly,
* but otherwise we'd need to call it every free() */
ext4_discard_preallocations(inode);
ext4_free_blocks(handle, inode, NULL, newblock,
EXT4_C2B(sbi, allocated_clusters), fb_flags);
goto out2;
}
/* previous routine could use block we allocated */
newblock = ext4_ext_pblock(&newex);
allocated = ext4_ext_get_actual_len(&newex);
if (allocated > map->m_len)
allocated = map->m_len;
map->m_flags |= EXT4_MAP_NEW;
/*
* Reduce the reserved cluster count to reflect successful deferred
* allocation of delayed allocated clusters or direct allocation of
* clusters discovered to be delayed allocated. Once allocated, a
* cluster is not included in the reserved count.
*/
if (test_opt(inode->i_sb, DELALLOC) && !map_from_cluster) {
if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
/*
* When allocating delayed allocated clusters, simply
* reduce the reserved cluster count and claim quota
*/
ext4_da_update_reserve_space(inode, allocated_clusters,
1);
} else {
ext4_lblk_t lblk, len;
unsigned int n;
/*
* When allocating non-delayed allocated clusters
* (from fallocate, filemap, DIO, or clusters
* allocated when delalloc has been disabled by
* ext4_nonda_switch), reduce the reserved cluster
* count by the number of allocated clusters that
* have previously been delayed allocated. Quota
* has been claimed by ext4_mb_new_blocks() above,
* so release the quota reservations made for any
* previously delayed allocated clusters.
*/
lblk = EXT4_LBLK_CMASK(sbi, map->m_lblk);
len = allocated_clusters << sbi->s_cluster_bits;
n = ext4_es_delayed_clu(inode, lblk, len);
if (n > 0)
ext4_da_update_reserve_space(inode, (int) n, 0);
}
}
/*
* Cache the extent and update transaction to commit on fdatasync only
* when it is _not_ an unwritten extent.
*/
if ((flags & EXT4_GET_BLOCKS_UNWRIT_EXT) == 0)
ext4_update_inode_fsync_trans(handle, inode, 1);
else
ext4_update_inode_fsync_trans(handle, inode, 0);
out:
if (allocated > map->m_len)
allocated = map->m_len;
ext4_ext_show_leaf(inode, path);
map->m_flags |= EXT4_MAP_MAPPED;
map->m_pblk = newblock;
map->m_len = allocated;
out2:
ext4_ext_drop_refs(path);
kfree(path);
trace_ext4_ext_map_blocks_exit(inode, flags, map,
err ? err : allocated);
return err ? err : allocated;
}
Commit Message: ext4: zero out the unused memory region in the extent tree block
This commit zeroes out the unused memory region in the buffer_head
corresponding to the extent metablock after writing the extent header
and the corresponding extent node entries.
This is done to prevent random uninitialized data from getting into
the filesystem when the extent block is synced.
This fixes CVE-2019-11833.
Signed-off-by: Sriram Rajagopalan <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
Cc: [email protected]
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct net_device *init_airo_card( unsigned short irq, int port, int is_pcmcia,
struct device *dmdev)
{
return _init_airo_card ( irq, port, is_pcmcia, NULL, dmdev);
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE omx_vdec::free_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_U32 port,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned int nPortIndex;
(void) hComp;
DEBUG_PRINT_LOW("In for decoder free_buffer");
if (m_state == OMX_StateIdle &&
(BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) {
DEBUG_PRINT_LOW(" free buffer while Component in Loading pending");
} else if ((m_inp_bEnabled == OMX_FALSE && port == OMX_CORE_INPUT_PORT_INDEX)||
(m_out_bEnabled == OMX_FALSE && port == OMX_CORE_OUTPUT_PORT_INDEX)) {
DEBUG_PRINT_LOW("Free Buffer while port %u disabled", (unsigned int)port);
} else if ((port == OMX_CORE_INPUT_PORT_INDEX &&
BITMASK_PRESENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING)) ||
(port == OMX_CORE_OUTPUT_PORT_INDEX &&
BITMASK_PRESENT(&m_flags, OMX_COMPONENT_OUTPUT_ENABLE_PENDING))) {
DEBUG_PRINT_LOW("Free Buffer while port %u enable pending", (unsigned int)port);
} else if (m_state == OMX_StateExecuting || m_state == OMX_StatePause) {
DEBUG_PRINT_ERROR("Invalid state to free buffer,ports need to be disabled");
post_event(OMX_EventError,
OMX_ErrorPortUnpopulated,
OMX_COMPONENT_GENERATE_EVENT);
return OMX_ErrorIncorrectStateOperation;
} else if (m_state != OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Invalid state to free buffer,port lost Buffers");
post_event(OMX_EventError,
OMX_ErrorPortUnpopulated,
OMX_COMPONENT_GENERATE_EVENT);
}
if (port == OMX_CORE_INPUT_PORT_INDEX) {
/*Check if arbitrary bytes*/
if (!arbitrary_bytes && !input_use_buffer)
nPortIndex = buffer - m_inp_mem_ptr;
else
nPortIndex = buffer - m_inp_heap_ptr;
DEBUG_PRINT_LOW("free_buffer on i/p port - Port idx %d", nPortIndex);
if (nPortIndex < drv_ctx.ip_buf.actualcount) {
BITMASK_CLEAR(&m_inp_bm_count,nPortIndex);
BITMASK_CLEAR(&m_heap_inp_bm_count,nPortIndex);
if (input_use_buffer == true) {
DEBUG_PRINT_LOW("Free pmem Buffer index %d",nPortIndex);
if (m_phdr_pmem_ptr)
free_input_buffer(m_phdr_pmem_ptr[nPortIndex]);
} else {
if (arbitrary_bytes) {
if (m_phdr_pmem_ptr)
free_input_buffer(nPortIndex,m_phdr_pmem_ptr[nPortIndex]);
else
free_input_buffer(nPortIndex,NULL);
} else
free_input_buffer(buffer);
}
m_inp_bPopulated = OMX_FALSE;
if(release_input_done())
release_buffers(this, VDEC_BUFFER_TYPE_INPUT);
/*Free the Buffer Header*/
if (release_input_done()) {
DEBUG_PRINT_HIGH("ALL input buffers are freed/released");
free_input_buffer_header();
}
} else {
DEBUG_PRINT_ERROR("Error: free_buffer ,Port Index Invalid");
eRet = OMX_ErrorBadPortIndex;
}
if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING)
&& release_input_done()) {
DEBUG_PRINT_LOW("MOVING TO DISABLED STATE");
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING);
post_event(OMX_CommandPortDisable,
OMX_CORE_INPUT_PORT_INDEX,
OMX_COMPONENT_GENERATE_EVENT);
}
} else if (port == OMX_CORE_OUTPUT_PORT_INDEX) {
nPortIndex = buffer - client_buffers.get_il_buf_hdr();
if (nPortIndex < drv_ctx.op_buf.actualcount) {
DEBUG_PRINT_LOW("free_buffer on o/p port - Port idx %d", nPortIndex);
BITMASK_CLEAR(&m_out_bm_count,nPortIndex);
m_out_bPopulated = OMX_FALSE;
client_buffers.free_output_buffer (buffer);
if(release_output_done()) {
release_buffers(this, VDEC_BUFFER_TYPE_OUTPUT);
}
if (release_output_done()) {
free_output_buffer_header();
}
} else {
DEBUG_PRINT_ERROR("Error: free_buffer , Port Index Invalid");
eRet = OMX_ErrorBadPortIndex;
}
if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING)
&& release_output_done()) {
DEBUG_PRINT_LOW("FreeBuffer : If any Disable event pending,post it");
DEBUG_PRINT_LOW("MOVING TO DISABLED STATE");
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING);
#ifdef _ANDROID_ICS_
if (m_enable_android_native_buffers) {
DEBUG_PRINT_LOW("FreeBuffer - outport disabled: reset native buffers");
memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS));
}
#endif
post_event(OMX_CommandPortDisable,
OMX_CORE_OUTPUT_PORT_INDEX,
OMX_COMPONENT_GENERATE_EVENT);
}
} else {
eRet = OMX_ErrorBadPortIndex;
}
if ((eRet == OMX_ErrorNone) &&
(BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) {
if (release_done()) {
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_LOADING_PENDING);
post_event(OMX_CommandStateSet, OMX_StateLoaded,
OMX_COMPONENT_GENERATE_EVENT);
}
}
return eRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: add safety checks for freeing buffers
Allow only up to 64 buffers on input/output port (since the
allocation bitmap is only 64-wide).
Do not allow changing theactual buffer count while still
holding allocation (Client can technically negotiate
buffer count on a free/disabled port)
Add safety checks to free only as many buffers were allocated.
Fixes: Security Vulnerability - Heap Overflow and Possible Local
Privilege Escalation in MediaServer (libOmxVdec problem #3)
Bug: 27532282 27661749
Change-Id: I06dd680d43feaef3efdc87311e8a6703e234b523
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void ohci_sof(OHCIState *ohci)
{
ohci_eof_timer(ohci);
ohci_set_interrupt(ohci, OHCI_INTR_SF);
}
Commit Message:
CWE ID: CWE-835
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cib_connect(gboolean full)
{
int rc = pcmk_ok;
static gboolean need_pass = TRUE;
CRM_CHECK(cib != NULL, return -EINVAL);
if (getenv("CIB_passwd") != NULL) {
need_pass = FALSE;
}
if(watch_fencing && st == NULL) {
st = stonith_api_new();
}
if(watch_fencing && st->state == stonith_disconnected) {
crm_trace("Connecting to stonith");
rc = st->cmds->connect(st, crm_system_name, NULL);
if(rc == pcmk_ok) {
crm_trace("Setting up stonith callbacks");
st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback);
}
}
if (cib->state != cib_connected_query && cib->state != cib_connected_command) {
crm_trace("Connecting to the CIB");
if (as_console && need_pass && cib->variant == cib_remote) {
need_pass = FALSE;
print_as("Password:");
}
rc = cib->cmds->signon(cib, crm_system_name, cib_query);
if (rc != pcmk_ok) {
return rc;
}
current_cib = get_cib_copy(cib);
mon_refresh_display(NULL);
if (full) {
if (rc == pcmk_ok) {
rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy);
if (rc == -EPROTONOSUPPORT) {
print_as("Notification setup failed, won't be able to reconnect after failure");
if (as_console) {
sleep(2);
}
rc = pcmk_ok;
}
}
if (rc == pcmk_ok) {
cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update);
rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update);
}
if (rc != pcmk_ok) {
print_as("Notification setup failed, could not monitor CIB actions");
if (as_console) {
sleep(2);
}
clean_up(-rc);
}
}
}
return rc;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void SetUp() {
source_stride_ = (width_ + 31) & ~31;
reference_stride_ = width_ * 2;
rnd_.Reset(ACMRandom::DeterministicSeed());
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int dccp_timeout_nlattr_to_obj(struct nlattr *tb[],
struct net *net, void *data)
{
struct dccp_net *dn = dccp_pernet(net);
unsigned int *timeouts = data;
int i;
/* set default DCCP timeouts. */
for (i=0; i<CT_DCCP_MAX; i++)
timeouts[i] = dn->dccp_timeout[i];
/* there's a 1:1 mapping between attributes and protocol states. */
for (i=CTA_TIMEOUT_DCCP_UNSPEC+1; i<CTA_TIMEOUT_DCCP_MAX+1; i++) {
if (tb[i]) {
timeouts[i] = ntohl(nla_get_be32(tb[i])) * HZ;
}
}
return 0;
}
Commit Message: netfilter: nf_conntrack_dccp: fix skb_header_pointer API usages
Some occurences in the netfilter tree use skb_header_pointer() in
the following way ...
struct dccp_hdr _dh, *dh;
...
skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
... where dh itself is a pointer that is being passed as the copy
buffer. Instead, we need to use &_dh as the forth argument so that
we're copying the data into an actual buffer that sits on the stack.
Currently, we probably could overwrite memory on the stack (e.g.
with a possibly mal-formed DCCP packet), but unintentionally, as
we only want the buffer to be placed into _dh variable.
Fixes: 2bc780499aa3 ("[NETFILTER]: nf_conntrack: add DCCP protocol support")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cmsBool ParseIT8(cmsIT8* it8, cmsBool nosheet)
{
char* SheetTypePtr = it8 ->Tab[0].SheetType;
if (nosheet == 0) {
ReadType(it8, SheetTypePtr);
}
InSymbol(it8);
SkipEOLN(it8);
while (it8-> sy != SEOF &&
it8-> sy != SSYNERROR) {
switch (it8 -> sy) {
case SBEGIN_DATA_FORMAT:
if (!DataFormatSection(it8)) return FALSE;
break;
case SBEGIN_DATA:
if (!DataSection(it8)) return FALSE;
if (it8 -> sy != SEOF) {
AllocTable(it8);
it8 ->nTable = it8 ->TablesCount - 1;
if (nosheet == 0) {
if (it8 ->sy == SIDENT) {
while (isseparator(it8->ch))
NextCh(it8);
if (it8 ->ch == '\n' || it8->ch == '\r') {
cmsIT8SetSheetType(it8, it8 ->id);
InSymbol(it8);
}
else
{
cmsIT8SetSheetType(it8, "");
}
}
else
if (it8 ->sy == SSTRING) {
cmsIT8SetSheetType(it8, it8 ->str);
InSymbol(it8);
}
}
}
break;
case SEOLN:
SkipEOLN(it8);
break;
default:
if (!HeaderSection(it8)) return FALSE;
}
}
return (it8 -> sy != SSYNERROR);
}
Commit Message: Upgrade Visual studio 2017 15.8
- Upgrade to 15.8
- Add check on CGATS memory allocation (thanks to Quang Nguyen for
pointing out this)
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(obj TSRMLS_CC);
HashTable *rv;
zval *tmp, zrv;
char *pnstr, *path;
int pnlen, path_len;
char stmp[2];
*is_temp = 1;
if (!intern->std.properties) {
rebuild_object_properties(&intern->std);
}
ALLOC_HASHTABLE(rv);
ZEND_INIT_SYMTABLE_EX(rv, zend_hash_num_elements(intern->std.properties) + 3, 0);
INIT_PZVAL(&zrv);
Z_ARRVAL(zrv) = rv;
zend_hash_copy(rv, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *));
pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "pathName", sizeof("pathName")-1, &pnlen TSRMLS_CC);
path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC);
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, path, path_len, 1);
efree(pnstr);
if (intern->file_name) {
pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "fileName", sizeof("fileName")-1, &pnlen TSRMLS_CC);
spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC);
if (path_len && path_len < intern->file_name_len) {
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1);
} else {
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name, intern->file_name_len, 1);
}
efree(pnstr);
}
if (intern->type == SPL_FS_DIR) {
#ifdef HAVE_GLOB
pnstr = spl_gen_private_prop_name(spl_ce_DirectoryIterator, "glob", sizeof("glob")-1, &pnlen TSRMLS_CC);
if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->_path, intern->_path_len, 1);
} else {
add_assoc_bool_ex(&zrv, pnstr, pnlen+1, 0);
}
efree(pnstr);
#endif
pnstr = spl_gen_private_prop_name(spl_ce_RecursiveDirectoryIterator, "subPathName", sizeof("subPathName")-1, &pnlen TSRMLS_CC);
if (intern->u.dir.sub_path) {
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1);
} else {
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, "", 0, 1);
}
efree(pnstr);
}
if (intern->type == SPL_FS_FILE) {
pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "openMode", sizeof("openMode")-1, &pnlen TSRMLS_CC);
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.file.open_mode, intern->u.file.open_mode_len, 1);
efree(pnstr);
stmp[1] = '\0';
stmp[0] = intern->u.file.delimiter;
pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "delimiter", sizeof("delimiter")-1, &pnlen TSRMLS_CC);
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1);
efree(pnstr);
stmp[0] = intern->u.file.enclosure;
pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "enclosure", sizeof("enclosure")-1, &pnlen TSRMLS_CC);
add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1);
efree(pnstr);
}
return rv;
}
/* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: struct sctp_chunk *sctp_make_init_ack(const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
gfp_t gfp, int unkparam_len)
{
sctp_inithdr_t initack;
struct sctp_chunk *retval;
union sctp_params addrs;
struct sctp_sock *sp;
int addrs_len;
sctp_cookie_param_t *cookie;
int cookie_len;
size_t chunksize;
sctp_adaptation_ind_param_t aiparam;
sctp_supported_ext_param_t ext_param;
int num_ext = 0;
__u8 extensions[3];
sctp_paramhdr_t *auth_chunks = NULL,
*auth_hmacs = NULL,
*auth_random = NULL;
retval = NULL;
/* Note: there may be no addresses to embed. */
addrs = sctp_bind_addrs_to_raw(&asoc->base.bind_addr, &addrs_len, gfp);
initack.init_tag = htonl(asoc->c.my_vtag);
initack.a_rwnd = htonl(asoc->rwnd);
initack.num_outbound_streams = htons(asoc->c.sinit_num_ostreams);
initack.num_inbound_streams = htons(asoc->c.sinit_max_instreams);
initack.initial_tsn = htonl(asoc->c.initial_tsn);
/* FIXME: We really ought to build the cookie right
* into the packet instead of allocating more fresh memory.
*/
cookie = sctp_pack_cookie(asoc->ep, asoc, chunk, &cookie_len,
addrs.v, addrs_len);
if (!cookie)
goto nomem_cookie;
/* Calculate the total size of allocation, include the reserved
* space for reporting unknown parameters if it is specified.
*/
sp = sctp_sk(asoc->base.sk);
chunksize = sizeof(initack) + addrs_len + cookie_len + unkparam_len;
/* Tell peer that we'll do ECN only if peer advertised such cap. */
if (asoc->peer.ecn_capable)
chunksize += sizeof(ecap_param);
if (asoc->peer.prsctp_capable)
chunksize += sizeof(prsctp_param);
if (asoc->peer.asconf_capable) {
extensions[num_ext] = SCTP_CID_ASCONF;
extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
num_ext += 2;
}
if (sp->adaptation_ind)
chunksize += sizeof(aiparam);
if (asoc->peer.auth_capable) {
auth_random = (sctp_paramhdr_t *)asoc->c.auth_random;
chunksize += ntohs(auth_random->length);
auth_hmacs = (sctp_paramhdr_t *)asoc->c.auth_hmacs;
if (auth_hmacs->length)
chunksize += WORD_ROUND(ntohs(auth_hmacs->length));
else
auth_hmacs = NULL;
auth_chunks = (sctp_paramhdr_t *)asoc->c.auth_chunks;
if (auth_chunks->length)
chunksize += WORD_ROUND(ntohs(auth_chunks->length));
else
auth_chunks = NULL;
extensions[num_ext] = SCTP_CID_AUTH;
num_ext += 1;
}
if (num_ext)
chunksize += WORD_ROUND(sizeof(sctp_supported_ext_param_t) +
num_ext);
/* Now allocate and fill out the chunk. */
retval = sctp_make_control(asoc, SCTP_CID_INIT_ACK, 0, chunksize);
if (!retval)
goto nomem_chunk;
/* RFC 2960 6.4 Multi-homed SCTP Endpoints
*
* An endpoint SHOULD transmit reply chunks (e.g., SACK,
* HEARTBEAT ACK, * etc.) to the same destination transport
* address from which it received the DATA or control chunk
* to which it is replying.
*
* [INIT ACK back to where the INIT came from.]
*/
retval->transport = chunk->transport;
retval->subh.init_hdr =
sctp_addto_chunk(retval, sizeof(initack), &initack);
retval->param_hdr.v = sctp_addto_chunk(retval, addrs_len, addrs.v);
sctp_addto_chunk(retval, cookie_len, cookie);
if (asoc->peer.ecn_capable)
sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
if (num_ext) {
ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
ext_param.param_hdr.length =
htons(sizeof(sctp_supported_ext_param_t) + num_ext);
sctp_addto_chunk(retval, sizeof(sctp_supported_ext_param_t),
&ext_param);
sctp_addto_param(retval, num_ext, extensions);
}
if (asoc->peer.prsctp_capable)
sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
if (sp->adaptation_ind) {
aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
aiparam.param_hdr.length = htons(sizeof(aiparam));
aiparam.adaptation_ind = htonl(sp->adaptation_ind);
sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
}
if (asoc->peer.auth_capable) {
sctp_addto_chunk(retval, ntohs(auth_random->length),
auth_random);
if (auth_hmacs)
sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
auth_hmacs);
if (auth_chunks)
sctp_addto_chunk(retval, ntohs(auth_chunks->length),
auth_chunks);
}
/* We need to remove the const qualifier at this point. */
retval->asoc = (struct sctp_association *) asoc;
nomem_chunk:
kfree(cookie);
nomem_cookie:
kfree(addrs.v);
return retval;
}
Commit Message: net: sctp: fix NULL pointer dereference in af->from_addr_param on malformed packet
An SCTP server doing ASCONF will panic on malformed INIT ping-of-death
in the form of:
------------ INIT[PARAM: SET_PRIMARY_IP] ------------>
While the INIT chunk parameter verification dissects through many things
in order to detect malformed input, it misses to actually check parameters
inside of parameters. E.g. RFC5061, section 4.2.4 proposes a 'set primary
IP address' parameter in ASCONF, which has as a subparameter an address
parameter.
So an attacker may send a parameter type other than SCTP_PARAM_IPV4_ADDRESS
or SCTP_PARAM_IPV6_ADDRESS, param_type2af() will subsequently return 0
and thus sctp_get_af_specific() returns NULL, too, which we then happily
dereference unconditionally through af->from_addr_param().
The trace for the log:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000078
IP: [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp]
PGD 0
Oops: 0000 [#1] SMP
[...]
Pid: 0, comm: swapper Not tainted 2.6.32-504.el6.x86_64 #1 Bochs Bochs
RIP: 0010:[<ffffffffa01e9c62>] [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp]
[...]
Call Trace:
<IRQ>
[<ffffffffa01f2add>] ? sctp_bind_addr_copy+0x5d/0xe0 [sctp]
[<ffffffffa01e1fcb>] sctp_sf_do_5_1B_init+0x21b/0x340 [sctp]
[<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp]
[<ffffffffa01e5c09>] ? sctp_endpoint_lookup_assoc+0xc9/0xf0 [sctp]
[<ffffffffa01e61f6>] sctp_endpoint_bh_rcv+0x116/0x230 [sctp]
[<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp]
[<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp]
[<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]
[<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[...]
A minimal way to address this is to check for NULL as we do on all
other such occasions where we know sctp_get_af_specific() could
possibly return with NULL.
Fixes: d6de3097592b ("[SCTP]: Add the handling of "Set Primary IP Address" parameter to INIT")
Signed-off-by: Daniel Borkmann <[email protected]>
Cc: Vlad Yasevich <[email protected]>
Acked-by: Neil Horman <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IDNConversionResult IDNToUnicodeWithAdjustmentsImpl(
base::StringPiece host,
base::OffsetAdjuster::Adjustments* adjustments,
bool enable_spoof_checks) {
if (adjustments)
adjustments->clear();
base::string16 input16;
input16.reserve(host.length());
input16.insert(input16.end(), host.begin(), host.end());
bool is_tld_ascii = true;
size_t last_dot = host.rfind('.');
if (last_dot != base::StringPiece::npos &&
host.substr(last_dot).starts_with(".xn--")) {
is_tld_ascii = false;
}
IDNConversionResult result;
base::string16 out16;
for (size_t component_start = 0, component_end;
component_start < input16.length();
component_start = component_end + 1) {
component_end = input16.find('.', component_start);
if (component_end == base::string16::npos)
component_end = input16.length(); // For getting the last component.
size_t component_length = component_end - component_start;
size_t new_component_start = out16.length();
bool converted_idn = false;
if (component_end > component_start) {
bool has_idn_component = false;
converted_idn = IDNToUnicodeOneComponent(
input16.data() + component_start, component_length, is_tld_ascii,
enable_spoof_checks, &out16, &has_idn_component);
result.has_idn_component |= has_idn_component;
}
size_t new_component_length = out16.length() - new_component_start;
if (converted_idn && adjustments) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
component_start, component_length, new_component_length));
}
if (component_end < input16.length())
out16.push_back('.');
}
result.result = out16;
if (result.has_idn_component) {
result.matching_top_domain =
g_idn_spoof_checker.Get().GetSimilarTopDomain(out16);
if (enable_spoof_checks && !result.matching_top_domain.domain.empty()) {
if (adjustments)
adjustments->clear();
result.result = input16;
}
}
return result;
}
Commit Message: Restrict Latin Small Letter Thorn (U+00FE) to Icelandic domains
This character (þ) can be confused with both b and p when used in a domain
name. IDN spoof checker doesn't have a good way of flagging a character as
confusable with multiple characters, so it can't catch spoofs containing
this character. As a practical fix, this CL restricts this character to
domains under Iceland's ccTLD (.is). With this change, a domain name containing
"þ" with a non-.is TLD will be displayed in punycode in the UI.
This change affects less than 10 real world domains with limited popularity.
Bug: 798892, 843352, 904327, 1017707
Change-Id: Ib07190dcde406bf62ce4413688a4fb4859a51030
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1879992
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Christopher Thompson <[email protected]>
Cr-Commit-Position: refs/heads/master@{#709309}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ClipboardMessageFilter::OnWriteObjectsAsync(
const ui::Clipboard::ObjectMap& objects) {
scoped_ptr<ui::Clipboard::ObjectMap> sanitized_objects(
new ui::Clipboard::ObjectMap(objects));
sanitized_objects->erase(ui::Clipboard::CBF_SMBITMAP);
#if defined(OS_WIN)
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(
&WriteObjectsOnUIThread, base::Owned(sanitized_objects.release())));
#else
GetClipboard()->WriteObjects(
ui::CLIPBOARD_TYPE_COPY_PASTE, *sanitized_objects.get());
#endif
}
Commit Message: Refactor ui::Clipboard::ObjectMap sanitization in ClipboardMsgFilter.
BUG=352395
[email protected]
[email protected]
Review URL: https://codereview.chromium.org/200523004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@257164 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 1
Example 2:
Code: void BrowserCommandController::SetBlockCommandExecution(bool block) {
block_command_execution_ = block;
if (block) {
last_blocked_command_id_ = -1;
last_blocked_command_disposition_ = CURRENT_TAB;
}
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid)
{
XHCIEPContext *epctx;
assert(slotid >= 1 && slotid <= xhci->numslots);
assert(epid >= 1 && epid <= 31);
if (!xhci->slots[slotid-1].enabled) {
DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);
return;
}
epctx = xhci->slots[slotid-1].eps[epid-1];
if (!epctx) {
DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
epid, slotid);
return;
return;
}
xhci_kick_epctx(epctx, streamid);
}
Commit Message:
CWE ID: CWE-835
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: cleanup_pathname(struct archive_write_disk *a)
{
char *dest, *src;
char separator = '\0';
dest = src = a->name;
if (*src == '\0') {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Invalid empty pathname");
return (ARCHIVE_FAILED);
}
#if defined(__CYGWIN__)
cleanup_pathname_win(a);
#endif
/* Skip leading '/'. */
if (*src == '/')
separator = *src++;
/* Scan the pathname one element at a time. */
for (;;) {
/* src points to first char after '/' */
if (src[0] == '\0') {
break;
} else if (src[0] == '/') {
/* Found '//', ignore second one. */
src++;
continue;
} else if (src[0] == '.') {
if (src[1] == '\0') {
/* Ignore trailing '.' */
break;
} else if (src[1] == '/') {
/* Skip './'. */
src += 2;
continue;
} else if (src[1] == '.') {
if (src[2] == '/' || src[2] == '\0') {
/* Conditionally warn about '..' */
if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"Path contains '..'");
return (ARCHIVE_FAILED);
}
}
/*
* Note: Under no circumstances do we
* remove '..' elements. In
* particular, restoring
* '/foo/../bar/' should create the
* 'foo' dir as a side-effect.
*/
}
}
/* Copy current element, including leading '/'. */
if (separator)
*dest++ = '/';
while (*src != '\0' && *src != '/') {
*dest++ = *src++;
}
if (*src == '\0')
break;
/* Skip '/' separator. */
separator = *src++;
}
/*
* We've just copied zero or more path elements, not including the
* final '/'.
*/
if (dest == a->name) {
/*
* Nothing got copied. The path must have been something
* like '.' or '/' or './' or '/././././/./'.
*/
if (separator)
*dest++ = '/';
else
*dest++ = '.';
}
/* Terminate the result. */
*dest = '\0';
return (ARCHIVE_OK);
}
Commit Message: Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option
This fixes a directory traversal in the cpio tool.
CWE ID: CWE-22
Target: 1
Example 2:
Code: struct request *blk_get_request(struct request_queue *q, unsigned int op,
blk_mq_req_flags_t flags)
{
struct request *req;
WARN_ON_ONCE(op & REQ_NOWAIT);
WARN_ON_ONCE(flags & ~(BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_PREEMPT));
if (q->mq_ops) {
req = blk_mq_alloc_request(q, op, flags);
if (!IS_ERR(req) && q->mq_ops->initialize_rq_fn)
q->mq_ops->initialize_rq_fn(req);
} else {
req = blk_old_get_request(q, op, flags);
if (!IS_ERR(req) && q->initialize_rq_fn)
q->initialize_rq_fn(req);
}
return req;
}
Commit Message: block: blk_init_allocated_queue() set q->fq as NULL in the fail case
We find the memory use-after-free issue in __blk_drain_queue()
on the kernel 4.14. After read the latest kernel 4.18-rc6 we
think it has the same problem.
Memory is allocated for q->fq in the blk_init_allocated_queue().
If the elevator init function called with error return, it will
run into the fail case to free the q->fq.
Then the __blk_drain_queue() uses the same memory after the free
of the q->fq, it will lead to the unpredictable event.
The patch is to set q->fq as NULL in the fail case of
blk_init_allocated_queue().
Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery")
Cc: <[email protected]>
Reviewed-by: Ming Lei <[email protected]>
Reviewed-by: Bart Van Assche <[email protected]>
Signed-off-by: xiao jin <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: COMPAT_SYSCALL_DEFINE5(waitid,
int, which, compat_pid_t, pid,
struct compat_siginfo __user *, infop, int, options,
struct compat_rusage __user *, uru)
{
struct rusage ru;
struct waitid_info info = {.status = 0};
long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
int signo = 0;
if (err > 0) {
signo = SIGCHLD;
err = 0;
}
if (!err && uru) {
/* kernel_waitid() overwrites everything in ru */
if (COMPAT_USE_64BIT_TIME)
err = copy_to_user(uru, &ru, sizeof(ru));
else
err = put_compat_rusage(&ru, uru);
if (err)
return -EFAULT;
}
if (!infop)
return err;
user_access_begin();
unsafe_put_user(signo, &infop->si_signo, Efault);
unsafe_put_user(0, &infop->si_errno, Efault);
unsafe_put_user(info.cause, &infop->si_code, Efault);
unsafe_put_user(info.pid, &infop->si_pid, Efault);
unsafe_put_user(info.uid, &infop->si_uid, Efault);
unsafe_put_user(info.status, &infop->si_status, Efault);
user_access_end();
return err;
Efault:
user_access_end();
return -EFAULT;
}
Commit Message: fix infoleak in waitid(2)
kernel_waitid() can return a PID, an error or 0. rusage is filled in the first
case and waitid(2) rusage should've been copied out exactly in that case, *not*
whenever kernel_waitid() has not returned an error. Compat variant shares that
braino; none of kernel_wait4() callers do, so the below ought to fix it.
Reported-and-tested-by: Alexander Potapenko <[email protected]>
Fixes: ce72a16fa705 ("wait4(2)/waitid(2): separate copying rusage to userland")
Cc: [email protected] # v4.13
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: sysapi_translate_arch( const char *machine, const char *)
{
char tmp[64];
char *tmparch;
#if defined(AIX)
/* AIX machines have a ton of different models encoded into the uname
structure, so go to some other function to decode and group the
architecture together */
struct utsname buf;
if( uname(&buf) < 0 ) {
return NULL;
}
return( get_aix_arch( &buf ) );
#elif defined(HPUX)
return( get_hpux_arch( ) );
#else
if( !strcmp(machine, "alpha") ) {
sprintf( tmp, "ALPHA" );
}
else if( !strcmp(machine, "i86pc") ) {
sprintf( tmp, "INTEL" );
}
else if( !strcmp(machine, "i686") ) {
sprintf( tmp, "INTEL" );
}
else if( !strcmp(machine, "i586") ) {
sprintf( tmp, "INTEL" );
}
else if( !strcmp(machine, "i486") ) {
sprintf( tmp, "INTEL" );
}
else if( !strcmp(machine, "i386") ) { //LDAP entry
#if defined(Darwin)
/* Mac OS X often claims to be i386 in uname, even if the
* hardware is x86_64 and the OS can run 64-bit binaries.
* We'll base our architecture name on the default build
* target for gcc. In 10.5 and earlier, that's i386.
* On 10.6, it's x86_64.
* The value we're querying is the kernel version.
* 10.6 kernels have a version that starts with "10."
* Older versions have a lower first number.
*/
int ret;
char val[32];
size_t len = sizeof(val);
/* assume x86 */
sprintf( tmp, "INTEL" );
ret = sysctlbyname("kern.osrelease", &val, &len, NULL, 0);
if (ret == 0 && strncmp(val, "10.", 3) == 0) {
/* but we could be proven wrong */
sprintf( tmp, "X86_64" );
}
#else
sprintf( tmp, "INTEL" );
#endif
}
else if( !strcmp(machine, "ia64") ) {
sprintf( tmp, "IA64" );
}
else if( !strcmp(machine, "x86_64") ) {
sprintf( tmp, "X86_64" );
}
else if( !strcmp(machine, "amd64") ) {
sprintf( tmp, "X86_64" );
}
else if( !strcmp(machine, "sun4u") ) {
sprintf( tmp, "SUN4u" );
}
else if( !strcmp(machine, "sun4m") ) {
sprintf( tmp, "SUN4x" );
}
else if( !strcmp(machine, "sun4c") ) {
sprintf( tmp, "SUN4x" );
}
else if( !strcmp(machine, "sparc") ) { //LDAP entry
sprintf( tmp, "SUN4x" );
}
else if( !strcmp(machine, "Power Macintosh") ) { //LDAP entry
sprintf( tmp, "PPC" );
}
else if( !strcmp(machine, "ppc") ) {
sprintf( tmp, "PPC" );
}
else if( !strcmp(machine, "ppc32") ) {
sprintf( tmp, "PPC" );
}
else if( !strcmp(machine, "ppc64") ) {
sprintf( tmp, "PPC64" );
}
else {
sprintf( tmp, machine );
}
tmparch = strdup( tmp );
if( !tmparch ) {
EXCEPT( "Out of memory!" );
}
return( tmparch );
#endif /* if HPUX else */
}
Commit Message:
CWE ID: CWE-134
Target: 1
Example 2:
Code: static void regulator_dev_release(struct device *dev)
{
struct regulator_dev *rdev = dev_get_drvdata(dev);
kfree(rdev);
}
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 <[email protected]>
Signed-off-by: Mark Brown <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: in_upper_context(int depth, int context, xmlNode * xml_node)
{
if (context == 0) {
return 0;
}
if (xml_node->properties) {
return depth;
} else if (depth < context) {
xmlNode *child = NULL;
for (child = __xml_first_child(xml_node); child != NULL; child = __xml_next(child)) {
if (in_upper_context(depth + 1, context, child)) {
return depth;
}
}
}
return 0;
}
Commit Message: Fix: acl: Do not delay evaluation of added nodes in some situations
It is not appropriate when the node has no children as it is not a
placeholder
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: build_principal_va(krb5_context context, krb5_principal princ,
unsigned int rlen, const char *realm, va_list ap)
{
krb5_error_code retval = 0;
char *r = NULL;
krb5_data *data = NULL;
krb5_int32 count = 0;
krb5_int32 size = 2; /* initial guess at needed space */
char *component = NULL;
data = malloc(size * sizeof(krb5_data));
if (!data) { retval = ENOMEM; }
if (!retval) {
r = strdup(realm);
if (!r) { retval = ENOMEM; }
}
while (!retval && (component = va_arg(ap, char *))) {
if (count == size) {
krb5_data *new_data = NULL;
size *= 2;
new_data = realloc(data, size * sizeof(krb5_data));
if (new_data) {
data = new_data;
} else {
retval = ENOMEM;
}
}
if (!retval) {
data[count].length = strlen(component);
data[count].data = strdup(component);
if (!data[count].data) { retval = ENOMEM; }
count++;
}
}
if (!retval) {
princ->type = KRB5_NT_UNKNOWN;
princ->magic = KV5M_PRINCIPAL;
princ->realm = make_data(r, rlen);
princ->data = data;
princ->length = count;
r = NULL; /* take ownership */
data = NULL; /* take ownership */
}
if (data) {
while (--count >= 0) {
free(data[count].data);
}
free(data);
}
free(r);
return retval;
}
Commit Message: Fix build_principal memory bug [CVE-2015-2697]
In build_principal_va(), use k5memdup0() instead of strdup() to make a
copy of the realm, to ensure that we allocate the correct number of
bytes and do not read past the end of the input string. This bug
affects krb5_build_principal(), krb5_build_principal_va(), and
krb5_build_principal_alloc_va(). krb5_build_principal_ext() is not
affected.
CVE-2015-2697:
In MIT krb5 1.7 and later, an authenticated attacker may be able to
cause a KDC to crash using a TGS request with a large realm field
beginning with a null byte. If the KDC attempts to find a referral to
answer the request, it constructs a principal name for lookup using
krb5_build_principal() with the requested realm. Due to a bug in this
function, the null byte causes only one byte be allocated for the
realm field of the constructed principal, far less than its length.
Subsequent operations on the lookup principal may cause a read beyond
the end of the mapped memory region, causing the KDC process to crash.
CVSSv2: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8252 (new)
target_version: 1.14
tags: pullup
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int nfs_invalidate_mapping_nolock(struct inode *inode, struct address_space *mapping)
{
struct nfs_inode *nfsi = NFS_I(inode);
if (mapping->nrpages != 0) {
int ret = invalidate_inode_pages2(mapping);
if (ret < 0)
return ret;
}
spin_lock(&inode->i_lock);
nfsi->cache_validity &= ~NFS_INO_INVALID_DATA;
if (S_ISDIR(inode->i_mode))
memset(nfsi->cookieverf, 0, sizeof(nfsi->cookieverf));
spin_unlock(&inode->i_lock);
nfs_inc_stats(inode, NFSIOS_DATAINVALIDATE);
dfprintk(PAGECACHE, "NFS: (%s/%Ld) data cache invalidated\n",
inode->i_sb->s_id, (long long)NFS_FILEID(inode));
return 0;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RTCPeerConnection::createOffer(PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback, const Dictionary& mediaConstraints, ExceptionCode& ec)
{
if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) {
ec = INVALID_STATE_ERR;
return;
}
if (!successCallback) {
ec = TYPE_MISMATCH_ERR;
return;
}
RefPtr<MediaConstraints> constraints = MediaConstraintsImpl::create(mediaConstraints, ec);
if (ec)
return;
RefPtr<RTCSessionDescriptionRequestImpl> request = RTCSessionDescriptionRequestImpl::create(scriptExecutionContext(), successCallback, errorCallback);
m_peerHandler->createOffer(request.release(), constraints);
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CSSDefaultStyleSheets::loadFullDefaultStyle()
{
if (simpleDefaultStyleSheet) {
ASSERT(defaultStyle);
ASSERT(defaultPrintStyle == defaultStyle);
delete defaultStyle;
simpleDefaultStyleSheet->deref();
defaultStyle = RuleSet::create().leakPtr();
defaultPrintStyle = RuleSet::create().leakPtr();
simpleDefaultStyleSheet = 0;
} else {
ASSERT(!defaultStyle);
defaultStyle = RuleSet::create().leakPtr();
defaultPrintStyle = RuleSet::create().leakPtr();
defaultQuirksStyle = RuleSet::create().leakPtr();
}
String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet();
defaultStyleSheet = parseUASheet(defaultRules);
defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval());
defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());
String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet();
quirksStyleSheet = parseUASheet(quirksRules);
defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
}
Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun.
We've been bitten by the Simple Default Stylesheet being out
of sync with the real html.css twice this week.
The Simple Default Stylesheet was invented years ago for Mac:
http://trac.webkit.org/changeset/36135
It nicely handles the case where you just want to create
a single WebView and parse some simple HTML either without
styling said HTML, or only to display a small string, etc.
Note that this optimization/complexity *only* helps for the
very first document, since the default stylesheets are
all static (process-global) variables. Since any real page
on the internet uses a tag not covered by the simple default
stylesheet, not real load benefits from this optimization.
Only uses of WebView which were just rendering small bits
of text might have benefited from this. about:blank would
also have used this sheet.
This was a common application for some uses of WebView back
in those days. These days, even with WebView on Android,
there are likely much larger overheads than parsing the
html.css stylesheet, so making it required seems like the
right tradeoff of code-simplicity for this case.
BUG=319556
Review URL: https://codereview.chromium.org/73723005
git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 1
Example 2:
Code: png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
png_size_t buffer_length)
{
png_ptr->current_buffer = buffer;
png_ptr->current_buffer_size = buffer_length;
png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
png_ptr->current_buffer_ptr = png_ptr->current_buffer;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Image *ReadWBMPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
int
byte;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
bit;
unsigned short
header;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (ReadBlob(image,2,(unsigned char *) &header) == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (header != 0)
ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported");
/*
Initialize image structure.
*/
if (WBMPReadInteger(image,&image->columns) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if (WBMPReadInteger(image,&image->rows) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert bi-level image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
{
byte=ReadBlobByte(image);
if (byte == EOF)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 1 : 0);
bit++;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: jbig2_sd_count_referred(Jbig2Ctx *ctx, Jbig2Segment *segment)
{
int index;
Jbig2Segment *rsegment;
int n_dicts = 0;
for (index = 0; index < segment->referred_to_segment_count; index++) {
rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]);
if (rsegment && ((rsegment->flags & 63) == 0) &&
rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL))
n_dicts++;
}
return (n_dicts);
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: UserSelectionScreen::~UserSelectionScreen() {
proximity_auth::ScreenlockBridge::Get()->SetLockHandler(nullptr);
ui::UserActivityDetector* activity_detector = ui::UserActivityDetector::Get();
if (activity_detector && activity_detector->HasObserver(this))
activity_detector->RemoveObserver(this);
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ShelfLayoutManager::OnLockStateChanged(bool locked) {
UpdateVisibilityState();
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long AudioTrack::Parse(Segment* pSegment, const Info& info,
long long element_start, long long element_size,
AudioTrack*& pResult) {
if (pResult)
return -1;
if (info.type != Track::kAudio)
return -1;
IMkvReader* const pReader = pSegment->m_pReader;
const Settings& s = info.settings;
assert(s.start >= 0);
assert(s.size >= 0);
long long pos = s.start;
assert(pos >= 0);
const long long stop = pos + s.size;
double rate = 8000.0; // MKV default
long long channels = 1;
long long bit_depth = 0;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x35) { // Sample Rate
status = UnserializeFloat(pReader, pos, size, rate);
if (status < 0)
return status;
if (rate <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x1F) { // Channel Count
channels = UnserializeUInt(pReader, pos, size);
if (channels <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x2264) { // Bit Depth
bit_depth = UnserializeUInt(pReader, pos, size);
if (bit_depth <= 0)
return E_FILE_FORMAT_INVALID;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
AudioTrack* const pTrack =
new (std::nothrow) AudioTrack(pSegment, element_start, element_size);
if (pTrack == NULL)
return -1; // generic error
const int status = info.Copy(pTrack->m_info);
if (status) {
delete pTrack;
return status;
}
pTrack->m_rate = rate;
pTrack->m_channels = channels;
pTrack->m_bitDepth = bit_depth;
pResult = pTrack;
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
Target: 1
Example 2:
Code: static inline int deliver_skb(struct sk_buff *skb,
struct packet_type *pt_prev,
struct net_device *orig_dev)
{
atomic_inc(&skb->users);
return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
}
Commit Message: veth: Dont kfree_skb() after dev_forward_skb()
In case of congestion, netif_rx() frees the skb, so we must assume
dev_forward_skb() also consume skb.
Bug introduced by commit 445409602c092
(veth: move loopback logic to common location)
We must change dev_forward_skb() to always consume skb, and veth to not
double free it.
Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3
Reported-by: Martín Ferrari <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void v9fs_device_unrealize_common(V9fsState *s, Error **errp)
{
g_free(s->ctx.fs_root);
g_free(s->tag);
}
Commit Message:
CWE ID: CWE-400
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
{
if (isMainThread()) {
blobRegistry().addDataToStream(url, streamData);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
callOnMainThread(&addDataToStreamTask, context.leakPtr());
}
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 1
Example 2:
Code: presym_free_symlists ()
{
lt_dlsymlists_t *lists;
LT_DLMUTEX_LOCK ();
lists = preloaded_symbols;
while (lists)
{
lt_dlsymlists_t *tmp = lists;
lists = lists->next;
LT_DLFREE (tmp);
}
preloaded_symbols = 0;
LT_DLMUTEX_UNLOCK ();
return 0;
}
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void snd_pcm_set_sync(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
runtime->sync.id32[0] = substream->pcm->card->number;
runtime->sync.id32[1] = -1;
runtime->sync.id32[2] = -1;
runtime->sync.id32[3] = -1;
}
Commit Message: ALSA: pcm : Call kill_fasync() in stream lock
Currently kill_fasync() is called outside the stream lock in
snd_pcm_period_elapsed(). This is potentially racy, since the stream
may get released even during the irq handler is running. Although
snd_pcm_release_substream() calls snd_pcm_drop(), this doesn't
guarantee that the irq handler finishes, thus the kill_fasync() call
outside the stream spin lock may be invoked after the substream is
detached, as recently reported by KASAN.
As a quick workaround, move kill_fasync() call inside the stream
lock. The fasync is rarely used interface, so this shouldn't have a
big impact from the performance POV.
Ideally, we should implement some sync mechanism for the proper finish
of stream and irq handler. But this oneliner should suffice for most
cases, so far.
Reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
const char
*option;
Image
*image;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
opj_codestream_index_t
*codestream_index = (opj_codestream_index_t *) NULL;
opj_dparameters_t
parameters;
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned char
sans[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JP2 codec.
*/
if (ReadBlob(image,4,sans) != 4)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SeekBlob(image,SEEK_SET,0);
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
else
if (IsJ2K(sans,4) != MagickFalse)
jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_set_default_decoder_parameters(¶meters);
option=GetImageOption(image_info,"jp2:reduce-factor");
if (option != (const char *) NULL)
parameters.cp_reduce=StringToInteger(option);
option=GetImageOption(image_info,"jp2:quality-layers");
if (option == (const char *) NULL)
option=GetImageOption(image_info,"jp2:layer-number");
if (option != (const char *) NULL)
parameters.cp_layer=StringToInteger(option);
if (opj_setup_decoder(jp2_codec,¶meters) == 0)
{
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
}
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
jp2_status=1;
if ((image->columns != 0) && (image->rows != 0))
{
/*
Extract an area from the image.
*/
jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
(OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
(OPJ_INT32) image->extract_info.x+(ssize_t) image->columns,
(OPJ_INT32) image->extract_info.y+(ssize_t) image->rows);
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
}
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
(unsigned int) image_info->scene-1);
else
if (image->ping == MagickFalse)
{
jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
if (jp2_status != 0)
jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
}
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
opj_stream_destroy(jp2_stream);
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0))
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
}
}
/*
Convert JP2 image.
*/
image->columns=(size_t) jp2_image->comps[0].w;
image->rows=(size_t) jp2_image->comps[0].h;
image->depth=jp2_image->comps[0].prec;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->compression=JPEG2000Compression;
if (jp2_image->color_space == 2)
{
SetImageColorspace(image,GRAYColorspace);
if (jp2_image->numcomps > 1)
image->matte=MagickTrue;
}
else
if (jp2_image->color_space == 3)
SetImageColorspace(image,Rec601YCbCrColorspace);
if (jp2_image->numcomps > 3)
image->matte=MagickTrue;
if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
{
StringInfo
*profile;
profile=BlobToStringInfo(jp2_image->icc_profile_buf,
jp2_image->icc_profile_len);
if (profile != (StringInfo *) NULL)
SetImageProfile(image,"icc",profile);
}
if (image->ping != MagickFalse)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
return(GetFirstImageInList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
double
pixel,
scale;
scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
(jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
switch (i)
{
case 0:
{
q->red=ClampToQuantum(pixel);
q->green=q->red;
q->blue=q->red;
q->opacity=OpaqueOpacity;
break;
}
case 1:
{
if (jp2_image->numcomps == 2)
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
q->green=ClampToQuantum(pixel);
break;
}
case 2:
{
q->blue=ClampToQuantum(pixel);
break;
}
case 3:
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free resources.
*/
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: ...
CWE ID: CWE-20
Target: 1
Example 2:
Code: void DebuggerSendCommandFunction::SendDetachedError() {
error_ = debugger_api_constants::kDetachedWhileHandlingError;
SendResponse(false);
}
Commit Message: [DevTools] Do not allow Page.setDownloadBehavior for extensions
Bug: 866426
Change-Id: I71b672978e1a8ec779ede49da16b21198567d3a4
Reviewed-on: https://chromium-review.googlesource.com/c/1270007
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598004}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int common_timer_set(struct k_itimer *timr, int flags,
struct itimerspec64 *new_setting,
struct itimerspec64 *old_setting)
{
const struct k_clock *kc = timr->kclock;
bool sigev_none;
ktime_t expires;
if (old_setting)
common_timer_get(timr, old_setting);
/* Prevent rearming by clearing the interval */
timr->it_interval = 0;
/*
* Careful here. On SMP systems the timer expiry function could be
* active and spinning on timr->it_lock.
*/
if (kc->timer_try_to_cancel(timr) < 0)
return TIMER_RETRY;
timr->it_active = 0;
timr->it_requeue_pending = (timr->it_requeue_pending + 2) &
~REQUEUE_PENDING;
timr->it_overrun_last = 0;
/* Switch off the timer when it_value is zero */
if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec)
return 0;
timr->it_interval = timespec64_to_ktime(new_setting->it_interval);
expires = timespec64_to_ktime(new_setting->it_value);
sigev_none = (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE;
kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none);
timr->it_active = !sigev_none;
return 0;
}
Commit Message: posix-timer: Properly check sigevent->sigev_notify
timer_create() specifies via sigevent->sigev_notify the signal delivery for
the new timer. The valid modes are SIGEV_NONE, SIGEV_SIGNAL, SIGEV_THREAD
and (SIGEV_SIGNAL | SIGEV_THREAD_ID).
The sanity check in good_sigevent() is only checking the valid combination
for the SIGEV_THREAD_ID bit, i.e. SIGEV_SIGNAL, but if SIGEV_THREAD_ID is
not set it accepts any random value.
This has no real effects on the posix timer and signal delivery code, but
it affects show_timer() which handles the output of /proc/$PID/timers. That
function uses a string array to pretty print sigev_notify. The access to
that array has no bound checks, so random sigev_notify cause access beyond
the array bounds.
Add proper checks for the valid notify modes and remove the SIGEV_THREAD_ID
masking from various code pathes as SIGEV_NONE can never be set in
combination with SIGEV_THREAD_ID.
Reported-by: Eric Biggers <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Reported-by: Alexey Dobriyan <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: John Stultz <[email protected]>
Cc: [email protected]
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages)
{
unsigned long i;
for (i = 0; i < npages; ++i)
kvm_release_pfn_clean(pfn + i);
}
Commit Message: kvm: iommu: fix the third parameter of kvm_iommu_put_pages (CVE-2014-3601)
The third parameter of kvm_iommu_put_pages is wrong,
It should be 'gfn - slot->base_gfn'.
By making gfn very large, malicious guest or userspace can cause kvm to
go to this error path, and subsequently to pass a huge value as size.
Alternatively if gfn is small, then pages would be pinned but never
unpinned, causing host memory leak and local DOS.
Passing a reasonable but large value could be the most dangerous case,
because it would unpin a page that should have stayed pinned, and thus
allow the device to DMA into arbitrary memory. However, this cannot
happen because of the condition that can trigger the error:
- out of memory (where you can't allocate even a single page)
should not be possible for the attacker to trigger
- when exceeding the iommu's address space, guest pages after gfn
will also exceed the iommu's address space, and inside
kvm_iommu_put_pages() the iommu_iova_to_phys() will fail. The
page thus would not be unpinned at all.
Reported-by: Jack Morgenstein <[email protected]>
Cc: [email protected]
Signed-off-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value, int protocol)
{
struct dwc3_gadget_ep_cmd_params params;
struct dwc3 *dwc = dep->dwc;
int ret;
if (usb_endpoint_xfer_isoc(dep->endpoint.desc)) {
dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
return -EINVAL;
}
memset(¶ms, 0x00, sizeof(params));
if (value) {
struct dwc3_trb *trb;
unsigned transfer_in_flight;
unsigned started;
if (dep->flags & DWC3_EP_STALL)
return 0;
if (dep->number > 1)
trb = dwc3_ep_prev_trb(dep, dep->trb_enqueue);
else
trb = &dwc->ep0_trb[dep->trb_enqueue];
transfer_in_flight = trb->ctrl & DWC3_TRB_CTRL_HWO;
started = !list_empty(&dep->started_list);
if (!protocol && ((dep->direction && transfer_in_flight) ||
(!dep->direction && started))) {
return -EAGAIN;
}
ret = dwc3_send_gadget_ep_cmd(dep, DWC3_DEPCMD_SETSTALL,
¶ms);
if (ret)
dev_err(dwc->dev, "failed to set STALL on %s\n",
dep->name);
else
dep->flags |= DWC3_EP_STALL;
} else {
if (!(dep->flags & DWC3_EP_STALL))
return 0;
ret = dwc3_send_clear_stall_ep_cmd(dep);
if (ret)
dev_err(dwc->dev, "failed to clear STALL on %s\n",
dep->name);
else
dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
}
return ret;
}
Commit Message: usb: dwc3: gadget: never call ->complete() from ->ep_queue()
This is a requirement which has always existed but, somehow, wasn't
reflected in the documentation and problems weren't found until now
when Tuba Yavuz found a possible deadlock happening between dwc3 and
f_hid. She described the situation as follows:
spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire
/* we our function has been disabled by host */
if (!hidg->req) {
free_ep_req(hidg->in_ep, hidg->req);
goto try_again;
}
[...]
status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC);
=>
[...]
=> usb_gadget_giveback_request
=>
f_hidg_req_complete
=>
spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire
Note that this happens because dwc3 would call ->complete() on a
failed usb_ep_queue() due to failed Start Transfer command. This is,
anyway, a theoretical situation because dwc3 currently uses "No
Response Update Transfer" command for Bulk and Interrupt endpoints.
It's still good to make this case impossible to happen even if the "No
Reponse Update Transfer" command is changed.
Reported-by: Tuba Yavuz <[email protected]>
Signed-off-by: Felipe Balbi <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: pcf_read_TOC( FT_Stream stream,
PCF_Face face )
{
FT_Error error;
PCF_Toc toc = &face->toc;
PCF_Table tables;
FT_Memory memory = FT_FACE( face )->memory;
FT_UInt n;
if ( FT_STREAM_SEEK ( 0 ) ||
FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) )
return FT_THROW( Cannot_Open_Resource );
if ( toc->version != PCF_FILE_VERSION ||
toc->count > FT_ARRAY_MAX( face->toc.tables ) ||
toc->count == 0 )
return FT_THROW( Invalid_File_Format );
if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) )
return FT_THROW( Out_Of_Memory );
tables = face->toc.tables;
for ( n = 0; n < toc->count; n++ )
{
if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) )
goto Exit;
tables++;
}
/* Sort tables and check for overlaps. Because they are almost */
/* always ordered already, an in-place bubble sort with simultaneous */
/* boundary checking seems appropriate. */
tables = face->toc.tables;
for ( n = 0; n < toc->count - 1; n++ )
{
FT_UInt i, have_change;
have_change = 0;
for ( i = 0; i < toc->count - 1 - n; i++ )
{
PCF_TableRec tmp;
if ( tables[i].offset > tables[i + 1].offset )
{
tmp = tables[i];
tables[i] = tables[i + 1];
tables[i + 1] = tmp;
have_change = 1;
}
if ( ( tables[i].size > tables[i + 1].offset ) ||
( tables[i].offset > tables[i + 1].offset - tables[i].size ) )
{
error = FT_THROW( Invalid_Offset );
goto Exit;
}
}
if ( !have_change )
break;
}
#ifdef FT_DEBUG_LEVEL_TRACE
{
FT_TRACE4(( " %d: type=%s, format=0x%X, "
"size=%ld (0x%lX), offset=%ld (0x%lX)\n",
i, name,
tables[i].format,
tables[i].size, tables[i].size,
tables[i].offset, tables[i].offset ));
}
}
Commit Message:
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int read_tfra(MOVContext *mov, AVIOContext *f)
{
MOVFragmentIndex* index = NULL;
int version, fieldlength, i, j;
int64_t pos = avio_tell(f);
uint32_t size = avio_rb32(f);
void *tmp;
if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
return 1;
}
av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
index = av_mallocz(sizeof(MOVFragmentIndex));
if (!index) {
return AVERROR(ENOMEM);
}
tmp = av_realloc_array(mov->fragment_index_data,
mov->fragment_index_count + 1,
sizeof(MOVFragmentIndex*));
if (!tmp) {
av_freep(&index);
return AVERROR(ENOMEM);
}
mov->fragment_index_data = tmp;
mov->fragment_index_data[mov->fragment_index_count++] = index;
version = avio_r8(f);
avio_rb24(f);
index->track_id = avio_rb32(f);
fieldlength = avio_rb32(f);
index->item_count = avio_rb32(f);
index->items = av_mallocz_array(
index->item_count, sizeof(MOVFragmentIndexItem));
if (!index->items) {
index->item_count = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < index->item_count; i++) {
int64_t time, offset;
if (version == 1) {
time = avio_rb64(f);
offset = avio_rb64(f);
} else {
time = avio_rb32(f);
offset = avio_rb32(f);
}
index->items[i].time = time;
index->items[i].moof_offset = offset;
for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
avio_r8(f);
for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
avio_r8(f);
for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
avio_r8(f);
}
avio_seek(f, pos + size, SEEK_SET);
return 0;
}
Commit Message: avformat/mov: Fix DoS in read_tfra()
Fixes: Missing EOF check in loop
No testcase
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-834
Target: 1
Example 2:
Code: static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
{
cfs_rq->tasks_timeline = RB_ROOT;
INIT_LIST_HEAD(&cfs_rq->tasks);
#ifdef CONFIG_FAIR_GROUP_SCHED
cfs_rq->rq = rq;
#endif
cfs_rq->min_vruntime = (u64)(-(1LL << 20));
}
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 <[email protected]>
Reported-by: Bjoern B. Brandenburg <[email protected]>
Tested-by: Yong Zhang <[email protected]>
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: [email protected]
LKML-Reference: <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void set_request_type(MediaStreamRequestType type) { request_type_ = type; }
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len,
RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value,
const RBinDwarfCompUnitHdr *hdr,
const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf;
const ut8 *buf_end = obuf + obuf_len;
size_t j;
if (!spec || !value || !hdr || !obuf || obuf_len < 0) {
return NULL;
}
value->form = spec->attr_form;
value->name = spec->attr_name;
value->encoding.block.data = NULL;
value->encoding.str_struct.string = NULL;
value->encoding.str_struct.offset = 0;
switch (spec->attr_form) {
case DW_FORM_addr:
switch (hdr->pointer_size) {
case 1:
value->encoding.address = READ (buf, ut8);
break;
case 2:
value->encoding.address = READ (buf, ut16);
break;
case 4:
value->encoding.address = READ (buf, ut32);
break;
case 8:
value->encoding.address = READ (buf, ut64);
break;
default:
eprintf("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size);
return NULL;
}
break;
case DW_FORM_block2:
value->encoding.block.length = READ (buf, ut16);
if (value->encoding.block.length > 0) {
value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_block4:
value->encoding.block.length = READ (buf, ut32);
if (value->encoding.block.length > 0) {
ut8 *data = calloc (sizeof (ut8), value->encoding.block.length);
if (data) {
for (j = 0; j < value->encoding.block.length; j++) {
data[j] = READ (buf, ut8);
}
}
value->encoding.block.data = data;
}
break;
//// This causes segfaults to happen
case DW_FORM_data2:
value->encoding.data = READ (buf, ut16);
break;
case DW_FORM_data4:
value->encoding.data = READ (buf, ut32);
break;
case DW_FORM_data8:
value->encoding.data = READ (buf, ut64);
break;
case DW_FORM_string:
value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL;
buf += (strlen ((const char*)buf) + 1);
break;
case DW_FORM_block:
buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length);
if (!buf) {
return NULL;
}
value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
break;
case DW_FORM_block1:
value->encoding.block.length = READ (buf, ut8);
value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
break;
case DW_FORM_flag:
value->encoding.flag = READ (buf, ut8);
break;
case DW_FORM_sdata:
buf = r_leb128 (buf, &value->encoding.sdata);
break;
case DW_FORM_strp:
value->encoding.str_struct.offset = READ (buf, ut32);
if (debug_str && value->encoding.str_struct.offset < debug_str_len) {
value->encoding.str_struct.string = strdup (
(const char *)(debug_str +
value->encoding.str_struct.offset));
} else {
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_udata:
{
ut64 ndata = 0;
const ut8 *data = (const ut8*)&ndata;
buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata);
memcpy (&value->encoding.data, data, sizeof (value->encoding.data));
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_ref_addr:
value->encoding.reference = READ (buf, ut64); // addr size of machine
break;
case DW_FORM_ref1:
value->encoding.reference = READ (buf, ut8);
break;
case DW_FORM_ref2:
value->encoding.reference = READ (buf, ut16);
break;
case DW_FORM_ref4:
value->encoding.reference = READ (buf, ut32);
break;
case DW_FORM_ref8:
value->encoding.reference = READ (buf, ut64);
break;
case DW_FORM_data1:
value->encoding.data = READ (buf, ut8);
break;
default:
eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form);
value->encoding.data = 0;
return NULL;
}
return buf;
}
Commit Message: Fix #8813 - segfault in dwarf parser
CWE ID: CWE-125
Target: 1
Example 2:
Code: const char* PropStateToString(int prop_state) {
switch (static_cast<IBusPropState>(prop_state)) {
case PROP_STATE_UNCHECKED:
return "UNCHECKED";
case PROP_STATE_CHECKED:
return "CHECKED";
case PROP_STATE_INCONSISTENT:
return "INCONSISTENT";
}
return "UNKNOWN";
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: test_bson_steal (void)
{
bson_t stack_alloced;
bson_t *heap_alloced;
bson_t dst;
uint8_t *alloc;
uint8_t *buf;
size_t len;
uint32_t len_le;
/* inline, stack-allocated */
bson_init (&stack_alloced);
BSON_APPEND_INT32 (&stack_alloced, "a", 1);
ASSERT (bson_steal (&dst, &stack_alloced));
ASSERT (bson_has_field (&dst, "a"));
ASSERT (dst.flags & BSON_FLAG_INLINE);
/* src was invalidated */
ASSERT (!bson_validate (&stack_alloced, BSON_VALIDATE_NONE, 0));
bson_destroy (&dst);
/* spilled over, stack-allocated */
bson_init (&stack_alloced);
bloat (&stack_alloced);
alloc = ((bson_impl_alloc_t *) &stack_alloced)->alloc;
ASSERT (bson_steal (&dst, &stack_alloced));
/* data was transferred */
ASSERT (alloc == ((bson_impl_alloc_t *) &dst)->alloc);
ASSERT (bson_has_field (&dst, "99"));
ASSERT (!(dst.flags & BSON_FLAG_INLINE));
ASSERT (!bson_validate (&stack_alloced, BSON_VALIDATE_NONE, 0));
bson_destroy (&dst);
/* inline, heap-allocated */
heap_alloced = bson_new ();
BSON_APPEND_INT32 (heap_alloced, "a", 1);
ASSERT (bson_steal (&dst, heap_alloced));
ASSERT (bson_has_field (&dst, "a"));
ASSERT (dst.flags & BSON_FLAG_INLINE);
bson_destroy (&dst);
/* spilled over, heap-allocated */
heap_alloced = bson_new ();
bloat (heap_alloced);
alloc = ((bson_impl_alloc_t *) heap_alloced)->alloc;
ASSERT (bson_steal (&dst, heap_alloced));
/* data was transferred */
ASSERT (alloc == ((bson_impl_alloc_t *) &dst)->alloc);
ASSERT (bson_has_field (&dst, "99"));
ASSERT (!(dst.flags & BSON_FLAG_INLINE));
bson_destroy (&dst);
/* test stealing from a bson created with bson_new_from_buffer */
buf = bson_malloc0 (5);
len = 5;
len_le = BSON_UINT32_TO_LE (5);
memcpy (buf, &len_le, sizeof (len_le));
heap_alloced = bson_new_from_buffer (&buf, &len, bson_realloc_ctx, NULL);
ASSERT (bson_steal (&dst, heap_alloced));
ASSERT (dst.flags & BSON_FLAG_NO_FREE);
ASSERT (dst.flags & BSON_FLAG_STATIC);
ASSERT (((bson_impl_alloc_t *) &dst)->realloc == bson_realloc_ctx);
ASSERT (((bson_impl_alloc_t *) &dst)->realloc_func_ctx == NULL);
bson_destroy (&dst);
bson_free (buf);
}
Commit Message: Fix for CVE-2018-16790 -- Verify bounds before binary length read.
As reported here: https://jira.mongodb.org/browse/CDRIVER-2819,
a heap overread occurs due a failure to correctly verify data
bounds.
In the original check, len - o returns the data left including the
sizeof(l) we just read. Instead, the comparison should check
against the data left NOT including the binary int32, i.e. just
subtype (byte*) instead of int32 subtype (byte*).
Added in test for corrupted BSON example.
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata,
const u8 *addr, gfp_t gfp)
{
struct ieee80211_local *local = sdata->local;
struct sta_info *sta;
struct timespec uptime;
struct ieee80211_tx_latency_bin_ranges *tx_latency;
int i;
sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp);
if (!sta)
return NULL;
rcu_read_lock();
tx_latency = rcu_dereference(local->tx_latency);
/* init stations Tx latency statistics && TID bins */
if (tx_latency) {
sta->tx_lat = kzalloc(IEEE80211_NUM_TIDS *
sizeof(struct ieee80211_tx_latency_stat),
GFP_ATOMIC);
if (!sta->tx_lat) {
rcu_read_unlock();
goto free;
}
if (tx_latency->n_ranges) {
for (i = 0; i < IEEE80211_NUM_TIDS; i++) {
/* size of bins is size of the ranges +1 */
sta->tx_lat[i].bin_count =
tx_latency->n_ranges + 1;
sta->tx_lat[i].bins =
kcalloc(sta->tx_lat[i].bin_count,
sizeof(u32), GFP_ATOMIC);
if (!sta->tx_lat[i].bins) {
rcu_read_unlock();
goto free;
}
}
}
}
rcu_read_unlock();
spin_lock_init(&sta->lock);
INIT_WORK(&sta->drv_unblock_wk, sta_unblock);
INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work);
mutex_init(&sta->ampdu_mlme.mtx);
#ifdef CONFIG_MAC80211_MESH
if (ieee80211_vif_is_mesh(&sdata->vif) &&
!sdata->u.mesh.user_mpm)
init_timer(&sta->plink_timer);
sta->nonpeer_pm = NL80211_MESH_POWER_ACTIVE;
#endif
memcpy(sta->sta.addr, addr, ETH_ALEN);
sta->local = local;
sta->sdata = sdata;
sta->last_rx = jiffies;
sta->sta_state = IEEE80211_STA_NONE;
do_posix_clock_monotonic_gettime(&uptime);
sta->last_connected = uptime.tv_sec;
ewma_init(&sta->avg_signal, 1024, 8);
for (i = 0; i < ARRAY_SIZE(sta->chain_signal_avg); i++)
ewma_init(&sta->chain_signal_avg[i], 1024, 8);
if (sta_prepare_rate_control(local, sta, gfp))
goto free;
for (i = 0; i < IEEE80211_NUM_TIDS; i++) {
/*
* timer_to_tid must be initialized with identity mapping
* to enable session_timer's data differentiation. See
* sta_rx_agg_session_timer_expired for usage.
*/
sta->timer_to_tid[i] = i;
}
for (i = 0; i < IEEE80211_NUM_ACS; i++) {
skb_queue_head_init(&sta->ps_tx_buf[i]);
skb_queue_head_init(&sta->tx_filtered[i]);
}
for (i = 0; i < IEEE80211_NUM_TIDS; i++)
sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX);
sta->sta.smps_mode = IEEE80211_SMPS_OFF;
if (sdata->vif.type == NL80211_IFTYPE_AP ||
sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
struct ieee80211_supported_band *sband =
local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)];
u8 smps = (sband->ht_cap.cap & IEEE80211_HT_CAP_SM_PS) >>
IEEE80211_HT_CAP_SM_PS_SHIFT;
/*
* Assume that hostapd advertises our caps in the beacon and
* this is the known_smps_mode for a station that just assciated
*/
switch (smps) {
case WLAN_HT_SMPS_CONTROL_DISABLED:
sta->known_smps_mode = IEEE80211_SMPS_OFF;
break;
case WLAN_HT_SMPS_CONTROL_STATIC:
sta->known_smps_mode = IEEE80211_SMPS_STATIC;
break;
case WLAN_HT_SMPS_CONTROL_DYNAMIC:
sta->known_smps_mode = IEEE80211_SMPS_DYNAMIC;
break;
default:
WARN_ON(1);
}
}
sta_dbg(sdata, "Allocated STA %pM\n", sta->sta.addr);
return sta;
free:
if (sta->tx_lat) {
for (i = 0; i < IEEE80211_NUM_TIDS; i++)
kfree(sta->tx_lat[i].bins);
kfree(sta->tx_lat);
}
kfree(sta);
return NULL;
}
Commit Message: mac80211: fix AP powersave TX vs. wakeup race
There is a race between the TX path and the STA wakeup: while
a station is sleeping, mac80211 buffers frames until it wakes
up, then the frames are transmitted. However, the RX and TX
path are concurrent, so the packet indicating wakeup can be
processed while a packet is being transmitted.
This can lead to a situation where the buffered frames list
is emptied on the one side, while a frame is being added on
the other side, as the station is still seen as sleeping in
the TX path.
As a result, the newly added frame will not be send anytime
soon. It might be sent much later (and out of order) when the
station goes to sleep and wakes up the next time.
Additionally, it can lead to the crash below.
Fix all this by synchronising both paths with a new lock.
Both path are not fastpath since they handle PS situations.
In a later patch we'll remove the extra skb queue locks to
reduce locking overhead.
BUG: unable to handle kernel
NULL pointer dereference at 000000b0
IP: [<ff6f1791>] ieee80211_report_used_skb+0x11/0x3e0 [mac80211]
*pde = 00000000
Oops: 0000 [#1] SMP DEBUG_PAGEALLOC
EIP: 0060:[<ff6f1791>] EFLAGS: 00210282 CPU: 1
EIP is at ieee80211_report_used_skb+0x11/0x3e0 [mac80211]
EAX: e5900da0 EBX: 00000000 ECX: 00000001 EDX: 00000000
ESI: e41d00c0 EDI: e5900da0 EBP: ebe458e4 ESP: ebe458b0
DS: 007b ES: 007b FS: 00d8 GS: 00e0 SS: 0068
CR0: 8005003b CR2: 000000b0 CR3: 25a78000 CR4: 000407d0
DR0: 00000000 DR1: 00000000 DR2: 00000000 DR3: 00000000
DR6: ffff0ff0 DR7: 00000400
Process iperf (pid: 3934, ti=ebe44000 task=e757c0b0 task.ti=ebe44000)
iwlwifi 0000:02:00.0: I iwl_pcie_enqueue_hcmd Sending command LQ_CMD (#4e), seq: 0x0903, 92 bytes at 3[3]:9
Stack:
e403b32c ebe458c4 00200002 00200286 e403b338 ebe458cc c10960bb e5900da0
ff76a6ec ebe458d8 00000000 e41d00c0 e5900da0 ebe458f0 ff6f1b75 e403b210
ebe4598c ff723dc1 00000000 ff76a6ec e597c978 e403b758 00000002 00000002
Call Trace:
[<ff6f1b75>] ieee80211_free_txskb+0x15/0x20 [mac80211]
[<ff723dc1>] invoke_tx_handlers+0x1661/0x1780 [mac80211]
[<ff7248a5>] ieee80211_tx+0x75/0x100 [mac80211]
[<ff7249bf>] ieee80211_xmit+0x8f/0xc0 [mac80211]
[<ff72550e>] ieee80211_subif_start_xmit+0x4fe/0xe20 [mac80211]
[<c149ef70>] dev_hard_start_xmit+0x450/0x950
[<c14b9aa9>] sch_direct_xmit+0xa9/0x250
[<c14b9c9b>] __qdisc_run+0x4b/0x150
[<c149f732>] dev_queue_xmit+0x2c2/0xca0
Cc: [email protected]
Reported-by: Yaara Rozenblum <[email protected]>
Signed-off-by: Emmanuel Grumbach <[email protected]>
Reviewed-by: Stanislaw Gruszka <[email protected]>
[reword commit log, use a separate lock]
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: static MagickBooleanType GetICCProperty(const Image *image,const char *property,
ExceptionInfo *exception)
{
const StringInfo
*profile;
magick_unreferenced(property);
profile=GetImageProfile(image,"icc");
if (profile == (StringInfo *) NULL)
profile=GetImageProfile(image,"icm");
if (profile == (StringInfo *) NULL)
return(MagickFalse);
if (GetStringInfoLength(profile) < 128)
return(MagickFalse); /* minimum ICC profile length */
#if defined(MAGICKCORE_LCMS_DELEGATE)
{
cmsHPROFILE
icc_profile;
icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile),
(cmsUInt32Number) GetStringInfoLength(profile));
if (icc_profile != (cmsHPROFILE *) NULL)
{
#if defined(LCMS_VERSION) && (LCMS_VERSION < 2000)
const char
*name;
name=cmsTakeProductName(icc_profile);
if (name != (const char *) NULL)
(void) SetImageProperty((Image *) image,"icc:name",name,exception);
#else
char
info[MagickPathExtent];
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription,
"en","US",info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:description",info,
exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoManufacturer,
"en","US",info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:manufacturer",info,
exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoModel,"en",
"US",info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:model",info,exception);
(void) cmsGetProfileInfoASCII(icc_profile,cmsInfoCopyright,
"en","US",info,MagickPathExtent);
(void) SetImageProperty((Image *) image,"icc:copyright",info,exception);
#endif
(void) cmsCloseProfile(icc_profile);
}
}
#endif
return(MagickTrue);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GpuMessageFilter::OnCreateViewCommandBuffer(
int32 surface_id,
const GPUCreateCommandBufferConfig& init_params,
IPC::Message* reply) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
GpuSurfaceTracker* surface_tracker = GpuSurfaceTracker::Get();
gfx::GLSurfaceHandle compositing_surface;
int renderer_id = 0;
int render_widget_id = 0;
bool result = surface_tracker->GetRenderWidgetIDForSurface(
surface_id, &renderer_id, &render_widget_id);
if (result && renderer_id == render_process_id_) {
compositing_surface = surface_tracker->GetSurfaceHandle(surface_id);
} else {
DLOG(ERROR) << "Renderer " << render_process_id_
<< " tried to access a surface for renderer " << renderer_id;
}
if (compositing_surface.parent_gpu_process_id &&
compositing_surface.parent_gpu_process_id != gpu_process_id_) {
linked_ptr<CreateViewCommandBufferRequest> request(
new CreateViewCommandBufferRequest(surface_id, init_params, reply));
pending_requests_.push_back(request);
return;
}
GpuProcessHost* host = GpuProcessHost::FromID(gpu_process_id_);
if (!host || compositing_surface.is_null()) {
reply->set_reply_error();
Send(reply);
return;
}
host->CreateViewCommandBuffer(
compositing_surface,
surface_id,
render_process_id_,
init_params,
base::Bind(&GpuMessageFilter::CreateCommandBufferCallback,
AsWeakPtr(),
reply));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void svc_rdma_xdr_encode_reply_array(struct rpcrdma_write_array *ary,
int chunks)
{
ary->wc_discrim = xdr_one;
ary->wc_nchunks = cpu_to_be32(chunks);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Target: 1
Example 2:
Code: ZEND_API int add_next_index_string(zval *arg, const char *str, int duplicate) /* {{{ */
{
zval *tmp;
MAKE_STD_ZVAL(tmp);
ZVAL_STRING(tmp, str, duplicate);
return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp, sizeof(zval *), NULL);
}
/* }}} */
Commit Message:
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: nfs4_proc_layoutcommit(struct nfs4_layoutcommit_data *data, bool sync)
{
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_LAYOUTCOMMIT],
.rpc_argp = &data->args,
.rpc_resp = &data->res,
.rpc_cred = data->cred,
};
struct rpc_task_setup task_setup_data = {
.task = &data->task,
.rpc_client = NFS_CLIENT(data->args.inode),
.rpc_message = &msg,
.callback_ops = &nfs4_layoutcommit_ops,
.callback_data = data,
};
struct rpc_task *task;
int status = 0;
dprintk("NFS: initiating layoutcommit call. sync %d "
"lbw: %llu inode %lu\n", sync,
data->args.lastbytewritten,
data->args.inode->i_ino);
if (!sync) {
data->inode = nfs_igrab_and_active(data->args.inode);
if (data->inode == NULL) {
nfs4_layoutcommit_release(data);
return -EAGAIN;
}
task_setup_data.flags = RPC_TASK_ASYNC;
}
nfs4_init_sequence(&data->args.seq_args, &data->res.seq_res, 1);
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
if (sync)
status = task->tk_status;
trace_nfs4_layoutcommit(data->args.inode, status);
dprintk("%s: status %d\n", __func__, status);
rpc_put_task(task);
return status;
}
Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client
---Steps to Reproduce--
<nfs-server>
# cat /etc/exports
/nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt)
/nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt)
<nfs-client>
# mount -t nfs nfs-server:/nfs/ /mnt/
# ll /mnt/*/
<nfs-server>
# cat /etc/exports
/nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server)
/nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt)
# service nfs restart
<nfs-client>
# ll /mnt/*/ --->>>>> oops here
[ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null)
[ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0
[ 5123.104131] Oops: 0000 [#1]
[ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd]
[ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214
[ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014
[ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000
[ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246
[ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240
[ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908
[ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000
[ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800
[ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240
[ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000
[ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0
[ 5123.112888] Stack:
[ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000
[ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6
[ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800
[ 5123.115264] Call Trace:
[ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4]
[ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4]
[ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4]
[ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0
[ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160
[ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70
[ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160
[ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33
[ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.122308] RSP <ffff88005877fdb8>
[ 5123.122942] CR2: 0000000000000000
Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops")
Cc: [email protected] # v3.13+
Signed-off-by: Kinglong Mee <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: MediaControlsHeaderView::MediaControlsHeaderView() {
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, kMediaControlsHeaderInsets,
kMediaControlsHeaderChildSpacing));
auto app_icon_view = std::make_unique<views::ImageView>();
app_icon_view->SetImageSize(gfx::Size(kIconSize, kIconSize));
app_icon_view->SetVerticalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetHorizontalAlignment(views::ImageView::Alignment::kLeading);
app_icon_view->SetBorder(views::CreateEmptyBorder(kIconPadding));
app_icon_view->SetBackground(
views::CreateRoundedRectBackground(SK_ColorWHITE, kIconCornerRadius));
app_icon_view_ = AddChildView(std::move(app_icon_view));
gfx::Font default_font;
int font_size_delta = kHeaderTextFontSize - default_font.GetFontSize();
gfx::Font font = default_font.Derive(font_size_delta, gfx::Font::NORMAL,
gfx::Font::Weight::NORMAL);
gfx::FontList font_list(font);
auto app_name_view = std::make_unique<views::Label>();
app_name_view->SetFontList(font_list);
app_name_view->SetHorizontalAlignment(gfx::ALIGN_LEFT);
app_name_view->SetEnabledColor(SK_ColorWHITE);
app_name_view->SetAutoColorReadabilityEnabled(false);
app_name_view_ = AddChildView(std::move(app_name_view));
}
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 <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool HasEnoughSpaceFor(int64 num_bytes) {
int64 free_space = GetAmountOfFreeDiskSpace();
free_space -= kMinFreeSpace;
return (free_space >= num_bytes);
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: views::DialogDelegateView* CreateAndShowPrompt(
ExtensionInstallPromptTestHelper* helper) {
std::unique_ptr<ExtensionInstallDialogView> dialog(
new ExtensionInstallDialogView(profile(), web_contents(),
helper->GetCallback(), CreatePrompt()));
views::DialogDelegateView* delegate_view = dialog.get();
views::Widget* modal_dialog = views::DialogDelegate::CreateDialogWidget(
dialog.release(), nullptr,
platform_util::GetViewForWindow(
browser()->window()->GetNativeWindow()));
modal_dialog->Show();
return delegate_view;
}
Commit Message: [Extensions UI] Initially disabled OK button for extension install prompts and enable them after a 500 ms time period.
BUG=394518
Review-Url: https://codereview.chromium.org/2716353003
Cr-Commit-Position: refs/heads/master@{#461933}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ext4_ext_insert_extent(handle_t *handle, struct inode *inode,
struct ext4_ext_path *path,
struct ext4_extent *newext, int flag)
{
struct ext4_extent_header *eh;
struct ext4_extent *ex, *fex;
struct ext4_extent *nearex; /* nearest extent */
struct ext4_ext_path *npath = NULL;
int depth, len, err;
ext4_lblk_t next;
unsigned uninitialized = 0;
BUG_ON(ext4_ext_get_actual_len(newext) == 0);
depth = ext_depth(inode);
ex = path[depth].p_ext;
BUG_ON(path[depth].p_hdr == NULL);
/* try to insert block into found extent and return */
if (ex && (flag != EXT4_GET_BLOCKS_PRE_IO)
&& ext4_can_extents_be_merged(inode, ex, newext)) {
ext_debug("append [%d]%d block to %d:[%d]%d (from %llu)\n",
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
le32_to_cpu(ex->ee_block),
ext4_ext_is_uninitialized(ex),
ext4_ext_get_actual_len(ex), ext_pblock(ex));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
return err;
/*
* ext4_can_extents_be_merged should have checked that either
* both extents are uninitialized, or both aren't. Thus we
* need to check only one of them here.
*/
if (ext4_ext_is_uninitialized(ex))
uninitialized = 1;
ex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)
+ ext4_ext_get_actual_len(newext));
if (uninitialized)
ext4_ext_mark_uninitialized(ex);
eh = path[depth].p_hdr;
nearex = ex;
goto merge;
}
repeat:
depth = ext_depth(inode);
eh = path[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))
goto has_space;
/* probably next leaf has space for us? */
fex = EXT_LAST_EXTENT(eh);
next = ext4_ext_next_leaf_block(inode, path);
if (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block)
&& next != EXT_MAX_BLOCK) {
ext_debug("next leaf block - %d\n", next);
BUG_ON(npath != NULL);
npath = ext4_ext_find_extent(inode, next, NULL);
if (IS_ERR(npath))
return PTR_ERR(npath);
BUG_ON(npath->p_depth != path->p_depth);
eh = npath[depth].p_hdr;
if (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {
ext_debug("next leaf isnt full(%d)\n",
le16_to_cpu(eh->eh_entries));
path = npath;
goto repeat;
}
ext_debug("next leaf has no free space(%d,%d)\n",
le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));
}
/*
* There is no free space in the found leaf.
* We're gonna add a new leaf in the tree.
*/
err = ext4_ext_create_new_leaf(handle, inode, path, newext);
if (err)
goto cleanup;
depth = ext_depth(inode);
eh = path[depth].p_hdr;
has_space:
nearex = path[depth].p_ext;
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto cleanup;
if (!nearex) {
/* there is no extent in this leaf, create first one */
ext_debug("first extent in the leaf: %d:%llu:[%d]%d\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext));
path[depth].p_ext = EXT_FIRST_EXTENT(eh);
} else if (le32_to_cpu(newext->ee_block)
> le32_to_cpu(nearex->ee_block)) {
/* BUG_ON(newext->ee_block == nearex->ee_block); */
if (nearex != EXT_LAST_EXTENT(eh)) {
len = EXT_MAX_EXTENT(eh) - nearex;
len = (len - 1) * sizeof(struct ext4_extent);
len = len < 0 ? 0 : len;
ext_debug("insert %d:%llu:[%d]%d after: nearest 0x%p, "
"move %d from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
nearex, len, nearex + 1, nearex + 2);
memmove(nearex + 2, nearex + 1, len);
}
path[depth].p_ext = nearex + 1;
} else {
BUG_ON(newext->ee_block == nearex->ee_block);
len = (EXT_MAX_EXTENT(eh) - nearex) * sizeof(struct ext4_extent);
len = len < 0 ? 0 : len;
ext_debug("insert %d:%llu:[%d]%d before: nearest 0x%p, "
"move %d from 0x%p to 0x%p\n",
le32_to_cpu(newext->ee_block),
ext_pblock(newext),
ext4_ext_is_uninitialized(newext),
ext4_ext_get_actual_len(newext),
nearex, len, nearex + 1, nearex + 2);
memmove(nearex + 1, nearex, len);
path[depth].p_ext = nearex;
}
le16_add_cpu(&eh->eh_entries, 1);
nearex = path[depth].p_ext;
nearex->ee_block = newext->ee_block;
ext4_ext_store_pblock(nearex, ext_pblock(newext));
nearex->ee_len = newext->ee_len;
merge:
/* try to merge extents to the right */
if (flag != EXT4_GET_BLOCKS_PRE_IO)
ext4_ext_try_to_merge(inode, path, nearex);
/* try to merge extents to the left */
/* time to correct all indexes above */
err = ext4_ext_correct_indexes(handle, inode, path);
if (err)
goto cleanup;
err = ext4_ext_dirty(handle, inode, path + depth);
cleanup:
if (npath) {
ext4_ext_drop_refs(npath);
kfree(npath);
}
ext4_ext_invalidate_cache(inode);
return err;
}
Commit Message: ext4: use ext4_get_block_write in buffer write
Allocate uninitialized extent before ext4 buffer write and
convert the extent to initialized after io completes.
The purpose is to make sure an extent can only be marked
initialized after it has been written with new data so
we can safely drop the i_mutex lock in ext4 DIO read without
exposing stale data. This helps to improve multi-thread DIO
read performance on high-speed disks.
Skip the nobh and data=journal mount cases to make things simple for now.
Signed-off-by: Jiaying Zhang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: IntPoint FrameView::convertFromRenderer(const RenderObject& renderer, const IntPoint& rendererPoint) const
{
IntPoint point = roundedIntPoint(renderer.localToAbsolute(rendererPoint, UseTransforms));
point.moveBy(-scrollPosition());
return point;
}
Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea.
updateWidgetPositions() can destroy the render tree, so it should never
be called from inside RenderLayerScrollableArea. Leaving it there allows
for the potential of use-after-free bugs.
BUG=402407
[email protected]
Review URL: https://codereview.chromium.org/490473003
git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: CheckClientDownloadRequest(
content::DownloadItem* item,
const CheckDownloadCallback& callback,
DownloadProtectionService* service,
const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager,
BinaryFeatureExtractor* binary_feature_extractor)
: item_(item),
url_chain_(item->GetUrlChain()),
referrer_url_(item->GetReferrerUrl()),
tab_url_(item->GetTabUrl()),
tab_referrer_url_(item->GetTabReferrerUrl()),
zipped_executable_(false),
callback_(callback),
service_(service),
binary_feature_extractor_(binary_feature_extractor),
database_manager_(database_manager),
pingback_enabled_(service_->enabled()),
finished_(false),
type_(ClientDownloadRequest::WIN_EXECUTABLE),
start_time_(base::TimeTicks::Now()),
weakptr_factory_(this) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
item_->AddObserver(this);
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DevToolsAgentHostImpl::InnerAttachClient(DevToolsAgentHostClient* client) {
scoped_refptr<DevToolsAgentHostImpl> protect(this);
DevToolsSession* session = new DevToolsSession(this, client);
sessions_.insert(session);
session_by_client_[client].reset(session);
AttachSession(session);
if (sessions_.size() == 1)
NotifyAttached();
DevToolsManager* manager = DevToolsManager::GetInstance();
if (manager->delegate())
manager->delegate()->ClientAttached(this, client);
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20
Target: 1
Example 2:
Code: MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
Quantum
*pixels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_authentic_pixels_handler !=
(GetAuthenticPixelsHandler) NULL)
{
pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns,
rows,exception);
return(pixels);
}
assert(id < (int) cache_info->number_threads);
pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows,
cache_info->nexus_info[id],exception);
return(pixels);
}
Commit Message: Set pixel cache to undefined if any resource limit is exceeded
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long Cluster::Parse(long long& pos, long& len) const {
long status = Load(pos, len);
if (status < 0)
return status;
assert(m_pos >= m_element_start);
assert(m_timecode >= 0);
const long long cluster_stop =
(m_element_size < 0) ? -1 : m_element_start + m_element_size;
if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
return 1; // nothing else to do
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_pos;
for (;;) {
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((total >= 0) && (pos >= total)) {
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) // error
return static_cast<long>(id);
if (id == 0) // weird
return E_FILE_FORMAT_INVALID;
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { // Cluster or Cues ID
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
pos += len; // consume ID field
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; // consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) // weird
continue;
const long long block_stop = pos + size;
if (cluster_stop >= 0) {
if (block_stop > cluster_stop) {
if ((id == 0x20) || (id == 0x23))
return E_FILE_FORMAT_INVALID;
pos = cluster_stop;
break;
}
} else if ((total >= 0) && (block_stop > total)) {
m_element_size = total - m_element_start;
pos = total;
break;
} else if (block_stop > avail) {
len = static_cast<long>(size);
return E_BUFFER_NOT_FULL;
}
Cluster* const this_ = const_cast<Cluster*>(this);
if (id == 0x20) // BlockGroup
return this_->ParseBlockGroup(size, pos, len);
if (id == 0x23) // SimpleBlock
return this_->ParseSimpleBlock(size, pos, len);
pos += size; // consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert(m_element_size > 0);
m_pos = pos;
assert((cluster_stop < 0) || (m_pos <= cluster_stop));
if (m_entries_count > 0) {
const long idx = m_entries_count - 1;
const BlockEntry* const pLast = m_entries[idx];
assert(pLast);
const Block* const pBlock = pLast->GetBlock();
assert(pBlock);
const long long start = pBlock->m_start;
if ((total >= 0) && (start > total))
return -1; // defend against trucated stream
const long long size = pBlock->m_size;
const long long stop = start + size;
assert((cluster_stop < 0) || (stop <= cluster_stop));
if ((total >= 0) && (stop > total))
return -1; // defend against trucated stream
}
return 1; // no more entries
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen;
int exthdrlen;
int dst_exthdrlen;
int hh_len;
int mtu;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
exthdrlen = (opt ? opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
mtu = cork->fragsize;
}
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM)
sock_tx_timestamp(sk, &tx_flags);
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if (length > mtu) {
int proto = sk->sk_protocol;
if (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
if (proto == IPPROTO_UDP &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags, rt);
if (err)
goto error;
return 0;
}
}
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (skb == NULL || skb_prev == NULL)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->ip_summed = CHECKSUM_NONE;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
struct page_frag *pfrag = sk_page_frag(sk);
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
Commit Message: ipv6: ip6_append_data_mtu did not care about pmtudisc and frag_size
If the socket had an IPV6_MTU value set, ip6_append_data_mtu lost track
of this when appending the second frame on a corked socket. This results
in the following splat:
[37598.993962] ------------[ cut here ]------------
[37598.994008] kernel BUG at net/core/skbuff.c:2064!
[37598.994008] invalid opcode: 0000 [#1] SMP
[37598.994008] Modules linked in: tcp_lp uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_core videodev media vfat fat usb_storage fuse ebtable_nat xt_CHECKSUM bridge stp llc ipt_MASQUERADE nf_conntrack_netbios_ns nf_conntrack_broadcast ip6table_mangle ip6t_REJECT nf_conntrack_ipv6 nf_defrag_ipv6 iptable_nat
+nf_nat_ipv4 nf_nat iptable_mangle nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ebtable_filter ebtables ip6table_filter ip6_tables be2iscsi iscsi_boot_sysfs bnx2i cnic uio cxgb4i cxgb4 cxgb3i cxgb3 mdio libcxgbi ib_iser rdma_cm ib_addr iw_cm ib_cm ib_sa ib_mad ib_core iscsi_tcp libiscsi_tcp libiscsi
+scsi_transport_iscsi rfcomm bnep iTCO_wdt iTCO_vendor_support snd_hda_codec_conexant arc4 iwldvm mac80211 snd_hda_intel acpi_cpufreq mperf coretemp snd_hda_codec microcode cdc_wdm cdc_acm
[37598.994008] snd_hwdep cdc_ether snd_seq snd_seq_device usbnet mii joydev btusb snd_pcm bluetooth i2c_i801 e1000e lpc_ich mfd_core ptp iwlwifi pps_core snd_page_alloc mei cfg80211 snd_timer thinkpad_acpi snd tpm_tis soundcore rfkill tpm tpm_bios vhost_net tun macvtap macvlan kvm_intel kvm uinput binfmt_misc
+dm_crypt i915 i2c_algo_bit drm_kms_helper drm i2c_core wmi video
[37598.994008] CPU 0
[37598.994008] Pid: 27320, comm: t2 Not tainted 3.9.6-200.fc18.x86_64 #1 LENOVO 27744PG/27744PG
[37598.994008] RIP: 0010:[<ffffffff815443a5>] [<ffffffff815443a5>] skb_copy_and_csum_bits+0x325/0x330
[37598.994008] RSP: 0018:ffff88003670da18 EFLAGS: 00010202
[37598.994008] RAX: ffff88018105c018 RBX: 0000000000000004 RCX: 00000000000006c0
[37598.994008] RDX: ffff88018105a6c0 RSI: ffff88018105a000 RDI: ffff8801e1b0aa00
[37598.994008] RBP: ffff88003670da78 R08: 0000000000000000 R09: ffff88018105c040
[37598.994008] R10: ffff8801e1b0aa00 R11: 0000000000000000 R12: 000000000000fff8
[37598.994008] R13: 00000000000004fc R14: 00000000ffff0504 R15: 0000000000000000
[37598.994008] FS: 00007f28eea59740(0000) GS:ffff88023bc00000(0000) knlGS:0000000000000000
[37598.994008] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[37598.994008] CR2: 0000003d935789e0 CR3: 00000000365cb000 CR4: 00000000000407f0
[37598.994008] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[37598.994008] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[37598.994008] Process t2 (pid: 27320, threadinfo ffff88003670c000, task ffff88022c162ee0)
[37598.994008] Stack:
[37598.994008] ffff88022e098a00 ffff88020f973fc0 0000000000000008 00000000000004c8
[37598.994008] ffff88020f973fc0 00000000000004c4 ffff88003670da78 ffff8801e1b0a200
[37598.994008] 0000000000000018 00000000000004c8 ffff88020f973fc0 00000000000004c4
[37598.994008] Call Trace:
[37598.994008] [<ffffffff815fc21f>] ip6_append_data+0xccf/0xfe0
[37598.994008] [<ffffffff8158d9f0>] ? ip_copy_metadata+0x1a0/0x1a0
[37598.994008] [<ffffffff81661f66>] ? _raw_spin_lock_bh+0x16/0x40
[37598.994008] [<ffffffff8161548d>] udpv6_sendmsg+0x1ed/0xc10
[37598.994008] [<ffffffff812a2845>] ? sock_has_perm+0x75/0x90
[37598.994008] [<ffffffff815c3693>] inet_sendmsg+0x63/0xb0
[37598.994008] [<ffffffff812a2973>] ? selinux_socket_sendmsg+0x23/0x30
[37598.994008] [<ffffffff8153a450>] sock_sendmsg+0xb0/0xe0
[37598.994008] [<ffffffff810135d1>] ? __switch_to+0x181/0x4a0
[37598.994008] [<ffffffff8153d97d>] sys_sendto+0x12d/0x180
[37598.994008] [<ffffffff810dfb64>] ? __audit_syscall_entry+0x94/0xf0
[37598.994008] [<ffffffff81020ed1>] ? syscall_trace_enter+0x231/0x240
[37598.994008] [<ffffffff8166a7e7>] tracesys+0xdd/0xe2
[37598.994008] Code: fe 07 00 00 48 c7 c7 04 28 a6 81 89 45 a0 4c 89 4d b8 44 89 5d a8 e8 1b ac b1 ff 44 8b 5d a8 4c 8b 4d b8 8b 45 a0 e9 cf fe ff ff <0f> 0b 66 0f 1f 84 00 00 00 00 00 66 66 66 66 90 55 48 89 e5 48
[37598.994008] RIP [<ffffffff815443a5>] skb_copy_and_csum_bits+0x325/0x330
[37598.994008] RSP <ffff88003670da18>
[37599.007323] ---[ end trace d69f6a17f8ac8eee ]---
While there, also check if path mtu discovery is activated for this
socket. The logic was adapted from ip6_append_data when first writing
on the corked socket.
This bug was introduced with commit
0c1833797a5a6ec23ea9261d979aa18078720b74 ("ipv6: fix incorrect ipsec
fragment").
v2:
a) Replace IPV6_PMTU_DISC_DO with IPV6_PMTUDISC_PROBE.
b) Don't pass ipv6_pinfo to ip6_append_data_mtu (suggestion by Gao
feng, thanks!).
c) Change mtu to unsigned int, else we get a warning about
non-matching types because of the min()-macro type-check.
Acked-by: Gao feng <[email protected]>
Cc: YOSHIFUJI Hideaki <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: void PrintingMessageFilter::OnCheckForCancel(const std::string& preview_ui_addr,
int preview_request_id,
bool* cancel) {
PrintPreviewUI::GetCurrentPrintPreviewStatus(preview_ui_addr,
preview_request_id,
cancel);
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline sp<IMemoryHeap> find_heap(const sp<IBinder>& binder) {
return gHeapCache->find_heap(binder);
}
Commit Message: Sanity check IMemory access versus underlying mmap
Bug 26877992
Change-Id: Ibbf4b1061e4675e4e96bc944a865b53eaf6984fe
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int hfsplus_rename_cat(u32 cnid,
struct inode *src_dir, struct qstr *src_name,
struct inode *dst_dir, struct qstr *dst_name)
{
struct super_block *sb = src_dir->i_sb;
struct hfs_find_data src_fd, dst_fd;
hfsplus_cat_entry entry;
int entry_size, type;
int err;
dprint(DBG_CAT_MOD, "rename_cat: %u - %lu,%s - %lu,%s\n",
cnid, src_dir->i_ino, src_name->name,
dst_dir->i_ino, dst_name->name);
err = hfs_find_init(HFSPLUS_SB(sb)->cat_tree, &src_fd);
if (err)
return err;
dst_fd = src_fd;
/* find the old dir entry and read the data */
hfsplus_cat_build_key(sb, src_fd.search_key, src_dir->i_ino, src_name);
err = hfs_brec_find(&src_fd);
if (err)
goto out;
hfs_bnode_read(src_fd.bnode, &entry, src_fd.entryoffset,
src_fd.entrylength);
/* create new dir entry with the data from the old entry */
hfsplus_cat_build_key(sb, dst_fd.search_key, dst_dir->i_ino, dst_name);
err = hfs_brec_find(&dst_fd);
if (err != -ENOENT) {
if (!err)
err = -EEXIST;
goto out;
}
err = hfs_brec_insert(&dst_fd, &entry, src_fd.entrylength);
if (err)
goto out;
dst_dir->i_size++;
dst_dir->i_mtime = dst_dir->i_ctime = CURRENT_TIME_SEC;
/* finally remove the old entry */
hfsplus_cat_build_key(sb, src_fd.search_key, src_dir->i_ino, src_name);
err = hfs_brec_find(&src_fd);
if (err)
goto out;
err = hfs_brec_remove(&src_fd);
if (err)
goto out;
src_dir->i_size--;
src_dir->i_mtime = src_dir->i_ctime = CURRENT_TIME_SEC;
/* remove old thread entry */
hfsplus_cat_build_key(sb, src_fd.search_key, cnid, NULL);
err = hfs_brec_find(&src_fd);
if (err)
goto out;
type = hfs_bnode_read_u16(src_fd.bnode, src_fd.entryoffset);
err = hfs_brec_remove(&src_fd);
if (err)
goto out;
/* create new thread entry */
hfsplus_cat_build_key(sb, dst_fd.search_key, cnid, NULL);
entry_size = hfsplus_fill_cat_thread(sb, &entry, type,
dst_dir->i_ino, dst_name);
err = hfs_brec_find(&dst_fd);
if (err != -ENOENT) {
if (!err)
err = -EEXIST;
goto out;
}
err = hfs_brec_insert(&dst_fd, &entry, entry_size);
hfsplus_mark_inode_dirty(dst_dir, HFSPLUS_I_CAT_DIRTY);
hfsplus_mark_inode_dirty(src_dir, HFSPLUS_I_CAT_DIRTY);
out:
hfs_bnode_put(dst_fd.bnode);
hfs_find_exit(&src_fd);
return err;
}
Commit Message: hfsplus: Fix potential buffer overflows
Commit ec81aecb2966 ("hfs: fix a potential buffer overflow") fixed a few
potential buffer overflows in the hfs filesystem. But as Timo Warns
pointed out, these changes also need to be made on the hfsplus
filesystem as well.
Reported-by: Timo Warns <[email protected]>
Acked-by: WANG Cong <[email protected]>
Cc: Alexey Khoroshilov <[email protected]>
Cc: Miklos Szeredi <[email protected]>
Cc: Sage Weil <[email protected]>
Cc: Eugene Teo <[email protected]>
Cc: Roman Zippel <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Christoph Hellwig <[email protected]>
Cc: Alexey Dobriyan <[email protected]>
Cc: Dave Anderson <[email protected]>
Cc: stable <[email protected]>
Cc: Andrew Morton <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: GF_Box *video_sample_entry_New()
{
GF_MPEGVisualSampleEntryBox *tmp;
GF_SAFEALLOC(tmp, GF_MPEGVisualSampleEntryBox);
if (tmp == NULL) return NULL;
gf_isom_video_sample_entry_init((GF_VisualSampleEntryBox *)tmp);
return (GF_Box *)tmp;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AppControllerImpl::SetClient(mojom::AppControllerClientPtr client) {
client_ = std::move(client);
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Node::InsertionNotificationRequest HTMLStyleElement::InsertedInto(
ContainerNode* insertion_point) {
HTMLElement::InsertedInto(insertion_point);
return kInsertionShouldCallDidNotifySubtreeInsertions;
}
Commit Message: Do not crash while reentrantly appending to style element.
When a node is inserted into a container, it is notified via
::InsertedInto. However, a node may request a second notification via
DidNotifySubtreeInsertionsToDocument, which occurs after all the children
have been notified as well. *StyleElement is currently using this
second notification.
This causes a problem, because *ScriptElement is using the same mechanism,
which in turn means that scripts can execute before the state of
*StyleElements are properly updated.
This patch avoids ::DidNotifySubtreeInsertionsToDocument, and instead
processes the stylesheet in ::InsertedInto. The original reason for using
::DidNotifySubtreeInsertionsToDocument in the first place appears to be
invalid now, as the test case is still passing.
[email protected], [email protected]
Bug: 853709, 847570
Cq-Include-Trybots: luci.chromium.try:linux_layout_tests_slimming_paint_v2;master.tryserver.blink:linux_trusty_blink_rel
Change-Id: Ic0b5fa611044c78c5745cf26870a747f88920a14
Reviewed-on: https://chromium-review.googlesource.com/1104347
Commit-Queue: Anders Ruud <[email protected]>
Reviewed-by: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#568368}
CWE ID: CWE-416
Target: 1
Example 2:
Code: person_get_trailing(const person_t* person)
{
return person->follow_distance;
}
Commit Message: Fix integer overflow in layer_resize in map_engine.c (#268)
* Fix integer overflow in layer_resize in map_engine.c
There's a buffer overflow bug in the function layer_resize. It allocates
a buffer `tilemap` with size `x_size * y_size * sizeof(struct map_tile)`.
But it didn't check for integer overflow, so if x_size and y_size are
very large, it's possible that the buffer size is smaller than needed,
causing a buffer overflow later.
PoC: `SetLayerSize(0, 0x7FFFFFFF, 0x7FFFFFFF);`
* move malloc to a separate line
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: function_stat_next(void *v, int idx)
{
struct ftrace_profile *rec = v;
struct ftrace_profile_page *pg;
pg = (struct ftrace_profile_page *)((unsigned long)rec & PAGE_MASK);
again:
if (idx != 0)
rec++;
if ((void *)rec >= (void *)&pg->records[pg->index]) {
pg = pg->next;
if (!pg)
return NULL;
rec = &pg->records[0];
if (!rec->counter)
goto again;
}
return rec;
}
Commit Message: tracing: Fix possible NULL pointer dereferences
Currently set_ftrace_pid and set_graph_function files use seq_lseek
for their fops. However seq_open() is called only for FMODE_READ in
the fops->open() so that if an user tries to seek one of those file
when she open it for writing, it sees NULL seq_file and then panic.
It can be easily reproduced with following command:
$ cd /sys/kernel/debug/tracing
$ echo 1234 | sudo tee -a set_ftrace_pid
In this example, GNU coreutils' tee opens the file with fopen(, "a")
and then the fopen() internally calls lseek().
Link: http://lkml.kernel.org/r/[email protected]
Cc: Frederic Weisbecker <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Namhyung Kim <[email protected]>
Cc: [email protected]
Signed-off-by: Namhyung Kim <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool msr_mtrr_valid(unsigned msr)
{
switch (msr) {
case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
case MSR_MTRRfix64K_00000:
case MSR_MTRRfix16K_80000:
case MSR_MTRRfix16K_A0000:
case MSR_MTRRfix4K_C0000:
case MSR_MTRRfix4K_C8000:
case MSR_MTRRfix4K_D0000:
case MSR_MTRRfix4K_D8000:
case MSR_MTRRfix4K_E0000:
case MSR_MTRRfix4K_E8000:
case MSR_MTRRfix4K_F0000:
case MSR_MTRRfix4K_F8000:
case MSR_MTRRdefType:
case MSR_IA32_CR_PAT:
return true;
case 0x2f8:
return true;
}
return false;
}
Commit Message: KVM: MTRR: remove MSR 0x2f8
MSR 0x2f8 accessed the 124th Variable Range MTRR ever since MTRR support
was introduced by 9ba075a664df ("KVM: MTRR support").
0x2f8 became harmful when 910a6aae4e2e ("KVM: MTRR: exactly define the
size of variable MTRRs") shrinked the array of VR MTRRs from 256 to 8,
which made access to index 124 out of bounds. The surrounding code only
WARNs in this situation, thus the guest gained a limited read/write
access to struct kvm_arch_vcpu.
0x2f8 is not a valid VR MTRR MSR, because KVM has/advertises only 16 VR
MTRR MSRs, 0x200-0x20f. Every VR MTRR is set up using two MSRs, 0x2f8
was treated as a PHYSBASE and 0x2f9 would be its PHYSMASK, but 0x2f9 was
not implemented in KVM, therefore 0x2f8 could never do anything useful
and getting rid of it is safe.
This fixes CVE-2016-3713.
Fixes: 910a6aae4e2e ("KVM: MTRR: exactly define the size of variable MTRRs")
Cc: [email protected]
Reported-by: David Matlack <[email protected]>
Signed-off-by: Andy Honig <[email protected]>
Signed-off-by: Radim Krčmář <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-284
Target: 1
Example 2:
Code: void V8TestObject::VoidMethodBooleanOrElementSequenceArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_voidMethodBooleanOrElementSequenceArg");
test_object_v8_internal::VoidMethodBooleanOrElementSequenceArgMethod(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ContextState::RestoreTextureUnitBindings(
GLuint unit, const ContextState* prev_state) const {
DCHECK_LT(unit, texture_units.size());
const TextureUnit& texture_unit = texture_units[unit];
GLuint service_id_2d = Get2dServiceId(texture_unit);
GLuint service_id_cube = GetCubeServiceId(texture_unit);
GLuint service_id_oes = GetOesServiceId(texture_unit);
GLuint service_id_arb = GetArbServiceId(texture_unit);
bool bind_texture_2d = true;
bool bind_texture_cube = true;
bool bind_texture_oes =
feature_info_->feature_flags().oes_egl_image_external ||
feature_info_->feature_flags().nv_egl_stream_consumer_external;
bool bind_texture_arb = feature_info_->feature_flags().arb_texture_rectangle;
if (prev_state) {
const TextureUnit& prev_unit = prev_state->texture_units[unit];
bind_texture_2d = service_id_2d != Get2dServiceId(prev_unit);
bind_texture_cube = service_id_cube != GetCubeServiceId(prev_unit);
bind_texture_oes =
bind_texture_oes && service_id_oes != GetOesServiceId(prev_unit);
bind_texture_arb =
bind_texture_arb && service_id_arb != GetArbServiceId(prev_unit);
}
if (!bind_texture_2d && !bind_texture_cube
&& !bind_texture_oes && !bind_texture_arb) {
return;
}
api()->glActiveTextureFn(GL_TEXTURE0 + unit);
if (bind_texture_2d) {
api()->glBindTextureFn(GL_TEXTURE_2D, service_id_2d);
}
if (bind_texture_cube) {
api()->glBindTextureFn(GL_TEXTURE_CUBE_MAP, service_id_cube);
}
if (bind_texture_oes) {
api()->glBindTextureFn(GL_TEXTURE_EXTERNAL_OES, service_id_oes);
}
if (bind_texture_arb) {
api()->glBindTextureFn(GL_TEXTURE_RECTANGLE_ARB, service_id_arb);
}
}
Commit Message: Fix tabs sharing TEXTURE_2D_ARRAY/TEXTURE_3D data.
In linux and android, we are seeing an issue where texture data from one
tab overwrites the texture data of another tab. This is happening for apps
which are using webgl2 texture of type TEXTURE_2D_ARRAY/TEXTURE_3D.
Due to a bug in virtual context save/restore code for above texture formats,
the texture data is not properly restored while switching tabs. Hence
texture data from one tab overwrites other.
This CL has fix for that issue, an update for existing test expectations
and a new unit test for this bug.
Bug: 788448
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: Ie933984cdd2d1381f42eb4638f730c8245207a28
Reviewed-on: https://chromium-review.googlesource.com/930327
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: vikas soni <[email protected]>
Cr-Commit-Position: refs/heads/master@{#539111}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int nsv_read_chunk(AVFormatContext *s, int fill_header)
{
NSVContext *nsv = s->priv_data;
AVIOContext *pb = s->pb;
AVStream *st[2] = {NULL, NULL};
NSVStream *nst;
AVPacket *pkt;
int i, err = 0;
uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */
uint32_t vsize;
uint16_t asize;
uint16_t auxsize;
if (nsv->ahead[0].data || nsv->ahead[1].data)
return 0; //-1; /* hey! eat what you've in your plate first! */
null_chunk_retry:
if (pb->eof_reached)
return -1;
for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)
err = nsv_resync(s);
if (err < 0)
return err;
if (nsv->state == NSV_FOUND_NSVS)
err = nsv_parse_NSVs_header(s);
if (err < 0)
return err;
if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)
return -1;
auxcount = avio_r8(pb);
vsize = avio_rl16(pb);
asize = avio_rl16(pb);
vsize = (vsize << 4) | (auxcount >> 4);
auxcount &= 0x0f;
av_log(s, AV_LOG_TRACE, "NSV CHUNK %"PRIu8" aux, %"PRIu32" bytes video, %"PRIu16" bytes audio\n",
auxcount, vsize, asize);
/* skip aux stuff */
for (i = 0; i < auxcount; i++) {
uint32_t av_unused auxtag;
auxsize = avio_rl16(pb);
auxtag = avio_rl32(pb);
avio_skip(pb, auxsize);
vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */
}
if (pb->eof_reached)
return -1;
if (!vsize && !asize) {
nsv->state = NSV_UNSYNC;
goto null_chunk_retry;
}
/* map back streams to v,a */
if (s->nb_streams > 0)
st[s->streams[0]->id] = s->streams[0];
if (s->nb_streams > 1)
st[s->streams[1]->id] = s->streams[1];
if (vsize && st[NSV_ST_VIDEO]) {
nst = st[NSV_ST_VIDEO]->priv_data;
pkt = &nsv->ahead[NSV_ST_VIDEO];
av_get_packet(pb, pkt, vsize);
pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;
pkt->dts = nst->frame_offset;
pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
for (i = 0; i < FFMIN(8, vsize); i++)
av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02"PRIx8"\n",
i, pkt->data[i]);
}
if(st[NSV_ST_VIDEO])
((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
if (asize && st[NSV_ST_AUDIO]) {
nst = st[NSV_ST_AUDIO]->priv_data;
pkt = &nsv->ahead[NSV_ST_AUDIO];
/* read raw audio specific header on the first audio chunk... */
/* on ALL audio chunks ?? seems so! */
if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {
uint8_t bps;
uint8_t channels;
uint16_t samplerate;
bps = avio_r8(pb);
channels = avio_r8(pb);
samplerate = avio_rl16(pb);
if (!channels || !samplerate)
return AVERROR_INVALIDDATA;
asize-=4;
av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",
bps, channels, samplerate);
if (fill_header) {
st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */
if (bps != 16) {
av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%"PRIu8")!!!\n", bps);
}
bps /= channels; // ???
if (bps == 8)
st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
samplerate /= 4;/* UGH ??? XXX */
channels = 1;
st[NSV_ST_AUDIO]->codecpar->channels = channels;
st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate;
av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",
bps, channels, samplerate);
}
}
av_get_packet(pb, pkt, asize);
pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;
pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {
/* on a nsvs frame we have new information on a/v sync */
pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);
pkt->dts *= (int64_t)1000 * nsv->framerate.den;
pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;
av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%"PRId16", dts:%"PRId64,
nsv->avsync, pkt->dts);
}
nst->frame_offset++;
}
nsv->state = NSV_UNSYNC;
return 0;
}
Commit Message: nsvdec: don't ignore the return value of av_get_packet()
Fixes invalid reads with corrupted files.
CC: [email protected]
Bug-Id: 1039
CWE ID: CWE-476
Target: 1
Example 2:
Code: void TopSitesImpl::OnGotMostVisitedThumbnails(
const scoped_refptr<MostVisitedThumbnails>& thumbnails) {
DCHECK(thread_checker_.CalledOnValidThread());
cache_->SetTopSites(thumbnails->most_visited);
SetTopSites(thumbnails->most_visited,
CALL_LOCATION_FROM_ON_GOT_MOST_VISITED_THUMBNAILS);
cache_->SetThumbnails(thumbnails->url_to_images_map);
ResetThreadSafeImageCache();
MoveStateToLoaded();
timer_.Start(FROM_HERE, kFirstDelayAtStartup, this,
&TopSitesImpl::StartQueryForMostVisited);
}
Commit Message: TopSites: Clear thumbnails from the cache when their URLs get removed
We already cleared the thumbnails from persistent storage, but they
remained in the in-memory cache, so they remained accessible (until the
next Chrome restart) even after all browsing data was cleared.
Bug: 758169
Change-Id: Id916d22358430a82e6d5043ac04fa463a32f824f
Reviewed-on: https://chromium-review.googlesource.com/758640
Commit-Queue: Marc Treib <[email protected]>
Reviewed-by: Sylvain Defresne <[email protected]>
Cr-Commit-Position: refs/heads/master@{#514861}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::string SanitizeEndpoint(const std::string& value) {
if (value.find('&') != std::string::npos
|| value.find('?') != std::string::npos)
return std::string();
return value;
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: double VideoTrack::GetFrameRate() const
{
return m_rate;
}
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
Target: 1
Example 2:
Code: blink::WebBluetooth* RenderFrameImpl::bluetooth() {
if (!bluetooth_) {
bluetooth_.reset(new WebBluetoothImpl(
ChildThreadImpl::current()->thread_safe_sender(), routing_id_));
}
return bluetooth_.get();
}
Commit Message: Connect WebUSB client interface to the devices app
This provides a basic WebUSB client interface in
content/renderer. Most of the interface is unimplemented,
but this CL hooks up navigator.usb.getDevices() to the
browser's Mojo devices app to enumerate available USB
devices.
BUG=492204
Review URL: https://codereview.chromium.org/1293253002
Cr-Commit-Position: refs/heads/master@{#344881}
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void gen_helper_in_func(TCGMemOp ot, TCGv v, TCGv_i32 n)
{
switch (ot) {
case MO_8:
gen_helper_inb(v, cpu_env, n);
break;
case MO_16:
gen_helper_inw(v, cpu_env, n);
break;
case MO_32:
gen_helper_inl(v, cpu_env, n);
break;
default:
tcg_abort();
}
}
Commit Message: tcg/i386: Check the size of instruction being translated
This fixes the bug: 'user-to-root privesc inside VM via bad translation
caching' reported by Jann Horn here:
https://bugs.chromium.org/p/project-zero/issues/detail?id=1122
Reviewed-by: Richard Henderson <[email protected]>
CC: Peter Maydell <[email protected]>
CC: Paolo Bonzini <[email protected]>
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Pranith Kumar <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-94
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
Commit Message: Fix for bug #72790 and bug #72799
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void tracked_request_end(BdrvTrackedRequest *req)
{
if (req->serialising) {
req->bs->serialising_in_flight--;
}
QLIST_REMOVE(req, list);
qemu_co_queue_restart_all(&req->wait_queue);
}
Commit Message:
CWE ID: CWE-190
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: HTMLCollection* Document::WindowNamedItems(const AtomicString& name) {
return EnsureCachedCollection<WindowNameCollection>(kWindowNamedItems, name);
}
Commit Message: Cleanup and remove dead code in SetFocusedElement
This early-out was added in:
https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc
Back then, we applied fragment focus in LayoutUpdated() which could
cause this issue. This got cleaned up in:
https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2
so that focus is no longer applied after layout.
+Cleanup: Goto considered harmful
Bug: 795381
Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417
Commit-Queue: David Bokan <[email protected]>
Reviewed-by: Stefan Zager <[email protected]>
Cr-Commit-Position: refs/heads/master@{#641101}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline bool unconditional(const struct arpt_arp *arp)
{
static const struct arpt_arp uncond;
return memcmp(arp, &uncond, sizeof(uncond)) == 0;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: status_t MediaPlayerService::AudioOutput::setPlaybackRate(const AudioPlaybackRate &rate)
{
ALOGV("setPlaybackRate(%f %f %d %d)",
rate.mSpeed, rate.mPitch, rate.mFallbackMode, rate.mStretchMode);
Mutex::Autolock lock(mLock);
if (mTrack == 0) {
mPlaybackRate = rate;
return OK;
}
status_t res = mTrack->setPlaybackRate(rate);
if (res != NO_ERROR) {
return res;
}
CHECK_GT(rate.mSpeed, 0.f);
mPlaybackRate = rate;
if (mSampleRateHz != 0) {
mMsecsPerFrame = 1E3f / (rate.mSpeed * mSampleRateHz);
}
return res;
}
Commit Message: MediaPlayerService: avoid invalid static cast
Bug: 30204103
Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028
(cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d)
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev,
uint32_t max_frags, bool has_virt_hdr)
{
struct NetTxPkt *p = g_malloc0(sizeof *p);
p->pci_dev = pci_dev;
p->vec = g_malloc((sizeof *p->vec) *
(max_frags + NET_TX_PKT_PL_START_FRAG));
p->raw = g_malloc((sizeof *p->raw) * max_frags);
p->max_payload_frags = max_frags;
p->max_raw_frags = max_frags;
p->max_raw_frags = max_frags;
p->has_virt_hdr = has_virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =
p->has_virt_hdr ? sizeof p->virt_hdr : 0;
p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;
p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr;
*pkt = p;
}
Commit Message:
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE SoftAVC::setConfig(
OMX_INDEXTYPE index, const OMX_PTR _params) {
switch (index) {
case OMX_IndexConfigVideoIntraVOPRefresh:
{
OMX_CONFIG_INTRAREFRESHVOPTYPE *params =
(OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params;
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
mKeyFrameRequested = params->IntraRefreshVOP;
return OMX_ErrorNone;
}
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE *params =
(OMX_VIDEO_CONFIG_BITRATETYPE *)_params;
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (mBitrate != params->nEncodeBitrate) {
mBitrate = params->nEncodeBitrate;
mBitrateUpdated = true;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::setConfig(index, _params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
Target: 1
Example 2:
Code: void DocumentLoader::ClearMainResourceHandle() {
if (!main_resource_)
return;
main_resource_->RemoveClient(this);
main_resource_ = nullptr;
}
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 <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MediaStreamManager::StopMediaStreamFromBrowser(const std::string& label) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DeviceRequest* request = FindRequest(label);
if (!request)
return;
if (request->device_stopped_cb) {
for (const MediaStreamDevice& device : request->devices) {
request->device_stopped_cb.Run(label, device);
}
}
CancelRequest(label);
}
Commit Message: Fix MediaObserver notifications in MediaStreamManager.
This CL fixes the stream type used to notify MediaObserver about
cancelled MediaStream requests.
Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate
that all stream types should be cancelled.
However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this
way and the request to update the UI is ignored.
This CL sends a separate notification for each stream type so that the
UI actually gets updated for all stream types in use.
Bug: 816033
Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405
Reviewed-on: https://chromium-review.googlesource.com/939630
Commit-Queue: Guido Urdaneta <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540122}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec,
nal_header_t *ps_nal)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 i;
WORD32 sps_id;
pps_t *ps_pps;
sps_t *ps_sps;
slice_header_t *ps_slice_hdr;
WORD32 disable_deblocking_filter_flag;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 idr_pic_flag;
WORD32 pps_id;
WORD32 first_slice_in_pic_flag;
WORD32 no_output_of_prior_pics_flag = 0;
WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type;
WORD32 num_poc_total_curr = 0;
WORD32 slice_address;
if(ps_codec->i4_slice_error == 1)
return ret;
idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) ||
(NAL_IDR_N_LP == i1_nal_unit_type);
BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1);
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1);
}
UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm);
pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2);
/* Get the current PPS structure */
ps_pps = ps_codec->s_parse.ps_pps_base + pps_id;
if(0 == ps_pps->i1_pps_valid)
{
pps_t *ps_pps_ref = ps_codec->ps_pps_base;
while(0 == ps_pps_ref->i1_pps_valid)
ps_pps_ref++;
if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1))
return IHEVCD_INVALID_HEADER;
ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id);
}
/* Get SPS id for the current PPS */
sps_id = ps_pps->i1_sps_id;
/* Get the current SPS structure */
ps_sps = ps_codec->s_parse.ps_sps_base + sps_id;
/* When the current slice is the first in a pic,
* check whether the previous frame is complete
* If the previous frame is incomplete -
* treat the remaining CTBs as skip */
if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) &&
first_slice_in_pic_flag)
{
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
if(first_slice_in_pic_flag)
{
ps_codec->s_parse.i4_cur_slice_idx = 0;
}
else
{
/* If the current slice is not the first slice in the pic,
* but the first one to be parsed, set the current slice indx to 1
* Treat the first slice to be missing and copy the current slice header
* to the first one */
if(0 == ps_codec->i4_pic_present)
ps_codec->s_parse.i4_cur_slice_idx = 1;
}
ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
if((ps_pps->i1_dependent_slice_enabled_flag) &&
(!first_slice_in_pic_flag))
{
BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1);
/* If dependendent slice, copy slice header from previous slice */
if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0))
{
ihevcd_copy_slice_hdr(ps_codec,
(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)),
((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1)));
}
ps_slice_hdr->i1_dependent_slice_flag = value;
}
else
{
ps_slice_hdr->i1_dependent_slice_flag = 0;
}
ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type;
ps_slice_hdr->i1_pps_id = pps_id;
ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag;
ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1;
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag;
}
ps_slice_hdr->i1_pps_id = pps_id;
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
WORD32 num_bits;
/* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */
num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1);
BITS_PARSE("slice_address", value, ps_bitstrm, num_bits);
slice_address = value;
/* If slice address is greater than the number of CTBs in a picture,
* ignore the slice */
if(value >= ps_sps->i4_pic_size_in_ctb)
return IHEVCD_IGNORE_SLICE;
}
else
{
slice_address = 0;
}
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i1_pic_output_flag = 1;
ps_slice_hdr->i4_pic_order_cnt_lsb = 0;
ps_slice_hdr->i1_num_long_term_sps = 0;
ps_slice_hdr->i1_num_long_term_pics = 0;
for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++)
{
BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1);
}
UEV_PARSE("slice_type", value, ps_bitstrm);
ps_slice_hdr->i1_slice_type = value;
/* If the picture is IRAP, slice type must be equal to ISLICE */
if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) &&
(ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23))
ps_slice_hdr->i1_slice_type = ISLICE;
if((ps_slice_hdr->i1_slice_type < 0) ||
(ps_slice_hdr->i1_slice_type > 2))
return IHEVCD_IGNORE_SLICE;
if(ps_pps->i1_output_flag_present_flag)
{
BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_pic_output_flag = value;
}
ps_slice_hdr->i1_colour_plane_id = 0;
if(1 == ps_sps->i1_separate_colour_plane_flag)
{
BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2);
ps_slice_hdr->i1_colour_plane_id = value;
}
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0;
if(!idr_pic_flag)
{
WORD32 st_rps_idx;
WORD32 num_neg_pics;
WORD32 num_pos_pics;
WORD8 *pi1_used;
BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->i4_pic_order_cnt_lsb = value;
BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value;
if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag)
{
WORD32 numbits;
ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0;
if(ps_sps->i1_num_short_term_ref_pic_sets > 1)
{
numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1);
BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits);
ps_slice_hdr->i1_short_term_ref_pic_set_idx = value;
}
st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx;
num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics;
num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics;
pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used;
}
else
{
ihevcd_short_term_ref_pic_set(ps_bitstrm,
&ps_sps->as_stref_picset[0],
ps_sps->i1_num_short_term_ref_pic_sets,
ps_sps->i1_num_short_term_ref_pic_sets,
&ps_slice_hdr->s_stref_picset);
st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets;
num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics;
num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics;
pi1_used = ps_slice_hdr->s_stref_picset.ai1_used;
}
if(ps_sps->i1_long_term_ref_pics_present_flag)
{
if(ps_sps->i1_num_long_term_ref_pics_sps > 0)
{
UEV_PARSE("num_long_term_sps", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_sps = value;
ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics);
}
UEV_PARSE("num_long_term_pics", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_pics = value;
ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics -
ps_slice_hdr->i1_num_long_term_sps);
for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps +
ps_slice_hdr->i1_num_long_term_pics); i++)
{
if(i < ps_slice_hdr->i1_num_long_term_sps)
{
/* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */
WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps);
BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits);
ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->ai1_lt_ref_pic_poc_lsb_sps[value];
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value];
}
else
{
BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->ai4_poc_lsb_lt[i] = value;
BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value;
}
BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value;
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0;
if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i])
{
UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm);
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value;
}
if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps))
{
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1];
}
}
}
for(i = 0; i < num_neg_pics + num_pos_pics; i++)
{
if(pi1_used[i])
{
num_poc_total_curr++;
}
}
for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++)
{
if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i])
{
num_poc_total_curr++;
}
}
if(ps_sps->i1_sps_temporal_mvp_enable_flag)
{
BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value;
}
}
ps_slice_hdr->i1_slice_sao_luma_flag = 0;
ps_slice_hdr->i1_slice_sao_chroma_flag = 0;
if(ps_sps->i1_sample_adaptive_offset_enabled_flag)
{
BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_luma_flag = value;
BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_chroma_flag = value;
}
ps_slice_hdr->i1_max_num_merge_cand = 1;
ps_slice_hdr->i1_cabac_init_flag = 0;
ps_slice_hdr->i1_num_ref_idx_l0_active = 0;
ps_slice_hdr->i1_num_ref_idx_l1_active = 0;
ps_slice_hdr->i1_slice_cb_qp_offset = 0;
ps_slice_hdr->i1_slice_cr_qp_offset = 0;
if((PSLICE == ps_slice_hdr->i1_slice_type) ||
(BSLICE == ps_slice_hdr->i1_slice_type))
{
BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_num_ref_idx_active_override_flag = value;
if(ps_slice_hdr->i1_num_ref_idx_active_override_flag)
{
UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1;
}
}
else
{
ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active;
}
}
ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1);
ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1);
if(0 == num_poc_total_curr)
return IHEVCD_IGNORE_SLICE;
if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1))
{
ihevcd_ref_pic_list_modification(ps_bitstrm,
ps_slice_hdr, num_poc_total_curr);
}
else
{
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0;
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0;
}
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_mvd_l1_zero_flag = value;
}
ps_slice_hdr->i1_cabac_init_flag = 0;
if(ps_pps->i1_cabac_init_present_flag)
{
BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_cabac_init_flag = value;
}
ps_slice_hdr->i1_collocated_from_l0_flag = 1;
ps_slice_hdr->i1_collocated_ref_idx = 0;
if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag)
{
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_collocated_from_l0_flag = value;
}
if((ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) ||
(!ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1)))
{
UEV_PARSE("collocated_ref_idx", value, ps_bitstrm);
ps_slice_hdr->i1_collocated_ref_idx = value;
}
}
ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1);
if((ps_pps->i1_weighted_pred_flag && (PSLICE == ps_slice_hdr->i1_slice_type)) ||
(ps_pps->i1_weighted_bipred_flag && (BSLICE == ps_slice_hdr->i1_slice_type)))
{
ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr);
}
UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm);
ps_slice_hdr->i1_max_num_merge_cand = 5 - value;
}
ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5);
SEV_PARSE("slice_qp_delta", value, ps_bitstrm);
ps_slice_hdr->i1_slice_qp_delta = value;
if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag)
{
SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cb_qp_offset = value;
SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cr_qp_offset = value;
}
ps_slice_hdr->i1_deblocking_filter_override_flag = 0;
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2;
ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2;
disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
if(ps_pps->i1_deblocking_filter_control_present_flag)
{
if(ps_pps->i1_deblocking_filter_override_enabled_flag)
{
BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_deblocking_filter_override_flag = value;
}
if(ps_slice_hdr->i1_deblocking_filter_override_flag)
{
BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value;
disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag;
if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)
{
SEV_PARSE("beta_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_beta_offset_div2 = value;
SEV_PARSE("tc_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_tc_offset_div2 = value;
}
}
}
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag;
if(ps_pps->i1_loop_filter_across_slices_enabled_flag &&
(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag || !disable_deblocking_filter_flag))
{
BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value;
}
}
/* Check sanity of slice */
if((!first_slice_in_pic_flag) &&
(ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base;
/* According to the standard, the above conditions must be satisfied - But for error resilience,
* only the following conditions are checked */
if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) ||
(ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb))
{
return IHEVCD_IGNORE_SLICE;
}
}
if(0 == ps_codec->i4_pic_present)
{
ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb);
}
else
{
ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt;
}
if(!first_slice_in_pic_flag)
{
/* Check if the current slice belongs to the same pic (Pic being parsed) */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
{
/* If the Next CTB's index is less than the slice address,
* the previous slice is incomplete.
* Indicate slice error, and treat the remaining CTBs as skip */
if(slice_address > ps_codec->s_parse.i4_next_ctb_indx)
{
if(ps_codec->i4_pic_present)
{
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
return ret;
}
else
{
return IHEVCD_IGNORE_SLICE;
}
}
/* If the slice address is less than the next CTB's index,
* extra CTBs have been decoded in the previous slice.
* Ignore the current slice. Treat it as incomplete */
else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx)
{
return IHEVCD_IGNORE_SLICE;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
/* The current slice does not belong to the pic that is being parsed */
else
{
/* The previous pic is incomplete.
* Treat the remaining CTBs as skip */
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
/* If the previous pic is complete,
* return if the current slice is dependant
* otherwise, update the parse context's POC */
else
{
if(ps_slice_hdr->i1_dependent_slice_flag)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
}
}
/* If the slice is the first slice in the pic, update the parse context's POC */
else
{
/* If the first slice is repeated, ignore the second occurrence
* If any other slice is repeated, the CTB addr will be greater than the slice addr,
* and hence the second occurrence is ignored */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
ps_slice_hdr->i4_num_entry_point_offsets = 0;
if((ps_pps->i1_tiles_enabled_flag) ||
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm);
ps_slice_hdr->i4_num_entry_point_offsets = value;
{
WORD32 max_num_entry_point_offsets;
if((ps_pps->i1_tiles_enabled_flag) &&
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1);
}
else if(ps_pps->i1_tiles_enabled_flag)
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows;
}
else
{
max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1);
}
ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets,
0, max_num_entry_point_offsets);
}
if(ps_slice_hdr->i4_num_entry_point_offsets > 0)
{
UEV_PARSE("offset_len_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_offset_len = value + 1;
for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++)
{
BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len);
/* TODO: pu4_entry_point_offset needs to be initialized */
}
}
}
if(ps_pps->i1_slice_header_extension_present_flag)
{
UEV_PARSE("slice_header_extension_length", value, ps_bitstrm);
ps_slice_hdr->i2_slice_header_extension_length = value;
for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++)
{
BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8);
}
}
ihevcd_bits_flush_to_byte_boundary(ps_bitstrm);
{
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
WORD32 r_idx;
if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(0 == ps_codec->u4_pic_cnt))
{
for(i = 0; i < MAX_DPB_BUFS; i++)
{
if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf)
{
pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf;
mv_buf_t *ps_mv_buf;
/* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */
ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc);
/* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */
ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf;
for(i = 0; i < BUF_MGR_MAX_CNT; i++)
{
if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc)
{
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, i, BUF_MGR_REF);
break;
}
ps_mv_buf++;
}
}
}
/* Initialize the reference lists to NULL
* This is done to take care of the cases where the first pic is not IDR
* but the reference list is not created for the first pic because
* pic count is zero leaving the reference list uninitialised */
for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL;
}
}
else
{
ret = ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr);
if ((WORD32)IHEVCD_SUCCESS != ret)
{
return ret;
}
}
}
/* Fill the remaining entries of the reference lists with the nearest POC
* This is done to handle cases where there is a corruption in the reference index */
if(ps_codec->i4_pic_present)
{
pic_buf_t *ps_pic_buf_ref;
mv_buf_t *ps_mv_buf_ref;
WORD32 r_idx;
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr;
ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt);
if(NULL == ps_pic_buf_ref)
{
ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic;
ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf;
}
else
{
ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc);
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
/* Update slice address in the header */
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb;
ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb;
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x;
ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y;
}
}
else
{
ps_slice_hdr->i2_ctb_x = 0;
ps_slice_hdr->i2_ctb_y = 0;
ps_slice_hdr->i2_independent_ctb_x = 0;
ps_slice_hdr->i2_independent_ctb_y = 0;
}
/* If the first slice in the pic is missing, copy the current slice header to
* the first slice's header */
if((!first_slice_in_pic_flag) &&
(0 == ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base;
ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)));
ps_codec->i4_slice_error = 1;
ps_slice_hdr_prev->i2_ctb_x = 0;
ps_slice_hdr_prev->i2_ctb_y = 0;
ps_codec->s_parse.i4_ctb_x = 0;
ps_codec->s_parse.i4_ctb_y = 0;
ps_codec->s_parse.i4_cur_slice_idx = 0;
if((ps_slice_hdr->i2_ctb_x == 0) &&
(ps_slice_hdr->i2_ctb_y == 0))
{
ps_slice_hdr->i2_ctb_x++;
}
}
{
/* If skip B is enabled,
* ignore pictures that are non-reference
* TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is
* sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/
if((i1_nal_unit_type < NAL_BLA_W_LP) &&
(i1_nal_unit_type % 2 == 0))
{
if(IVD_SKIP_B == ps_codec->e_pic_skip_mode)
return IHEVCD_IGNORE_SLICE;
}
/* If skip PB is enabled,
* decode only I slices */
if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) &&
(ISLICE != ps_slice_hdr->i1_slice_type))
{
return IHEVCD_IGNORE_SLICE;
}
}
return ret;
}
Commit Message: Check only allocated mv bufs for releasing from reference
When checking mv bufs for releasing from reference, unallocated
mv bufs were also checked. This issue was fixed by restricting
the loop count to allocated number of mv bufs.
Bug: 34896906
Bug: 34819017
Change-Id: If832f590b301f414d4cd5206414efc61a70c17cb
(cherry picked from commit 23bfe3e06d53ea749073a5d7ceda84239742b2c2)
CWE ID:
Target: 1
Example 2:
Code: static int sctp_setsockopt_maxburst(struct sock *sk,
char __user *optval,
unsigned int optlen)
{
struct sctp_assoc_value params;
struct sctp_sock *sp;
struct sctp_association *asoc;
int val;
int assoc_id = 0;
if (optlen == sizeof(int)) {
pr_warn("Use of int in max_burst socket option deprecated\n");
pr_warn("Use struct sctp_assoc_value instead\n");
if (copy_from_user(&val, optval, optlen))
return -EFAULT;
} else if (optlen == sizeof(struct sctp_assoc_value)) {
if (copy_from_user(¶ms, optval, optlen))
return -EFAULT;
val = params.assoc_value;
assoc_id = params.assoc_id;
} else
return -EINVAL;
sp = sctp_sk(sk);
if (assoc_id != 0) {
asoc = sctp_id2assoc(sk, assoc_id);
if (!asoc)
return -EINVAL;
asoc->max_burst = val;
} else
sp->max_burst = val;
return 0;
}
Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS
Building sctp may fail with:
In function ‘copy_from_user’,
inlined from ‘sctp_getsockopt_assoc_stats’ at
net/sctp/socket.c:5656:20:
arch/x86/include/asm/uaccess_32.h:211:26: error: call to
‘copy_from_user_overflow’ declared with attribute error: copy_from_user()
buffer size is not provably correct
if built with W=1 due to a missing parameter size validation
before the call to copy_from_user.
Signed-off-by: Guenter Roeck <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: usage(int iExitCode)
{
char word[32];
sprintf( word, getJobActionString(mode) );
fprintf( stderr, "Usage: %s [options] [constraints]\n", MyName );
fprintf( stderr, " where [options] is zero or more of:\n" );
fprintf( stderr, " -help Display this message and exit\n" );
fprintf( stderr, " -version Display version information and exit\n" );
fprintf( stderr, " -name schedd_name Connect to the given schedd\n" );
fprintf( stderr, " -pool hostname Use the given central manager to find daemons\n" );
fprintf( stderr, " -addr <ip:port> Connect directly to the given \"sinful string\"\n" );
if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) {
fprintf( stderr, " -reason reason Use the given RemoveReason\n");
} else if( mode == JA_RELEASE_JOBS ) {
fprintf( stderr, " -reason reason Use the given ReleaseReason\n");
} else if( mode == JA_HOLD_JOBS ) {
fprintf( stderr, " -reason reason Use the given HoldReason\n");
fprintf( stderr, " -subcode number Set HoldReasonSubCode\n");
}
if( mode == JA_REMOVE_JOBS || mode == JA_REMOVE_X_JOBS ) {
fprintf( stderr,
" -forcex Force the immediate local removal of jobs in the X state\n"
" (only affects jobs already being removed)\n" );
}
if( mode == JA_VACATE_JOBS || mode == JA_VACATE_FAST_JOBS ) {
fprintf( stderr,
" -fast Use a fast vacate (hardkill)\n" );
}
fprintf( stderr, " and where [constraints] is one of:\n" );
fprintf( stderr, " cluster.proc %s the given job\n", word );
fprintf( stderr, " cluster %s the given cluster of jobs\n", word );
fprintf( stderr, " user %s all jobs owned by user\n", word );
fprintf( stderr, " -constraint expr %s all jobs matching the boolean expression\n", word );
fprintf( stderr, " -all %s all jobs "
"(cannot be used with other constraints)\n", word );
exit( iExitCode );
}
Commit Message:
CWE ID: CWE-134
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
int ret = -ENOMEM, i;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
if (npages > ARRAY_SIZE(pages))
return -ERANGE;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
/* for decoding across pages */
res.acl_scratch = alloc_page(GFP_KERNEL);
if (!res.acl_scratch)
goto out_free;
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
/* Handle the case where the passed-in buffer is too short */
if (res.acl_flags & NFS4_ACL_TRUNC) {
/* Did the user only issue a request for the acl length? */
if (buf == NULL)
goto out_ok;
ret = -ERANGE;
goto out_free;
}
nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len);
if (buf)
_copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len);
out_ok:
ret = res.acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (res.acl_scratch)
__free_page(res.acl_scratch);
return ret;
}
Commit Message: NFSv4: Check for buffer length in __nfs4_get_acl_uncached
Commit 1f1ea6c "NFSv4: Fix buffer overflow checking in
__nfs4_get_acl_uncached" accidently dropped the checking for too small
result buffer length.
If someone uses getxattr on "system.nfs4_acl" on an NFSv4 mount
supporting ACLs, the ACL has not been cached and the buffer suplied is
too short, we still copy the complete ACL, resulting in kernel and user
space memory corruption.
Signed-off-by: Sven Wegener <[email protected]>
Cc: [email protected]
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: virtual void afterTest()
{
EXPECT_GE(2, m_numDraws);
EXPECT_EQ(1, m_numCommits);
}
Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests
https://bugs.webkit.org/show_bug.cgi?id=70161
Reviewed by David Levin.
Source/WebCore:
Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor
thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was
destroyed.
This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit
task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the
CCThreadProxy have been drained.
Covered by the now-enabled CCLayerTreeHostTest* unit tests.
* WebCore.gypi:
* platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added.
(WebCore::CCScopedMainThreadProxy::create):
(WebCore::CCScopedMainThreadProxy::postTask):
(WebCore::CCScopedMainThreadProxy::shutdown):
(WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy):
(WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown):
* platform/graphics/chromium/cc/CCThreadProxy.cpp:
(WebCore::CCThreadProxy::CCThreadProxy):
(WebCore::CCThreadProxy::~CCThreadProxy):
(WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread):
* platform/graphics/chromium/cc/CCThreadProxy.h:
Source/WebKit/chromium:
Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple
thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor
thread scheduling draws by itself.
* tests/CCLayerTreeHostTest.cpp:
(::CCLayerTreeHostTest::timeout):
(::CCLayerTreeHostTest::clearTimeout):
(::CCLayerTreeHostTest::CCLayerTreeHostTest):
(::CCLayerTreeHostTest::onEndTest):
(::CCLayerTreeHostTest::TimeoutTask::TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::clearTest):
(::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask):
(::CCLayerTreeHostTest::TimeoutTask::Run):
(::CCLayerTreeHostTest::runTest):
(::CCLayerTreeHostTest::doBeginTest):
(::CCLayerTreeHostTestThreadOnly::runTest):
(::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread):
git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c);
switch (type) {
case EVP_CTRL_INIT:
gctx->key_set = 0;
gctx->iv_set = 0;
gctx->ivlen = EVP_CIPHER_CTX_iv_length(c);
gctx->iv = EVP_CIPHER_CTX_iv_noconst(c);
gctx->taglen = -1;
gctx->iv_gen = 0;
gctx->tls_aad_len = -1;
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
if (arg <= 0)
return 0;
/* Allocate memory for IV if needed */
if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) {
if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c))
OPENSSL_free(gctx->iv);
gctx->iv = OPENSSL_malloc(arg);
if (gctx->iv == NULL)
return 0;
}
gctx->ivlen = arg;
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c))
return 0;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
gctx->taglen = arg;
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c)
|| gctx->taglen < 0)
return 0;
memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg);
return 1;
case EVP_CTRL_GCM_SET_IV_FIXED:
/* Special case: -1 length restores whole IV */
if (arg == -1) {
memcpy(gctx->iv, ptr, gctx->ivlen);
gctx->iv_gen = 1;
return 1;
}
/*
* Fixed field must be at least 4 bytes and invocation field at least
* 8.
*/
if ((arg < 4) || (gctx->ivlen - arg) < 8)
return 0;
if (arg)
memcpy(gctx->iv, ptr, arg);
if (EVP_CIPHER_CTX_encrypting(c)
&& RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0)
return 0;
gctx->iv_gen = 1;
return 1;
case EVP_CTRL_GCM_IV_GEN:
if (gctx->iv_gen == 0 || gctx->key_set == 0)
return 0;
CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
if (arg <= 0 || arg > gctx->ivlen)
arg = gctx->ivlen;
memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg);
/*
* Invocation field will be at least 8 bytes in size and so no need
* to check wrap around or increment more than last 8 bytes.
*/
ctr64_inc(gctx->iv + gctx->ivlen - 8);
gctx->iv_set = 1;
return 1;
case EVP_CTRL_GCM_SET_IV_INV:
if (gctx->iv_gen == 0 || gctx->key_set == 0
|| EVP_CIPHER_CTX_encrypting(c))
return 0;
memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);
CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
gctx->iv_set = 1;
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
/* Save the AAD for later use */
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
gctx->tls_aad_len = arg;
{
unsigned int len =
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8
| EVP_CIPHER_CTX_buf_noconst(c)[arg - 1];
/* Correct length for explicit IV */
len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
/* If decrypting correct for tag too */
if (!EVP_CIPHER_CTX_encrypting(c))
len -= EVP_GCM_TLS_TAG_LEN;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff;
}
/* Extra padding: tag appended to record */
return EVP_GCM_TLS_TAG_LEN;
case EVP_CTRL_COPY:
{
EVP_CIPHER_CTX *out = ptr;
EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out);
if (gctx->gcm.key) {
if (gctx->gcm.key != &gctx->ks)
return 0;
gctx_out->gcm.key = &gctx_out->ks;
}
if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c))
gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out);
else {
gctx_out->iv = OPENSSL_malloc(gctx->ivlen);
if (gctx_out->iv == NULL)
return 0;
memcpy(gctx_out->iv, gctx->iv, gctx->ivlen);
}
return 1;
}
default:
return -1;
}
}
Commit Message: crypto/evp: harden AEAD ciphers.
Originally a crash in 32-bit build was reported CHACHA20-POLY1305
cipher. The crash is triggered by truncated packet and is result
of excessive hashing to the edge of accessible memory. Since hash
operation is read-only it is not considered to be exploitable
beyond a DoS condition. Other ciphers were hardened.
Thanks to Robert Święcki for report.
CVE-2017-3731
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHPAPI char *php_escape_html_entities_ex(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset, zend_bool double_encode TSRMLS_DC)
{
size_t cursor, maxlen, len;
char *replaced;
enum entity_charset charset = determine_charset(hint_charset TSRMLS_CC);
int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
entity_table_opt entity_table;
const enc_to_uni *to_uni_table = NULL;
const entity_ht *inv_map = NULL; /* used for !double_encode */
/* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */
const unsigned char *replacement = NULL;
size_t replacement_len = 0;
if (all) { /* replace with all named entities */
if (CHARSET_PARTIAL_SUPPORT(charset)) {
php_error_docref0(NULL TSRMLS_CC, E_STRICT, "Only basic entities "
"substitution is supported for multi-byte encodings other than UTF-8; "
"functionality is equivalent to htmlspecialchars");
}
LIMIT_ALL(all, doctype, charset);
}
entity_table = determine_entity_table(all, doctype);
if (all && !CHARSET_UNICODE_COMPAT(charset)) {
to_uni_table = enc_to_uni_index[charset];
}
if (!double_encode) {
/* first arg is 1 because we want to identify valid named entities
* even if we are only encoding the basic ones */
inv_map = unescape_inverse_map(1, flags);
}
if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) {
if (charset == cs_utf_8) {
replacement = (const unsigned char*)"\xEF\xBF\xBD";
replacement_len = sizeof("\xEF\xBF\xBD") - 1;
} else {
replacement = (const unsigned char*)"�";
replacement_len = sizeof("�") - 1;
}
}
/* initial estimate */
if (oldlen < 64) {
maxlen = 128;
} else {
maxlen = 2 * oldlen;
if (maxlen < oldlen) {
zend_error_noreturn(E_ERROR, "Input string is too long");
return NULL;
}
}
replaced = emalloc(maxlen + 1); /* adding 1 is safe: maxlen is even */
len = 0;
cursor = 0;
while (cursor < oldlen) {
const unsigned char *mbsequence = NULL;
size_t mbseqlen = 0,
cursor_before = cursor;
int status = SUCCESS;
unsigned int this_char = get_next_char(charset, old, oldlen, &cursor, &status);
/* guarantee we have at least 40 bytes to write.
* In HTML5, entities may take up to 33 bytes */
if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */
replaced = safe_erealloc(replaced, maxlen , 1, 128 + 1);
maxlen += 128;
}
if (status == FAILURE) {
/* invalid MB sequence */
if (flags & ENT_HTML_IGNORE_ERRORS) {
continue;
} else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) {
memcpy(&replaced[len], replacement, replacement_len);
len += replacement_len;
continue;
} else {
efree(replaced);
*newlen = 0;
return STR_EMPTY_ALLOC();
}
} else { /* SUCCESS */
mbsequence = &old[cursor_before];
mbseqlen = cursor - cursor_before;
}
if (this_char != '&') { /* no entity on this position */
const unsigned char *rep = NULL;
size_t rep_len = 0;
if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
goto pass_char_through;
if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */
if (to_uni_table != NULL) {
/* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8
* is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT,
* we're using a single byte encoding */
map_to_unicode(this_char, to_uni_table, &this_char);
if (this_char == 0xFFFF) /* no mapping; pass through */
goto pass_char_through;
}
/* the cursor may advance */
find_entity_for_char(this_char, charset, entity_table.ms_table, &rep,
&rep_len, old, oldlen, &cursor);
} else {
find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len);
}
if (rep != NULL) {
replaced[len++] = '&';
memcpy(&replaced[len], rep, rep_len);
len += rep_len;
replaced[len++] = ';';
} else {
/* we did not find an entity for this char.
* check for its validity, if its valid pass it unchanged */
if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
if (CHARSET_UNICODE_COMPAT(charset)) {
if (!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
} else if (to_uni_table) {
if (!all) /* otherwise we already did this */
map_to_unicode(this_char, to_uni_table, &this_char);
if (!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
} else {
/* not a unicode code point, unless, coincidentally, it's in
* the 0x20..0x7D range (except 0x5C in sjis). We know nothing
* about other code points, because we have no tables. Since
* Unicode code points in that range are not disallowed in any
* document type, we could do nothing. However, conversion
* tables frequently map 0x00-0x1F to the respective C0 code
* points. Let's play it safe and admit that's the case */
if (this_char <= 0x7D &&
!unicode_cp_is_allowed(this_char, doctype)) {
mbsequence = replacement;
mbseqlen = replacement_len;
}
}
}
pass_char_through:
if (mbseqlen > 1) {
memcpy(replaced + len, mbsequence, mbseqlen);
len += mbseqlen;
} else {
replaced[len++] = mbsequence[0];
}
}
} else { /* this_char == '&' */
if (double_encode) {
encode_amp:
memcpy(&replaced[len], "&", sizeof("&") - 1);
len += sizeof("&") - 1;
} else { /* no double encode */
/* check if entity is valid */
size_t ent_len; /* not counting & or ; */
/* peek at next char */
if (old[cursor] == '#') { /* numeric entity */
unsigned code_point;
int valid;
char *pos = (char*)&old[cursor+1];
valid = process_numeric_entity((const char **)&pos, &code_point);
if (valid == FAILURE)
goto encode_amp;
if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
if (!numeric_entity_is_allowed(code_point, doctype))
goto encode_amp;
}
ent_len = pos - (char*)&old[cursor];
} else { /* named entity */
/* check for vality of named entity */
const char *start = &old[cursor],
*next = start;
unsigned dummy1, dummy2;
if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
goto encode_amp;
if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) {
if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
&& start[1] == 'p' && start[2] == 'o' && start[3] == 's')) {
/* uses html4 inv_map, which doesn't include apos;. This is a
* hack to support it */
goto encode_amp;
}
}
}
/* checks passed; copy entity to result */
/* entity size is unbounded, we may need more memory */
/* at this point maxlen - len >= 40 */
if (maxlen - len < ent_len + 2 /* & and ; */) {
/* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */
replaced = safe_erealloc(replaced, maxlen, 1, ent_len + 128 + 1);
maxlen += ent_len + 128;
}
replaced[len++] = '&';
memcpy(&replaced[len], &old[cursor], ent_len);
len += ent_len;
replaced[len++] = ';';
cursor += ent_len + 1;
}
}
}
replaced[len] = '\0';
*newlen = len;
return replaced;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190
Target: 1
Example 2:
Code: void Document::FinishedParsing() {
DCHECK(!GetScriptableDocumentParser() || !parser_->IsParsing());
DCHECK(!GetScriptableDocumentParser() || ready_state_ != kLoading);
SetParsingState(kInDOMContentLoaded);
DocumentParserTiming::From(*this).MarkParserStop();
if (!document_timing_.DomContentLoadedEventStart())
document_timing_.MarkDomContentLoadedEventStart();
DispatchEvent(Event::CreateBubble(EventTypeNames::DOMContentLoaded));
if (!document_timing_.DomContentLoadedEventEnd())
document_timing_.MarkDomContentLoadedEventEnd();
SetParsingState(kFinishedParsing);
Microtask::PerformCheckpoint(V8PerIsolateData::MainThreadIsolate());
ScriptableDocumentParser* parser = GetScriptableDocumentParser();
well_formed_ = parser && parser->WellFormed();
if (LocalFrame* frame = this->GetFrame()) {
const bool main_resource_was_already_requested =
frame->Loader().StateMachine()->CommittedFirstRealDocumentLoad();
if (main_resource_was_already_requested)
UpdateStyleAndLayoutTree();
BeginLifecycleUpdatesIfRenderingReady();
frame->Loader().FinishedParsing();
TRACE_EVENT_INSTANT1("devtools.timeline", "MarkDOMContent",
TRACE_EVENT_SCOPE_THREAD, "data",
InspectorMarkLoadEvent::Data(frame));
probe::domContentLoadedEventFired(frame);
}
element_data_cache_clear_timer_.StartOneShot(10, BLINK_FROM_HERE);
fetcher_->ClearPreloads(ResourceFetcher::kClearSpeculativeMarkupPreloads);
if (IsPrefetchOnly())
WebPrerenderingSupport::Current()->PrefetchFinished();
}
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 <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static long aio_read_events_ring(struct kioctx *ctx,
struct io_event __user *event, long nr)
{
struct aio_ring *ring;
unsigned head, tail, pos;
long ret = 0;
int copy_ret;
mutex_lock(&ctx->ring_lock);
/* Access to ->ring_pages here is protected by ctx->ring_lock. */
ring = kmap_atomic(ctx->ring_pages[0]);
head = ring->head;
tail = ring->tail;
kunmap_atomic(ring);
/*
* Ensure that once we've read the current tail pointer, that
* we also see the events that were stored up to the tail.
*/
smp_rmb();
pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
if (head == tail)
goto out;
head %= ctx->nr_events;
tail %= ctx->nr_events;
while (ret < nr) {
long avail;
struct io_event *ev;
struct page *page;
avail = (head <= tail ? tail : ctx->nr_events) - head;
if (head == tail)
break;
avail = min(avail, nr - ret);
avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
pos = head + AIO_EVENTS_OFFSET;
page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
pos %= AIO_EVENTS_PER_PAGE;
ev = kmap(page);
copy_ret = copy_to_user(event + ret, ev + pos,
sizeof(*ev) * avail);
kunmap(page);
if (unlikely(copy_ret)) {
ret = -EFAULT;
goto out;
}
ret += avail;
head += avail;
head %= ctx->nr_events;
}
ring = kmap_atomic(ctx->ring_pages[0]);
ring->head = head;
kunmap_atomic(ring);
flush_dcache_page(ctx->ring_pages[0]);
pr_debug("%li h%u t%u\n", ret, head, tail);
out:
mutex_unlock(&ctx->ring_lock);
return ret;
}
Commit Message: AIO: properly check iovec sizes
In Linus's tree, the iovec code has been reworked massively, but in
older kernels the AIO layer should be checking this before passing the
request on to other layers.
Many thanks to Ben Hawkes of Google Project Zero for pointing out the
issue.
Reported-by: Ben Hawkes <[email protected]>
Acked-by: Benjamin LaHaise <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: copy_thread(unsigned long clone_flags, unsigned long stack_start,
unsigned long stk_sz, struct task_struct *p)
{
struct thread_info *thread = task_thread_info(p);
struct pt_regs *childregs = task_pt_regs(p);
memset(&thread->cpu_context, 0, sizeof(struct cpu_context_save));
if (likely(!(p->flags & PF_KTHREAD))) {
*childregs = *current_pt_regs();
childregs->ARM_r0 = 0;
if (stack_start)
childregs->ARM_sp = stack_start;
} else {
memset(childregs, 0, sizeof(struct pt_regs));
thread->cpu_context.r4 = stk_sz;
thread->cpu_context.r5 = stack_start;
childregs->ARM_cpsr = SVC_MODE;
}
thread->cpu_context.pc = (unsigned long)ret_from_fork;
thread->cpu_context.sp = (unsigned long)childregs;
clear_ptrace_hw_breakpoint(p);
if (clone_flags & CLONE_SETTLS)
thread->tp_value = childregs->ARM_r3;
thread_notify(THREAD_NOTIFY_COPY, thread);
return 0;
}
Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork
Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to
prevent it from being used as a covert channel between two tasks.
There are more and more applications coming to Windows RT,
Wine could support them, but mostly they expect to have
the thread environment block (TEB) in TPIDRURW.
This patch preserves that register per thread instead of clearing it.
Unlike the TPIDRURO, which is already switched, the TPIDRURW
can be updated from userspace so needs careful treatment in the case that we
modify TPIDRURW and call fork(). To avoid this we must always read
TPIDRURW in copy_thread.
Signed-off-by: André Hentschel <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
Signed-off-by: Jonathan Austin <[email protected]>
Signed-off-by: Russell King <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: void DeleteChannel(IPC::Channel* channel) {
delete channel;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: do_command (unsigned char c)
{
static int dtr_up = 0;
int newbaud, newflow, newparity, newbits;
const char *xfr_cmd;
char *fname;
int r;
switch (c) {
case KEY_EXIT:
return 1;
case KEY_QUIT:
term_set_hupcl(tty_fd, 0);
term_flush(tty_fd);
term_apply(tty_fd);
term_erase(tty_fd);
return 1;
case KEY_STATUS:
show_status(dtr_up);
break;
case KEY_PULSE:
fd_printf(STO, "\r\n*** pulse DTR ***\r\n");
if ( term_pulse_dtr(tty_fd) < 0 )
fd_printf(STO, "*** FAILED\r\n");
break;
case KEY_TOGGLE:
if ( dtr_up )
r = term_lower_dtr(tty_fd);
else
r = term_raise_dtr(tty_fd);
if ( r >= 0 ) dtr_up = ! dtr_up;
fd_printf(STO, "\r\n*** DTR: %s ***\r\n",
dtr_up ? "up" : "down");
break;
case KEY_BAUD_UP:
case KEY_BAUD_DN:
if (c == KEY_BAUD_UP)
opts.baud = baud_up(opts.baud);
else
opts.baud = baud_down(opts.baud);
term_set_baudrate(tty_fd, opts.baud);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newbaud = term_get_baudrate(tty_fd, NULL);
if ( opts.baud != newbaud ) {
fd_printf(STO, "\r\n*** baud: %d (%d) ***\r\n",
opts.baud, newbaud);
} else {
fd_printf(STO, "\r\n*** baud: %d ***\r\n", opts.baud);
}
set_tty_write_sz(newbaud);
break;
case KEY_FLOW:
opts.flow = flow_next(opts.flow);
term_set_flowcntrl(tty_fd, opts.flow);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newflow = term_get_flowcntrl(tty_fd);
if ( opts.flow != newflow ) {
fd_printf(STO, "\r\n*** flow: %s (%s) ***\r\n",
flow_str[opts.flow], flow_str[newflow]);
} else {
fd_printf(STO, "\r\n*** flow: %s ***\r\n",
flow_str[opts.flow]);
}
break;
case KEY_PARITY:
opts.parity = parity_next(opts.parity);
term_set_parity(tty_fd, opts.parity);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newparity = term_get_parity(tty_fd);
if (opts.parity != newparity ) {
fd_printf(STO, "\r\n*** parity: %s (%s) ***\r\n",
parity_str[opts.parity],
parity_str[newparity]);
} else {
fd_printf(STO, "\r\n*** parity: %s ***\r\n",
parity_str[opts.parity]);
}
break;
case KEY_BITS:
opts.databits = bits_next(opts.databits);
term_set_databits(tty_fd, opts.databits);
tty_q.len = 0; term_flush(tty_fd);
term_apply(tty_fd);
newbits = term_get_databits(tty_fd);
if (opts.databits != newbits ) {
fd_printf(STO, "\r\n*** databits: %d (%d) ***\r\n",
opts.databits, newbits);
} else {
fd_printf(STO, "\r\n*** databits: %d ***\r\n",
opts.databits);
}
break;
case KEY_LECHO:
opts.lecho = ! opts.lecho;
fd_printf(STO, "\r\n*** local echo: %s ***\r\n",
opts.lecho ? "yes" : "no");
break;
case KEY_SEND:
case KEY_RECEIVE:
xfr_cmd = (c == KEY_SEND) ? opts.send_cmd : opts.receive_cmd;
if ( xfr_cmd[0] == '\0' ) {
fd_printf(STO, "\r\n*** command disabled ***\r\n");
break;
}
fname = read_filename();
if (fname == NULL) {
fd_printf(STO, "*** cannot read filename ***\r\n");
break;
}
run_cmd(tty_fd, xfr_cmd, fname, NULL);
free(fname);
break;
case KEY_BREAK:
term_break(tty_fd);
fd_printf(STO, "\r\n*** break sent ***\r\n");
break;
default:
break;
}
return 0;
}
Commit Message: Do not use "/bin/sh" to run external commands.
Picocom no longer uses /bin/sh to run external commands for
file-transfer operations. Parsing the command line and spliting it into
arguments is now performed internally by picocom, using quoting rules
very similar to those of the Unix shell. Hopefully, this makes it
impossible to inject shell-commands when supplying filenames or
extra arguments to the send- and receive-file commands.
CWE ID: CWE-77
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static boolean ReadICCProfile(j_decompress_ptr jpeg_info)
{
char
magick[12];
ErrorManager
*error_manager;
ExceptionInfo
*exception;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*icc_profile,
*profile;
/*
Read color profile.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
for (i=0; i < 12; i++)
magick[i]=(char) GetCharacter(jpeg_info);
if (LocaleCompare(magick,ICC_PROFILE) != 0)
{
/*
Not a ICC profile, return.
*/
for (i=0; i < (ssize_t) (length-12); i++)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
(void) GetCharacter(jpeg_info); /* id */
(void) GetCharacter(jpeg_info); /* markers */
length-=14;
error_manager=(ErrorManager *) jpeg_info->client_data;
exception=error_manager->exception;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=GetCharacter(jpeg_info);
if (c == EOF)
break;
*p++=(unsigned char) c;
}
if (i != (ssize_t) length)
{
profile=DestroyStringInfo(profile);
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"InsufficientImageDataInFile","`%s'",
image->filename);
return(FALSE);
}
error_manager->profile=NULL;
icc_profile=(StringInfo *) GetImageProfile(image,"icc");
if (icc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(icc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"icc",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: ICC, %.20g bytes",(double) length);
return(TRUE);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641
CWE ID:
Target: 1
Example 2:
Code: mISDN_sock_link(struct mISDN_sock_list *l, struct sock *sk)
{
write_lock_bh(&l->lock);
sk_add_node(sk, &l->head);
write_unlock_bh(&l->lock);
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int do_remount_sb(struct super_block *sb, int flags, void *data, int force)
{
int retval;
int remount_ro;
if (sb->s_writers.frozen != SB_UNFROZEN)
return -EBUSY;
#ifdef CONFIG_BLOCK
if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev))
return -EACCES;
#endif
if (flags & MS_RDONLY)
acct_auto_close(sb);
shrink_dcache_sb(sb);
sync_filesystem(sb);
remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY);
/* If we are remounting RDONLY and current sb is read/write,
make sure there are no rw files opened */
if (remount_ro) {
if (force) {
mark_files_ro(sb);
} else {
retval = sb_prepare_remount_readonly(sb);
if (retval)
return retval;
}
}
if (sb->s_op->remount_fs) {
retval = sb->s_op->remount_fs(sb, &flags, data);
if (retval) {
if (!force)
goto cancel_readonly;
/* If forced remount, go ahead despite any errors */
WARN(1, "forced remount of a %s fs returned %i\n",
sb->s_type->name, retval);
}
}
sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK);
/* Needs to be ordered wrt mnt_is_readonly() */
smp_wmb();
sb->s_readonly_remount = 0;
/*
* Some filesystems modify their metadata via some other path than the
* bdev buffer cache (eg. use a private mapping, or directories in
* pagecache, etc). Also file data modifications go via their own
* mappings. So If we try to mount readonly then copy the filesystem
* from bdev, we could get stale data, so invalidate it to give a best
* effort at coherency.
*/
if (remount_ro && sb->s_bdev)
invalidate_bdev(sb->s_bdev);
return 0;
cancel_readonly:
sb->s_readonly_remount = 0;
return retval;
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: vips_foreign_load_gif_scan_image( VipsForeignLoadGif *gif )
{
VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( gif );
GifFileType *file = gif->file;
ColorMapObject *map = file->Image.ColorMap ?
file->Image.ColorMap : file->SColorMap;
GifByteType *extension;
if( DGifGetImageDesc( gif->file ) == GIF_ERROR ) {
vips_foreign_load_gif_error( gif );
return( -1 );
}
/* Check that the frame looks sane. Perhaps giflib checks
* this for us.
*/
if( file->Image.Left < 0 ||
file->Image.Width < 1 ||
file->Image.Width > 10000 ||
file->Image.Left + file->Image.Width > file->SWidth ||
file->Image.Top < 0 ||
file->Image.Height < 1 ||
file->Image.Height > 10000 ||
file->Image.Top + file->Image.Height > file->SHeight ) {
vips_error( class->nickname, "%s", _( "bad frame size" ) );
return( -1 );
}
/* Test for a non-greyscale colourmap for this frame.
*/
if( !gif->has_colour &&
map ) {
int i;
for( i = 0; i < map->ColorCount; i++ )
if( map->Colors[i].Red != map->Colors[i].Green ||
map->Colors[i].Green != map->Colors[i].Blue ) {
gif->has_colour = TRUE;
break;
}
}
/* Step over compressed image data.
*/
do {
if( vips_foreign_load_gif_code_next( gif, &extension ) )
return( -1 );
} while( extension != NULL );
return( 0 );
}
Commit Message: fetch map after DGifGetImageDesc()
Earlier refactoring broke GIF map fetch.
CWE ID:
Target: 1
Example 2:
Code: OVS_EXCLUDED(ofproto_mutex)
{
struct oftable *table;
cmap_destroy(&ofproto->groups);
hmap_remove(&all_ofprotos, &ofproto->hmap_node);
free(ofproto->name);
free(ofproto->type);
free(ofproto->mfr_desc);
free(ofproto->hw_desc);
free(ofproto->sw_desc);
free(ofproto->serial_desc);
free(ofproto->dp_desc);
hmap_destroy(&ofproto->ports);
hmap_destroy(&ofproto->ofport_usage);
shash_destroy(&ofproto->port_by_name);
simap_destroy(&ofproto->ofp_requests);
OFPROTO_FOR_EACH_TABLE (table, ofproto) {
oftable_destroy(table);
}
free(ofproto->tables);
ovs_mutex_lock(&ofproto->vl_mff_map.mutex);
mf_vl_mff_map_clear(&ofproto->vl_mff_map, true);
ovs_mutex_unlock(&ofproto->vl_mff_map.mutex);
cmap_destroy(&ofproto->vl_mff_map.cmap);
ovs_mutex_destroy(&ofproto->vl_mff_map.mutex);
tun_metadata_free(ovsrcu_get_protected(struct tun_table *,
&ofproto->metadata_tab));
ovs_assert(hindex_is_empty(&ofproto->cookies));
hindex_destroy(&ofproto->cookies);
ovs_assert(hmap_is_empty(&ofproto->learned_cookies));
hmap_destroy(&ofproto->learned_cookies);
ofproto->ofproto_class->dealloc(ofproto);
}
Commit Message: ofproto: Fix OVS crash when reverting old flows in bundle commit
During bundle commit flows which are added in bundle are applied
to ofproto in-order. In case if a flow cannot be added (e.g. flow
action is go-to group id which does not exist), OVS tries to
revert back all previous flows which were successfully applied
from the same bundle. This is possible since OVS maintains list
of old flows which were replaced by flows from the bundle.
While reinserting old flows ovs asserts due to check on rule
state != RULE_INITIALIZED. This will work only for new flows, but
for old flow the rule state will be RULE_REMOVED. This is causing
an assert and OVS crash.
The ovs assert check should be modified to != RULE_INSERTED to prevent
any existing rule being re-inserted and allow new rules and old rules
(in case of revert) to get inserted.
Here is an example to trigger the assert:
$ ovs-vsctl add-br br-test -- set Bridge br-test datapath_type=netdev
$ cat flows.txt
flow add table=1,priority=0,in_port=2,actions=NORMAL
flow add table=1,priority=0,in_port=3,actions=NORMAL
$ ovs-ofctl dump-flows -OOpenflow13 br-test
cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=2 actions=NORMAL
cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=3 actions=NORMAL
$ cat flow-modify.txt
flow modify table=1,priority=0,in_port=2,actions=drop
flow modify table=1,priority=0,in_port=3,actions=group:10
$ ovs-ofctl bundle br-test flow-modify.txt -OOpenflow13
First flow rule will be modified since it is a valid rule. However second
rule is invalid since no group with id 10 exists. Bundle commit tries to
revert (insert) the first rule to old flow which results in ovs_assert at
ofproto_rule_insert__() since old rule->state = RULE_REMOVED.
Signed-off-by: Vishal Deep Ajmera <[email protected]>
Signed-off-by: Ben Pfaff <[email protected]>
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int r_bin_dwarf_init_abbrev_decl(RBinDwarfAbbrevDecl *ad) {
if (!ad) {
return -EINVAL;
}
ad->specs = calloc (sizeof( RBinDwarfAttrSpec), ABBREV_DECL_CAP);
if (!ad->specs) {
return -ENOMEM;
}
ad->capacity = ABBREV_DECL_CAP;
ad->length = 0;
return 0;
}
Commit Message: Fix #8813 - segfault in dwarf parser
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) {
current_content_source_id_ = next_source_id;
did_receive_first_frame_after_navigation_ = false;
if (enable_surface_synchronization_) {
visual_properties_ack_pending_ = false;
viz::LocalSurfaceId old_surface_id = view_->GetLocalSurfaceId();
if (view_)
view_->DidNavigate();
viz::LocalSurfaceId new_surface_id = view_->GetLocalSurfaceId();
if (old_surface_id == new_surface_id)
return;
} else {
if (last_received_content_source_id_ >= current_content_source_id_)
return;
}
if (!new_content_rendering_timeout_)
return;
new_content_rendering_timeout_->Start(new_content_rendering_delay_);
}
Commit Message: Start rendering timer after first navigation
Currently the new content rendering timer in the browser process,
which clears an old page's contents 4 seconds after a navigation if the
new page doesn't draw in that time, is not set on the first navigation
for a top-level frame.
This is problematic because content can exist before the first
navigation, for instance if it was created by a javascript: URL.
This CL removes the code that skips the timer activation on the first
navigation.
Bug: 844881
Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584
Reviewed-on: https://chromium-review.googlesource.com/1188589
Reviewed-by: Fady Samuel <[email protected]>
Reviewed-by: ccameron <[email protected]>
Commit-Queue: Ken Buchanan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586913}
CWE ID: CWE-20
Target: 1
Example 2:
Code: ReattachToOldMaster(DeviceIntPtr dev)
{
DeviceIntPtr master = NULL;
if (IsMaster(dev))
return;
dixLookupDevice(&master, dev->saved_master_id, serverClient, DixUseAccess);
if (master) {
AttachDevice(serverClient, dev, master);
dev->saved_master_id = 0;
}
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);
if (!config) {
LOG_WARN(LOG_TAG, "%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();
if (!config) {
LOG_ERROR(LOG_TAG, "%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))
unlink(LEGACY_CONFIG_FILE_PATH);
}
alarm_timer = alarm_new();
if (!alarm_timer) {
LOG_ERROR(LOG_TAG, "%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
Commit Message: Fix crashes with lots of discovered LE devices
When loads of devices are discovered a config file which is too large
can be written out, which causes the BT daemon to crash on startup.
This limits the number of config entries for unpaired devices which
are initialized, and prevents a large number from being saved to the
filesystem.
Bug: 26071376
Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx)
{
struct sta_info *sta = tx->sta;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb);
struct ieee80211_local *local = tx->local;
if (unlikely(!sta))
return TX_CONTINUE;
if (unlikely((test_sta_flag(sta, WLAN_STA_PS_STA) ||
test_sta_flag(sta, WLAN_STA_PS_DRIVER)) &&
!(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER))) {
int ac = skb_get_queue_mapping(tx->skb);
ps_dbg(sta->sdata, "STA %pM aid %d: PS buffer for AC %d\n",
sta->sta.addr, sta->sta.aid, ac);
if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER)
purge_old_ps_buffers(tx->local);
if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) {
struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]);
ps_dbg(tx->sdata,
"STA %pM TX buffer for AC %d full - dropping oldest frame\n",
sta->sta.addr, ac);
ieee80211_free_txskb(&local->hw, old);
} else
tx->local->total_ps_buffered++;
info->control.jiffies = jiffies;
info->control.vif = &tx->sdata->vif;
info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING;
info->flags &= ~IEEE80211_TX_TEMPORARY_FLAGS;
skb_queue_tail(&sta->ps_tx_buf[ac], tx->skb);
if (!timer_pending(&local->sta_cleanup))
mod_timer(&local->sta_cleanup,
round_jiffies(jiffies +
STA_INFO_CLEANUP_INTERVAL));
/*
* We queued up some frames, so the TIM bit might
* need to be set, recalculate it.
*/
sta_info_recalc_tim(sta);
return TX_QUEUED;
} else if (unlikely(test_sta_flag(sta, WLAN_STA_PS_STA))) {
ps_dbg(tx->sdata,
"STA %pM in PS mode, but polling/in SP -> send frame\n",
sta->sta.addr);
}
return TX_CONTINUE;
}
Commit Message: mac80211: fix AP powersave TX vs. wakeup race
There is a race between the TX path and the STA wakeup: while
a station is sleeping, mac80211 buffers frames until it wakes
up, then the frames are transmitted. However, the RX and TX
path are concurrent, so the packet indicating wakeup can be
processed while a packet is being transmitted.
This can lead to a situation where the buffered frames list
is emptied on the one side, while a frame is being added on
the other side, as the station is still seen as sleeping in
the TX path.
As a result, the newly added frame will not be send anytime
soon. It might be sent much later (and out of order) when the
station goes to sleep and wakes up the next time.
Additionally, it can lead to the crash below.
Fix all this by synchronising both paths with a new lock.
Both path are not fastpath since they handle PS situations.
In a later patch we'll remove the extra skb queue locks to
reduce locking overhead.
BUG: unable to handle kernel
NULL pointer dereference at 000000b0
IP: [<ff6f1791>] ieee80211_report_used_skb+0x11/0x3e0 [mac80211]
*pde = 00000000
Oops: 0000 [#1] SMP DEBUG_PAGEALLOC
EIP: 0060:[<ff6f1791>] EFLAGS: 00210282 CPU: 1
EIP is at ieee80211_report_used_skb+0x11/0x3e0 [mac80211]
EAX: e5900da0 EBX: 00000000 ECX: 00000001 EDX: 00000000
ESI: e41d00c0 EDI: e5900da0 EBP: ebe458e4 ESP: ebe458b0
DS: 007b ES: 007b FS: 00d8 GS: 00e0 SS: 0068
CR0: 8005003b CR2: 000000b0 CR3: 25a78000 CR4: 000407d0
DR0: 00000000 DR1: 00000000 DR2: 00000000 DR3: 00000000
DR6: ffff0ff0 DR7: 00000400
Process iperf (pid: 3934, ti=ebe44000 task=e757c0b0 task.ti=ebe44000)
iwlwifi 0000:02:00.0: I iwl_pcie_enqueue_hcmd Sending command LQ_CMD (#4e), seq: 0x0903, 92 bytes at 3[3]:9
Stack:
e403b32c ebe458c4 00200002 00200286 e403b338 ebe458cc c10960bb e5900da0
ff76a6ec ebe458d8 00000000 e41d00c0 e5900da0 ebe458f0 ff6f1b75 e403b210
ebe4598c ff723dc1 00000000 ff76a6ec e597c978 e403b758 00000002 00000002
Call Trace:
[<ff6f1b75>] ieee80211_free_txskb+0x15/0x20 [mac80211]
[<ff723dc1>] invoke_tx_handlers+0x1661/0x1780 [mac80211]
[<ff7248a5>] ieee80211_tx+0x75/0x100 [mac80211]
[<ff7249bf>] ieee80211_xmit+0x8f/0xc0 [mac80211]
[<ff72550e>] ieee80211_subif_start_xmit+0x4fe/0xe20 [mac80211]
[<c149ef70>] dev_hard_start_xmit+0x450/0x950
[<c14b9aa9>] sch_direct_xmit+0xa9/0x250
[<c14b9c9b>] __qdisc_run+0x4b/0x150
[<c149f732>] dev_queue_xmit+0x2c2/0xca0
Cc: [email protected]
Reported-by: Yaara Rozenblum <[email protected]>
Signed-off-by: Emmanuel Grumbach <[email protected]>
Reviewed-by: Stanislaw Gruszka <[email protected]>
[reword commit log, use a separate lock]
Signed-off-by: Johannes Berg <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: float ewk_frame_text_zoom_get(const Evas_Object* ewkFrame)
{
EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData, -1.0);
EINA_SAFETY_ON_NULL_RETURN_VAL(smartData->frame, -1.0);
return smartData->frame->textZoomFactor();
}
Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing
https://bugs.webkit.org/show_bug.cgi?id=85879
Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17
Reviewed by Noam Rosenthal.
Source/WebKit/efl:
_ewk_frame_smart_del() is considering now that the frame can be present in cache.
loader()->detachFromParent() is only applied for the main frame.
loader()->cancelAndClear() is not used anymore.
* ewk/ewk_frame.cpp:
(_ewk_frame_smart_del):
LayoutTests:
* platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html.
git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int kvm_iommu_unmap_guest(struct kvm *kvm)
{
struct iommu_domain *domain = kvm->arch.iommu_domain;
/* check if iommu exists and in use */
if (!domain)
return 0;
mutex_lock(&kvm->slots_lock);
kvm_iommu_unmap_memslots(kvm);
kvm->arch.iommu_domain = NULL;
kvm->arch.iommu_noncoherent = false;
mutex_unlock(&kvm->slots_lock);
iommu_domain_free(domain);
return 0;
}
Commit Message: kvm: fix excessive pages un-pinning in kvm_iommu_map error path.
The third parameter of kvm_unpin_pages() when called from
kvm_iommu_map_pages() is wrong, it should be the number of pages to un-pin
and not the page size.
This error was facilitated with an inconsistent API: kvm_pin_pages() takes
a size, but kvn_unpin_pages() takes a number of pages, so fix the problem
by matching the two.
This was introduced by commit 350b8bd ("kvm: iommu: fix the third parameter
of kvm_iommu_put_pages (CVE-2014-3601)"), which fixes the lack of
un-pinning for pages intended to be un-pinned (i.e. memory leak) but
unfortunately potentially aggravated the number of pages we un-pin that
should have stayed pinned. As far as I understand though, the same
practical mitigations apply.
This issue was found during review of Red Hat 6.6 patches to prepare
Ksplice rebootless updates.
Thanks to Vegard for his time on a late Friday evening to help me in
understanding this code.
Fixes: 350b8bd ("kvm: iommu: fix the third parameter of... (CVE-2014-3601)")
Cc: [email protected]
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: Vegard Nossum <[email protected]>
Signed-off-by: Jamie Iles <[email protected]>
Reviewed-by: Sasha Levin <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void handle_pxe_menu(cmd_tbl_t *cmdtp, struct pxe_menu *cfg)
{
void *choice;
struct menu *m;
int err;
#ifdef CONFIG_CMD_BMP
/* display BMP if available */
if (cfg->bmp) {
if (get_relfile(cmdtp, cfg->bmp, image_load_addr)) {
run_command("cls", 0);
bmp_display(image_load_addr,
BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
} else {
printf("Skipping background bmp %s for failure\n",
cfg->bmp);
}
}
#endif
m = pxe_menu_to_menu(cfg);
if (!m)
return;
err = menu_get_choice(m, &choice);
menu_destroy(m);
/*
* err == 1 means we got a choice back from menu_get_choice.
*
* err == -ENOENT if the menu was setup to select the default but no
* default was set. in that case, we should continue trying to boot
* labels that haven't been attempted yet.
*
* otherwise, the user interrupted or there was some other error and
* we give up.
*/
if (err == 1) {
err = label_boot(cmdtp, choice);
if (!err)
return;
} else if (err != -ENOENT) {
return;
}
boot_unattempted_labels(cmdtp, cfg);
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
Target: 1
Example 2:
Code: int32_t Plugin::GetPOSIXFileDesc(const nacl::string& url) {
PLUGIN_PRINTF(("Plugin::GetFileDesc (url=%s)\n", url.c_str()));
int32_t file_desc_ok_to_close = NACL_NO_FILE_DESC;
std::map<nacl::string, int32_t>::iterator it = url_fd_map_.find(url);
if (it != url_fd_map_.end())
file_desc_ok_to_close = DUP(it->second);
return file_desc_ok_to_close;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void flush_altivec_to_thread(struct task_struct *tsk)
{
if (tsk->thread.regs) {
preempt_disable();
if (tsk->thread.regs->msr & MSR_VEC) {
#ifdef CONFIG_SMP
BUG_ON(tsk != current);
#endif
giveup_altivec_maybe_transactional(tsk);
}
preempt_enable();
}
}
Commit Message: powerpc/tm: Fix crash when forking inside a transaction
When we fork/clone we currently don't copy any of the TM state to the new
thread. This results in a TM bad thing (program check) when the new process is
switched in as the kernel does a tmrechkpt with TEXASR FS not set. Also, since
R1 is from userspace, we trigger the bad kernel stack pointer detection. So we
end up with something like this:
Bad kernel stack pointer 0 at c0000000000404fc
cpu 0x2: Vector: 700 (Program Check) at [c00000003ffefd40]
pc: c0000000000404fc: restore_gprs+0xc0/0x148
lr: 0000000000000000
sp: 0
msr: 9000000100201030
current = 0xc000001dd1417c30
paca = 0xc00000000fe00800 softe: 0 irq_happened: 0x01
pid = 0, comm = swapper/2
WARNING: exception is not recoverable, can't continue
The below fixes this by flushing the TM state before we copy the task_struct to
the clone. To do this we go through the tmreclaim patch, which removes the
checkpointed registers from the CPU and transitions the CPU out of TM suspend
mode. Hence we need to call tmrechkpt after to restore the checkpointed state
and the TM mode for the current task.
To make this fail from userspace is simply:
tbegin
li r0, 2
sc
<boom>
Kudos to Adhemerval Zanella Neto for finding this.
Signed-off-by: Michael Neuling <[email protected]>
cc: Adhemerval Zanella Neto <[email protected]>
cc: [email protected]
Signed-off-by: Benjamin Herrenschmidt <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void init_vmcb(struct vcpu_svm *svm)
{
struct vmcb_control_area *control = &svm->vmcb->control;
struct vmcb_save_area *save = &svm->vmcb->save;
svm->vcpu.fpu_active = 1;
svm->vcpu.arch.hflags = 0;
set_cr_intercept(svm, INTERCEPT_CR0_READ);
set_cr_intercept(svm, INTERCEPT_CR3_READ);
set_cr_intercept(svm, INTERCEPT_CR4_READ);
set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
set_dr_intercepts(svm);
set_exception_intercept(svm, PF_VECTOR);
set_exception_intercept(svm, UD_VECTOR);
set_exception_intercept(svm, MC_VECTOR);
set_intercept(svm, INTERCEPT_INTR);
set_intercept(svm, INTERCEPT_NMI);
set_intercept(svm, INTERCEPT_SMI);
set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
set_intercept(svm, INTERCEPT_RDPMC);
set_intercept(svm, INTERCEPT_CPUID);
set_intercept(svm, INTERCEPT_INVD);
set_intercept(svm, INTERCEPT_HLT);
set_intercept(svm, INTERCEPT_INVLPG);
set_intercept(svm, INTERCEPT_INVLPGA);
set_intercept(svm, INTERCEPT_IOIO_PROT);
set_intercept(svm, INTERCEPT_MSR_PROT);
set_intercept(svm, INTERCEPT_TASK_SWITCH);
set_intercept(svm, INTERCEPT_SHUTDOWN);
set_intercept(svm, INTERCEPT_VMRUN);
set_intercept(svm, INTERCEPT_VMMCALL);
set_intercept(svm, INTERCEPT_VMLOAD);
set_intercept(svm, INTERCEPT_VMSAVE);
set_intercept(svm, INTERCEPT_STGI);
set_intercept(svm, INTERCEPT_CLGI);
set_intercept(svm, INTERCEPT_SKINIT);
set_intercept(svm, INTERCEPT_WBINVD);
set_intercept(svm, INTERCEPT_MONITOR);
set_intercept(svm, INTERCEPT_MWAIT);
set_intercept(svm, INTERCEPT_XSETBV);
control->iopm_base_pa = iopm_base;
control->msrpm_base_pa = __pa(svm->msrpm);
control->int_ctl = V_INTR_MASKING_MASK;
init_seg(&save->es);
init_seg(&save->ss);
init_seg(&save->ds);
init_seg(&save->fs);
init_seg(&save->gs);
save->cs.selector = 0xf000;
save->cs.base = 0xffff0000;
/* Executable/Readable Code Segment */
save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
save->cs.limit = 0xffff;
save->gdtr.limit = 0xffff;
save->idtr.limit = 0xffff;
init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
svm_set_efer(&svm->vcpu, 0);
save->dr6 = 0xffff0ff0;
kvm_set_rflags(&svm->vcpu, 2);
save->rip = 0x0000fff0;
svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
/*
* svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
* It also updates the guest-visible cr0 value.
*/
svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
kvm_mmu_reset_context(&svm->vcpu);
save->cr4 = X86_CR4_PAE;
/* rdx = ?? */
if (npt_enabled) {
/* Setup VMCB for Nested Paging */
control->nested_ctl = 1;
clr_intercept(svm, INTERCEPT_INVLPG);
clr_exception_intercept(svm, PF_VECTOR);
clr_cr_intercept(svm, INTERCEPT_CR3_READ);
clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
save->g_pat = svm->vcpu.arch.pat;
save->cr3 = 0;
save->cr4 = 0;
}
svm->asid_generation = 0;
svm->nested.vmcb = 0;
svm->vcpu.arch.hflags = 0;
if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
control->pause_filter_count = 3000;
set_intercept(svm, INTERCEPT_PAUSE);
}
mark_all_dirty(svm->vmcb);
enable_gif(svm);
}
Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered
It was found that a guest can DoS a host by triggering an infinite
stream of "alignment check" (#AC) exceptions. This causes the
microcode to enter an infinite loop where the core never receives
another interrupt. The host kernel panics pretty quickly due to the
effects (CVE-2015-5307).
Signed-off-by: Eric Northup <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: pgp_select_file(sc_card_t *card, const sc_path_t *path, sc_file_t **ret)
{
struct pgp_priv_data *priv = DRVDATA(card);
pgp_blob_t *blob;
unsigned int path_start = 0;
unsigned int n;
sc_path_t dummy_path;
LOG_FUNC_CALLED(card->ctx);
if (path->type == SC_PATH_TYPE_DF_NAME)
LOG_FUNC_RETURN(card->ctx, iso_ops->select_file(card, path, ret));
if (path->len < 2 || (path->len & 1))
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
"invalid path length");
if (path->type == SC_PATH_TYPE_FILE_ID && path->len != 2)
LOG_TEST_RET(card->ctx, SC_ERROR_INVALID_ARGUMENTS,
"invalid path type");
/* Due to pkcs15init implementation, sometimes a file at path "11001101"
* need to be written (one use case is when importing key&cert from p12 file).
* This file does not exist in OpenPGP but pkcs15 requires that
* writing this file must be successful.
* So, we pretend that selecting & writing this file is successful.
* The "11001101"is defined in sc_pkcs15emu_get_df() function, pkcs15-sync.c file. */
sc_format_path("11001101", &dummy_path);
if (sc_compare_path(path, &dummy_path)) {
if (ret != NULL) {
*ret = sc_file_new();
/* One use case of this dummy file is after writing certificate in pkcs15init.
* So we set its size to be the same as max certificate size the card supports. */
(*ret)->size = priv->max_cert_size;
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
/* ignore explicitly mentioned MF at the path's beginning */
path_start = pgp_strip_path(card, path);
/* starting with the MF ... */
blob = priv->mf;
/* ... recurse through the tree following the path */
for (n = path_start; n < path->len; n += 2) {
unsigned int id = bebytes2ushort(path->value + n);
int r = pgp_get_blob(card, blob, id, &blob);
/* This file ID is referred when importing key&certificate via pkcs15init, like above.
* We pretend to successfully find this inexistent file. */
if (id == 0x4402 || id == 0x5f48) {
if (ret == NULL)
/* No need to return file */
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
/* Else, need to return file */
*ret = sc_file_new();
(*ret)->size = priv->max_cert_size;
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
if (r < 0) { /* failure */
LOG_FUNC_RETURN(card->ctx, r);
}
}
/* success: select file = set "current" pointer to blob found */
priv->current = blob;
if (ret)
sc_file_dup(ret, blob->file);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool WebRequestPermissions::CanExtensionAccessURL(
const extensions::InfoMap* extension_info_map,
const std::string& extension_id,
const GURL& url,
bool crosses_incognito,
HostPermissionsCheck host_permissions_check) {
if (!extension_info_map)
return true;
const extensions::Extension* extension =
extension_info_map->extensions().GetByID(extension_id);
if (!extension)
return false;
if (crosses_incognito && !extension_info_map->CanCrossIncognito(extension))
return false;
switch (host_permissions_check) {
case DO_NOT_CHECK_HOST:
break;
case REQUIRE_HOST_PERMISSION:
if (!((url.SchemeIs(url::kAboutScheme) ||
extension->permissions_data()->HasHostPermission(url) ||
url.GetOrigin() == extension->url()))) {
return false;
}
break;
case REQUIRE_ALL_URLS:
if (!extension->permissions_data()->HasEffectiveAccessToAllHosts())
return false;
break;
}
return true;
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t MPEG4Extractor::parse3GPPMetaData(off64_t offset, size_t size, int depth) {
if (size < 4 || size == SIZE_MAX) {
return ERROR_MALFORMED;
}
uint8_t *buffer = new (std::nothrow) uint8_t[size + 1];
if (buffer == NULL) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
offset, buffer, size) != (ssize_t)size) {
delete[] buffer;
buffer = NULL;
return ERROR_IO;
}
uint32_t metadataKey = 0;
switch (mPath[depth]) {
case FOURCC('t', 'i', 't', 'l'):
{
metadataKey = kKeyTitle;
break;
}
case FOURCC('p', 'e', 'r', 'f'):
{
metadataKey = kKeyArtist;
break;
}
case FOURCC('a', 'u', 't', 'h'):
{
metadataKey = kKeyWriter;
break;
}
case FOURCC('g', 'n', 'r', 'e'):
{
metadataKey = kKeyGenre;
break;
}
case FOURCC('a', 'l', 'b', 'm'):
{
if (buffer[size - 1] != '\0') {
char tmp[4];
sprintf(tmp, "%u", buffer[size - 1]);
mFileMetaData->setCString(kKeyCDTrackNumber, tmp);
}
metadataKey = kKeyAlbum;
break;
}
case FOURCC('y', 'r', 'r', 'c'):
{
char tmp[5];
uint16_t year = U16_AT(&buffer[4]);
if (year < 10000) {
sprintf(tmp, "%u", year);
mFileMetaData->setCString(kKeyYear, tmp);
}
break;
}
default:
break;
}
if (metadataKey > 0) {
bool isUTF8 = true; // Common case
char16_t *framedata = NULL;
int len16 = 0; // Number of UTF-16 characters
if (size - 6 >= 4) {
len16 = ((size - 6) / 2) - 1; // don't include 0x0000 terminator
framedata = (char16_t *)(buffer + 6);
if (0xfffe == *framedata) {
for (int i = 0; i < len16; i++) {
framedata[i] = bswap_16(framedata[i]);
}
}
if (0xfeff == *framedata) {
framedata++;
len16--;
isUTF8 = false;
}
}
if (isUTF8) {
buffer[size] = 0;
mFileMetaData->setCString(metadataKey, (const char *)buffer + 6);
} else {
String8 tmpUTF8str(framedata, len16);
mFileMetaData->setCString(metadataKey, tmpUTF8str.string());
}
}
delete[] buffer;
buffer = NULL;
return OK;
}
Commit Message: Prevent integer underflow if size is below 6
When processing 3GPP metadata, a subtraction operation may underflow and
lead to a rather large linear byteswap operation in the subsequent
framedata decoding code. Bound the 'size' value to prevent this from
occurring.
Bug: 20923261
Change-Id: I35dfbc8878c6b65cfe8b8adb7351a77ad4d604e5
(cherry picked from commit 9458e715d391ee8fe455fc31f07ff35ce12e0531)
CWE ID: CWE-119
Target: 1
Example 2:
Code: nfsd_create(struct svc_rqst *rqstp, struct svc_fh *fhp,
char *fname, int flen, struct iattr *iap,
int type, dev_t rdev, struct svc_fh *resfhp)
{
struct dentry *dentry, *dchild = NULL;
struct inode *dirp;
__be32 err;
int host_err;
if (isdotent(fname, flen))
return nfserr_exist;
err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_NOP);
if (err)
return err;
dentry = fhp->fh_dentry;
dirp = d_inode(dentry);
host_err = fh_want_write(fhp);
if (host_err)
return nfserrno(host_err);
fh_lock_nested(fhp, I_MUTEX_PARENT);
dchild = lookup_one_len(fname, dentry, flen);
host_err = PTR_ERR(dchild);
if (IS_ERR(dchild))
return nfserrno(host_err);
err = fh_compose(resfhp, fhp->fh_export, dchild, fhp);
/*
* We unconditionally drop our ref to dchild as fh_compose will have
* already grabbed its own ref for it.
*/
dput(dchild);
if (err)
return err;
return nfsd_create_locked(rqstp, fhp, fname, flen, iap, type,
rdev, resfhp);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int snd_ctl_elem_write(struct snd_card *card, struct snd_ctl_file *file,
struct snd_ctl_elem_value *control)
{
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int index_offset;
int result;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_id(card, &control->id);
if (kctl == NULL) {
result = -ENOENT;
} else {
index_offset = snd_ctl_get_ioff(kctl, &control->id);
vd = &kctl->vd[index_offset];
if (!(vd->access & SNDRV_CTL_ELEM_ACCESS_WRITE) ||
kctl->put == NULL ||
(file && vd->owner && vd->owner != file)) {
result = -EPERM;
} else {
snd_ctl_build_ioff(&control->id, kctl, index_offset);
result = kctl->put(kctl, control);
}
if (result > 0) {
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE,
&control->id);
return 0;
}
}
up_read(&card->controls_rwsem);
return result;
}
Commit Message: ALSA: control: Don't access controls outside of protected regions
A control that is visible on the card->controls list can be freed at any time.
This means we must not access any of its memory while not holding the
controls_rw_lock. Otherwise we risk a use after free access.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: parse_tsquery(char *buf,
PushFunction pushval,
Datum opaque,
bool isplain)
{
struct TSQueryParserStateData state;
int i;
TSQuery query;
int commonlen;
QueryItem *ptr;
ListCell *cell;
/* init state */
state.buffer = buf;
state.buf = buf;
state.state = (isplain) ? WAITSINGLEOPERAND : WAITFIRSTOPERAND;
state.count = 0;
state.polstr = NIL;
/* init value parser's state */
state.valstate = init_tsvector_parser(state.buffer, true, true);
/* init list of operand */
state.sumlen = 0;
state.lenop = 64;
state.curop = state.op = (char *) palloc(state.lenop);
*(state.curop) = '\0';
/* parse query & make polish notation (postfix, but in reverse order) */
makepol(&state, pushval, opaque);
close_tsvector_parser(state.valstate);
if (list_length(state.polstr) == 0)
{
ereport(NOTICE,
(errmsg("text-search query doesn't contain lexemes: \"%s\"",
state.buffer)));
query = (TSQuery) palloc(HDRSIZETQ);
SET_VARSIZE(query, HDRSIZETQ);
query->size = 0;
return query;
}
/* Pack the QueryItems in the final TSQuery struct to return to caller */
commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen);
query = (TSQuery) palloc0(commonlen);
SET_VARSIZE(query, commonlen);
query->size = list_length(state.polstr);
ptr = GETQUERY(query);
/* Copy QueryItems to TSQuery */
i = 0;
foreach(cell, state.polstr)
{
QueryItem *item = (QueryItem *) lfirst(cell);
switch (item->type)
{
case QI_VAL:
memcpy(&ptr[i], item, sizeof(QueryOperand));
break;
case QI_VALSTOP:
ptr[i].type = QI_VALSTOP;
break;
case QI_OPR:
memcpy(&ptr[i], item, sizeof(QueryOperator));
break;
default:
elog(ERROR, "unrecognized QueryItem type: %d", item->type);
}
i++;
}
/* Copy all the operand strings to TSQuery */
memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen);
pfree(state.op);
/* Set left operand pointers for every operator. */
findoprnd(ptr, query->size);
return query;
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189
Target: 1
Example 2:
Code: bool RenderFrameImpl::IsPluginHandledExternally(
const blink::WebElement& plugin_element,
const blink::WebURL& url,
const blink::WebString& suggested_mime_type) {
#if BUILDFLAG(ENABLE_PLUGINS)
if (!BrowserPluginManager::Get()) {
return false;
}
int32_t tentative_element_instance_id =
BrowserPluginManager::Get()->GetNextInstanceID();
return GetContentClient()->renderer()->MaybeCreateMimeHandlerView(
this, plugin_element, GURL(url), suggested_mime_type.Utf8(),
tentative_element_instance_id);
#else
return false;
#endif
}
Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s)
ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl.
We need to reset external_popup_menu_ before calling it.
Bug: 912211
Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc
Reviewed-on: https://chromium-review.googlesource.com/c/1381325
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618026}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CLASS redcine_load_raw()
{
#ifdef HAVE_LIBJASPER
int c, row, col;
jas_stream_t *in;
jas_image_t *jimg;
jas_matrix_t *jmat;
jas_seqent_t *data;
ushort *img, *pix;
jas_init();
in = jas_stream_fopen (ifname, "rb");
jas_stream_seek (in, data_offset+20, SEEK_SET);
jimg = jas_image_decode (in, -1, 0);
if (!jimg) longjmp (failure, 3);
jmat = jas_matrix_create (height/2, width/2);
merror (jmat, "redcine_load_raw()");
img = (ushort *) calloc ((height+2)*(width+2), 2);
merror (img, "redcine_load_raw()");
FORC4 {
jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat);
data = jas_matrix_getref (jmat, 0, 0);
for (row = c >> 1; row < height; row+=2)
for (col = c & 1; col < width; col+=2)
img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2];
}
for (col=1; col <= width; col++) {
img[col] = img[2*(width+2)+col];
img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col];
}
for (row=0; row < height+2; row++) {
img[row*(width+2)] = img[row*(width+2)+2];
img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3];
}
for (row=1; row <= height; row++) {
pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1));
for ( ; col <= width; col+=2, pix+=2) {
c = (((pix[0] - 0x800) << 3) +
pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2;
pix[0] = LIM(c,0,4095);
}
}
for (row=0; row < height; row++)
for (col=0; col < width; col++)
BAYER(row,col) = curve[img[(row+1)*(width+2)+col+1]];
free (img);
jas_matrix_destroy (jmat);
jas_image_destroy (jimg);
jas_stream_close (in);
#endif
}
Commit Message: Avoid overflow in ljpeg_start().
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info)
{
int rc = -ENOMEM, xid;
struct cifsSesInfo *ses;
xid = GetXid();
ses = cifs_find_smb_ses(server, volume_info->username);
if (ses) {
cFYI(1, "Existing smb sess found (status=%d)", ses->status);
/* existing SMB ses has a server reference already */
cifs_put_tcp_session(server);
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our ses reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
if (ses->need_reconnect) {
cFYI(1, "Session needs reconnect");
rc = cifs_setup_session(xid, ses,
volume_info->local_nls);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
}
mutex_unlock(&ses->session_mutex);
FreeXid(xid);
return ses;
}
cFYI(1, "Existing smb sess not found");
ses = sesInfoAlloc();
if (ses == NULL)
goto get_ses_fail;
/* new SMB session uses our server ref */
ses->server = server;
if (server->addr.sockAddr6.sin6_family == AF_INET6)
sprintf(ses->serverName, "%pI6",
&server->addr.sockAddr6.sin6_addr);
else
sprintf(ses->serverName, "%pI4",
&server->addr.sockAddr.sin_addr.s_addr);
if (volume_info->username)
strncpy(ses->userName, volume_info->username,
MAX_USERNAME_SIZE);
/* volume_info->password freed at unmount */
if (volume_info->password) {
ses->password = kstrdup(volume_info->password, GFP_KERNEL);
if (!ses->password)
goto get_ses_fail;
}
if (volume_info->domainname) {
int len = strlen(volume_info->domainname);
ses->domainName = kmalloc(len + 1, GFP_KERNEL);
if (ses->domainName)
strcpy(ses->domainName, volume_info->domainname);
}
ses->linux_uid = volume_info->linux_uid;
ses->overrideSecFlg = volume_info->secFlg;
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (!rc)
rc = cifs_setup_session(xid, ses, volume_info->local_nls);
mutex_unlock(&ses->session_mutex);
if (rc)
goto get_ses_fail;
/* success, put it on the list */
write_lock(&cifs_tcp_ses_lock);
list_add(&ses->smb_ses_list, &server->smb_ses_list);
write_unlock(&cifs_tcp_ses_lock);
FreeXid(xid);
return ses;
get_ses_fail:
sesInfoFree(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
Commit Message: cifs: clean up cifs_find_smb_ses (try #2)
This patch replaces the earlier patch by the same name. The only
difference is that MAX_PASSWORD_SIZE has been increased to attempt to
match the limits that windows enforces.
Do a better job of matching sessions by authtype. Matching by username
for a Kerberos session is incorrect, and anonymous sessions need special
handling.
Also, in the case where we do match by username, we also need to match
by password. That ensures that someone else doesn't "borrow" an existing
session without needing to know the password.
Finally, passwords can be longer than 16 bytes. Bump MAX_PASSWORD_SIZE
to 512 to match the size that the userspace mount helper allows.
Signed-off-by: Jeff Layton <[email protected]>
Signed-off-by: Steve French <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: void Tab::OnFocus() {
controller_->UpdateHoverCard(this, true);
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: kadm5_get_principal(void *server_handle, krb5_principal principal,
kadm5_principal_ent_t entry,
long in_mask)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_error_code ret = 0;
long mask;
int i;
kadm5_server_handle_t handle = server_handle;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
/*
* In version 1, all the defined fields are always returned.
* entry is a pointer to a kadm5_principal_ent_t_v1 that should be
* filled with allocated memory.
*/
mask = in_mask;
memset(entry, 0, sizeof(*entry));
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return ret;
if ((mask & KADM5_POLICY) &&
adb.policy && (adb.aux_attributes & KADM5_POLICY)) {
if ((entry->policy = strdup(adb.policy)) == NULL) {
ret = ENOMEM;
goto done;
}
}
if (mask & KADM5_AUX_ATTRIBUTES)
entry->aux_attributes = adb.aux_attributes;
if ((mask & KADM5_PRINCIPAL) &&
(ret = krb5_copy_principal(handle->context, kdb->princ,
&entry->principal))) {
goto done;
}
if (mask & KADM5_PRINC_EXPIRE_TIME)
entry->princ_expire_time = kdb->expiration;
if ((mask & KADM5_LAST_PWD_CHANGE) &&
(ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb,
&(entry->last_pwd_change)))) {
goto done;
}
if (mask & KADM5_PW_EXPIRATION)
entry->pw_expiration = kdb->pw_expiration;
if (mask & KADM5_MAX_LIFE)
entry->max_life = kdb->max_life;
/* this is a little non-sensical because the function returns two */
/* values that must be checked separately against the mask */
if ((mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME)) {
ret = krb5_dbe_lookup_mod_princ_data(handle->context, kdb,
&(entry->mod_date),
&(entry->mod_name));
if (ret) {
goto done;
}
if (! (mask & KADM5_MOD_TIME))
entry->mod_date = 0;
if (! (mask & KADM5_MOD_NAME)) {
krb5_free_principal(handle->context, entry->mod_name);
entry->mod_name = NULL;
}
}
if (mask & KADM5_ATTRIBUTES)
entry->attributes = kdb->attributes;
if (mask & KADM5_KVNO)
for (entry->kvno = 0, i=0; i<kdb->n_key_data; i++)
if ((krb5_kvno) kdb->key_data[i].key_data_kvno > entry->kvno)
entry->kvno = kdb->key_data[i].key_data_kvno;
if (mask & KADM5_MKVNO) {
ret = krb5_dbe_get_mkvno(handle->context, kdb, &entry->mkvno);
if (ret)
goto done;
}
if (mask & KADM5_MAX_RLIFE)
entry->max_renewable_life = kdb->max_renewable_life;
if (mask & KADM5_LAST_SUCCESS)
entry->last_success = kdb->last_success;
if (mask & KADM5_LAST_FAILED)
entry->last_failed = kdb->last_failed;
if (mask & KADM5_FAIL_AUTH_COUNT)
entry->fail_auth_count = kdb->fail_auth_count;
if (mask & KADM5_TL_DATA) {
krb5_tl_data *tl, *tl2;
entry->tl_data = NULL;
tl = kdb->tl_data;
while (tl) {
if (tl->tl_data_type > 255) {
if ((tl2 = dup_tl_data(tl)) == NULL) {
ret = ENOMEM;
goto done;
}
tl2->tl_data_next = entry->tl_data;
entry->tl_data = tl2;
entry->n_tl_data++;
}
tl = tl->tl_data_next;
}
}
if (mask & KADM5_KEY_DATA) {
entry->n_key_data = kdb->n_key_data;
if(entry->n_key_data) {
entry->key_data = malloc(entry->n_key_data*sizeof(krb5_key_data));
if (entry->key_data == NULL) {
ret = ENOMEM;
goto done;
}
} else
entry->key_data = NULL;
for (i = 0; i < entry->n_key_data; i++)
ret = krb5_copy_key_data_contents(handle->context,
&kdb->key_data[i],
&entry->key_data[i]);
if (ret)
goto done;
}
ret = KADM5_OK;
done:
if (ret && entry->principal) {
krb5_free_principal(handle->context, entry->principal);
entry->principal = NULL;
}
kdb_free_entry(handle, kdb, &adb);
return ret;
}
Commit Message: Null pointer deref in kadmind [CVE-2012-1013]
The fix for #6626 could cause kadmind to dereference a null pointer if
a create-principal request contains no password but does contain the
KRB5_KDB_DISALLOW_ALL_TIX flag (e.g. "addprinc -randkey -allow_tix
name"). Only clients authorized to create principals can trigger the
bug. Fix the bug by testing for a null password in check_1_6_dummy.
CVSSv2 vector: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C
[[email protected]: Minor style change and commit message]
ticket: 7152
target_version: 1.10.2
tags: pullup
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int key_reject_and_link(struct key *key,
unsigned timeout,
unsigned error,
struct key *keyring,
struct key *authkey)
{
struct assoc_array_edit *edit;
struct timespec now;
int ret, awaken, link_ret = 0;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
if (keyring) {
if (keyring->restrict_link)
return -EPERM;
link_ret = __key_link_begin(keyring, &key->index_key, &edit);
}
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* mark the key as being negatively instantiated */
atomic_inc(&key->user->nikeys);
key->reject_error = -error;
smp_wmb();
set_bit(KEY_FLAG_NEGATIVE, &key->flags);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
now = current_kernel_time();
key->expiry = now.tv_sec + timeout;
key_schedule_gc(key->expiry + key_gc_delay);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
ret = 0;
/* and link it into the destination keyring */
if (keyring && link_ret == 0)
__key_link(key, &edit);
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
}
mutex_unlock(&key_construction_mutex);
if (keyring && link_ret == 0)
__key_link_end(keyring, &key->index_key, edit);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
return ret == 0 ? link_ret : ret;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: void DataReductionProxySettings::GetContentLengths(
unsigned int days,
int64_t* original_content_length,
int64_t* received_content_length,
int64_t* last_update_time) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(data_reduction_proxy_service_->compression_stats());
data_reduction_proxy_service_->compression_stats()->GetContentLengths(
days, original_content_length, received_content_length, last_update_time);
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: exsltStrAlignFunction (xmlXPathParserContextPtr ctxt, int nargs) {
xmlChar *str, *padding, *alignment, *ret;
int str_l, padding_l;
if ((nargs < 2) || (nargs > 3)) {
xmlXPathSetArityError(ctxt);
return;
}
if (nargs == 3)
alignment = xmlXPathPopString(ctxt);
else
alignment = NULL;
padding = xmlXPathPopString(ctxt);
str = xmlXPathPopString(ctxt);
str_l = xmlUTF8Strlen (str);
padding_l = xmlUTF8Strlen (padding);
if (str_l == padding_l) {
xmlXPathReturnString (ctxt, str);
xmlFree(padding);
xmlFree(alignment);
return;
}
if (str_l > padding_l) {
ret = xmlUTF8Strndup (str, padding_l);
} else {
if (xmlStrEqual(alignment, (const xmlChar *) "right")) {
ret = xmlUTF8Strndup (padding, padding_l - str_l);
ret = xmlStrcat (ret, str);
} else if (xmlStrEqual(alignment, (const xmlChar *) "center")) {
int left = (padding_l - str_l) / 2;
int right_start;
ret = xmlUTF8Strndup (padding, left);
ret = xmlStrcat (ret, str);
right_start = xmlUTF8Strsize (padding, left + str_l);
ret = xmlStrcat (ret, padding + right_start);
} else {
int str_s;
str_s = xmlStrlen (str);
ret = xmlStrdup (str);
ret = xmlStrcat (ret, padding + str_s);
}
}
xmlXPathReturnString (ctxt, ret);
xmlFree(str);
xmlFree(padding);
xmlFree(alignment);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int entersafe_gen_key(sc_card_t *card, sc_entersafe_gen_key_data *data)
{
int r;
size_t len = data->key_length >> 3;
sc_apdu_t apdu;
u8 rbuf[300];
u8 sbuf[4],*p;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* MSE */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x01, 0xB8);
apdu.lc=0x04;
sbuf[0]=0x83;
sbuf[1]=0x02;
sbuf[2]=data->key_id;
sbuf[3]=0x2A;
apdu.data = sbuf;
apdu.datalen=4;
apdu.lc=4;
apdu.le=0;
r=entersafe_transmit_apdu(card, &apdu, 0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe set MSE failed");
/* generate key */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00);
apdu.le = 0;
sbuf[0] = (u8)(data->key_length >> 8);
sbuf[1] = (u8)(data->key_length);
apdu.data = sbuf;
apdu.lc = 2;
apdu.datalen = 2;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe generate keypair failed");
/* read public key via READ PUBLIC KEY */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xE6, 0x2A, data->key_id);
apdu.cla = 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = entersafe_transmit_apdu(card, &apdu,0,0,0,0);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe get pukey failed");
data->modulus = malloc(len);
if (!data->modulus)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_OUT_OF_MEMORY);
p=rbuf;
assert(*p=='E');
p+=2+p[1];
/* N */
assert(*p=='N');
++p;
if(*p++>0x80)
{
u8 len_bytes=(*(p-1))&0x0f;
size_t module_len=0;
while(len_bytes!=0)
{
module_len=module_len<<8;
module_len+=*p++;
--len_bytes;
}
}
entersafe_reverse_buffer(p,len);
memcpy(data->modulus,p,len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
Target: 1
Example 2:
Code: kadm5_ret_t kadm5_decrypt_key(void *server_handle,
kadm5_principal_ent_t entry, krb5_int32
ktype, krb5_int32 stype, krb5_int32
kvno, krb5_keyblock *keyblock,
krb5_keysalt *keysalt, int *kvnop)
{
kadm5_server_handle_t handle = server_handle;
krb5_db_entry dbent;
krb5_key_data *key_data;
krb5_keyblock *mkey_ptr;
int ret;
CHECK_HANDLE(server_handle);
if (entry->n_key_data == 0 || entry->key_data == NULL)
return EINVAL;
/* find_enctype only uses these two fields */
dbent.n_key_data = entry->n_key_data;
dbent.key_data = entry->key_data;
if ((ret = krb5_dbe_find_enctype(handle->context, &dbent, ktype,
stype, kvno, &key_data)))
return ret;
/* find_mkey only uses this field */
dbent.tl_data = entry->tl_data;
if ((ret = krb5_dbe_find_mkey(handle->context, &dbent, &mkey_ptr))) {
/* try refreshing master key list */
/* XXX it would nice if we had the mkvno here for optimization */
if (krb5_db_fetch_mkey_list(handle->context, master_princ,
&master_keyblock) == 0) {
if ((ret = krb5_dbe_find_mkey(handle->context, &dbent,
&mkey_ptr))) {
return ret;
}
} else {
return ret;
}
}
if ((ret = krb5_dbe_decrypt_key_data(handle->context, NULL, key_data,
keyblock, keysalt)))
return ret;
/*
* Coerce the enctype of the output keyblock in case we got an
* inexact match on the enctype; this behavior will go away when
* the key storage architecture gets redesigned for 1.3.
*/
if (ktype != -1)
keyblock->enctype = ktype;
if (kvnop)
*kvnop = key_data->key_data_kvno;
return KADM5_OK;
}
Commit Message: Null pointer deref in kadmind [CVE-2012-1013]
The fix for #6626 could cause kadmind to dereference a null pointer if
a create-principal request contains no password but does contain the
KRB5_KDB_DISALLOW_ALL_TIX flag (e.g. "addprinc -randkey -allow_tix
name"). Only clients authorized to create principals can trigger the
bug. Fix the bug by testing for a null password in check_1_6_dummy.
CVSSv2 vector: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C
[[email protected]: Minor style change and commit message]
ticket: 7152
target_version: 1.10.2
tags: pullup
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync(
content::CauseForGpuLaunch cause_for_gpu_launch) {
if (gpu_channel_.get()) {
if (gpu_channel_->state() == GpuChannelHost::kUnconnected ||
gpu_channel_->state() == GpuChannelHost::kConnected)
return GetGpuChannel();
gpu_channel_ = NULL;
}
int client_id = 0;
IPC::ChannelHandle channel_handle;
base::ProcessHandle renderer_process_for_gpu;
content::GPUInfo gpu_info;
if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch,
&client_id,
&channel_handle,
&renderer_process_for_gpu,
&gpu_info)) ||
channel_handle.name.empty() ||
#if defined(OS_POSIX)
channel_handle.socket.fd == -1 ||
#endif
renderer_process_for_gpu == base::kNullProcessHandle) {
gpu_channel_ = NULL;
return NULL;
}
gpu_channel_ = new GpuChannelHost(this, 0, client_id);
gpu_channel_->set_gpu_info(gpu_info);
content::GetContentClient()->SetGpuInfo(gpu_info);
gpu_channel_->Connect(channel_handle, renderer_process_for_gpu);
return GetGpuChannel();
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
vstart += verdef->vd_aux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
Commit Message: Fix #8685 - Crash in ELF version parsing
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ext4_add_entry(handle_t *handle, struct dentry *dentry,
struct inode *inode)
{
struct inode *dir = dentry->d_parent->d_inode;
struct buffer_head *bh;
struct ext4_dir_entry_2 *de;
struct ext4_dir_entry_tail *t;
struct super_block *sb;
int retval;
int dx_fallback=0;
unsigned blocksize;
ext4_lblk_t block, blocks;
int csum_size = 0;
if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
csum_size = sizeof(struct ext4_dir_entry_tail);
sb = dir->i_sb;
blocksize = sb->s_blocksize;
if (!dentry->d_name.len)
return -EINVAL;
if (is_dx(dir)) {
retval = ext4_dx_add_entry(handle, dentry, inode);
if (!retval || (retval != ERR_BAD_DX_DIR))
return retval;
ext4_clear_inode_flag(dir, EXT4_INODE_INDEX);
dx_fallback++;
ext4_mark_inode_dirty(handle, dir);
}
blocks = dir->i_size >> sb->s_blocksize_bits;
for (block = 0; block < blocks; block++) {
bh = ext4_bread(handle, dir, block, 0, &retval);
if(!bh)
return retval;
if (!buffer_verified(bh) &&
!ext4_dirent_csum_verify(dir,
(struct ext4_dir_entry *)bh->b_data))
return -EIO;
set_buffer_verified(bh);
retval = add_dirent_to_buf(handle, dentry, inode, NULL, bh);
if (retval != -ENOSPC) {
brelse(bh);
return retval;
}
if (blocks == 1 && !dx_fallback &&
EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_DIR_INDEX))
return make_indexed_dir(handle, dentry, inode, bh);
brelse(bh);
}
bh = ext4_append(handle, dir, &block, &retval);
if (!bh)
return retval;
de = (struct ext4_dir_entry_2 *) bh->b_data;
de->inode = 0;
de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize);
if (csum_size) {
t = EXT4_DIRENT_TAIL(bh->b_data, blocksize);
initialize_dirent_tail(t, blocksize);
}
retval = add_dirent_to_buf(handle, dentry, inode, de, bh);
brelse(bh);
if (retval == 0)
ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY);
return retval;
}
Commit Message: ext4: make orphan functions be no-op in no-journal mode
Instead of checking whether the handle is valid, we check if journal
is enabled. This avoids taking the s_orphan_lock mutex in all cases
when there is no journal in use, including the error paths where
ext4_orphan_del() is called with a handle set to NULL.
Signed-off-by: Anatol Pomozov <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int mm_answer_auth2_read_banner(int sock, Buffer *m)
{
char *banner;
buffer_clear(m);
banner = auth2_read_banner();
buffer_put_cstring(m, banner != NULL ? banner : "");
mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
free(banner);
return (0);
}
Commit Message: set sshpam_ctxt to NULL after free
Avoids use-after-free in monitor when privsep child is compromised.
Reported by Moritz Jodeit; ok dtucker@
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes)
{
attributes->usage = (audio_usage_t) parcel.readInt32();
attributes->content_type = (audio_content_type_t) parcel.readInt32();
attributes->source = (audio_source_t) parcel.readInt32();
attributes->flags = (audio_flags_mask_t) parcel.readInt32();
const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags);
if (hasFlattenedTag) {
String16 tags = parcel.readString16();
ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size());
if (realTagSize <= 0) {
strcpy(attributes->tags, "");
} else {
size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ?
AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize;
utf16_to_utf8(tags.string(), tagSize, attributes->tags);
}
} else {
ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values");
strcpy(attributes->tags, "");
}
}
Commit Message: Add bound checks to utf16_to_utf8
Bug: 29250543
Change-Id: I3518416e89ed901021970958fb6005fd69129f7c
(cherry picked from commit 1d3f4278b2666d1a145af2f54782c993aa07d1d9)
CWE ID: CWE-119
Target: 1
Example 2:
Code: const byte* wc_ecc_ctx_get_own_salt(ecEncCtx* ctx)
{
if (ctx == NULL || ctx->protocol == 0)
return NULL;
if (ctx->protocol == REQ_RESP_CLIENT) {
if (ctx->cliSt == ecCLI_INIT) {
ctx->cliSt = ecCLI_SALT_GET;
return ctx->clientSalt;
}
else {
ctx->cliSt = ecCLI_BAD_STATE;
return NULL;
}
}
else if (ctx->protocol == REQ_RESP_SERVER) {
if (ctx->srvSt == ecSRV_INIT) {
ctx->srvSt = ecSRV_SALT_GET;
return ctx->serverSalt;
}
else {
ctx->srvSt = ecSRV_BAD_STATE;
return NULL;
}
}
return NULL;
}
Commit Message: Change ECDSA signing to use blinding.
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool GLES2DecoderImpl::SimulateAttrib0(
GLuint max_vertex_accessed, bool* simulated) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
const VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_->GetVertexAttribInfo(0);
bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL;
if (info->enabled() && attrib_0_used) {
return true;
}
typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4;
GLuint num_vertices = max_vertex_accessed + 1;
GLuint size_needed = 0;
if (num_vertices == 0 ||
!SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)),
&size_needed) ||
size_needed > 0x7FFFFFFFU) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
CopyRealGLErrorsToWrapper();
glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
if (static_cast<GLsizei>(size_needed) > attrib_0_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0");
return false;
}
attrib_0_buffer_matches_value_ = false;
}
if (attrib_0_used &&
(!attrib_0_buffer_matches_value_ ||
(info->value().v[0] != attrib_0_value_.v[0] ||
info->value().v[1] != attrib_0_value_.v[1] ||
info->value().v[2] != attrib_0_value_.v[2] ||
info->value().v[3] != attrib_0_value_.v[3]))) {
std::vector<Vec4> temp(num_vertices, info->value());
glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]);
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = info->value();
attrib_0_size_ = size_needed;
}
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);
if (info->divisor())
glVertexAttribDivisorANGLE(0, 0);
*simulated = true;
return true;
}
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:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: fbOver (CARD32 x, CARD32 y)
{
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height);
CARD32
fbOver (CARD32 x, CARD32 y)
{
CARD16 a = ~x >> 24;
CARD16 t;
CARD32 m,n,o,p;
m = FbOverU(x,y,0,a,t);
n = FbOverU(x,y,8,a,t);
o = FbOverU(x,y,16,a,t);
p = FbOverU(x,y,24,a,t);
return m|n|o|p;
}
CARD32
fbOver24 (CARD32 x, CARD32 y)
{
CARD16 a = ~x >> 24;
CARD16 t;
CARD32 m,n,o;
m = FbOverU(x,y,0,a,t);
n = FbOverU(x,y,8,a,t);
o = FbOverU(x,y,16,a,t);
return m|n|o;
}
CARD32
fbIn (CARD32 x, CARD8 y)
{
CARD16 a = y;
CARD16 t;
CARD32 m,n,o,p;
m = FbInU(x,0,a,t);
n = FbInU(x,8,a,t);
o = FbInU(x,16,a,t);
p = FbInU(x,24,a,t);
return m|n|o|p;
}
#define genericCombine24(a,b,c,d) (((a)*(c)+(b)*(d)))
/*
* This macro does src IN mask OVER dst when src and dst are 0888.
* If src has alpha, this will not work
*/
#define inOver0888(alpha, source, destval, dest) { \
CARD32 dstrb=destval&0xFF00FF; CARD32 dstag=(destval>>8)&0xFF00FF; \
CARD32 drb=((source&0xFF00FF)-dstrb)*alpha; CARD32 dag=(((source>>8)&0xFF00FF)-dstag)*alpha; \
WRITE(dest, ((((drb>>8) + dstrb) & 0x00FF00FF) | ((((dag>>8) + dstag) << 8) & 0xFF00FF00))); \
}
/*
* This macro does src IN mask OVER dst when src and dst are 0565 and
* mask is a 5-bit alpha value. Again, if src has alpha, this will not
* work.
*/
#define inOver0565(alpha, source, destval, dest) { \
CARD16 dstrb = destval & 0xf81f; CARD16 dstg = destval & 0x7e0; \
CARD32 drb = ((source&0xf81f)-dstrb)*alpha; CARD32 dg=((source & 0x7e0)-dstg)*alpha; \
WRITE(dest, ((((drb>>5) + dstrb)&0xf81f) | (((dg>>5) + dstg) & 0x7e0))); \
}
#define inOver2x0565(alpha, source, destval, dest) { \
CARD32 dstrb = destval & 0x07e0f81f; CARD32 dstg = (destval & 0xf81f07e0)>>5; \
CARD32 drb = ((source&0x07e0f81f)-dstrb)*alpha; CARD32 dg=(((source & 0xf81f07e0)>>5)-dstg)*alpha; \
WRITE(dest, ((((drb>>5) + dstrb)&0x07e0f81f) | ((((dg>>5) + dstg)<<5) & 0xf81f07e0))); \
}
#if IMAGE_BYTE_ORDER == LSBFirst
#define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \
temp=count&3; \
where-=temp; \
workingWhere=(CARD32 *)where; \
workingVal=READ(workingWhere++); \
count=4-temp; \
workingVal>>=(8*temp)
#define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)&0xff; (y)>>=8; (x)--;}
#define readPackedSource(where) readPacked(where,ws,workingSource,wsrc)
#define readPackedDest(where) readPacked(where,wd,workingiDest,widst)
#define writePacked(what) workingoDest>>=8; workingoDest|=(what<<24); ww--; if(!ww) { ww=4; WRITE (wodst++, workingoDest); }
#else
#warning "I havn't tested fbCompositeTrans_0888xnx0888() on big endian yet!"
#define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \
temp=count&3; \
where-=temp; \
workingWhere=(CARD32 *)where; \
workingVal=READ(workingWhere++); \
count=4-temp; \
workingVal<<=(8*temp)
#define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)>>24; (y)<<=8; (x)--;}
#define readPackedSource(where) readPacked(where,ws,workingSource,wsrc)
#define readPackedDest(where) readPacked(where,wd,workingiDest,widst)
#define writePacked(what) workingoDest<<=8; workingoDest|=what; ww--; if(!ww) { ww=4; WRITE(wodst++, workingoDest); }
#endif
/*
* Naming convention:
*
* opSRCxMASKxDST
*/
void
fbCompositeSolidMask_nx8x8888 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 src, srca;
CARD32 *dstLine, *dst, d, dstMask;
CARD8 *maskLine, *mask, m;
FbStride dstStride, maskStride;
CARD16 w;
fbComposeGetSolid(pSrc, src, pDst->format);
dstMask = FbFullMask (pDst->pDrawable->depth);
srca = src >> 24;
if (src == 0)
return;
fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1);
fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
mask = maskLine;
maskLine += maskStride;
w = width;
while (w--)
{
m = READ(mask++);
if (m == 0xff)
{
if (srca == 0xff)
WRITE(dst, src & dstMask);
else
WRITE(dst, fbOver (src, READ(dst)) & dstMask);
}
else if (m)
{
d = fbIn (src, m);
WRITE(dst, fbOver (d, READ(dst)) & dstMask);
}
dst++;
}
}
fbFinishAccess (pMask->pDrawable);
fbFinishAccess (pDst->pDrawable);
}
void
fbCompositeSolidMask_nx8888x8888C (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 src, srca;
CARD32 *dstLine, *dst, d, dstMask;
CARD32 *maskLine, *mask, ma;
FbStride dstStride, maskStride;
CARD16 w;
CARD32 m, n, o, p;
fbComposeGetSolid(pSrc, src, pDst->format);
dstMask = FbFullMask (pDst->pDrawable->depth);
srca = src >> 24;
if (src == 0)
return;
fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1);
fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
mask = maskLine;
maskLine += maskStride;
w = width;
while (w--)
{
ma = READ(mask++);
if (ma == 0xffffffff)
{
if (srca == 0xff)
WRITE(dst, src & dstMask);
else
WRITE(dst, fbOver (src, READ(dst)) & dstMask);
}
else if (ma)
{
d = READ(dst);
#define FbInOverC(src,srca,msk,dst,i,result) { \
CARD16 __a = FbGet8(msk,i); \
CARD32 __t, __ta; \
CARD32 __i; \
__t = FbIntMult (FbGet8(src,i), __a,__i); \
__ta = (CARD8) ~FbIntMult (srca, __a,__i); \
__t = __t + FbIntMult(FbGet8(dst,i),__ta,__i); \
__t = (CARD32) (CARD8) (__t | (-(__t >> 8))); \
result = __t << (i); \
}
FbInOverC (src, srca, ma, d, 0, m);
FbInOverC (src, srca, ma, d, 8, n);
FbInOverC (src, srca, ma, d, 16, o);
FbInOverC (src, srca, ma, d, 24, p);
WRITE(dst, m|n|o|p);
}
dst++;
}
}
fbFinishAccess (pMask->pDrawable);
fbFinishAccess (pDst->pDrawable);
}
#define srcAlphaCombine24(a,b) genericCombine24(a,b,srca,srcia)
void
fbCompositeSolidMask_nx8x0888 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 src, srca, srcia;
CARD8 *dstLine, *dst, *edst;
CARD8 *maskLine, *mask, m;
FbStride dstStride, maskStride;
CARD16 w;
CARD32 rs,gs,bs,rd,gd,bd;
fbComposeGetSolid(pSrc, src, pDst->format);
srca = src >> 24;
srcia = 255-srca;
if (src == 0)
return;
rs=src&0xff;
gs=(src>>8)&0xff;
bs=(src>>16)&0xff;
fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3);
fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1);
while (height--)
{
/* fixme: cleanup unused */
unsigned long wt, wd;
CARD32 workingiDest;
CARD32 *widst;
edst = dst = dstLine;
dstLine += dstStride;
mask = maskLine;
maskLine += maskStride;
w = width;
#ifndef NO_MASKED_PACKED_READ
setupPackedReader(wd,wt,edst,widst,workingiDest);
#endif
while (w--)
{
#ifndef NO_MASKED_PACKED_READ
readPackedDest(rd);
readPackedDest(gd);
readPackedDest(bd);
#else
rd = READ(edst++);
gd = READ(edst++);
bd = READ(edst++);
#endif
m = READ(mask++);
if (m == 0xff)
{
if (srca == 0xff)
{
WRITE(dst++, rs);
WRITE(dst++, gs);
WRITE(dst++, bs);
}
else
{
WRITE(dst++, (srcAlphaCombine24(rs, rd)>>8));
WRITE(dst++, (srcAlphaCombine24(gs, gd)>>8));
WRITE(dst++, (srcAlphaCombine24(bs, bd)>>8));
}
}
else if (m)
{
int na=(srca*(int)m)>>8;
int nia=255-na;
WRITE(dst++, (genericCombine24(rs, rd, na, nia)>>8));
WRITE(dst++, (genericCombine24(gs, gd, na, nia)>>8));
WRITE(dst++, (genericCombine24(bs, bd, na, nia)>>8));
}
else
{
dst+=3;
}
}
}
fbFinishAccess (pMask->pDrawable);
fbFinishAccess (pDst->pDrawable);
}
void
fbCompositeSolidMask_nx8x0565 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 src, srca8, srca5;
CARD16 *dstLine, *dst;
CARD16 d;
CARD32 t;
CARD8 *maskLine, *mask, m;
FbStride dstStride, maskStride;
CARD16 w,src16;
fbComposeGetSolid(pSrc, src, pDst->format);
if (src == 0)
return;
srca8 = (src >> 24);
srca5 = (srca8 >> 3);
src16 = cvt8888to0565(src);
fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1);
fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
mask = maskLine;
maskLine += maskStride;
w = width;
while (w--)
{
m = READ(mask++);
if (m == 0)
dst++;
else if (srca5 == (0xff >> 3))
{
if (m == 0xff)
WRITE(dst++, src16);
else
{
d = READ(dst);
m >>= 3;
inOver0565 (m, src16, d, dst++);
}
}
else
{
d = READ(dst);
if (m == 0xff)
{
t = fbOver24 (src, cvt0565to0888 (d));
}
else
{
t = fbIn (src, m);
t = fbOver (t, cvt0565to0888 (d));
}
WRITE(dst++, cvt8888to0565 (t));
}
}
}
fbFinishAccess (pMask->pDrawable);
fbFinishAccess (pDst->pDrawable);
}
static void
fbCompositeSolidMask_nx8888x0565 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 src, srca8, srca5;
CARD16 *dstLine, *dst;
CARD16 d;
CARD32 *maskLine, *mask;
CARD32 t;
CARD8 m;
FbStride dstStride, maskStride;
CARD16 w, src16;
fbComposeGetSolid(pSrc, src, pDst->format);
if (src == 0)
return;
srca8 = src >> 24;
srca5 = srca8 >> 3;
src16 = cvt8888to0565(src);
fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1);
fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
mask = maskLine;
maskLine += maskStride;
w = width;
while (w--)
{
m = READ(mask++) >> 24;
if (m == 0)
dst++;
else if (srca5 == (0xff >> 3))
{
if (m == 0xff)
WRITE(dst++, src16);
else
{
d = READ(dst);
m >>= 3;
inOver0565 (m, src16, d, dst++);
}
}
else
{
if (m == 0xff)
{
d = READ(dst);
t = fbOver24 (src, cvt0565to0888 (d));
WRITE(dst++, cvt8888to0565 (t));
}
else
{
d = READ(dst);
t = fbIn (src, m);
t = fbOver (t, cvt0565to0888 (d));
WRITE(dst++, cvt8888to0565 (t));
}
}
}
}
}
void
fbCompositeSolidMask_nx8888x0565C (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 src, srca;
CARD16 src16;
CARD16 *dstLine, *dst;
CARD32 d;
CARD32 *maskLine, *mask, ma;
FbStride dstStride, maskStride;
CARD16 w;
CARD32 m, n, o;
fbComposeGetSolid(pSrc, src, pDst->format);
srca = src >> 24;
if (src == 0)
return;
src16 = cvt8888to0565(src);
fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1);
fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
mask = maskLine;
maskLine += maskStride;
w = width;
while (w--)
{
ma = READ(mask++);
if (ma == 0xffffffff)
{
if (srca == 0xff)
{
WRITE(dst, src16);
}
else
{
d = READ(dst);
d = fbOver24 (src, cvt0565to0888(d));
WRITE(dst, cvt8888to0565(d));
}
}
else if (ma)
{
d = READ(dst);
d = cvt0565to0888(d);
FbInOverC (src, srca, ma, d, 0, m);
FbInOverC (src, srca, ma, d, 8, n);
FbInOverC (src, srca, ma, d, 16, o);
d = m|n|o;
WRITE(dst, cvt8888to0565(d));
}
dst++;
}
}
fbFinishAccess (pMask->pDrawable);
fbFinishAccess (pDst->pDrawable);
}
void
fbCompositeSrc_8888x8888 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 *dstLine, *dst, dstMask;
CARD32 *srcLine, *src, s;
FbStride dstStride, srcStride;
CARD8 a;
CARD16 w;
fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1);
fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1);
dstMask = FbFullMask (pDst->pDrawable->depth);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
src = srcLine;
srcLine += srcStride;
w = width;
while (w--)
{
s = READ(src++);
a = s >> 24;
if (a == 0xff)
WRITE(dst, s & dstMask);
else if (a)
WRITE(dst, fbOver (s, READ(dst)) & dstMask);
dst++;
}
}
fbFinishAccess (pSrc->pDrawable);
fbFinishAccess (pDst->pDrawable);
}
void
fbCompositeSrc_8888x0888 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD8 *dstLine, *dst;
CARD32 d;
CARD32 *srcLine, *src, s;
CARD8 a;
FbStride dstStride, srcStride;
CARD16 w;
fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3);
fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
src = srcLine;
srcLine += srcStride;
w = width;
while (w--)
{
s = READ(src++);
a = s >> 24;
if (a)
{
if (a == 0xff)
d = s;
else
d = fbOver24 (s, Fetch24(dst));
Store24(dst,d);
}
dst += 3;
}
}
fbFinishAccess (pSrc->pDrawable);
fbFinishAccess (pDst->pDrawable);
}
void
fbCompositeSrc_8888x0565 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD16 *dstLine, *dst;
CARD32 d;
CARD32 *srcLine, *src, s;
CARD8 a;
FbStride dstStride, srcStride;
CARD16 w;
fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1);
fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
src = srcLine;
srcLine += srcStride;
w = width;
while (w--)
{
s = READ(src++);
a = s >> 24;
if (a)
{
if (a == 0xff)
d = s;
else
{
d = READ(dst);
d = fbOver24 (s, cvt0565to0888(d));
}
WRITE(dst, cvt8888to0565(d));
}
dst++;
}
}
fbFinishAccess (pDst->pDrawable);
fbFinishAccess (pSrc->pDrawable);
}
void
fbCompositeSrcAdd_8000x8000 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD8 *dstLine, *dst;
CARD8 *srcLine, *src;
FbStride dstStride, srcStride;
CARD16 w;
CARD8 s, d;
CARD16 t;
fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 1);
fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
src = srcLine;
srcLine += srcStride;
w = width;
while (w--)
{
s = READ(src++);
if (s)
{
if (s != 0xff)
{
d = READ(dst);
t = d + s;
s = t | (0 - (t >> 8));
}
WRITE(dst, s);
}
dst++;
}
}
fbFinishAccess (pDst->pDrawable);
fbFinishAccess (pSrc->pDrawable);
}
void
fbCompositeSrcAdd_8888x8888 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 *dstLine, *dst;
CARD32 *srcLine, *src;
FbStride dstStride, srcStride;
CARD16 w;
CARD32 s, d;
CARD16 t;
CARD32 m,n,o,p;
fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1);
fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
src = srcLine;
srcLine += srcStride;
w = width;
while (w--)
{
s = READ(src++);
if (s)
{
if (s != 0xffffffff)
{
d = READ(dst);
if (d)
{
m = FbAdd(s,d,0,t);
n = FbAdd(s,d,8,t);
o = FbAdd(s,d,16,t);
p = FbAdd(s,d,24,t);
s = m|n|o|p;
}
}
WRITE(dst, s);
}
dst++;
}
}
fbFinishAccess (pDst->pDrawable);
fbFinishAccess (pSrc->pDrawable);
}
static void
fbCompositeSrcAdd_8888x8x8 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD8 *dstLine, *dst;
CARD8 *maskLine, *mask;
FbStride dstStride, maskStride;
CARD16 w;
CARD32 src;
CARD8 sa;
fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1);
fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1);
fbComposeGetSolid (pSrc, src, pDst->format);
sa = (src >> 24);
while (height--)
{
dst = dstLine;
dstLine += dstStride;
mask = maskLine;
maskLine += maskStride;
w = width;
while (w--)
{
CARD16 tmp;
CARD16 a;
CARD32 m, d;
CARD32 r;
a = READ(mask++);
d = READ(dst);
m = FbInU (sa, 0, a, tmp);
r = FbAdd (m, d, 0, tmp);
WRITE(dst++, r);
}
}
fbFinishAccess(pDst->pDrawable);
fbFinishAccess(pMask->pDrawable);
}
void
fbCompositeSrcAdd_1000x1000 (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
FbBits *dstBits, *srcBits;
FbStride dstStride, srcStride;
int dstBpp, srcBpp;
int dstXoff, dstYoff;
int srcXoff, srcYoff;
fbGetDrawable(pSrc->pDrawable, srcBits, srcStride, srcBpp, srcXoff, srcYoff);
fbGetDrawable(pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff);
fbBlt (srcBits + srcStride * (ySrc + srcYoff),
srcStride,
xSrc + srcXoff,
dstBits + dstStride * (yDst + dstYoff),
dstStride,
xDst + dstXoff,
width,
height,
GXor,
FB_ALLONES,
srcBpp,
FALSE,
FALSE);
fbFinishAccess(pDst->pDrawable);
fbFinishAccess(pSrc->pDrawable);
}
void
fbCompositeSolidMask_nx1xn (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
FbBits *dstBits;
FbStip *maskBits;
FbStride dstStride, maskStride;
int dstBpp, maskBpp;
int dstXoff, dstYoff;
int maskXoff, maskYoff;
FbBits src;
fbComposeGetSolid(pSrc, src, pDst->format);
fbGetStipDrawable (pMask->pDrawable, maskBits, maskStride, maskBpp, maskXoff, maskYoff);
fbGetDrawable (pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff);
switch (dstBpp) {
case 32:
break;
case 24:
break;
case 16:
src = cvt8888to0565(src);
break;
}
src = fbReplicatePixel (src, dstBpp);
fbBltOne (maskBits + maskStride * (yMask + maskYoff),
maskStride,
xMask + maskXoff,
dstBits + dstStride * (yDst + dstYoff),
dstStride,
(xDst + dstXoff) * dstBpp,
dstBpp,
width * dstBpp,
height,
0x0,
src,
FB_ALLONES,
0x0);
fbFinishAccess (pDst->pDrawable);
fbFinishAccess (pMask->pDrawable);
}
# define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b))
/*
* Apply a constant alpha value in an over computation
*/
static void
fbCompositeSrcSrc_nxn (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height);
static void
fbCompositeTrans_0565xnx0565(CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD16 *dstLine, *dst;
CARD16 *srcLine, *src;
FbStride dstStride, srcStride;
CARD16 w;
FbBits mask;
CARD8 maskAlpha;
CARD16 s_16, d_16;
CARD32 s_32, d_32;
fbComposeGetSolid (pMask, mask, pDst->format);
maskAlpha = mask >> 27;
if (!maskAlpha)
return;
if (maskAlpha == 0xff)
{
fbCompositeSrcSrc_nxn (PictOpSrc, pSrc, pMask, pDst,
xSrc, ySrc, xMask, yMask, xDst, yDst,
width, height);
return;
}
fbComposeGetStart (pSrc, xSrc, ySrc, CARD16, srcStride, srcLine, 1);
fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1);
while (height--)
{
CARD32 *isrc, *idst;
dst = dstLine;
dstLine += dstStride;
src = srcLine;
srcLine += srcStride;
w = width;
if(((long)src&1)==1)
{
s_16 = READ(src++);
d_16 = READ(dst);
inOver0565(maskAlpha, s_16, d_16, dst++);
w--;
}
isrc=(CARD32 *)src;
if(((long)dst&1)==0)
{
idst=(CARD32 *)dst;
while (w>1)
{
s_32 = READ(isrc++);
d_32 = READ(idst);
inOver2x0565(maskAlpha, s_32, d_32, idst++);
w-=2;
}
dst=(CARD16 *)idst;
}
else
{
while (w > 1)
{
s_32 = READ(isrc++);
#if IMAGE_BYTE_ORDER == LSBFirst
s_16=s_32&0xffff;
#else
s_16=s_32>>16;
#endif
d_16 = READ(dst);
inOver0565 (maskAlpha, s_16, d_16, dst++);
#if IMAGE_BYTE_ORDER == LSBFirst
s_16=s_32>>16;
#else
s_16=s_32&0xffff;
#endif
d_16 = READ(dst);
inOver0565(maskAlpha, s_16, d_16, dst++);
w-=2;
}
}
src=(CARD16 *)isrc;
if(w!=0)
{
s_16 = READ(src);
d_16 = READ(dst);
inOver0565(maskAlpha, s_16, d_16, dst);
}
}
fbFinishAccess (pSrc->pDrawable);
fbFinishAccess (pDst->pDrawable);
}
/* macros for "i can't believe it's not fast" packed pixel handling */
#define alphamaskCombine24(a,b) genericCombine24(a,b,maskAlpha,maskiAlpha)
static void
fbCompositeTrans_0888xnx0888(CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD8 *dstLine, *dst,*idst;
CARD8 *srcLine, *src;
FbStride dstStride, srcStride;
CARD16 w;
FbBits mask;
CARD16 maskAlpha,maskiAlpha;
fbComposeGetSolid (pMask, mask, pDst->format);
maskAlpha = mask >> 24;
maskiAlpha= 255-maskAlpha;
if (!maskAlpha)
return;
/*
if (maskAlpha == 0xff)
{
fbCompositeSrc_0888x0888 (op, pSrc, pMask, pDst,
xSrc, ySrc, xMask, yMask, xDst, yDst,
width, height);
return;
}
*/
fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 3);
fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3);
{
unsigned long ws,wt;
CARD32 workingSource;
CARD32 *wsrc, *wdst, *widst;
CARD32 rs, rd, nd;
CARD8 *isrc;
/* are xSrc and xDst at the same alignment? if not, we need to be complicated :) */
/* if(0==0) */
if ((((xSrc * 3) & 3) != ((xDst * 3) & 3)) ||
((srcStride & 3) != (dstStride & 3)))
{
while (height--)
{
dst = dstLine;
dstLine += dstStride;
isrc = src = srcLine;
srcLine += srcStride;
w = width*3;
setupPackedReader(ws,wt,isrc,wsrc,workingSource);
/* get to word aligned */
switch(~(long)dst&3)
{
case 1:
readPackedSource(rs);
/* *dst++=alphamaskCombine24(rs, *dst)>>8; */
rd = READ(dst); /* make gcc happy. hope it doens't cost us too much performance*/
WRITE(dst++, alphamaskCombine24(rs, rd) >> 8);
w--; if(w==0) break;
case 2:
readPackedSource(rs);
rd = READ(dst);
WRITE(dst++, alphamaskCombine24(rs, rd) >> 8);
w--; if(w==0) break;
case 3:
readPackedSource(rs);
rd = READ(dst);
WRITE(dst++,alphamaskCombine24(rs, rd) >> 8);
w--; if(w==0) break;
}
wdst=(CARD32 *)dst;
while (w>3)
{
rs=READ(wsrc++);
/* FIXME: write a special readPackedWord macro, which knows how to
* halfword combine
*/
#if IMAGE_BYTE_ORDER == LSBFirst
rd=READ(wdst);
readPackedSource(nd);
readPackedSource(rs);
nd|=rs<<8;
readPackedSource(rs);
nd|=rs<<16;
readPackedSource(rs);
nd|=rs<<24;
#else
readPackedSource(nd);
nd<<=24;
readPackedSource(rs);
nd|=rs<<16;
readPackedSource(rs);
nd|=rs<<8;
readPackedSource(rs);
nd|=rs;
#endif
inOver0888(maskAlpha, nd, rd, wdst++);
w-=4;
}
src=(CARD8 *)wdst;
switch(w)
{
case 3:
readPackedSource(rs);
rd=READ(dst);
WRITE(dst++,alphamaskCombine24(rs, rd)>>8);
case 2:
readPackedSource(rs);
rd = READ(dst);
WRITE(dst++, alphamaskCombine24(rs, rd)>>8);
case 1:
readPackedSource(rs);
rd = READ(dst);
WRITE(dst++, alphamaskCombine24(rs, rd)>>8);
}
}
}
else
{
while (height--)
{
idst=dst = dstLine;
dstLine += dstStride;
src = srcLine;
srcLine += srcStride;
w = width*3;
/* get to word aligned */
switch(~(long)src&3)
{
case 1:
rd=alphamaskCombine24(READ(src++), READ(dst))>>8;
WRITE(dst++, rd);
w--; if(w==0) break;
case 2:
rd=alphamaskCombine24(READ(src++), READ(dst))>>8;
WRITE(dst++, rd);
w--; if(w==0) break;
case 3:
rd=alphamaskCombine24(READ(src++), READ(dst))>>8;
WRITE(dst++, rd);
w--; if(w==0) break;
}
wsrc=(CARD32 *)src;
widst=(CARD32 *)dst;
while(w>3)
{
rs = READ(wsrc++);
rd = READ(widst);
inOver0888 (maskAlpha, rs, rd, widst++);
w-=4;
}
src=(CARD8 *)wsrc;
dst=(CARD8 *)widst;
switch(w)
{
case 3:
rd=alphamaskCombine24(READ(src++), READ(dst))>>8;
WRITE(dst++, rd);
case 2:
rd=alphamaskCombine24(READ(src++), READ(dst))>>8;
WRITE(dst++, rd);
case 1:
rd=alphamaskCombine24(READ(src++), READ(dst))>>8;
WRITE(dst++, rd);
}
}
}
}
}
/*
* Simple bitblt
*/
static void
fbCompositeSrcSrc_nxn (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
FbBits *dst;
FbBits *src;
FbStride dstStride, srcStride;
int srcXoff, srcYoff;
int dstXoff, dstYoff;
int srcBpp;
int dstBpp;
Bool reverse = FALSE;
Bool upsidedown = FALSE;
fbGetDrawable(pSrc->pDrawable,src,srcStride,srcBpp,srcXoff,srcYoff);
fbGetDrawable(pDst->pDrawable,dst,dstStride,dstBpp,dstXoff,dstYoff);
fbBlt (src + (ySrc + srcYoff) * srcStride,
srcStride,
(xSrc + srcXoff) * srcBpp,
dst + (yDst + dstYoff) * dstStride,
dstStride,
(xDst + dstXoff) * dstBpp,
(width) * dstBpp,
(height),
GXcopy,
FB_ALLONES,
dstBpp,
reverse,
upsidedown);
fbFinishAccess(pSrc->pDrawable);
fbFinishAccess(pDst->pDrawable);
}
/*
* Solid fill
void
fbCompositeSolidSrc_nxn (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
}
*/
#define SCANLINE_BUFFER_LENGTH 2048
static void
fbCompositeRectWrapper (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH * 3];
CARD32 *scanline_buffer = _scanline_buffer;
FbComposeData data;
data.op = op;
data.src = pSrc;
data.mask = pMask;
data.dest = pDst;
data.xSrc = xSrc;
data.ySrc = ySrc;
data.xMask = xMask;
}
void
fbComposite (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
case PICT_x8r8g8b8:
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8x8888mmx;
else
CARD16 width,
CARD16 height)
{
RegionRec region;
int n;
BoxPtr pbox;
CompositeFunc func = NULL;
Bool srcRepeat = pSrc->pDrawable && pSrc->repeatType == RepeatNormal;
Bool maskRepeat = FALSE;
Bool srcTransform = pSrc->transform != 0;
break;
Bool srcAlphaMap = pSrc->alphaMap != 0;
Bool maskAlphaMap = FALSE;
Bool dstAlphaMap = pDst->alphaMap != 0;
int x_msk, y_msk, x_src, y_src, x_dst, y_dst;
int w, h, w_this, h_this;
#ifdef USE_MMX
static Bool mmx_setup = FALSE;
func = fbCompositeSolidMask_nx8888x8888Cmmx;
else
#endif
}
#endif
xDst += pDst->pDrawable->x;
yDst += pDst->pDrawable->y;
if (pSrc->pDrawable) {
xSrc += pSrc->pDrawable->x;
ySrc += pSrc->pDrawable->y;
}
if (srcRepeat && srcTransform &&
pSrc->pDrawable->width == 1 &&
pSrc->pDrawable->height == 1)
else
if (pMask && pMask->pDrawable)
{
xMask += pMask->pDrawable->x;
yMask += pMask->pDrawable->y;
maskRepeat = pMask->repeatType == RepeatNormal;
if (pMask->filter == PictFilterConvolution)
}
else
{
switch (pDst->format) {
case PICT_r5g6b5:
func = fbCompositeSolidMask_nx8888x0565;
break;
default:
break;
}
}
break;
case PICT_a8b8g8r8:
if (pMask->componentAlpha) {
switch (pDst->format) {
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x8888Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x8888C;
break;
case PICT_b5g6r5:
#ifdef USE_MMX
if (fbHaveMMX())
func = fbCompositeSolidMask_nx8888x0565Cmmx;
else
#endif
func = fbCompositeSolidMask_nx8888x0565C;
break;
default:
break;
}
}
else
{
switch (pDst->format) {
case PICT_b5g6r5:
func = fbCompositeSolidMask_nx8888x0565;
break;
default:
break;
}
}
break;
case PICT_a1:
switch (pDst->format) {
case PICT_r5g6b5:
case PICT_b5g6r5:
case PICT_r8g8b8:
case PICT_b8g8r8:
case PICT_a8r8g8b8:
case PICT_x8r8g8b8:
case PICT_a8b8g8r8:
case PICT_x8b8g8r8:
{
FbBits src;
fbComposeGetSolid(pSrc, src, pDst->format);
if ((src & 0xff000000) == 0xff000000)
func = fbCompositeSolidMask_nx1xn;
break;
}
default:
break;
}
break;
default:
break;
}
Commit Message:
CWE ID: CWE-189
Target: 1
Example 2:
Code: FileSystemOperation::ScopedQuotaNotifier::~ScopedQuotaNotifier() {
if (quota_util_) {
DCHECK(quota_util_->proxy());
quota_util_->proxy()->EndUpdateOrigin(origin_url_, type_);
}
}
Commit Message: Crash fix in fileapi::FileSystemOperation::DidGetUsageAndQuotaAndRunTask
https://chromiumcodereview.appspot.com/10008047 introduced delete-with-inflight-tasks in Write sequence but I failed to convert this callback to use WeakPtr().
BUG=128178
TEST=manual test
Review URL: https://chromiumcodereview.appspot.com/10408006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137635 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebLocalFrameImpl::SetScrollOffset(const WebSize& offset) {
if (ScrollableArea* scrollable_area = LayoutViewport()) {
scrollable_area->SetScrollOffset(ScrollOffset(offset.width, offset.height),
kProgrammaticScroll);
}
}
Commit Message: Do not forward resource timing to parent frame after back-forward navigation
LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to
send timing info to parent except for the first navigation. This flag is
cleared when the first timing is sent to parent, however this does not happen
if iframe's first navigation was by back-forward navigation. For such
iframes, we shouldn't send timings to parent at all.
Bug: 876822
Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5
Reviewed-on: https://chromium-review.googlesource.com/1186215
Reviewed-by: Kinuko Yasuda <[email protected]>
Commit-Queue: Kunihiko Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#585736}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int skt_read(int fd, void *p, size_t len)
{
int read;
struct pollfd pfd;
struct timespec ts;
FNLOG();
ts_log("skt_read recv", len, NULL);
if ((read = recv(fd, p, len, MSG_NOSIGNAL)) == -1)
{
ERROR("write failed with errno=%d\n", errno);
return -1;
}
return read;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Target: 1
Example 2:
Code: bool readArrayBufferView(v8::Handle<v8::Value>* value, CompositeCreator& creator)
{
ArrayBufferViewSubTag subTag;
uint32_t byteOffset;
uint32_t byteLength;
RefPtr<ArrayBuffer> arrayBuffer;
v8::Handle<v8::Value> arrayBufferV8Value;
if (!readArrayBufferViewSubTag(&subTag))
return false;
if (!doReadUint32(&byteOffset))
return false;
if (!doReadUint32(&byteLength))
return false;
if (!creator.consumeTopOfStack(&arrayBufferV8Value))
return false;
if (arrayBufferV8Value.IsEmpty())
return false;
arrayBuffer = V8ArrayBuffer::toNative(arrayBufferV8Value.As<v8::Object>());
if (!arrayBuffer)
return false;
v8::Handle<v8::Object> creationContext = m_scriptState->context()->Global();
switch (subTag) {
case ByteArrayTag:
*value = toV8(Int8Array::create(arrayBuffer.release(), byteOffset, byteLength), creationContext, isolate());
break;
case UnsignedByteArrayTag:
*value = toV8(Uint8Array::create(arrayBuffer.release(), byteOffset, byteLength), creationContext, isolate());
break;
case UnsignedByteClampedArrayTag:
*value = toV8(Uint8ClampedArray::create(arrayBuffer.release(), byteOffset, byteLength), creationContext, isolate());
break;
case ShortArrayTag: {
uint32_t shortLength = byteLength / sizeof(int16_t);
if (shortLength * sizeof(int16_t) != byteLength)
return false;
*value = toV8(Int16Array::create(arrayBuffer.release(), byteOffset, shortLength), creationContext, isolate());
break;
}
case UnsignedShortArrayTag: {
uint32_t shortLength = byteLength / sizeof(uint16_t);
if (shortLength * sizeof(uint16_t) != byteLength)
return false;
*value = toV8(Uint16Array::create(arrayBuffer.release(), byteOffset, shortLength), creationContext, isolate());
break;
}
case IntArrayTag: {
uint32_t intLength = byteLength / sizeof(int32_t);
if (intLength * sizeof(int32_t) != byteLength)
return false;
*value = toV8(Int32Array::create(arrayBuffer.release(), byteOffset, intLength), creationContext, isolate());
break;
}
case UnsignedIntArrayTag: {
uint32_t intLength = byteLength / sizeof(uint32_t);
if (intLength * sizeof(uint32_t) != byteLength)
return false;
*value = toV8(Uint32Array::create(arrayBuffer.release(), byteOffset, intLength), creationContext, isolate());
break;
}
case FloatArrayTag: {
uint32_t floatLength = byteLength / sizeof(float);
if (floatLength * sizeof(float) != byteLength)
return false;
*value = toV8(Float32Array::create(arrayBuffer.release(), byteOffset, floatLength), creationContext, isolate());
break;
}
case DoubleArrayTag: {
uint32_t floatLength = byteLength / sizeof(double);
if (floatLength * sizeof(double) != byteLength)
return false;
*value = toV8(Float64Array::create(arrayBuffer.release(), byteOffset, floatLength), creationContext, isolate());
break;
}
case DataViewTag:
*value = toV8(DataView::create(arrayBuffer.release(), byteOffset, byteLength), creationContext, isolate());
break;
default:
return false;
}
return !value->IsEmpty();
}
Commit Message: Replace further questionable HashMap::add usages in bindings
BUG=390928
[email protected]
Review URL: https://codereview.chromium.org/411273002
git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
int do_rf64 = 0, write_junk = 1;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_riff_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so rf64", total_data_bytes);
write_junk = 0;
do_rf64 = 1;
}
else if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so riff", total_data_bytes);
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1);
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk);
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk))) ||
(write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
return TRUE;
}
Commit Message: issue #27, do not overwrite stack on corrupt RF64 file
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static char *print_object( cJSON *item, int depth, int fmt )
{
char **entries = 0, **names = 0;
char *out = 0, *ptr, *ret, *str;
int len = 7, i = 0, j;
cJSON *child = item->child;
int numentries = 0, fail = 0;
/* Count the number of entries. */
while ( child ) {
++numentries;
child = child->next;
}
/* Allocate space for the names and the objects. */
if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) )
return 0;
if ( ! ( names = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) {
cJSON_free( entries );
return 0;
}
memset( entries, 0, sizeof(char*) * numentries );
memset( names, 0, sizeof(char*) * numentries );
/* Collect all the results into our arrays. */
child = item->child;
++depth;
if ( fmt )
len += depth;
while ( child ) {
names[i] = str = print_string_ptr( child->string );
entries[i++] = ret = print_value( child, depth, fmt );
if ( str && ret )
len += strlen( ret ) + strlen( str ) + 2 + ( fmt ? 2 + depth : 0 );
else
fail = 1;
child = child->next;
}
/* Try to allocate the output string. */
if ( ! fail ) {
out = (char*) cJSON_malloc( len );
if ( ! out )
fail = 1;
}
/* Handle failure. */
if ( fail ) {
for ( i = 0; i < numentries; ++i ) {
if ( names[i] )
cJSON_free( names[i] );
if ( entries[i] )
cJSON_free( entries[i] );
}
cJSON_free( names );
cJSON_free( entries );
return 0;
}
/* Compose the output. */
*out = '{';
ptr = out + 1;
if ( fmt )
*ptr++ = '\n';
*ptr = 0;
for ( i = 0; i < numentries; ++i ) {
if ( fmt )
for ( j = 0; j < depth; ++j )
*ptr++ = '\t';
strcpy( ptr, names[i] );
ptr += strlen( names[i] );
*ptr++ = ':';
if ( fmt )
*ptr++ = '\t';
strcpy( ptr, entries[i] );
ptr += strlen( entries[i] );
if ( i != numentries - 1 )
*ptr++ = ',';
if ( fmt )
*ptr++ = '\n';
*ptr = 0;
cJSON_free( names[i] );
cJSON_free( entries[i] );
}
cJSON_free( names );
cJSON_free( entries );
if ( fmt )
for ( i = 0; i < depth - 1; ++i )
*ptr++ = '\t';
*ptr++ = '}';
*ptr++ = 0;
return out;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void DataPipeProducerDispatcher::StartSerialize(uint32_t* num_bytes,
uint32_t* num_ports,
uint32_t* num_handles) {
base::AutoLock lock(lock_);
DCHECK(in_transit_);
*num_bytes = sizeof(SerializedState);
*num_ports = 1;
*num_handles = 1;
}
Commit Message: [mojo-core] Validate data pipe endpoint metadata
Ensures that we don't blindly trust specified buffer size and offset
metadata when deserializing data pipe consumer and producer handles.
Bug: 877182
Change-Id: I30f3eceafb5cee06284c2714d08357ef911d6fd9
Reviewed-on: https://chromium-review.googlesource.com/1192922
Reviewed-by: Reilly Grant <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586704}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int raw_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct net *net = sock_net(sk);
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
struct flowi4 fl4;
int free = 0;
__be32 daddr;
__be32 saddr;
u8 tos;
int err;
struct ip_options_data opt_copy;
struct raw_frag_vec rfv;
err = -EMSGSIZE;
if (len > 0xFFFF)
goto out;
/*
* Check the flags.
*/
err = -EOPNOTSUPP;
if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */
goto out; /* compatibility */
/*
* Get and verify the address.
*/
if (msg->msg_namelen) {
DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
err = -EINVAL;
if (msg->msg_namelen < sizeof(*usin))
goto out;
if (usin->sin_family != AF_INET) {
pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n",
__func__, current->comm);
err = -EAFNOSUPPORT;
if (usin->sin_family)
goto out;
}
daddr = usin->sin_addr.s_addr;
/* ANK: I did not forget to get protocol from port field.
* I just do not know, who uses this weirdness.
* IP_HDRINCL is much more convenient.
*/
} else {
err = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
}
ipc.sockc.tsflags = sk->sk_tsflags;
ipc.addr = inet->inet_saddr;
ipc.opt = NULL;
ipc.tx_flags = 0;
ipc.ttl = 0;
ipc.tos = -1;
ipc.oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
err = ip_cmsg_send(sk, msg, &ipc, false);
if (unlikely(err)) {
kfree(ipc.opt);
goto out;
}
if (ipc.opt)
free = 1;
}
saddr = ipc.addr;
ipc.addr = daddr;
if (!ipc.opt) {
struct ip_options_rcu *inet_opt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
memcpy(&opt_copy, inet_opt,
sizeof(*inet_opt) + inet_opt->opt.optlen);
ipc.opt = &opt_copy.opt;
}
rcu_read_unlock();
}
if (ipc.opt) {
err = -EINVAL;
/* Linux does not mangle headers on raw sockets,
* so that IP options + IP_HDRINCL is non-sense.
*/
if (inet->hdrincl)
goto done;
if (ipc.opt->opt.srr) {
if (!daddr)
goto done;
daddr = ipc.opt->opt.faddr;
}
}
tos = get_rtconn_flags(&ipc, sk);
if (msg->msg_flags & MSG_DONTROUTE)
tos |= RTO_ONLINK;
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
} else if (!ipc.oif)
ipc.oif = inet->uc_index;
flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE,
inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol,
inet_sk_flowi_flags(sk) |
(inet->hdrincl ? FLOWI_FLAG_KNOWN_NH : 0),
daddr, saddr, 0, 0, sk->sk_uid);
if (!inet->hdrincl) {
rfv.msg = msg;
rfv.hlen = 0;
err = raw_probe_proto_opt(&rfv, &fl4);
if (err)
goto done;
}
security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
rt = ip_route_output_flow(net, &fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
goto done;
}
err = -EACCES;
if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST))
goto done;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = raw_send_hdrinc(sk, &fl4, msg, len,
&rt, msg->msg_flags, &ipc.sockc);
else {
sock_tx_timestamp(sk, ipc.sockc.tsflags, &ipc.tx_flags);
if (!ipc.addr)
ipc.addr = fl4.daddr;
lock_sock(sk);
err = ip_append_data(sk, &fl4, raw_getfrag,
&rfv, len, 0,
&ipc, &rt, msg->msg_flags);
if (err)
ip_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE)) {
err = ip_push_pending_frames(sk, &fl4);
if (err == -ENOBUFS && !inet->recverr)
err = 0;
}
release_sock(sk);
}
done:
if (free)
kfree(ipc.opt);
ip_rt_put(rt);
out:
if (err < 0)
return err;
return len;
do_confirm:
if (msg->msg_flags & MSG_PROBE)
dst_confirm_neigh(&rt->dst, &fl4.daddr);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
Commit Message: net: ipv4: fix for a race condition in raw_sendmsg
inet->hdrincl is racy, and could lead to uninitialized stack pointer
usage, so its value should be read only once.
Fixes: c008ba5bdc9f ("ipv4: Avoid reading user iov twice after raw_probe_proto_opt")
Signed-off-by: Mohamed Ghannam <[email protected]>
Reviewed-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void fdct4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fdct4x4_c(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int __init snd_compress_init(void)
{
return 0;
}
Commit Message: ALSA: compress: fix an integer overflow check
I previously added an integer overflow check here but looking at it now,
it's still buggy.
The bug happens in snd_compr_allocate_buffer(). We multiply
".fragments" and ".fragment_size" and that doesn't overflow but then we
save it in an unsigned int so it truncates the high bits away and we
allocate a smaller than expected size.
Fixes: b35cc8225845 ('ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()')
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
return aes_set_key_common(tfm, crypto_tfm_ctx(tfm), in_key, key_len);
}
Commit Message: crypto: aesni - fix memory usage in GCM decryption
The kernel crypto API logic requires the caller to provide the
length of (ciphertext || authentication tag) as cryptlen for the
AEAD decryption operation. Thus, the cipher implementation must
calculate the size of the plaintext output itself and cannot simply use
cryptlen.
The RFC4106 GCM decryption operation tries to overwrite cryptlen memory
in req->dst. As the destination buffer for decryption only needs to hold
the plaintext memory but cryptlen references the input buffer holding
(ciphertext || authentication tag), the assumption of the destination
buffer length in RFC4106 GCM operation leads to a too large size. This
patch simply uses the already calculated plaintext size.
In addition, this patch fixes the offset calculation of the AAD buffer
pointer: as mentioned before, cryptlen already includes the size of the
tag. Thus, the tag does not need to be added. With the addition, the AAD
will be written beyond the already allocated buffer.
Note, this fixes a kernel crash that can be triggered from user space
via AF_ALG(aead) -- simply use the libkcapi test application
from [1] and update it to use rfc4106-gcm-aes.
Using [1], the changes were tested using CAVS vectors to demonstrate
that the crypto operation still delivers the right results.
[1] http://www.chronox.de/libkcapi.html
CC: Tadeusz Struk <[email protected]>
Cc: [email protected]
Signed-off-by: Stephan Mueller <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
unsigned int *pipelens, unsigned int numpipes,
int create_empty_fragment)
{
unsigned char *outbuf[SSL_MAX_PIPELINES], *plen[SSL_MAX_PIPELINES];
SSL3_RECORD wr[SSL_MAX_PIPELINES];
int i, mac_size, clear = 0;
int prefix_len = 0;
int eivlen;
size_t align = 0;
SSL3_BUFFER *wb;
SSL_SESSION *sess;
unsigned int totlen = 0;
unsigned int j;
for (j = 0; j < numpipes; j++)
totlen += pipelens[j];
/*
* first check if there is a SSL3_BUFFER still being written out. This
* will happen with non blocking IO
*/
if (RECORD_LAYER_write_pending(&s->rlayer))
return (ssl3_write_pending(s, type, buf, totlen));
/* If we have an alert to send, lets send it */
if (s->s3->alert_dispatch) {
i = s->method->ssl_dispatch_alert(s);
if (i <= 0)
return (i);
/* if it went, fall through and send more stuff */
}
if (s->rlayer.numwpipes < numpipes)
if (!ssl3_setup_write_buffer(s, numpipes, 0))
return -1;
if (totlen == 0 && !create_empty_fragment)
return 0;
sess = s->session;
if ((sess == NULL) ||
(s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL)) {
clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
mac_size = 0;
} else {
mac_size = EVP_MD_CTX_size(s->write_hash);
if (mac_size < 0)
goto err;
}
/*
* 'create_empty_fragment' is true only when this function calls itself
*/
if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
/*
* countermeasure against known-IV weakness in CBC ciphersuites (see
* http://www.openssl.org/~bodo/tls-cbc.txt)
*/
if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
/*
* recursive function call with 'create_empty_fragment' set; this
* prepares and buffers the data for an empty fragment (these
* 'prefix_len' bytes are sent out later together with the actual
* payload)
*/
unsigned int tmppipelen = 0;
prefix_len = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1);
if (prefix_len <= 0)
goto err;
if (prefix_len >
(SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
/* insufficient space */
SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
goto err;
}
}
s->s3->empty_fragment_done = 1;
}
if (create_empty_fragment) {
wb = &s->rlayer.wbuf[0];
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
/*
* extra fragment would be couple of cipher blocks, which would be
* multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
* payload, then we can just pretend we simply have two headers.
*/
align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
outbuf[0] = SSL3_BUFFER_get_buf(wb) + align;
SSL3_BUFFER_set_offset(wb, align);
} else if (prefix_len) {
wb = &s->rlayer.wbuf[0];
outbuf[0] = SSL3_BUFFER_get_buf(wb) + SSL3_BUFFER_get_offset(wb)
+ prefix_len;
} else {
for (j = 0; j < numpipes; j++) {
wb = &s->rlayer.wbuf[j];
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
outbuf[j] = SSL3_BUFFER_get_buf(wb) + align;
SSL3_BUFFER_set_offset(wb, align);
}
}
/* Explicit IV length, block ciphers appropriate version flag */
if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
if (mode == EVP_CIPH_CBC_MODE) {
eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
if (eivlen <= 1)
eivlen = 0;
}
/* Need explicit part of IV for GCM mode */
else if (mode == EVP_CIPH_GCM_MODE)
eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
else if (mode == EVP_CIPH_CCM_MODE)
eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
else
eivlen = 0;
} else
eivlen = 0;
totlen = 0;
/* Clear our SSL3_RECORD structures */
memset(wr, 0, sizeof wr);
for (j = 0; j < numpipes; j++) {
/* write the header */
*(outbuf[j]++) = type & 0xff;
SSL3_RECORD_set_type(&wr[j], type);
*(outbuf[j]++) = (s->version >> 8);
/*
* Some servers hang if initial client hello is larger than 256 bytes
* and record version number > TLS 1.0
*/
if (SSL_get_state(s) == TLS_ST_CW_CLNT_HELLO
&& !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
*(outbuf[j]++) = 0x1;
else
*(outbuf[j]++) = s->version & 0xff;
/* field where we are to write out packet length */
plen[j] = outbuf[j];
outbuf[j] += 2;
/* lets setup the record stuff. */
SSL3_RECORD_set_data(&wr[j], outbuf[j] + eivlen);
SSL3_RECORD_set_length(&wr[j], (int)pipelens[j]);
SSL3_RECORD_set_input(&wr[j], (unsigned char *)&buf[totlen]);
totlen += pipelens[j];
/*
* we now 'read' from wr->input, wr->length bytes into wr->data
*/
/* first we compress */
if (s->compress != NULL) {
if (!ssl3_do_compress(s, &wr[j])) {
SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
goto err;
}
} else {
memcpy(wr[j].data, wr[j].input, wr[j].length);
SSL3_RECORD_reset_input(&wr[j]);
}
/*
* we should still have the output to wr->data and the input from
* wr->input. Length should be wr->length. wr->data still points in the
* wb->buf
*/
if (!SSL_USE_ETM(s) && mac_size != 0) {
if (s->method->ssl3_enc->mac(s, &wr[j],
&(outbuf[j][wr[j].length + eivlen]),
1) < 0)
goto err;
SSL3_RECORD_add_length(&wr[j], mac_size);
}
SSL3_RECORD_set_data(&wr[j], outbuf[j]);
SSL3_RECORD_reset_input(&wr[j]);
if (eivlen) {
/*
* if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
*/
SSL3_RECORD_add_length(&wr[j], eivlen);
}
}
if (s->method->ssl3_enc->enc(s, wr, numpipes, 1) < 1)
goto err;
for (j = 0; j < numpipes; j++) {
if (SSL_USE_ETM(s) && mac_size != 0) {
if (s->method->ssl3_enc->mac(s, &wr[j],
outbuf[j] + wr[j].length, 1) < 0)
goto err;
SSL3_RECORD_add_length(&wr[j], mac_size);
}
/* record length after mac and block padding */
s2n(SSL3_RECORD_get_length(&wr[j]), plen[j]);
if (s->msg_callback)
s->msg_callback(1, 0, SSL3_RT_HEADER, plen[j] - 5, 5, s,
s->msg_callback_arg);
/*
* we should now have wr->data pointing to the encrypted data, which is
* wr->length long
*/
SSL3_RECORD_set_type(&wr[j], type); /* not needed but helps for
* debugging */
SSL3_RECORD_add_length(&wr[j], SSL3_RT_HEADER_LENGTH);
if (create_empty_fragment) {
/*
* we are in a recursive call; just return the length, don't write
* out anything here
*/
if (j > 0) {
/* We should never be pipelining an empty fragment!! */
SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
goto err;
}
return SSL3_RECORD_get_length(wr);
}
/* now let's set up wb */
SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
prefix_len + SSL3_RECORD_get_length(&wr[j]));
}
/*
* memorize arguments so that ssl3_write_pending can detect bad write
* retries later
*/
s->rlayer.wpend_tot = totlen;
s->rlayer.wpend_buf = buf;
s->rlayer.wpend_type = type;
s->rlayer.wpend_ret = totlen;
/* we now just need to write the buffer */
return ssl3_write_pending(s, type, buf, totlen);
err:
return -1;
}
Commit Message: Don't change the state of the ETM flags until CCS processing
Changing the ciphersuite during a renegotiation can result in a crash
leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS
so this is TLS only.
The problem is caused by changing the flag indicating whether to use ETM
or not immediately on negotiation of ETM, rather than at CCS. Therefore,
during a renegotiation, if the ETM state is changing (usually due to a
change of ciphersuite), then an error/crash will occur.
Due to the fact that there are separate CCS messages for read and write
we actually now need two flags to determine whether to use ETM or not.
CVE-2017-3733
Reviewed-by: Richard Levitte <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: void ExtensionsGuestViewMessageFilter::CreateMimeHandlerViewGuestOnUIThread(
int render_frame_id,
const std::string& view_id,
int element_instance_id,
const gfx::Size& element_size,
mime_handler::BeforeUnloadControlPtrInfo before_unload_control,
int32_t plugin_frame_routing_id,
bool is_full_page_plugin) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auto* manager = GetOrCreateGuestViewManager();
auto* rfh = RenderFrameHost::FromID(render_process_id_, render_frame_id);
auto* embedder_web_contents = WebContents::FromRenderFrameHost(rfh);
if (!embedder_web_contents)
return;
if (!AreRoutingIDsConsistent(rfh, plugin_frame_routing_id)) {
bad_message::ReceivedBadMessage(rfh->GetProcess(),
bad_message::MHVG_INVALID_PLUGIN_FRAME_ID);
return;
}
GuestViewManager::WebContentsCreatedCallback callback = base::BindOnce(
&ExtensionsGuestViewMessageFilter::MimeHandlerViewGuestCreatedCallback,
this, element_instance_id, render_process_id_, render_frame_id,
plugin_frame_routing_id, element_size, std::move(before_unload_control),
is_full_page_plugin);
base::DictionaryValue create_params;
create_params.SetString(mime_handler_view::kViewId, view_id);
create_params.SetInteger(guest_view::kElementWidth, element_size.width());
create_params.SetInteger(guest_view::kElementHeight, element_size.height());
manager->CreateGuest(MimeHandlerViewGuest::Type, embedder_web_contents,
create_params, std::move(callback));
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
const void *data)
{
void *target;
int chunklen = ntohs(chunk->chunk_hdr->length);
target = skb_put(chunk->skb, len);
if (data)
memcpy(target, data, len);
else
memset(target, 0, len);
/* Adjust the chunk length field. */
chunk->chunk_hdr->length = htons(chunklen + len);
chunk->chunk_end = skb_tail_pointer(chunk->skb);
return target;
}
Commit Message: net: sctp: fix NULL pointer dereference in af->from_addr_param on malformed packet
An SCTP server doing ASCONF will panic on malformed INIT ping-of-death
in the form of:
------------ INIT[PARAM: SET_PRIMARY_IP] ------------>
While the INIT chunk parameter verification dissects through many things
in order to detect malformed input, it misses to actually check parameters
inside of parameters. E.g. RFC5061, section 4.2.4 proposes a 'set primary
IP address' parameter in ASCONF, which has as a subparameter an address
parameter.
So an attacker may send a parameter type other than SCTP_PARAM_IPV4_ADDRESS
or SCTP_PARAM_IPV6_ADDRESS, param_type2af() will subsequently return 0
and thus sctp_get_af_specific() returns NULL, too, which we then happily
dereference unconditionally through af->from_addr_param().
The trace for the log:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000078
IP: [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp]
PGD 0
Oops: 0000 [#1] SMP
[...]
Pid: 0, comm: swapper Not tainted 2.6.32-504.el6.x86_64 #1 Bochs Bochs
RIP: 0010:[<ffffffffa01e9c62>] [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp]
[...]
Call Trace:
<IRQ>
[<ffffffffa01f2add>] ? sctp_bind_addr_copy+0x5d/0xe0 [sctp]
[<ffffffffa01e1fcb>] sctp_sf_do_5_1B_init+0x21b/0x340 [sctp]
[<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp]
[<ffffffffa01e5c09>] ? sctp_endpoint_lookup_assoc+0xc9/0xf0 [sctp]
[<ffffffffa01e61f6>] sctp_endpoint_bh_rcv+0x116/0x230 [sctp]
[<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp]
[<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp]
[<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]
[<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[...]
A minimal way to address this is to check for NULL as we do on all
other such occasions where we know sctp_get_af_specific() could
possibly return with NULL.
Fixes: d6de3097592b ("[SCTP]: Add the handling of "Set Primary IP Address" parameter to INIT")
Signed-off-by: Daniel Borkmann <[email protected]>
Cc: Vlad Yasevich <[email protected]>
Acked-by: Neil Horman <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GURL DevToolsUI::SanitizeFrontendURL(const GURL& url) {
return ::SanitizeFrontendURL(url, content::kChromeDevToolsScheme,
chrome::kChromeUIDevToolsHost, SanitizeFrontendPath(url.path()), true);
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200
Target: 1
Example 2:
Code: AXObject* AXObjectCacheImpl::getOrCreate(AbstractInlineTextBox* inlineTextBox) {
if (!inlineTextBox)
return 0;
if (AXObject* obj = get(inlineTextBox))
return obj;
AXObject* newObj = createFromInlineTextBox(inlineTextBox);
DCHECK(!get(inlineTextBox));
const AXID axid = getOrCreateAXID(newObj);
m_inlineTextBoxObjectMapping.set(inlineTextBox, axid);
newObj->init();
newObj->setLastKnownIsIgnoredValue(newObj->accessibilityIsIgnored());
return newObj;
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebPluginDelegateProxy::OnNotifyIMEStatus(int input_type,
const gfx::Rect& caret_rect) {
if (!render_view_)
return;
render_view_->Send(new ViewHostMsg_TextInputStateChanged(
render_view_->routing_id(),
static_cast<ui::TextInputType>(input_type),
true));
render_view_->Send(new ViewHostMsg_SelectionBoundsChanged(
render_view_->routing_id(), caret_rect, caret_rect));
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct mount *clone_mnt(struct mount *old, struct dentry *root,
int flag)
{
struct super_block *sb = old->mnt.mnt_sb;
struct mount *mnt;
int err;
mnt = alloc_vfsmnt(old->mnt_devname);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
mnt->mnt_group_id = 0; /* not a peer of original */
else
mnt->mnt_group_id = old->mnt_group_id;
if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
err = mnt_alloc_group_id(mnt);
if (err)
goto out_free;
}
mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~(MNT_WRITE_HOLD|MNT_MARKED);
/* Don't allow unprivileged users to change mount flags */
if ((flag & CL_UNPRIVILEGED) && (mnt->mnt.mnt_flags & MNT_READONLY))
mnt->mnt.mnt_flags |= MNT_LOCK_READONLY;
/* Don't allow unprivileged users to reveal what is under a mount */
if ((flag & CL_UNPRIVILEGED) && list_empty(&old->mnt_expire))
mnt->mnt.mnt_flags |= MNT_LOCKED;
atomic_inc(&sb->s_active);
mnt->mnt.mnt_sb = sb;
mnt->mnt.mnt_root = dget(root);
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
lock_mount_hash();
list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
unlock_mount_hash();
if ((flag & CL_SLAVE) ||
((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
list_add(&mnt->mnt_slave, &old->mnt_slave_list);
mnt->mnt_master = old;
CLEAR_MNT_SHARED(mnt);
} else if (!(flag & CL_PRIVATE)) {
if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
list_add(&mnt->mnt_share, &old->mnt_share);
if (IS_MNT_SLAVE(old))
list_add(&mnt->mnt_slave, &old->mnt_slave);
mnt->mnt_master = old->mnt_master;
}
if (flag & CL_MAKE_SHARED)
set_mnt_shared(mnt);
/* stick the duplicate mount on the same expiry list
* as the original if that was on one */
if (flag & CL_EXPIRE) {
if (!list_empty(&old->mnt_expire))
list_add(&mnt->mnt_expire, &old->mnt_expire);
}
return mnt;
out_free:
mnt_free_id(mnt);
free_vfsmnt(mnt);
return ERR_PTR(err);
}
Commit Message: mnt: Correct permission checks in do_remount
While invesgiating the issue where in "mount --bind -oremount,ro ..."
would result in later "mount --bind -oremount,rw" succeeding even if
the mount started off locked I realized that there are several
additional mount flags that should be locked and are not.
In particular MNT_NOSUID, MNT_NODEV, MNT_NOEXEC, and the atime
flags in addition to MNT_READONLY should all be locked. These
flags are all per superblock, can all be changed with MS_BIND,
and should not be changable if set by a more privileged user.
The following additions to the current logic are added in this patch.
- nosuid may not be clearable by a less privileged user.
- nodev may not be clearable by a less privielged user.
- noexec may not be clearable by a less privileged user.
- atime flags may not be changeable by a less privileged user.
The logic with atime is that always setting atime on access is a
global policy and backup software and auditing software could break if
atime bits are not updated (when they are configured to be updated),
and serious performance degradation could result (DOS attack) if atime
updates happen when they have been explicitly disabled. Therefore an
unprivileged user should not be able to mess with the atime bits set
by a more privileged user.
The additional restrictions are implemented with the addition of
MNT_LOCK_NOSUID, MNT_LOCK_NODEV, MNT_LOCK_NOEXEC, and MNT_LOCK_ATIME
mnt flags.
Taken together these changes and the fixes for MNT_LOCK_READONLY
should make it safe for an unprivileged user to create a user
namespace and to call "mount --bind -o remount,... ..." without
the danger of mount flags being changed maliciously.
Cc: [email protected]
Acked-by: Serge E. Hallyn <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: void vga_init_vbe(VGACommonState *s, Object *obj, MemoryRegion *system_memory)
{
/* With pc-0.12 and below we map both the PCI BAR and the fixed VBE region,
* so use an alias to avoid double-mapping the same region.
*/
memory_region_init_alias(&s->vram_vbe, obj, "vram.vbe",
&s->vram, 0, memory_region_size(&s->vram));
/* XXX: use optimized standard vga accesses */
memory_region_add_subregion(system_memory,
VBE_DISPI_LFB_PHYSICAL_ADDRESS,
&s->vram_vbe);
s->vbe_mapped = 1;
}
Commit Message:
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: WebRunnerMainDelegate::CreateContentBrowserClient() {
DCHECK(!browser_client_);
browser_client_ = std::make_unique<WebRunnerContentBrowserClient>(
std::move(context_channel_));
return browser_client_.get();
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
#ifdef AUTOKEY
filegen_register(statsdir, "cryptostats", &cryptostats);
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
filegen_register(statsdir, "timingstats", &timingstats);
#endif /* DEBUG_TIMING */
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
Commit Message: [Bug 1773] openssl not detected during ./configure.
[Bug 1774] Segfaults if cryptostats enabled and built without OpenSSL.
CWE ID: CWE-20
Target: 1
Example 2:
Code: LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "LogL16Decode";
LogLuvState* sp = DecoderState(tif);
int shft;
tmsize_t i;
tmsize_t npixels;
unsigned char* bp;
int16* tp;
int16 b;
tmsize_t cc;
int rc;
assert(s == 0);
assert(sp != NULL);
npixels = occ / sp->pixel_size;
if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
tp = (int16*) op;
else {
if(sp->tbuflen < npixels) {
TIFFErrorExt(tif->tif_clientdata, module,
"Translation buffer too short");
return (0);
}
tp = (int16*) sp->tbuf;
}
_TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));
bp = (unsigned char*) tif->tif_rawcp;
cc = tif->tif_rawcc;
/* get each byte string */
for (shft = 2*8; (shft -= 8) >= 0; ) {
for (i = 0; i < npixels && cc > 0; ) {
if (*bp >= 128) { /* run */
if( cc < 2 )
break;
rc = *bp++ + (2-128);
b = (int16)(*bp++ << shft);
cc -= 2;
while (rc-- && i < npixels)
tp[i++] |= b;
} else { /* non-run */
rc = *bp++; /* nul is noop */
while (--cc && rc-- && i < npixels)
tp[i++] |= (int16)*bp++ << shft;
}
}
if (i != npixels) {
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at row %lu (short %I64d pixels)",
(unsigned long) tif->tif_row,
(unsigned __int64) (npixels - i));
#else
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at row %lu (short %llu pixels)",
(unsigned long) tif->tif_row,
(unsigned long long) (npixels - i));
#endif
tif->tif_rawcp = (uint8*) bp;
tif->tif_rawcc = cc;
return (0);
}
}
(*sp->tfunc)(sp, op, npixels);
tif->tif_rawcp = (uint8*) bp;
tif->tif_rawcc = cc;
return (1);
}
Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer
overflow on generation of PixarLog / LUV compressed files, with
ColorMap, TransferFunction attached and nasty plays with bitspersample.
The fix for LUV has not been tested, but suffers from the same kind
of issue of PixarLog.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct sock *sk = sock->sk;
struct atm_vcc *vcc;
struct sk_buff *skb;
int copied, error = -EINVAL;
msg->msg_namelen = 0;
if (sock->state != SS_CONNECTED)
return -ENOTCONN;
/* only handle MSG_DONTWAIT and MSG_PEEK */
if (flags & ~(MSG_DONTWAIT | MSG_PEEK))
return -EOPNOTSUPP;
vcc = ATM_SD(sock);
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags))
return 0;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error);
if (!skb)
return error;
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (error)
return error;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc),
skb->truesize);
atm_return(vcc, skb->truesize);
}
skb_free_datagram(sk, skb);
return copied;
}
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 <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
{
struct key *key;
key_ref_t key_ref;
long ret;
/* find the key first */
key_ref = lookup_user_key(keyid, 0, 0);
if (IS_ERR(key_ref)) {
ret = -ENOKEY;
goto error;
}
key = key_ref_to_ptr(key_ref);
/* see if we can read it directly */
ret = key_permission(key_ref, KEY_NEED_READ);
if (ret == 0)
goto can_read_key;
if (ret != -EACCES)
goto error2;
/* we can't; see if it's searchable from this process's keyrings
* - we automatically take account of the fact that it may be
* dangling off an instantiation key
*/
if (!is_key_possessed(key_ref)) {
ret = -EACCES;
goto error2;
}
/* the key is probably readable - now try to read it */
can_read_key:
ret = -EOPNOTSUPP;
if (key->type->read) {
/* Read the data with the semaphore held (since we might sleep)
* to protect against the key being updated or revoked.
*/
down_read(&key->sem);
ret = key_validate(key);
if (ret == 0)
ret = key->type->read(key, buffer, buflen);
up_read(&key->sem);
}
error2:
key_put(key);
error:
return ret;
}
Commit Message: KEYS: prevent KEYCTL_READ on negative key
Because keyctl_read_key() looks up the key with no permissions
requested, it may find a negatively instantiated key. If the key is
also possessed, we went ahead and called ->read() on the key. But the
key payload will actually contain the ->reject_error rather than the
normal payload. Thus, the kernel oopses trying to read the
user_key_payload from memory address (int)-ENOKEY = 0x00000000ffffff82.
Fortunately the payload data is stored inline, so it shouldn't be
possible to abuse this as an arbitrary memory read primitive...
Reproducer:
keyctl new_session
keyctl request2 user desc '' @s
keyctl read $(keyctl show | awk '/user: desc/ {print $1}')
It causes a crash like the following:
BUG: unable to handle kernel paging request at 00000000ffffff92
IP: user_read+0x33/0xa0
PGD 36a54067 P4D 36a54067 PUD 0
Oops: 0000 [#1] SMP
CPU: 0 PID: 211 Comm: keyctl Not tainted 4.14.0-rc1 #337
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-20170228_101828-anatol 04/01/2014
task: ffff90aa3b74c3c0 task.stack: ffff9878c0478000
RIP: 0010:user_read+0x33/0xa0
RSP: 0018:ffff9878c047bee8 EFLAGS: 00010246
RAX: 0000000000000001 RBX: ffff90aa3d7da340 RCX: 0000000000000017
RDX: 0000000000000000 RSI: 00000000ffffff82 RDI: ffff90aa3d7da340
RBP: ffff9878c047bf00 R08: 00000024f95da94f R09: 0000000000000000
R10: 0000000000000001 R11: 0000000000000000 R12: 0000000000000000
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000000
FS: 00007f58ece69740(0000) GS:ffff90aa3e200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00000000ffffff92 CR3: 0000000036adc001 CR4: 00000000003606f0
Call Trace:
keyctl_read_key+0xac/0xe0
SyS_keyctl+0x99/0x120
entry_SYSCALL_64_fastpath+0x1f/0xbe
RIP: 0033:0x7f58ec787bb9
RSP: 002b:00007ffc8d401678 EFLAGS: 00000206 ORIG_RAX: 00000000000000fa
RAX: ffffffffffffffda RBX: 00007ffc8d402800 RCX: 00007f58ec787bb9
RDX: 0000000000000000 RSI: 00000000174a63ac RDI: 000000000000000b
RBP: 0000000000000004 R08: 00007ffc8d402809 R09: 0000000000000020
R10: 0000000000000000 R11: 0000000000000206 R12: 00007ffc8d402800
R13: 00007ffc8d4016e0 R14: 0000000000000000 R15: 0000000000000000
Code: e5 41 55 49 89 f5 41 54 49 89 d4 53 48 89 fb e8 a4 b4 ad ff 85 c0 74 09 80 3d b9 4c 96 00 00 74 43 48 8b b3 20 01 00 00 4d 85 ed <0f> b7 5e 10 74 29 4d 85 e4 74 24 4c 39 e3 4c 89 e2 4c 89 ef 48
RIP: user_read+0x33/0xa0 RSP: ffff9878c047bee8
CR2: 00000000ffffff92
Fixes: 61ea0c0ba904 ("KEYS: Skip key state checks when checking for possession")
Cc: <[email protected]> [v3.13+]
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: static PHP_FUNCTION(xmlwriter_set_indent)
{
zval *pind;
xmlwriter_object *intern;
xmlTextWriterPtr ptr;
int retval;
zend_bool indent;
#ifdef ZEND_ENGINE_2
zval *this = getThis();
if (this) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "b", &indent) == FAILURE) {
return;
}
XMLWRITER_FROM_OBJECT(intern, this);
} else
#endif
{
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rb", &pind, &indent) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(intern,xmlwriter_object *, &pind, -1, "XMLWriter", le_xmlwriter);
}
ptr = intern->ptr;
if (ptr) {
retval = xmlTextWriterSetIndent(ptr, indent);
if (retval == 0) {
RETURN_TRUE;
}
}
RETURN_FALSE;
}
Commit Message:
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int dtls1_is_timer_expired(SSL *s)
{
struct timeval timeleft;
/* Get time left until timeout, return false if no timer running */
if (dtls1_get_timeout(s, &timeleft) == NULL)
{
return 0;
}
/* Return false if timer is not expired yet */
if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0)
{
return 0;
}
/* Timer expired, so return true */
return 1;
}
Commit Message: Free up s->d1->buffered_app_data.q properly.
PR#3286
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) {
if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL ||
lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL ||
lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL ||
lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL ||
lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) {
JsVar *rhs;
int op = lex->tk;
JSP_ASSERT_MATCH(op);
rhs = jspeAssignmentExpression();
rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS
if (JSP_SHOULD_EXECUTE && lhs) {
if (op=='=') {
/* If we're assigning to this and we don't have a parent,
* add it to the symbol table root */
if (!jsvGetRefs(lhs) && jsvIsName(lhs)) {
if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs))
jsvAddName(execInfo.root, lhs);
}
jspReplaceWith(lhs, rhs);
} else {
if (op==LEX_PLUSEQUAL) op='+';
else if (op==LEX_MINUSEQUAL) op='-';
else if (op==LEX_MULEQUAL) op='*';
else if (op==LEX_DIVEQUAL) op='/';
else if (op==LEX_MODEQUAL) op='%';
else if (op==LEX_ANDEQUAL) op='&';
else if (op==LEX_OREQUAL) op='|';
else if (op==LEX_XOREQUAL) op='^';
else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT;
else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT;
else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED;
if (op=='+' && jsvIsName(lhs)) {
JsVar *currentValue = jsvSkipName(lhs);
if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) {
/* A special case for string += where this is the only use of the string
* and we're not appending to ourselves. In this case we can do a
* simple append (rather than clone + append)*/
JsVar *str = jsvAsString(rhs, false);
jsvAppendStringVarComplete(currentValue, str);
jsvUnLock(str);
op = 0;
}
jsvUnLock(currentValue);
}
if (op) {
/* Fallback which does a proper add */
JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op);
jspReplaceWith(lhs, res);
jsvUnLock(res);
}
}
}
jsvUnLock(rhs);
}
return lhs;
}
Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437)
CWE ID: CWE-125
Target: 1
Example 2:
Code: gfx::Rect TabStrip::GetDropBounds(int drop_index,
bool drop_before,
bool* is_beneath) {
DCHECK_NE(drop_index, -1);
Tab* tab = tab_at(std::min(drop_index, tab_count() - 1));
int center_x = tab->x();
const int width = tab->width();
const int overlap = TabStyle::GetTabOverlap();
if (drop_index < tab_count())
center_x += drop_before ? (overlap / 2) : (width / 2);
else
center_x += width - (overlap / 2);
center_x = GetMirroredXInView(center_x);
gfx::Point drop_loc(center_x - g_drop_indicator_width / 2,
-g_drop_indicator_height);
ConvertPointToScreen(this, &drop_loc);
gfx::Rect drop_bounds(drop_loc.x(), drop_loc.y(), g_drop_indicator_width,
g_drop_indicator_height);
display::Screen* screen = display::Screen::GetScreen();
display::Display display = screen->GetDisplayMatching(drop_bounds);
*is_beneath = !display.bounds().Contains(drop_bounds);
if (*is_beneath)
drop_bounds.Offset(0, drop_bounds.height() + height());
return drop_bounds;
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: raptor_rdfxml_parse_start(raptor_parser* rdf_parser)
{
raptor_uri *uri = rdf_parser->base_uri;
raptor_rdfxml_parser* rdf_xml_parser;
rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context;
/* base URI required for RDF/XML */
if(!uri)
return 1;
/* Optionally normalize language to lowercase
* http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier
*/
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE));
/* Optionally forbid internal network and file requests in the XML parser */
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_NET, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET));
raptor_sax2_set_option(rdf_xml_parser->sax2,
RAPTOR_OPTION_NO_FILE, NULL,
RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE));
if(rdf_parser->uri_filter)
raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter,
rdf_parser->uri_filter_user_data);
raptor_sax2_parse_start(rdf_xml_parser->sax2, uri);
/* Delete any existing id_set */
if(rdf_xml_parser->id_set) {
raptor_free_id_set(rdf_xml_parser->id_set);
rdf_xml_parser->id_set = NULL;
}
/* Create a new id_set if needed */
if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) {
rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world);
if(!rdf_xml_parser->id_set)
return 1;
}
return 0;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200
Output: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.