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: init_remote_listener(int port, gboolean encrypted)
{
int rc;
int *ssock = NULL;
struct sockaddr_in saddr;
int optval;
static struct mainloop_fd_callbacks remote_listen_fd_callbacks =
{
.dispatch = cib_remote_listen,
.destroy = remote_connection_destroy,
};
if (port <= 0) {
/* dont start it */
return 0;
}
if (encrypted) {
#ifndef HAVE_GNUTLS_GNUTLS_H
crm_warn("TLS support is not available");
return 0;
#else
crm_notice("Starting a tls listener on port %d.", port);
gnutls_global_init();
/* gnutls_global_set_log_level (10); */
gnutls_global_set_log_function(debug_log);
gnutls_dh_params_init(&dh_params);
gnutls_dh_params_generate2(dh_params, DH_BITS);
gnutls_anon_allocate_server_credentials(&anon_cred_s);
gnutls_anon_set_server_dh_params(anon_cred_s, dh_params);
#endif
} else {
crm_warn("Starting a plain_text listener on port %d.", port);
}
#ifndef HAVE_PAM
crm_warn("PAM is _not_ enabled!");
#endif
/* create server socket */
ssock = malloc(sizeof(int));
*ssock = socket(AF_INET, SOCK_STREAM, 0);
if (*ssock == -1) {
crm_perror(LOG_ERR, "Can not create server socket." ERROR_SUFFIX);
free(ssock);
return -1;
}
/* reuse address */
optval = 1;
rc = setsockopt(*ssock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
if(rc < 0) {
crm_perror(LOG_INFO, "Couldn't allow the reuse of local addresses by our remote listener");
}
/* bind server socket */
memset(&saddr, '\0', sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = INADDR_ANY;
saddr.sin_port = htons(port);
if (bind(*ssock, (struct sockaddr *)&saddr, sizeof(saddr)) == -1) {
crm_perror(LOG_ERR, "Can not bind server socket." ERROR_SUFFIX);
close(*ssock);
free(ssock);
return -2;
}
if (listen(*ssock, 10) == -1) {
crm_perror(LOG_ERR, "Can not start listen." ERROR_SUFFIX);
close(*ssock);
free(ssock);
return -3;
}
mainloop_add_fd("cib-remote", G_PRIORITY_DEFAULT, *ssock, ssock, &remote_listen_fd_callbacks);
return *ssock;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
Target: 1
Example 2:
Code: mm_auth_password(Authctxt *authctxt, char *password)
{
Buffer m;
int authenticated = 0;
debug3("%s entering", __func__);
buffer_init(&m);
buffer_put_cstring(&m, password);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTHPASSWORD, &m);
debug3("%s: waiting for MONITOR_ANS_AUTHPASSWORD", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_AUTHPASSWORD, &m);
authenticated = buffer_get_int(&m);
buffer_free(&m);
debug3("%s: user %sauthenticated",
__func__, authenticated ? "" : "not ");
return (authenticated);
}
Commit Message: Don't resend username to PAM; it already has it.
Pointed out by Moritz Jodeit; ok dtucker@
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 MediaInterfaceProxy::OnConnectionError() {
DVLOG(1) << __FUNCTION__;
DCHECK(thread_checker_.CalledOnValidThread());
interface_factory_ptr_.reset();
}
Commit Message: media: Support hosting mojo CDM in a standalone service
Currently when mojo CDM is enabled it is hosted in the MediaService
running in the process specified by "mojo_media_host". However, on
some platforms we need to run mojo CDM and other mojo media services in
different processes. For example, on desktop platforms, we want to run
mojo video decoder in the GPU process, but run the mojo CDM in the
utility process.
This CL adds a new build flag "enable_standalone_cdm_service". When
enabled, the mojo CDM service will be hosted in a standalone "cdm"
service running in the utility process. All other mojo media services
will sill be hosted in the "media" servie running in the process
specified by "mojo_media_host".
BUG=664364
TEST=Encrypted media browser tests using mojo CDM is still working.
Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487
Reviewed-on: https://chromium-review.googlesource.com/567172
Commit-Queue: Xiaohan Wang <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486947}
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: LoadWatcher(ScriptContext* context,
content::RenderFrame* frame,
v8::Local<v8::Function> cb)
: content::RenderFrameObserver(frame),
context_(context),
callback_(context->isolate(), cb) {
if (ExtensionFrameHelper::Get(frame)->
did_create_current_document_element()) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&LoadWatcher::CallbackAndDie, base::Unretained(this),
true));
}
}
Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated
BUG=585268,568130
Review URL: https://codereview.chromium.org/1684953002
Cr-Commit-Position: refs/heads/master@{#374758}
CWE ID:
Target: 1
Example 2:
Code: static WebPoint bottomRightMinusOne(const WebRect& rect)
{
return WebPoint(rect.x + rect.width - 1, rect.y + rect.height - 1);
}
Commit Message: Call didAccessInitialDocument when javascript: URLs are used.
BUG=265221
TEST=See bug for repro.
Review URL: https://chromiumcodereview.appspot.com/22572004
git-svn-id: svn://svn.chromium.org/blink/trunk@155790 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: void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
scoped_refptr<printing::PrinterQuery> printer_query;
if (!print_job_manager_->printing_enabled()) {
OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
return;
}
print_job_manager_->PopPrinterQuery(0, &printer_query);
if (!printer_query.get()) {
printer_query = new printing::PrinterQuery;
}
CancelableTask* task = NewRunnableMethod(
this,
&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
printer_query,
reply_msg);
printer_query->GetSettings(printing::PrinterQuery::DEFAULTS,
NULL,
0,
false,
true,
task);
}
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
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 AcceleratedSurfaceBuffersSwappedCompletedForGPU(int host_id,
int route_id,
bool alive,
bool did_swap) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU,
host_id,
route_id,
alive,
did_swap));
return;
}
GpuProcessHost* host = GpuProcessHost::FromID(host_id);
if (host) {
if (alive)
host->Send(new AcceleratedSurfaceMsg_BufferPresented(
route_id, did_swap, 0));
else
host->ForceShutdown();
}
}
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 int may_mknod(umode_t mode)
{
switch (mode & S_IFMT) {
case S_IFREG:
case S_IFCHR:
case S_IFBLK:
case S_IFIFO:
case S_IFSOCK:
case 0: /* zero mode translates to S_IFREG */
return 0;
case S_IFDIR:
return -EPERM;
default:
return -EINVAL;
}
}
Commit Message: fs: umount on symlink leaks mnt count
Currently umount on symlink blocks following umount:
/vz is separate mount
# ls /vz/ -al | grep test
drwxr-xr-x. 2 root root 4096 Jul 19 01:14 testdir
lrwxrwxrwx. 1 root root 11 Jul 19 01:16 testlink -> /vz/testdir
# umount -l /vz/testlink
umount: /vz/testlink: not mounted (expected)
# lsof /vz
# umount /vz
umount: /vz: device is busy. (unexpected)
In this case mountpoint_last() gets an extra refcount on path->mnt
Signed-off-by: Vasily Averin <[email protected]>
Acked-by: Ian Kent <[email protected]>
Acked-by: Jeff Layton <[email protected]>
Cc: [email protected]
Signed-off-by: Christoph Hellwig <[email protected]>
CWE ID: CWE-59
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 UpdatePolicyForEvent(const WebInputEvent* input_event,
NavigationPolicy* policy) {
if (!input_event)
return;
unsigned short button_number = 0;
if (input_event->GetType() == WebInputEvent::kMouseUp) {
const WebMouseEvent* mouse_event =
static_cast<const WebMouseEvent*>(input_event);
switch (mouse_event->button) {
case WebMouseEvent::Button::kLeft:
button_number = 0;
break;
case WebMouseEvent::Button::kMiddle:
button_number = 1;
break;
case WebMouseEvent::Button::kRight:
button_number = 2;
break;
default:
return;
}
} else if ((WebInputEvent::IsKeyboardEventType(input_event->GetType()) &&
static_cast<const WebKeyboardEvent*>(input_event)
->windows_key_code == VKEY_RETURN) ||
WebInputEvent::IsGestureEventType(input_event->GetType())) {
button_number = 0;
} else {
return;
}
bool ctrl = input_event->GetModifiers() & WebInputEvent::kControlKey;
bool shift = input_event->GetModifiers() & WebInputEvent::kShiftKey;
bool alt = input_event->GetModifiers() & WebInputEvent::kAltKey;
bool meta = input_event->GetModifiers() & WebInputEvent::kMetaKey;
NavigationPolicy user_policy = *policy;
NavigationPolicyFromMouseEvent(button_number, ctrl, shift, alt, meta,
&user_policy);
if (user_policy == kNavigationPolicyDownload &&
*policy != kNavigationPolicyIgnore)
return;
if (user_policy == kNavigationPolicyNewWindow &&
*policy == kNavigationPolicyNewPopup)
return;
*policy = user_policy;
}
Commit Message: Only allow downloading in response to real keyboard modifiers
BUG=848531
Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf
Reviewed-on: https://chromium-review.googlesource.com/1082216
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#564051}
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 test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
}
Commit Message: Check outbuf length in mutt_to_base64()
The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.
Thanks to Jeriko One for the bug report.
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void set_reg_mkey_segment(struct mlx5_mkey_seg *seg,
const struct ib_send_wr *wr)
{
const struct mlx5_umr_wr *umrwr = umr_wr(wr);
memset(seg, 0, sizeof(*seg));
if (wr->send_flags & MLX5_IB_SEND_UMR_DISABLE_MR)
seg->status = MLX5_MKEY_STATUS_FREE;
seg->flags = convert_access(umrwr->access_flags);
if (umrwr->pd)
seg->flags_pd = cpu_to_be32(to_mpd(umrwr->pd)->pdn);
if (wr->send_flags & MLX5_IB_SEND_UMR_UPDATE_TRANSLATION &&
!umrwr->length)
seg->flags_pd |= cpu_to_be32(MLX5_MKEY_LEN64);
seg->start_addr = cpu_to_be64(umrwr->virt_addr);
seg->len = cpu_to_be64(umrwr->length);
seg->log2_page_size = umrwr->page_shift;
seg->qpn_mkey7_0 = cpu_to_be32(0xffffff00 |
mlx5_mkey_variant(umrwr->mkey));
}
Commit Message: IB/mlx5: Fix leaking stack memory to userspace
mlx5_ib_create_qp_resp was never initialized and only the first 4 bytes
were written.
Fixes: 41d902cb7c32 ("RDMA/mlx5: Fix definition of mlx5_ib_create_qp_resp")
Cc: <[email protected]>
Acked-by: Leon Romanovsky <[email protected]>
Signed-off-by: Jason Gunthorpe <[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: int rose_parse_facilities(unsigned char *p,
struct rose_facilities_struct *facilities)
{
int facilities_len, len;
facilities_len = *p++;
if (facilities_len == 0)
return 0;
while (facilities_len > 0) {
if (*p == 0x00) {
facilities_len--;
p++;
switch (*p) {
case FAC_NATIONAL: /* National */
len = rose_parse_national(p + 1, facilities, facilities_len - 1);
facilities_len -= len + 1;
p += len + 1;
break;
case FAC_CCITT: /* CCITT */
len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1);
facilities_len -= len + 1;
p += len + 1;
break;
default:
printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p);
facilities_len--;
p++;
break;
}
} else
break; /* Error in facilities format */
}
return 1;
}
Commit Message: ROSE: prevent heap corruption with bad facilities
When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for
a remote host to provide more digipeaters than expected, resulting in
heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and
abort facilities parsing on failure.
Additionally, when parsing the FAC_CCITT_DEST_NSAP and
FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length
of less than 10, resulting in an underflow in a memcpy size, causing a
kernel panic due to massive heap corruption. A length of greater than
20 results in a stack overflow of the callsign array. Abort facilities
parsing on these invalid length values.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [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: int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
Commit Message: Proper fix for #248
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void restore_reserve_on_error(struct hstate *h,
struct vm_area_struct *vma, unsigned long address,
struct page *page)
{
if (unlikely(PagePrivate(page))) {
long rc = vma_needs_reservation(h, vma, address);
if (unlikely(rc < 0)) {
/*
* Rare out of memory condition in reserve map
* manipulation. Clear PagePrivate so that
* global reserve count will not be incremented
* by free_huge_page. This will make it appear
* as though the reservation for this page was
* consumed. This may prevent the task from
* faulting in the page at a later time. This
* is better than inconsistent global huge page
* accounting of reserve counts.
*/
ClearPagePrivate(page);
} else if (rc) {
rc = vma_add_reservation(h, vma, address);
if (unlikely(rc < 0))
/*
* See above comment about rare out of
* memory condition.
*/
ClearPagePrivate(page);
} else
vma_end_reservation(h, vma, address);
}
}
Commit Message: userfaultfd: hugetlbfs: prevent UFFDIO_COPY to fill beyond the end of i_size
This oops:
kernel BUG at fs/hugetlbfs/inode.c:484!
RIP: remove_inode_hugepages+0x3d0/0x410
Call Trace:
hugetlbfs_setattr+0xd9/0x130
notify_change+0x292/0x410
do_truncate+0x65/0xa0
do_sys_ftruncate.constprop.3+0x11a/0x180
SyS_ftruncate+0xe/0x10
tracesys+0xd9/0xde
was caused by the lack of i_size check in hugetlb_mcopy_atomic_pte.
mmap() can still succeed beyond the end of the i_size after vmtruncate
zapped vmas in those ranges, but the faults must not succeed, and that
includes UFFDIO_COPY.
We could differentiate the retval to userland to represent a SIGBUS like
a page fault would do (vs SIGSEGV), but it doesn't seem very useful and
we'd need to pick a random retval as there's no meaningful syscall
retval that would differentiate from SIGSEGV and SIGBUS, there's just
-EFAULT.
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Andrea Arcangeli <[email protected]>
Reviewed-by: Mike Kravetz <[email protected]>
Cc: Mike Rapoport <[email protected]>
Cc: "Dr. David Alan Gilbert" <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[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 perf_event_output(struct perf_event *event, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct perf_output_handle handle;
struct perf_event_header header;
/* protect the callchain buffers */
rcu_read_lock();
perf_prepare_sample(&header, data, event, regs);
if (perf_output_begin(&handle, event, header.size, nmi, 1))
goto exit;
perf_output_sample(&handle, &header, data, event);
perf_output_end(&handle);
exit:
rcu_read_unlock();
}
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
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: PHP_FUNCTION(mcrypt_decrypt)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_string_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Target: 1
Example 2:
Code: find_initrd (void)
{
#ifdef CONFIG_BLK_DEV_INITRD
if (ia64_boot_param->initrd_start) {
initrd_start = (unsigned long)__va(ia64_boot_param->initrd_start);
initrd_end = initrd_start+ia64_boot_param->initrd_size;
printk(KERN_INFO "Initial ramdisk at: 0x%lx (%lu bytes)\n",
initrd_start, ia64_boot_param->initrd_size);
}
#endif
}
Commit Message: [IA64] Workaround for RSE issue
Problem: An application violating the architectural rules regarding
operation dependencies and having specific Register Stack Engine (RSE)
state at the time of the violation, may result in an illegal operation
fault and invalid RSE state. Such faults may initiate a cascade of
repeated illegal operation faults within OS interruption handlers.
The specific behavior is OS dependent.
Implication: An application causing an illegal operation fault with
specific RSE state may result in a series of illegal operation faults
and an eventual OS stack overflow condition.
Workaround: OS interruption handlers that switch to kernel backing
store implement a check for invalid RSE state to avoid the series
of illegal operation faults.
The core of the workaround is the RSE_WORKAROUND code sequence
inserted into each invocation of the SAVE_MIN_WITH_COVER and
SAVE_MIN_WITH_COVER_R19 macros. This sequence includes hard-coded
constants that depend on the number of stacked physical registers
being 96. The rest of this patch consists of code to disable this
workaround should this not be the case (with the presumption that
if a future Itanium processor increases the number of registers, it
would also remove the need for this patch).
Move the start of the RBS up to a mod32 boundary to avoid some
corner cases.
The dispatch_illegal_op_fault code outgrew the spot it was
squatting in when built with this patch and CONFIG_VIRT_CPU_ACCOUNTING=y
Move it out to the end of the ivt.
Signed-off-by: Tony Luck <[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: scoped_refptr<const SharedBuffer> ImageResource::ResourceBuffer() const {
if (Data())
return Data();
return GetContent()->ResourceBuffer();
}
Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin
Partial revert of https://chromium-review.googlesource.com/535694.
Bug: 799477
Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3
Reviewed-on: https://chromium-review.googlesource.com/898427
Commit-Queue: Hiroshige Hayashizaki <[email protected]>
Reviewed-by: Kouhei Ueno <[email protected]>
Reviewed-by: Yutaka Hirano <[email protected]>
Reviewed-by: Takeshi Yoshino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#535176}
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: JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
base::android::InitVM(vm);
if (!content::android::OnJNIOnLoadInit())
return -1;
content::SetContentMainDelegate(new content::ShellMainDelegate());
return JNI_VERSION_1_4;
}
Commit Message: Fix content_shell with network service enabled not loading pages.
This regressed in my earlier cl r528763.
This is a reland of r547221.
Bug: 833612
Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b
Reviewed-on: https://chromium-review.googlesource.com/1064702
Reviewed-by: Jay Civelli <[email protected]>
Commit-Queue: John Abd-El-Malek <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560011}
CWE ID: CWE-264
Target: 1
Example 2:
Code: cached_NPN_GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount, NPIdentifier *identifiers)
{
/* XXX: could be optimized further */
invoke_NPN_GetStringIdentifiers(names, nameCount, identifiers);
#if USE_NPIDENTIFIER_CACHE
if (use_npidentifier_cache()) {
for (int i = 0; i < nameCount; i++) {
NPIdentifier ident = identifiers[i];
if (npidentifier_cache_lookup(ident) == NULL) {
npidentifier_cache_reserve(1);
npidentifier_cache_add_string(ident, names[i]);
}
}
}
#endif
}
Commit Message: Support all the new variables added
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 int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union {
struct tpacket_hdr *h1;
struct tpacket2_hdr *h2;
void *raw;
} h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_LOSING|TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timeval tv;
struct timespec ts;
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
macoff = netoff - maclen;
}
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) + skb->truesize <
(unsigned)sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_frame(po, &po->rx_ring, TP_STATUS_KERNEL);
if (!h.raw)
goto ring_is_full;
packet_increment_head(&po->rx_ring);
po->stats.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
if (!po->stats.tp_drops)
status &= ~TP_STATUS_LOSING;
spin_unlock(&sk->sk_receive_queue.lock);
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
&& shhwtstamps->syststamp.tv64)
tv = ktime_to_timeval(shhwtstamps->syststamp);
else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
&& shhwtstamps->hwtstamp.tv64)
tv = ktime_to_timeval(shhwtstamps->hwtstamp);
else if (skb->tstamp.tv64)
tv = ktime_to_timeval(skb->tstamp);
else
do_gettimeofday(&tv);
h.h1->tp_sec = tv.tv_sec;
h.h1->tp_usec = tv.tv_usec;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
&& shhwtstamps->syststamp.tv64)
ts = ktime_to_timespec(shhwtstamps->syststamp);
else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
&& shhwtstamps->hwtstamp.tv64)
ts = ktime_to_timespec(shhwtstamps->hwtstamp);
else if (skb->tstamp.tv64)
ts = ktime_to_timespec(skb->tstamp);
else
getnstimeofday(&ts);
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (vlan_tx_tag_present(skb)) {
h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
status |= TP_STATUS_VLAN_VALID;
} else {
h.h2->tp_vlan_tci = 0;
}
hdrlen = sizeof(*h.h2);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
__packet_set_status(po, h.raw, status);
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
{
u8 *start, *end;
end = (u8 *)PAGE_ALIGN((unsigned long)h.raw + macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
#endif
sk->sk_data_ready(sk, 0);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
kfree_skb(skb);
return 0;
ring_is_full:
po->stats.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk, 0);
kfree_skb(copy_skb);
goto drop_n_restore;
}
Commit Message: af_packet: prevent information leak
In 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace)
added a small information leak.
Add padding field and make sure its zeroed before copy to user.
Signed-off-by: Eric Dumazet <[email protected]>
CC: Patrick McHardy <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
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: bool AXNodeObject::isChecked() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLInputElement(*node))
return toHTMLInputElement(*node).shouldAppearChecked();
switch (ariaRoleAttribute()) {
case CheckBoxRole:
case MenuItemCheckBoxRole:
case MenuItemRadioRole:
case RadioButtonRole:
case SwitchRole:
if (equalIgnoringCase(
getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked),
"true"))
return true;
return false;
default:
break;
}
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static int ioapic_service(struct kvm_ioapic *ioapic, int irq, bool line_status)
{
union kvm_ioapic_redirect_entry *entry = &ioapic->redirtbl[irq];
struct kvm_lapic_irq irqe;
int ret;
if (entry->fields.mask)
return -1;
ioapic_debug("dest=%x dest_mode=%x delivery_mode=%x "
"vector=%x trig_mode=%x\n",
entry->fields.dest_id, entry->fields.dest_mode,
entry->fields.delivery_mode, entry->fields.vector,
entry->fields.trig_mode);
irqe.dest_id = entry->fields.dest_id;
irqe.vector = entry->fields.vector;
irqe.dest_mode = entry->fields.dest_mode;
irqe.trig_mode = entry->fields.trig_mode;
irqe.delivery_mode = entry->fields.delivery_mode << 8;
irqe.level = 1;
irqe.shorthand = 0;
irqe.msi_redir_hint = false;
if (irqe.trig_mode == IOAPIC_EDGE_TRIG)
ioapic->irr_delivered |= 1 << irq;
if (irq == RTC_GSI && line_status) {
/*
* pending_eoi cannot ever become negative (see
* rtc_status_pending_eoi_check_valid) and the caller
* ensures that it is only called if it is >= zero, namely
* if rtc_irq_check_coalesced returns false).
*/
BUG_ON(ioapic->rtc_status.pending_eoi != 0);
ret = kvm_irq_delivery_to_apic(ioapic->kvm, NULL, &irqe,
&ioapic->rtc_status.dest_map);
ioapic->rtc_status.pending_eoi = (ret < 0 ? 0 : ret);
} else
ret = kvm_irq_delivery_to_apic(ioapic->kvm, NULL, &irqe, NULL);
if (ret && irqe.trig_mode == IOAPIC_LEVEL_TRIG)
entry->fields.remote_irr = 1;
return ret;
}
Commit Message: KVM: x86: fix out-of-bounds accesses of rtc_eoi map
KVM was using arrays of size KVM_MAX_VCPUS with vcpu_id, but ID can be
bigger that the maximal number of VCPUs, resulting in out-of-bounds
access.
Found by syzkaller:
BUG: KASAN: slab-out-of-bounds in __apic_accept_irq+0xb33/0xb50 at addr [...]
Write of size 1 by task a.out/27101
CPU: 1 PID: 27101 Comm: a.out Not tainted 4.9.0-rc5+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
[...]
Call Trace:
[...] __apic_accept_irq+0xb33/0xb50 arch/x86/kvm/lapic.c:905
[...] kvm_apic_set_irq+0x10e/0x180 arch/x86/kvm/lapic.c:495
[...] kvm_irq_delivery_to_apic+0x732/0xc10 arch/x86/kvm/irq_comm.c:86
[...] ioapic_service+0x41d/0x760 arch/x86/kvm/ioapic.c:360
[...] ioapic_set_irq+0x275/0x6c0 arch/x86/kvm/ioapic.c:222
[...] kvm_ioapic_inject_all arch/x86/kvm/ioapic.c:235
[...] kvm_set_ioapic+0x223/0x310 arch/x86/kvm/ioapic.c:670
[...] kvm_vm_ioctl_set_irqchip arch/x86/kvm/x86.c:3668
[...] kvm_arch_vm_ioctl+0x1a08/0x23c0 arch/x86/kvm/x86.c:3999
[...] kvm_vm_ioctl+0x1fa/0x1a70 arch/x86/kvm/../../../virt/kvm/kvm_main.c:3099
Reported-by: Dmitry Vyukov <[email protected]>
Cc: [email protected]
Fixes: af1bae5497b9 ("KVM: x86: bump KVM_MAX_VCPU_ID to 1023")
Reviewed-by: Paolo Bonzini <[email protected]>
Reviewed-by: David Hildenbrand <[email protected]>
Signed-off-by: Radim Krčmář <[email protected]>
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: static void registerBlobURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->blobData.release());
}
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:
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 EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod6(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
DOMStringList* listArg(toDOMStringList(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->overloadedMethod(listArg);
return JSValue::encode(jsUndefined());
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 1
Example 2:
Code: void WebContentsImpl::NotifyNavigationEntryCommitted(
const LoadCommittedDetails& load_details) {
FOR_EACH_OBSERVER(
WebContentsObserver, observers_, NavigationEntryCommitted(load_details));
}
Commit Message: Cancel JavaScript dialogs when an interstitial appears.
BUG=295695
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/24360011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
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_pre_notify(int options, const char *op, xmlNode * existing, xmlNode * update)
{
xmlNode *update_msg = NULL;
const char *type = NULL;
const char *id = NULL;
gboolean needed = FALSE;
g_hash_table_foreach(client_list, need_pre_notify, &needed);
if (needed == FALSE) {
return;
}
/* TODO: consider pre-notification for removal */
update_msg = create_xml_node(NULL, "pre-notify");
if (update != NULL) {
id = crm_element_value(update, XML_ATTR_ID);
}
crm_xml_add(update_msg, F_TYPE, T_CIB_NOTIFY);
crm_xml_add(update_msg, F_SUBTYPE, T_CIB_PRE_NOTIFY);
crm_xml_add(update_msg, F_CIB_OPERATION, op);
if (id != NULL) {
crm_xml_add(update_msg, F_CIB_OBJID, id);
}
if (update != NULL) {
crm_xml_add(update_msg, F_CIB_OBJTYPE, crm_element_name(update));
} else if (existing != NULL) {
crm_xml_add(update_msg, F_CIB_OBJTYPE, crm_element_name(existing));
}
type = crm_element_value(update_msg, F_CIB_OBJTYPE);
attach_cib_generation(update_msg, "cib_generation", the_cib);
if (existing != NULL) {
add_message_xml(update_msg, F_CIB_EXISTING, existing);
}
if (update != NULL) {
add_message_xml(update_msg, F_CIB_UPDATE, update);
}
g_hash_table_foreach_remove(client_list, cib_notify_client, update_msg);
if (update == NULL) {
crm_trace("Performing operation %s (on section=%s)", op, type);
} else {
crm_trace("Performing %s on <%s%s%s>", op, type, id ? " id=" : "", id ? id : "");
}
free_xml(update_msg);
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
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: static void copyStereo24(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
*dst++ = src[1][i] >> 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119
Target: 1
Example 2:
Code: void fuse_request_send_background(struct fuse_conn *fc, struct fuse_req *req)
{
req->isreply = 1;
fuse_request_send_nowait(fc, req);
}
Commit Message: fuse: check size of FUSE_NOTIFY_INVAL_ENTRY message
FUSE_NOTIFY_INVAL_ENTRY didn't check the length of the write so the
message processing could overrun and result in a "kernel BUG at
fs/fuse/dev.c:629!"
Reported-by: Han-Wen Nienhuys <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
CC: [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 GpuCommandBufferStub::OnSignalSyncPointAck(uint32 id) {
Send(new GpuCommandBufferMsg_SignalSyncPointAck(route_id_, id));
}
Commit Message: Sizes going across an IPC should be uint32.
BUG=164946
Review URL: https://chromiumcodereview.appspot.com/11472038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 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 ssize_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate)
{
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(image);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if (next_image->storage_class != PseudoClass)
{
if (IsGrayImage(next_image,&next_image->exception) == MagickFalse)
channels=next_image->colorspace == CMYKColorspace ? 4 : 3;
if (next_image->matte != MagickFalse)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if (next_image->storage_class == PseudoClass)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsGrayImage(next_image,&next_image->exception) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateImage(next_image,MagickFalse);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->matte != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateImage(next_image,MagickFalse);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
&image->exception);
if (mask != (Image *) NULL)
{
if (mask->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/350
CWE ID: CWE-787
Target: 1
Example 2:
Code: void __exit bnep_sock_cleanup(void)
{
if (bt_sock_unregister(BTPROTO_BNEP) < 0)
BT_ERR("Can't unregister BNEP socket");
proto_unregister(&bnep_proto);
}
Commit Message: Bluetooth: bnep: fix buffer overflow
Struct ca is copied from userspace. It is not checked whether the "device"
field is NULL terminated. This potentially leads to BUG() inside of
alloc_netdev_mqs() and/or information leak by creating a device with a name
made of contents of kernel stack.
Signed-off-by: Vasiliy Kulikov <[email protected]>
Signed-off-by: Gustavo F. Padovan <[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: static int cqspi_of_get_pdata(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct cqspi_st *cqspi = platform_get_drvdata(pdev);
cqspi->is_decoded_cs = of_property_read_bool(np, "cdns,is-decoded-cs");
if (of_property_read_u32(np, "cdns,fifo-depth", &cqspi->fifo_depth)) {
dev_err(&pdev->dev, "couldn't determine fifo-depth\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,fifo-width", &cqspi->fifo_width)) {
dev_err(&pdev->dev, "couldn't determine fifo-width\n");
return -ENXIO;
}
if (of_property_read_u32(np, "cdns,trigger-address",
&cqspi->trigger_address)) {
dev_err(&pdev->dev, "couldn't determine trigger-address\n");
return -ENXIO;
}
return 0;
}
Commit Message: mtd: spi-nor: Off by one in cqspi_setup_flash()
There are CQSPI_MAX_CHIPSELECT elements in the ->f_pdata array so the >
should be >=.
Fixes: 140623410536 ('mtd: spi-nor: Add driver for Cadence Quad SPI Flash Controller')
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: Marek Vasut <[email protected]>
Signed-off-by: Cyrille Pitchen <[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: ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
Commit Message: ...
CWE ID: CWE-20
Target: 1
Example 2:
Code: static ut64 num_callback(RNum *user, const char *name, int *ok) {
RFlag *f = (RFlag*)user;
RFlagItem *item;
if (ok) {
*ok = 0;
}
item = ht_find (f->ht_name, name, NULL);
if (item) {
if (item->alias) {
return 0LL;
}
if (ok) {
*ok = 1;
}
return item->offset;
}
return 0LL;
}
Commit Message: Fix crash in wasm disassembler
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: WebsiteSettings::WebsiteSettings(
WebsiteSettingsUI* ui,
Profile* profile,
TabSpecificContentSettings* tab_specific_content_settings,
InfoBarService* infobar_service,
const GURL& url,
const content::SSLStatus& ssl,
content::CertStore* cert_store)
: TabSpecificContentSettings::SiteDataObserver(
tab_specific_content_settings),
ui_(ui),
infobar_service_(infobar_service),
show_info_bar_(false),
site_url_(url),
site_identity_status_(SITE_IDENTITY_STATUS_UNKNOWN),
cert_id_(0),
site_connection_status_(SITE_CONNECTION_STATUS_UNKNOWN),
cert_store_(cert_store),
content_settings_(profile->GetHostContentSettingsMap()),
chrome_ssl_host_state_delegate_(
ChromeSSLHostStateDelegateFactory::GetForProfile(profile)),
did_revoke_user_ssl_decisions_(false) {
Init(profile, url, ssl);
PresentSitePermissions();
PresentSiteData();
PresentSiteIdentity();
RecordWebsiteSettingsAction(WEBSITE_SETTINGS_OPENED);
}
Commit Message: Fix UAF in Origin Info Bubble and permission settings UI.
In addition to fixing the UAF, will this also fix the problem of the bubble
showing over the previous tab (if the bubble is open when the tab it was opened
for closes).
BUG=490492
TBR=tedchoc
Review URL: https://codereview.chromium.org/1317443002
Cr-Commit-Position: refs/heads/master@{#346023}
CWE ID:
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 put_prev_task(struct rq *rq, struct task_struct *prev)
{
if (prev->se.on_rq)
update_rq_clock(rq);
rq->skip_clock_update = 0;
prev->sched_class->put_prev_task(rq, prev);
}
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: 1
Example 2:
Code: point_recv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
Point *point;
point = (Point *) palloc(sizeof(Point));
point->x = pq_getmsgfloat8(buf);
point->y = pq_getmsgfloat8(buf);
PG_RETURN_POINT_P(point);
}
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: 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: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)
{ psf->header [psf->headindex++] = (x >> 56) ;
psf->header [psf->headindex++] = (x >> 48) ;
psf->header [psf->headindex++] = (x >> 40) ;
psf->header [psf->headindex++] = (x >> 32) ;
psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_be_8byte */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
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 WorkerProcessLauncher::Core::StopWorker() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
if (launch_success_timer_->IsRunning()) {
launch_success_timer_->Stop();
launch_backoff_.InformOfRequest(false);
}
self_ = this;
ipc_enabled_ = false;
if (process_watcher_.GetWatchedObject() != NULL) {
launcher_delegate_->KillProcess(CONTROL_C_EXIT);
return;
}
DCHECK(process_watcher_.GetWatchedObject() == NULL);
ipc_error_timer_->Stop();
process_exit_event_.Close();
if (stopping_) {
ipc_error_timer_.reset();
launch_timer_.reset();
self_ = NULL;
return;
}
self_ = NULL;
DWORD exit_code = launcher_delegate_->GetExitCode();
if (kMinPermanentErrorExitCode <= exit_code &&
exit_code <= kMaxPermanentErrorExitCode) {
worker_delegate_->OnPermanentError();
return;
}
launch_timer_->Start(FROM_HERE, launch_backoff_.GetTimeUntilRelease(),
this, &Core::LaunchWorker);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: DownloadDangerType DownloadItemImpl::GetDangerType() const {
return danger_type_;
}
Commit Message: Downloads : Fixed an issue of opening incorrect download file
When one download overwrites another completed download, calling download.open in the old download causes the new download to open, which could be dangerous and undesirable. In this CL, we are trying to avoid this by blocking the opening of the old download.
Bug: 793620
Change-Id: Ic948175756700ad7c08489c3cc347330daedb6f8
Reviewed-on: https://chromium-review.googlesource.com/826477
Reviewed-by: David Trainor <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Commit-Queue: Shakti Sahu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#525810}
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: ikev2_TS_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
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 InputHandlerProxy::DispatchSingleInputEvent(
std::unique_ptr<EventWithCallback> event_with_callback,
const base::TimeTicks now) {
const ui::LatencyInfo& original_latency_info =
event_with_callback->latency_info();
ui::LatencyInfo monitored_latency_info = original_latency_info;
std::unique_ptr<cc::SwapPromiseMonitor> latency_info_swap_promise_monitor =
input_handler_->CreateLatencyInfoSwapPromiseMonitor(
&monitored_latency_info);
current_overscroll_params_.reset();
InputHandlerProxy::EventDisposition disposition = RouteToTypeSpecificHandler(
event_with_callback->event(), original_latency_info);
blink::WebGestureEvent::Type type = event_with_callback->event().GetType();
switch (type) {
case blink::WebGestureEvent::kGestureScrollBegin:
is_first_gesture_scroll_update_ = true;
FALLTHROUGH;
case blink::WebGestureEvent::kGesturePinchBegin:
case blink::WebGestureEvent::kGestureScrollUpdate:
case blink::WebGestureEvent::kGesturePinchUpdate:
has_ongoing_compositor_scroll_or_pinch_ = disposition == DID_HANDLE;
break;
case blink::WebGestureEvent::kGestureScrollEnd:
case blink::WebGestureEvent::kGesturePinchEnd:
has_ongoing_compositor_scroll_or_pinch_ = false;
break;
default:
break;
}
switch (type) {
case blink::WebGestureEvent::kGestureScrollBegin:
momentum_scroll_jank_tracker_ =
std::make_unique<MomentumScrollJankTracker>();
break;
case blink::WebGestureEvent::kGestureScrollUpdate:
if (momentum_scroll_jank_tracker_) {
momentum_scroll_jank_tracker_->OnDispatchedInputEvent(
event_with_callback.get(), now);
}
break;
case blink::WebGestureEvent::kGestureScrollEnd:
momentum_scroll_jank_tracker_.reset();
break;
default:
break;
}
event_with_callback->RunCallbacks(disposition, monitored_latency_info,
std::move(current_overscroll_params_));
}
Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures"
This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2.
Reason for revert:
Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the
culprit for flakes in the build cycles as shown on:
https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw
Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818
Sample Failed Step: content_browsertests on Ubuntu-16.04
Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency
Original change's description:
> Add explicit flag for compositor scrollbar injected gestures
>
> The original change to enable scrollbar latency for the composited
> scrollbars incorrectly used an existing member to try and determine
> whether a GestureScrollUpdate was the first one in an injected sequence
> or not. is_first_gesture_scroll_update_ was incorrect because it is only
> updated when input is actually dispatched to InputHandlerProxy, and the
> flag is cleared for all GSUs before the location where it was being
> read.
>
> This bug was missed because of incorrect tests. The
> VerifyRecordedSamplesForHistogram method doesn't actually assert or
> expect anything - the return value must be inspected.
>
> As part of fixing up the tests, I made a few other changes to get them
> passing consistently across all platforms:
> - turn on main thread scrollbar injection feature (in case it's ever
> turned off we don't want the tests to start failing)
> - enable mock scrollbars
> - disable smooth scrolling
> - don't run scrollbar tests on Android
>
> The composited scrollbar button test is disabled due to a bug in how
> the mock theme reports its button sizes, which throws off the region
> detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed
> crbug.com/974063 for this issue).
>
> Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950
>
> Bug: 954007
> Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741
> Commit-Queue: Daniel Libby <[email protected]>
> Reviewed-by: David Bokan <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#669086}
Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 954007
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114
Cr-Commit-Position: refs/heads/master@{#669150}
CWE ID: CWE-281
Target: 1
Example 2:
Code: bool AnyBitsSet(GLbitfield bits, GLbitfield ref) {
DCHECK_NE(0u, ref);
return ((bits & ref) != 0);
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
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: int am_check_url(request_rec *r, const char *url)
{
const char *i;
for (i = url; *i; i++) {
if (*i >= 0 && *i < ' ') {
/* Deny all control-characters. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,
"Control character detected in URL.");
return HTTP_BAD_REQUEST;
}
}
return OK;
}
Commit Message: Fix redirect URL validation bypass
It turns out that browsers silently convert backslash characters into
forward slashes, while apr_uri_parse() does not.
This mismatch allows an attacker to bypass the redirect URL validation
by using an URL like:
https://sp.example.org/mellon/logout?ReturnTo=https:%5c%5cmalicious.example.org/
mod_auth_mellon will assume that it is a relative URL and allow the
request to pass through, while the browsers will use it as an absolute
url and redirect to https://malicious.example.org/ .
This patch fixes this issue by rejecting all redirect URLs with
backslashes.
CWE ID: CWE-601
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 ixheaacd_esbr_postradixcompute2(WORD32 *ptr_y, WORD32 *ptr_x,
const WORD32 *pdig_rev_tbl,
WORD32 npoints) {
WORD32 i, k;
WORD32 h2;
WORD32 x_0, x_1, x_2, x_3;
WORD32 x_4, x_5, x_6, x_7;
WORD32 x_8, x_9, x_a, x_b, x_c, x_d, x_e, x_f;
WORD32 n00, n10, n20, n30, n01, n11, n21, n31;
WORD32 n02, n12, n22, n32, n03, n13, n23, n33;
WORD32 n0, j0;
WORD32 *x2, *x0;
WORD32 *y0, *y1, *y2, *y3;
y0 = ptr_y;
y2 = ptr_y + (WORD32)npoints;
x0 = ptr_x;
x2 = ptr_x + (WORD32)(npoints >> 1);
y1 = y0 + (WORD32)(npoints >> 2);
y3 = y2 + (WORD32)(npoints >> 2);
j0 = 8;
n0 = npoints >> 1;
for (k = 0; k < 2; k++) {
for (i = 0; i<npoints>> 1; i += 8) {
h2 = *pdig_rev_tbl++ >> 2;
x_0 = *x0++;
x_1 = *x0++;
x_2 = *x0++;
x_3 = *x0++;
x_4 = *x0++;
x_5 = *x0++;
x_6 = *x0++;
x_7 = *x0++;
n00 = x_0 + x_2;
n01 = x_1 + x_3;
n20 = x_0 - x_2;
n21 = x_1 - x_3;
n10 = x_4 + x_6;
n11 = x_5 + x_7;
n30 = x_4 - x_6;
n31 = x_5 - x_7;
y0[h2] = n00;
y0[h2 + 1] = n01;
y1[h2] = n10;
y1[h2 + 1] = n11;
y2[h2] = n20;
y2[h2 + 1] = n21;
y3[h2] = n30;
y3[h2 + 1] = n31;
x_8 = *x2++;
x_9 = *x2++;
x_a = *x2++;
x_b = *x2++;
x_c = *x2++;
x_d = *x2++;
x_e = *x2++;
x_f = *x2++;
n02 = x_8 + x_a;
n03 = x_9 + x_b;
n22 = x_8 - x_a;
n23 = x_9 - x_b;
n12 = x_c + x_e;
n13 = x_d + x_f;
n32 = x_c - x_e;
n33 = x_d - x_f;
y0[h2 + 2] = n02;
y0[h2 + 3] = n03;
y1[h2 + 2] = n12;
y1[h2 + 3] = n13;
y2[h2 + 2] = n22;
y2[h2 + 3] = n23;
y3[h2 + 2] = n32;
y3[h2 + 3] = n33;
}
x0 += (WORD32)npoints >> 1;
x2 += (WORD32)npoints >> 1;
}
}
Commit Message: Fix for stack corruption in esbr
Bug: 110769924
Test: poc from bug before/after
Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e
(cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a)
(cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50)
CWE ID: CWE-787
Target: 1
Example 2:
Code: static MagickBooleanType DecodeImage(Image *image,unsigned char *luma,
unsigned char *chroma1,unsigned char *chroma2)
{
#define IsSync(sum) ((sum & 0xffffff00UL) == 0xfffffe00UL)
#define PCDGetBits(n) \
{ \
sum=(sum << n) & 0xffffffff; \
bits-=n; \
while (bits <= 24) \
{ \
if (p >= (buffer+0x800)) \
{ \
count=ReadBlob(image,0x800,buffer); \
p=buffer; \
} \
sum|=((unsigned int) (*p) << (24-bits)); \
bits+=8; \
p++; \
} \
}
typedef struct PCDTable
{
unsigned int
length,
sequence;
MagickStatusType
mask;
unsigned char
key;
} PCDTable;
PCDTable
*pcd_table[3];
register ssize_t
i,
j;
register PCDTable
*r;
register unsigned char
*p,
*q;
size_t
bits,
length,
plane,
pcd_length[3],
row,
sum;
ssize_t
count,
quantum;
unsigned char
*buffer;
/*
Initialize Huffman tables.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(luma != (unsigned char *) NULL);
assert(chroma1 != (unsigned char *) NULL);
assert(chroma2 != (unsigned char *) NULL);
buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
sum=0;
bits=32;
p=buffer+0x800;
for (i=0; i < 3; i++)
{
pcd_table[i]=(PCDTable *) NULL;
pcd_length[i]=0;
}
for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
{
PCDGetBits(8);
length=(sum & 0xff)+1;
pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length,
sizeof(*pcd_table[i]));
if (pcd_table[i] == (PCDTable *) NULL)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
r=pcd_table[i];
for (j=0; j < (ssize_t) length; j++)
{
PCDGetBits(8);
r->length=(unsigned int) (sum & 0xff)+1;
if (r->length > 16)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
return(MagickFalse);
}
PCDGetBits(16);
r->sequence=(unsigned int) (sum & 0xffff) << 16;
PCDGetBits(8);
r->key=(unsigned char) (sum & 0xff);
r->mask=(~((1U << (32-r->length))-1));
r++;
}
pcd_length[i]=(size_t) length;
}
/*
Search for Sync byte.
*/
for (i=0; i < 1; i++)
PCDGetBits(16);
for (i=0; i < 1; i++)
PCDGetBits(16);
while ((sum & 0x00fff000UL) != 0x00fff000UL)
PCDGetBits(8);
while (IsSync(sum) == 0)
PCDGetBits(1);
/*
Recover the Huffman encoded luminance and chrominance deltas.
*/
count=0;
length=0;
plane=0;
row=0;
q=luma;
for ( ; ; )
{
if (IsSync(sum) != 0)
{
/*
Determine plane and row number.
*/
PCDGetBits(16);
row=((sum >> 9) & 0x1fff);
if (row == image->rows)
break;
PCDGetBits(8);
plane=sum >> 30;
PCDGetBits(16);
switch (plane)
{
case 0:
{
q=luma+row*image->columns;
count=(ssize_t) image->columns;
break;
}
case 2:
{
q=chroma1+(row >> 1)*image->columns;
count=(ssize_t) (image->columns >> 1);
plane--;
break;
}
case 3:
{
q=chroma2+(row >> 1)*image->columns;
count=(ssize_t) (image->columns >> 1);
plane--;
break;
}
default:
{
ThrowBinaryException(CorruptImageError,"CorruptImage",
image->filename);
}
}
length=pcd_length[plane];
continue;
}
/*
Decode luminance or chrominance deltas.
*/
r=pcd_table[plane];
for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++)
r++;
if ((row > image->rows) || (r == (PCDTable *) NULL))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename);
while ((sum & 0x00fff000) != 0x00fff000)
PCDGetBits(8);
while (IsSync(sum) == 0)
PCDGetBits(1);
continue;
}
if (r->key < 128)
quantum=(ssize_t) (*q)+r->key;
else
quantum=(ssize_t) (*q)+r->key-256;
*q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum);
q++;
PCDGetBits(r->length);
count--;
}
/*
Relinquish resources.
*/
for (i=0; i < (image->columns > 1536 ? 3 : 1); i++)
pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
return(MagickTrue);
}
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: bool ProfileSyncService::encryption_pending() const {
return encryption_pending_;
}
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: | 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_stream_pad(jas_stream_t *stream, int n, int c)
{
int m;
m = n;
for (m = n; m > 0; --m) {
if (jas_stream_putc(stream, c) == EOF)
return n - m;
}
return n;
}
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
Target: 1
Example 2:
Code: void BookmarkManagerView::PerformSearch() {
search_factory_.RevokeAll();
tree_view_->SetController(NULL);
tree_view_->SetSelectedNode(tree_model_->search_node());
tree_view_->SetController(this);
SetTableModel(CreateSearchTableModel(), NULL, true);
}
Commit Message: Relands cl 16982 as it wasn't the cause of the build breakage. Here's
the description for that cl:
Lands http://codereview.chromium.org/115505 for bug
http://crbug.com/4030 for tyoshino.
BUG=http://crbug.com/4030
TEST=make sure control-w dismisses bookmark manager.
Review URL: http://codereview.chromium.org/113902
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@16987 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 DocumentLoader::addAllArchiveResources(Archive* archive)
{
if (!m_archiveResourceCollection)
m_archiveResourceCollection = adoptPtr(new ArchiveResourceCollection);
ASSERT(archive);
if (!archive)
return;
m_archiveResourceCollection->addAllResources(archive);
}
Commit Message: Unreviewed, rolling out r147402.
http://trac.webkit.org/changeset/147402
https://bugs.webkit.org/show_bug.cgi?id=112903
Source/WebCore:
* dom/Document.cpp:
(WebCore::Document::processHttpEquiv):
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::responseReceived):
LayoutTests:
* http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html:
* http/tests/security/XFrameOptions/x-frame-options-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
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: acc_ctx_hints(OM_uint32 *minor_status,
gss_ctx_id_t *ctx,
spnego_gss_cred_id_t spcred,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 tmpmin, ret;
gss_OID_set supported_mechSet;
spnego_gss_ctx_id_t sc = NULL;
*mechListMIC = GSS_C_NO_BUFFER;
supported_mechSet = GSS_C_NO_OID_SET;
*return_token = NO_TOKEN_SEND;
*negState = REJECT;
*minor_status = 0;
/* A hint request must be the first token received. */
if (*ctx != GSS_C_NO_CONTEXT)
return GSS_S_DEFECTIVE_TOKEN;
ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT,
&supported_mechSet);
if (ret != GSS_S_COMPLETE)
goto cleanup;
ret = make_NegHints(minor_status, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
sc = create_spnego_ctx();
if (sc == NULL) {
ret = GSS_S_FAILURE;
goto cleanup;
}
if (put_mech_set(supported_mechSet, &sc->DER_mechTypes) < 0) {
ret = GSS_S_FAILURE;
goto cleanup;
}
sc->internal_mech = GSS_C_NO_OID;
*negState = ACCEPT_INCOMPLETE;
*return_token = INIT_TOKEN_SEND;
sc->firstpass = 1;
*ctx = (gss_ctx_id_t)sc;
sc = NULL;
ret = GSS_S_COMPLETE;
cleanup:
release_spnego_ctx(&sc);
gss_release_oid_set(&tmpmin, &supported_mechSet);
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: static int proc_pid_personality(struct seq_file *m, struct pid_namespace *ns,
struct pid *pid, struct task_struct *task)
{
seq_printf(m, "%08x\n", task->personality);
return 0;
}
Commit Message: fix autofs/afs/etc. magic mountpoint breakage
We end up trying to kfree() nd.last.name on open("/mnt/tmp", O_CREAT)
if /mnt/tmp is an autofs direct mount. The reason is that nd.last_type
is bogus here; we want LAST_BIND for everything of that kind and we
get LAST_NORM left over from finding parent directory.
So make sure that it *is* set properly; set to LAST_BIND before
doing ->follow_link() - for normal symlinks it will be changed
by __vfs_follow_link() and everything else needs it set that way.
Signed-off-by: Al Viro <[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: static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
{
int i;
int interlaced;
int cid;
int display_width = track->par->width;
if (track->vos_data && track->vos_len > 0x29) {
if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
/* looks like a DNxHD bit stream */
interlaced = (track->vos_data[5] & 2);
cid = AV_RB32(track->vos_data + 0x28);
} else {
av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
return 0;
}
} else {
av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
return 0;
}
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "ACLR");
ffio_wfourcc(pb, "ACLR");
ffio_wfourcc(pb, "0001");
if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
} else { /* Full range (0-255) */
avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
}
avio_wb32(pb, 0); /* unknown */
if (track->tag == MKTAG('A','V','d','h')) {
avio_wb32(pb, 32);
ffio_wfourcc(pb, "ADHR");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, cid);
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 0); /* unknown */
return 0;
}
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "APRG");
ffio_wfourcc(pb, "APRG");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 120); /* size */
ffio_wfourcc(pb, "ARES");
ffio_wfourcc(pb, "ARES");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, cid); /* dnxhd cid, some id ? */
if ( track->par->sample_aspect_ratio.num > 0
&& track->par->sample_aspect_ratio.den > 0)
display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
avio_wb32(pb, display_width);
/* values below are based on samples created with quicktime and avid codecs */
if (interlaced) {
avio_wb32(pb, track->par->height / 2);
avio_wb32(pb, 2); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 4); /* unknown */
} else {
avio_wb32(pb, track->par->height);
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
if (track->par->height == 1080)
avio_wb32(pb, 5); /* unknown */
else
avio_wb32(pb, 6); /* unknown */
}
/* padding */
for (i = 0; i < 10; i++)
avio_wb64(pb, 0);
return 0;
}
Commit Message: avformat/movenc: Write version 2 of audio atom if channels is not known
The version 1 needs the channel count and would divide by 0
Fixes: division by 0
Fixes: fpe_movenc.c_1108_1.ogg
Fixes: fpe_movenc.c_1108_2.ogg
Fixes: fpe_movenc.c_1108_3.wav
Found-by: #CHEN HONGXU# <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-369
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: PHP_METHOD(Phar, addEmptyDir)
{
char *dirname;
size_t dirname_len;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &dirname, &dirname_len) == FAILURE) {
return;
}
if (dirname_len >= sizeof(".phar")-1 && !memcmp(dirname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot create a directory in magic \".phar\" directory");
return;
}
phar_mkdir(&phar_obj->archive, dirname, dirname_len);
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: void ChromeContentRendererClient::GetNavigationErrorStrings(
const WebKit::WebURLRequest& failed_request,
const WebKit::WebURLError& error,
std::string* error_html,
string16* error_description) {
const GURL failed_url = error.unreachableURL;
const Extension* extension = NULL;
const bool is_repost =
error.reason == net::ERR_CACHE_MISS &&
error.domain == WebString::fromUTF8(net::kErrorDomain) &&
EqualsASCII(failed_request.httpMethod(), "POST");
if (failed_url.is_valid() && !failed_url.SchemeIs(chrome::kExtensionScheme)) {
extension = extension_dispatcher_->extensions()->GetExtensionOrAppByURL(
ExtensionURLInfo(failed_url));
}
if (error_html) {
int resource_id;
DictionaryValue error_strings;
if (extension && !extension->from_bookmark()) {
LocalizedError::GetAppErrorStrings(error, failed_url, extension,
&error_strings);
resource_id = IDR_ERROR_APP_HTML;
} else {
if (is_repost) {
LocalizedError::GetFormRepostStrings(failed_url, &error_strings);
} else {
LocalizedError::GetStrings(error, &error_strings);
}
resource_id = IDR_NET_ERROR_HTML;
}
const base::StringPiece template_html(
ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id));
if (template_html.empty()) {
NOTREACHED() << "unable to load template. ID: " << resource_id;
} else {
*error_html = jstemplate_builder::GetTemplatesHtml(
template_html, &error_strings, "t");
}
}
if (error_description) {
if (!extension && !is_repost)
*error_description = LocalizedError::GetErrorDetails(error);
}
}
Commit Message: Do not require DevTools extension resources to be white-listed in manifest.
Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is
(a) trusted and
(b) picky on the frames it loads.
This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check.
BUG=none
TEST=DevToolsExtensionTest.*
Review URL: https://chromiumcodereview.appspot.com/9663076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 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: static int l2cap_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sock %p, sk %p", sock, sk);
err = sock_error(sk);
if (err)
return err;
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/* Check outgoing MTU */
if (sk->sk_type != SOCK_RAW && len > l2cap_pi(sk)->omtu)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state == BT_CONNECTED)
err = l2cap_do_send(sk, msg, len);
else
err = -ENOTCONN;
release_sock(sk);
return err;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[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: void RilSapSocket::sendResponse(MsgHeader* hdr) {
size_t encoded_size = 0;
uint32_t written_size;
size_t buffer_size = 0;
pb_ostream_t ostream;
bool success = false;
pthread_mutex_lock(&write_lock);
if ((success = pb_get_encoded_size(&encoded_size, MsgHeader_fields,
hdr)) && encoded_size <= INT32_MAX && commandFd != -1) {
buffer_size = encoded_size + sizeof(uint32_t);
uint8_t buffer[buffer_size];
written_size = htonl((uint32_t) encoded_size);
ostream = pb_ostream_from_buffer(buffer, buffer_size);
pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size));
success = pb_encode(&ostream, MsgHeader_fields, hdr);
if (success) {
RLOGD("Size: %d (0x%x) Size as written: 0x%x", encoded_size, encoded_size,
written_size);
log_hex("onRequestComplete", &buffer[sizeof(written_size)], encoded_size);
RLOGI("[%d] < SAP RESPONSE type: %d. id: %d. error: %d",
hdr->token, hdr->type, hdr->id,hdr->error );
if ( 0 != blockingWrite_helper(commandFd, buffer, buffer_size)) {
RLOGE("Error %d while writing to fd", errno);
} else {
RLOGD("Write successful");
}
} else {
RLOGE("Error while encoding response of type %d id %d buffer_size: %d: %s.",
hdr->type, hdr->id, buffer_size, PB_GET_ERROR(&ostream));
}
} else {
RLOGE("Not sending response type %d: encoded_size: %u. commandFd: %d. encoded size result: %d",
hdr->type, encoded_size, commandFd, success);
}
pthread_mutex_unlock(&write_lock);
}
Commit Message: Replace variable-length arrays on stack with malloc.
Bug: 30202619
Change-Id: Ib95e08a1c009d88a4b4fd8d8fdba0641c6129008
(cherry picked from commit 943905bb9f99e3caa856b42c531e2be752da8834)
CWE ID: CWE-264
Target: 1
Example 2:
Code: new_msg_register_opaque_type (u_int32_t seqnum, u_char ltype, u_char otype)
{
struct msg_register_opaque_type rmsg;
rmsg.lsatype = ltype;
rmsg.opaquetype = otype;
memset (&rmsg.pad, 0, sizeof (rmsg.pad));
return msg_new (MSG_REGISTER_OPAQUETYPE, &rmsg, seqnum,
sizeof (struct msg_register_opaque_type));
}
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 PassOwnPtr<CCThreadProxyScrollControllerAdapter> create(CCThreadProxy* proxy)
{
return adoptPtr(new CCThreadProxyScrollControllerAdapter(proxy));
}
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
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 FrameworkListener::init(const char *socketName UNUSED, bool withSeq) {
mCommands = new FrameworkCommandCollection();
errorRate = 0;
mCommandCount = 0;
mWithSeq = withSeq;
}
Commit Message: Fix vold vulnerability in FrameworkListener
Modify FrameworkListener to ignore commands that exceed the maximum
buffer length and send an error message.
Bug: 29831647
Change-Id: I9e57d1648d55af2ca0191bb47868e375ecc26950
Signed-off-by: Connor O'Brien <[email protected]>
(cherry picked from commit baa126dc158a40bc83c17c6d428c760e5b93fb1a)
(cherry picked from commit 470484d2a25ad432190a01d1c763b4b36db33c7e)
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int csnmp_read_host(user_data_t *ud) {
host_definition_t *host;
int status;
int success;
int i;
host = ud->data;
if (host->interval == 0)
host->interval = plugin_get_interval();
if (host->sess_handle == NULL)
csnmp_host_open_session(host);
if (host->sess_handle == NULL)
return (-1);
success = 0;
for (i = 0; i < host->data_list_len; i++) {
data_definition_t *data = host->data_list[i];
if (data->is_table)
status = csnmp_read_table(host, data);
else
status = csnmp_read_value(host, data);
if (status == 0)
success++;
}
if (success == 0)
return (-1);
return (0);
} /* int csnmp_read_host */
Commit Message: snmp plugin: Fix double free of request PDU
snmp_sess_synch_response() always frees request PDU, in both case of request
error and success. If error condition occurs inside of `while (status == 0)`
loop, double free of `req` happens.
Issue: #2291
Signed-off-by: Florian Forster <[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 tee_mmu_set_ctx(struct tee_ta_ctx *ctx)
{
struct thread_specific_data *tsd = thread_get_tsd();
core_mmu_set_user_map(NULL);
/*
* No matter what happens below, the current user TA will not be
* current any longer. Make sure pager is in sync with that.
* This function has to be called before there's a chance that
* pgt_free_unlocked() is called.
*
* Save translation tables in a cache if it's a user TA.
*/
pgt_free(&tsd->pgt_cache, tsd->ctx && is_user_ta_ctx(tsd->ctx));
if (ctx && is_user_ta_ctx(ctx)) {
struct core_mmu_user_map map;
struct user_ta_ctx *utc = to_user_ta_ctx(ctx);
core_mmu_create_user_map(utc, &map);
core_mmu_set_user_map(&map);
tee_pager_assign_uta_tables(utc);
}
tsd->ctx = ctx;
}
Commit Message: core: tee_mmu_check_access_rights() check all pages
Prior to this patch tee_mmu_check_access_rights() checks an address in
each page of a supplied range. If both the start and length of that
range is unaligned the last page in the range is sometimes not checked.
With this patch the first address of each page in the range is checked
to simplify the logic of checking each page and the range and also to
cover the last page under all circumstances.
Fixes: OP-TEE-2018-0005: "tee_mmu_check_access_rights does not check
final page of TA buffer"
Signed-off-by: Jens Wiklander <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Reviewed-by: Joakim Bech <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[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: ext4_xattr_create_cache(char *name)
{
return mb_cache_create(name, HASH_BUCKET_BITS);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19
Target: 1
Example 2:
Code: static void nfs4_close_done(struct rpc_task *task, void *data)
{
struct nfs4_closedata *calldata = data;
struct nfs4_state *state = calldata->state;
struct nfs_server *server = NFS_SERVER(calldata->inode);
if (!nfs4_sequence_done(task, &calldata->res.seq_res))
return;
/* hmm. we are done with the inode, and in the process of freeing
* the state_owner. we keep this around to process errors
*/
switch (task->tk_status) {
case 0:
if (calldata->roc)
pnfs_roc_set_barrier(state->inode,
calldata->roc_barrier);
nfs_set_open_stateid(state, &calldata->res.stateid, 0);
renew_lease(server, calldata->timestamp);
nfs4_close_clear_stateid_flags(state,
calldata->arg.fmode);
break;
case -NFS4ERR_STALE_STATEID:
case -NFS4ERR_OLD_STATEID:
case -NFS4ERR_BAD_STATEID:
case -NFS4ERR_EXPIRED:
if (calldata->arg.fmode == 0)
break;
default:
if (nfs4_async_handle_error(task, server, state) == -EAGAIN)
rpc_restart_call_prepare(task);
}
nfs_release_seqid(calldata->arg.seqid);
nfs_refresh_inode(calldata->inode, calldata->res.fattr);
}
Commit Message: NFSv4: include bitmap in nfsv4 get acl data
The NFSv4 bitmap size is unbounded: a server can return an arbitrary
sized bitmap in an FATTR4_WORD0_ACL request. Replace using the
nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server
with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data
xdr length to the (cached) acl page data.
This is a general solution to commit e5012d1f "NFSv4.1: update
nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead
when getting ACLs.
Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr
was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved.
Cc: [email protected]
Signed-off-by: Andy Adamson <[email protected]>
Signed-off-by: Trond Myklebust <[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: int print_filename(char *pathname, struct inode *inode)
{
char str[11], dummy[12], dummy2[12]; /* overflow safe */
char *userstr, *groupstr;
int padchars;
struct passwd *user;
struct group *group;
struct tm *t;
if(short_ls) {
printf("%s\n", pathname);
return 1;
}
user = getpwuid(inode->uid);
if(user == NULL) {
int res = snprintf(dummy, 12, "%d", inode->uid);
if(res < 0)
EXIT_UNSQUASH("snprintf failed in print_filename()\n");
else if(res >= 12)
/* unsigned int shouldn't ever need more than 11 bytes
* (including terminating '\0') to print in base 10 */
userstr = "*";
else
userstr = dummy;
} else
userstr = user->pw_name;
group = getgrgid(inode->gid);
if(group == NULL) {
int res = snprintf(dummy2, 12, "%d", inode->gid);
if(res < 0)
EXIT_UNSQUASH("snprintf failed in print_filename()\n");
else if(res >= 12)
/* unsigned int shouldn't ever need more than 11 bytes
* (including terminating '\0') to print in base 10 */
groupstr = "*";
else
groupstr = dummy2;
} else
groupstr = group->gr_name;
printf("%s %s/%s ", modestr(str, inode->mode), userstr, groupstr);
switch(inode->mode & S_IFMT) {
case S_IFREG:
case S_IFDIR:
case S_IFSOCK:
case S_IFIFO:
case S_IFLNK:
padchars = TOTALCHARS - strlen(userstr) -
strlen(groupstr);
printf("%*lld ", padchars > 0 ? padchars : 0,
inode->data);
break;
case S_IFCHR:
case S_IFBLK:
padchars = TOTALCHARS - strlen(userstr) -
strlen(groupstr) - 7;
printf("%*s%3d,%3d ", padchars > 0 ? padchars : 0, " ",
(int) inode->data >> 8, (int) inode->data &
0xff);
break;
}
t = localtime(&inode->time);
printf("%d-%02d-%02d %02d:%02d %s", t->tm_year + 1900, t->tm_mon + 1,
t->tm_mday, t->tm_hour, t->tm_min, pathname);
if((inode->mode & S_IFMT) == S_IFLNK)
printf(" -> %s", inode->symlink);
printf("\n");
return 1;
}
Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <[email protected]>
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: int inet_sk_rebuild_header(struct sock *sk)
{
struct inet_sock *inet = inet_sk(sk);
struct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0);
__be32 daddr;
int err;
/* Route is OK, nothing to do. */
if (rt)
return 0;
/* Reroute. */
daddr = inet->inet_daddr;
if (inet->opt && inet->opt->srr)
daddr = inet->opt->faddr;
rt = ip_route_output_ports(sock_net(sk), sk, daddr, inet->inet_saddr,
inet->inet_dport, inet->inet_sport,
sk->sk_protocol, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if);
if (!IS_ERR(rt)) {
err = 0;
sk_setup_caps(sk, &rt->dst);
} else {
err = PTR_ERR(rt);
/* Routing failed... */
sk->sk_route_caps = 0;
/*
* Other protocols have to map its equivalent state to TCP_SYN_SENT.
* DCCP maps its DCCP_REQUESTING state to TCP_SYN_SENT. -acme
*/
if (!sysctl_ip_dynaddr ||
sk->sk_state != TCP_SYN_SENT ||
(sk->sk_userlocks & SOCK_BINDADDR_LOCK) ||
(err = inet_sk_reselect_saddr(sk)) != 0)
sk->sk_err_soft = -err;
}
return err;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int common_perm_mnt_dentry(int op, struct vfsmount *mnt,
struct dentry *dentry, u32 mask)
{
struct path path = { mnt, dentry };
struct path_cond cond = { dentry->d_inode->i_uid,
dentry->d_inode->i_mode
};
return common_perm(op, &path, mask, &cond);
}
Commit Message: AppArmor: fix oops in apparmor_setprocattr
When invalid parameters are passed to apparmor_setprocattr a NULL deref
oops occurs when it tries to record an audit message. This is because
it is passing NULL for the profile parameter for aa_audit. But aa_audit
now requires that the profile passed is not NULL.
Fix this by passing the current profile on the task that is trying to
setprocattr.
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: John Johansen <[email protected]>
Cc: [email protected]
Signed-off-by: James Morris <[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: static void validate_coredump_safety(void)
{
#ifdef CONFIG_COREDUMP
if (suid_dumpable == SUID_DUMP_ROOT &&
core_pattern[0] != '/' && core_pattern[0] != '|') {
printk(KERN_WARNING "Unsafe core_pattern used with "\
"suid_dumpable=2. Pipe handler or fully qualified "\
"core dump path required.\n");
}
#endif
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400
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 CorePageLoadMetricsObserver::RecordTimingHistograms(
const page_load_metrics::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& info) {
if (info.started_in_foreground && info.first_background_time) {
const base::TimeDelta first_background_time =
info.first_background_time.value();
if (!info.time_to_commit) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforeCommit,
first_background_time);
} else if (!timing.first_paint ||
timing.first_paint > first_background_time) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundBeforePaint,
first_background_time);
}
if (timing.parse_start && first_background_time >= timing.parse_start &&
(!timing.parse_stop || timing.parse_stop > first_background_time)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramBackgroundDuringParse,
first_background_time);
}
}
if (failed_provisional_load_info_.error != net::OK) {
DCHECK(failed_provisional_load_info_.interval);
if (WasStartedInForegroundOptionalEventInForeground(
failed_provisional_load_info_.interval, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFailedProvisionalLoad,
failed_provisional_load_info_.interval.value());
}
}
if (!info.time_to_commit || timing.IsEmpty())
return;
const base::TimeDelta time_to_commit = info.time_to_commit.value();
if (WasStartedInForegroundOptionalEventInForeground(info.time_to_commit,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramCommit, time_to_commit);
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramCommit, time_to_commit);
}
if (timing.dom_content_loaded_event_start) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.dom_content_loaded_event_start, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramDomContentLoaded,
timing.dom_content_loaded_event_start.value());
PAGE_LOAD_HISTOGRAM(internal::kHistogramDomLoadingToDomContentLoaded,
timing.dom_content_loaded_event_start.value() -
timing.dom_loading.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramDomContentLoaded,
timing.dom_content_loaded_event_start.value());
}
}
if (timing.load_event_start) {
if (WasStartedInForegroundOptionalEventInForeground(timing.load_event_start,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramLoad,
timing.load_event_start.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramLoad,
timing.load_event_start.value());
}
}
if (timing.first_layout) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_layout,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstLayout,
timing.first_layout.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstLayout,
timing.first_layout.value());
}
}
if (timing.first_paint) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_paint,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstPaint,
timing.first_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstPaint,
timing.first_paint.value());
}
if (!info.started_in_foreground && info.first_foreground_time &&
timing.first_paint > info.first_foreground_time.value() &&
(!info.first_background_time ||
timing.first_paint < info.first_background_time.value())) {
PAGE_LOAD_HISTOGRAM(
internal::kHistogramForegroundToFirstPaint,
timing.first_paint.value() - info.first_foreground_time.value());
}
}
if (timing.first_text_paint) {
if (WasStartedInForegroundOptionalEventInForeground(timing.first_text_paint,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstTextPaint,
timing.first_text_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstTextPaint,
timing.first_text_paint.value());
}
}
if (timing.first_image_paint) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.first_image_paint, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstImagePaint,
timing.first_image_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstImagePaint,
timing.first_image_paint.value());
}
}
if (timing.first_contentful_paint) {
if (WasStartedInForegroundOptionalEventInForeground(
timing.first_contentful_paint, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaint,
timing.first_contentful_paint.value());
if (base::TimeTicks::IsHighResolution()) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintHigh,
timing.first_contentful_paint.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstContentfulPaintLow,
timing.first_contentful_paint.value());
}
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseStartToFirstContentfulPaint,
timing.first_contentful_paint.value() - timing.parse_start.value());
PAGE_LOAD_HISTOGRAM(
internal::kHistogramDomLoadingToFirstContentfulPaint,
timing.first_contentful_paint.value() - timing.dom_loading.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramFirstContentfulPaint,
timing.first_contentful_paint.value());
}
}
if (timing.parse_start) {
if (WasParseInForeground(timing.parse_start, timing.parse_stop, info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramParseBlockedOnScriptLoad,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseBlockedOnScriptLoadDocumentWrite,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
} else {
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoad,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoadDocumentWrite,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
}
}
if (timing.parse_stop) {
base::TimeDelta parse_duration =
timing.parse_stop.value() - timing.parse_start.value();
if (WasStartedInForegroundOptionalEventInForeground(timing.parse_stop,
info)) {
PAGE_LOAD_HISTOGRAM(internal::kHistogramParseDuration, parse_duration);
PAGE_LOAD_HISTOGRAM(
internal::kHistogramParseBlockedOnScriptLoadParseComplete,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::
kHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
} else {
PAGE_LOAD_HISTOGRAM(internal::kBackgroundHistogramParseDuration,
parse_duration);
PAGE_LOAD_HISTOGRAM(
internal::kBackgroundHistogramParseBlockedOnScriptLoadParseComplete,
timing.parse_blocked_on_script_load_duration.value());
PAGE_LOAD_HISTOGRAM(
internal::
kBackgroundHistogramParseBlockedOnScriptLoadDocumentWriteParseComplete,
timing.parse_blocked_on_script_load_from_document_write_duration
.value());
}
}
if (info.started_in_foreground) {
if (info.first_background_time)
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstBackground,
info.first_background_time.value());
} else {
if (info.first_foreground_time)
PAGE_LOAD_HISTOGRAM(internal::kHistogramFirstForeground,
info.first_foreground_time.value());
}
}
Commit Message: Remove clock resolution page load histograms.
These were temporary metrics intended to understand whether high/low
resolution clocks adversely impact page load metrics. After collecting a few
months of data it was determined that clock resolution doesn't adversely
impact our metrics, and it that these histograms were no longer needed.
BUG=394757
Review-Url: https://codereview.chromium.org/2155143003
Cr-Commit-Position: refs/heads/master@{#406143}
CWE ID:
Target: 1
Example 2:
Code: vrrp_handle_bfd_event(bfd_event_t * evt)
{
vrrp_tracked_bfd_t *vbfd;
tracking_vrrp_t *tbfd;
vrrp_t * vrrp;
element e, e1;
struct timeval time_now;
struct timeval timer_tmp;
uint32_t delivery_time;
if (__test_bit(LOG_DETAIL_BIT, &debug)) {
time_now = timer_now();
timersub(&time_now, &evt->sent_time, &timer_tmp);
delivery_time = timer_long(timer_tmp);
log_message(LOG_INFO, "Received BFD event: instance %s is in"
" state %s (delivered in %i usec)",
evt->iname, BFD_STATE_STR(evt->state), delivery_time);
}
LIST_FOREACH(vrrp_data->vrrp_track_bfds, vbfd, e) {
if (strcmp(vbfd->bname, evt->iname))
continue;
if ((vbfd->bfd_up && evt->state == BFD_STATE_UP) ||
(!vbfd->bfd_up && evt->state == BFD_STATE_DOWN))
continue;
vbfd->bfd_up = (evt->state == BFD_STATE_UP);
LIST_FOREACH(vbfd->tracking_vrrp, tbfd, e1) {
vrrp = tbfd->vrrp;
log_message(LOG_INFO, "VRRP_Instance(%s) Tracked BFD"
" instance %s is %s", vrrp->iname, evt->iname, vbfd->bfd_up ? "UP" : "DOWN");
if (tbfd->weight) {
if (vbfd->bfd_up)
vrrp->total_priority += abs(tbfd->weight);
else
vrrp->total_priority -= abs(tbfd->weight);
vrrp_set_effective_priority(vrrp);
continue;
}
if (vbfd->bfd_up)
try_up_instance(vrrp, false);
else
down_instance(vrrp);
}
break;
}
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59
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 parse_external_jpeg()
{
const char *file, *ext;
char *jname, *jfile, *jext;
FILE *save=ifp;
ext = strrchr (ifname, '.');
file = strrchr (ifname, '/');
if (!file) file = strrchr (ifname, '\\');
if (!file) file = ifname-1;
file++;
if (!ext || strlen(ext) != 4 || ext-file != 8) return;
jname = (char *) malloc (strlen(ifname) + 1);
merror (jname, "parse_external_jpeg()");
strcpy (jname, ifname);
jfile = file - ifname + jname;
jext = ext - ifname + jname;
if (strcasecmp (ext, ".jpg")) {
strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg");
if (isdigit(*file)) {
memcpy (jfile, file+4, 4);
memcpy (jfile+4, file, 4);
}
} else
while (isdigit(*--jext)) {
if (*jext != '9') {
(*jext)++;
break;
}
*jext = '0';
}
if (strcmp (jname, ifname)) {
if ((ifp = fopen (jname, "rb"))) {
dcraw_message (DCRAW_VERBOSE,_("Reading metadata from %s ...\n"), jname);
parse_tiff (12);
thumb_offset = 0;
is_raw = 1;
fclose (ifp);
}
}
if (!timestamp)
dcraw_message (DCRAW_WARNING,_("Failed to read metadata from %s\n"), jname);
free (jname);
ifp = save;
}
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: eXosip_init (struct eXosip_t *excontext)
{
osip_t *osip;
int i;
memset (excontext, 0, sizeof (eXosip_t));
excontext->dscp = 0x1A;
snprintf (excontext->ipv4_for_gateway, 256, "%s", "217.12.3.11");
snprintf (excontext->ipv6_for_gateway, 256, "%s", "2001:638:500:101:2e0:81ff:fe24:37c6");
#ifdef WIN32
/* Initializing windows socket library */
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD (1, 1);
i = WSAStartup (wVersionRequested, &wsaData);
if (i != 0) {
OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_WARNING, NULL, "eXosip: Unable to initialize WINSOCK, reason: %d\n", i));
/* return -1; It might be already initilized?? */
}
}
#endif
excontext->user_agent = osip_strdup ("eXosip/" EXOSIP_VERSION);
if (excontext->user_agent == NULL)
return OSIP_NOMEM;
excontext->j_calls = NULL;
excontext->j_stop_ua = 0;
#ifndef OSIP_MONOTHREAD
excontext->j_thread = NULL;
#endif
i = osip_list_init (&excontext->j_transactions);
excontext->j_reg = NULL;
#ifndef OSIP_MONOTHREAD
#if !defined (_WIN32_WCE)
excontext->j_cond = (struct osip_cond *) osip_cond_init ();
if (excontext->j_cond == NULL) {
osip_free (excontext->user_agent);
excontext->user_agent = NULL;
return OSIP_NOMEM;
}
#endif
excontext->j_mutexlock = (struct osip_mutex *) osip_mutex_init ();
if (excontext->j_mutexlock == NULL) {
osip_free (excontext->user_agent);
excontext->user_agent = NULL;
#if !defined (_WIN32_WCE)
osip_cond_destroy ((struct osip_cond *) excontext->j_cond);
excontext->j_cond = NULL;
#endif
return OSIP_NOMEM;
}
#endif
i = osip_init (&osip);
if (i != 0) {
OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_ERROR, NULL, "eXosip: Cannot initialize osip!\n"));
return i;
}
osip_set_application_context (osip, &excontext);
_eXosip_set_callbacks (osip);
excontext->j_osip = osip;
#ifndef OSIP_MONOTHREAD
/* open a TCP socket to wake up the application when needed. */
excontext->j_socketctl = jpipe ();
if (excontext->j_socketctl == NULL)
return OSIP_UNDEFINED_ERROR;
excontext->j_socketctl_event = jpipe ();
if (excontext->j_socketctl_event == NULL)
return OSIP_UNDEFINED_ERROR;
#endif
/* To be changed in osip! */
excontext->j_events = (osip_fifo_t *) osip_malloc (sizeof (osip_fifo_t));
if (excontext->j_events == NULL)
return OSIP_NOMEM;
osip_fifo_init (excontext->j_events);
excontext->use_rport = 1;
excontext->dns_capabilities = 2;
excontext->enable_dns_cache = 1;
excontext->ka_interval = 17000;
snprintf(excontext->ka_crlf, sizeof(excontext->ka_crlf), "\r\n\r\n");
excontext->ka_options = 0;
excontext->autoanswer_bye = 1;
excontext->auto_masquerade_contact = 1;
excontext->masquerade_via=0;
return OSIP_SUCCESS;
}
Commit Message:
CWE ID: CWE-189
Target: 1
Example 2:
Code: static inline unsigned rb_page_commit(struct buffer_page *bpage)
{
return local_read(&bpage->page->commit);
}
Commit Message: ring-buffer: Prevent overflow of size in ring_buffer_resize()
If the size passed to ring_buffer_resize() is greater than MAX_LONG - BUF_PAGE_SIZE
then the DIV_ROUND_UP() will return zero.
Here's the details:
# echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb
tracing_entries_write() processes this and converts kb to bytes.
18014398509481980 << 10 = 18446744073709547520
and this is passed to ring_buffer_resize() as unsigned long size.
size = DIV_ROUND_UP(size, BUF_PAGE_SIZE);
Where DIV_ROUND_UP(a, b) is (a + b - 1)/b
BUF_PAGE_SIZE is 4080 and here
18446744073709547520 + 4080 - 1 = 18446744073709551599
where 18446744073709551599 is still smaller than 2^64
2^64 - 18446744073709551599 = 17
But now 18446744073709551599 / 4080 = 4521260802379792
and size = size * 4080 = 18446744073709551360
This is checked to make sure its still greater than 2 * 4080,
which it is.
Then we convert to the number of buffer pages needed.
nr_page = DIV_ROUND_UP(size, BUF_PAGE_SIZE)
but this time size is 18446744073709551360 and
2^64 - (18446744073709551360 + 4080 - 1) = -3823
Thus it overflows and the resulting number is less than 4080, which makes
3823 / 4080 = 0
an nr_pages is set to this. As we already checked against the minimum that
nr_pages may be, this causes the logic to fail as well, and we crash the
kernel.
There's no reason to have the two DIV_ROUND_UP() (that's just result of
historical code changes), clean up the code and fix this bug.
Cc: [email protected] # 3.5+
Fixes: 83f40318dab00 ("ring-buffer: Make removal of ring buffer pages atomic")
Signed-off-by: Steven Rostedt <[email protected]>
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 flush_sigqueue(struct sigpending *queue)
{
struct sigqueue *q;
sigemptyset(&queue->signal);
while (!list_empty(&queue->list)) {
q = list_entry(queue->list.next, struct sigqueue , list);
list_del_init(&q->list);
__sigqueue_free(q);
}
}
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
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 tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union tpacket_uhdr h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timespec ts;
__u32 ts_status;
bool is_drop_n_account = false;
/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.
* We may add members to them until current aligned size without forcing
* userspace to call getsockopt(..., PACKET_HDRLEN, ...).
*/
BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
else if (skb->pkt_type != PACKET_OUTGOING &&
(skb->ip_summed == CHECKSUM_COMPLETE ||
skb_csum_unnecessary(skb)))
status |= TP_STATUS_CSUM_VALID;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned int maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
if (po->has_vnet_hdr)
netoff += sizeof(struct virtio_net_hdr);
macoff = netoff - maclen;
}
if (po->tp_version <= TPACKET_V2) {
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
} else if (unlikely(macoff + snaplen >
GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
u32 nval;
nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
snaplen, nval, macoff);
snaplen = nval;
if (unlikely((int)snaplen < 0)) {
snaplen = 0;
macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
}
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_rx_frame(po, skb,
TP_STATUS_KERNEL, (macoff+snaplen));
if (!h.raw)
goto drop_n_account;
if (po->tp_version <= TPACKET_V2) {
packet_increment_rx_head(po, &po->rx_ring);
/*
* LOSING will be reported till you read the stats,
* because it's COR - Clear On Read.
* Anyways, moving it for V1/V2 only as V3 doesn't need this
* at packet level.
*/
if (po->stats.stats1.tp_drops)
status |= TP_STATUS_LOSING;
}
po->stats.stats1.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
spin_unlock(&sk->sk_receive_queue.lock);
if (po->has_vnet_hdr) {
if (virtio_net_hdr_from_skb(skb, h.raw + macoff -
sizeof(struct virtio_net_hdr),
vio_le(), true)) {
spin_lock(&sk->sk_receive_queue.lock);
goto drop_n_account;
}
}
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
getnstimeofday(&ts);
status |= ts_status;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (skb_vlan_tag_present(skb)) {
h.h2->tp_vlan_tci = skb_vlan_tag_get(skb);
h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);
status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
} else {
h.h2->tp_vlan_tci = 0;
h.h2->tp_vlan_tpid = 0;
}
memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
hdrlen = sizeof(*h.h2);
break;
case TPACKET_V3:
/* tp_nxt_offset,vlan are already populated above.
* So DONT clear those fields here
*/
h.h3->tp_status |= status;
h.h3->tp_len = skb->len;
h.h3->tp_snaplen = snaplen;
h.h3->tp_mac = macoff;
h.h3->tp_net = netoff;
h.h3->tp_sec = ts.tv_sec;
h.h3->tp_nsec = ts.tv_nsec;
memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));
hdrlen = sizeof(*h.h3);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
if (po->tp_version <= TPACKET_V2) {
u8 *start, *end;
end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
smp_wmb();
#endif
if (po->tp_version <= TPACKET_V2) {
__packet_set_status(po, h.raw, status);
sk->sk_data_ready(sk);
} else {
prb_clear_blk_fill_status(&po->rx_ring);
}
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
if (!is_drop_n_account)
consume_skb(skb);
else
kfree_skb(skb);
return 0;
drop_n_account:
is_drop_n_account = true;
po->stats.stats1.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk);
kfree_skb(copy_skb);
goto drop_n_restore;
}
Commit Message: packet: Don't write vnet header beyond end of buffer
... which may happen with certain values of tp_reserve and maclen.
Fixes: 58d19b19cd99 ("packet: vnet_hdr support for tpacket_rcv")
Signed-off-by: Benjamin Poirier <[email protected]>
Cc: Willem de Bruijn <[email protected]>
Acked-by: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void vnc_client_read(void *opaque)
{
VncState *vs = opaque;
long ret;
#ifdef CONFIG_VNC_SASL
if (vs->sasl.conn && vs->sasl.runSSF)
ret = vnc_client_read_sasl(vs);
else
#endif /* CONFIG_VNC_SASL */
#ifdef CONFIG_VNC_WS
if (vs->encode_ws) {
ret = vnc_client_read_ws(vs);
if (ret == -1) {
vnc_disconnect_start(vs);
return;
} else if (ret == -2) {
vnc_client_error(vs);
return;
}
} else
#endif /* CONFIG_VNC_WS */
{
ret = vnc_client_read_plain(vs);
}
if (!ret) {
if (vs->csock == -1)
vnc_disconnect_finish(vs);
return;
}
while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
size_t len = vs->read_handler_expect;
int ret;
ret = vs->read_handler(vs, vs->input.buffer, len);
if (vs->csock == -1) {
vnc_disconnect_finish(vs);
return;
}
if (!ret) {
buffer_advance(&vs->input, len);
} else {
vs->read_handler_expect = ret;
}
}
}
Commit Message:
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 sas_destruct_devices(struct work_struct *work)
{
struct domain_device *dev, *n;
struct sas_discovery_event *ev = to_sas_discovery_event(work);
struct asd_sas_port *port = ev->port;
clear_bit(DISCE_DESTRUCT, &port->disc.pending);
list_for_each_entry_safe(dev, n, &port->destroy_list, disco_list_node) {
list_del_init(&dev->disco_list_node);
sas_remove_children(&dev->rphy->dev);
sas_rphy_delete(dev->rphy);
sas_unregister_common_dev(port, dev);
}
}
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:
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 OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
OPJ_UINT32 index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
OPJ_UINT32 resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
OPJ_UINT32 dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy);
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
for (pi->resno = pi->poc.resno0;
pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
OPJ_UINT32 levelno;
OPJ_INT32 trx0, try0;
OPJ_INT32 trx1, try1;
OPJ_UINT32 rpx, rpy;
OPJ_INT32 prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
(OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
- opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
(OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
- opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
Commit Message: Avoid division by zero in opj_pi_next_rpcl, opj_pi_next_pcrl and opj_pi_next_cprl (#938)
Fixes issues with id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 and
id:000019,sig:08,src:001098,op:flip1,pos:49
CWE ID: CWE-369
Target: 1
Example 2:
Code: static void tcp_v4_clear_md5_list(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
/* Free each key, then the set of key keys,
* the crypto element, and then decrement our
* hold on the last resort crypto.
*/
if (tp->md5sig_info->entries4) {
int i;
for (i = 0; i < tp->md5sig_info->entries4; i++)
kfree(tp->md5sig_info->keys4[i].base.key);
tp->md5sig_info->entries4 = 0;
tcp_free_md5sig_pool();
}
if (tp->md5sig_info->keys4) {
kfree(tp->md5sig_info->keys4);
tp->md5sig_info->keys4 = NULL;
tp->md5sig_info->alloced4 = 0;
}
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[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: LoginLibrary* CrosLibrary::GetLoginLibrary() {
return login_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
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: my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error)
{
*len = 0;
g_hash_table_foreach (table, hash_foreach, len);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int gpr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
struct pt_regs *regs = task_pt_regs(target);
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
regs,
0, sizeof(*regs));
}
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: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_);
}
if (cfg_.ts_number_layers > 1) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_SVC, 1);
}
vpx_svc_layer_id_t layer_id = {0, 0};
layer_id.spatial_layer_id = 0;
frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers);
layer_id.temporal_layer_id = SetLayerId(video->frame(),
cfg_.ts_number_layers);
if (video->frame() > 0) {
encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id);
}
}
const vpx_rational_t tb = video->timebase();
timebase_ = static_cast<double>(tb.num) / tb.den;
duration_ = 0;
}
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
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 bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kSegCountOffset = 6;
const size_t kEndCountOffset = 14;
const size_t kHeaderSize = 16;
const size_t kSegmentSize = 8; // total size of array elements for one segment
if (kEndCountOffset > size) {
return false;
}
size_t segCount = readU16(data, kSegCountOffset) >> 1;
if (kHeaderSize + segCount * kSegmentSize > size) {
return false;
}
for (size_t i = 0; i < segCount; i++) {
uint32_t end = readU16(data, kEndCountOffset + 2 * i);
uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i));
if (end < start) {
return false;
}
uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i));
if (rangeOffset == 0) {
uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i));
if (((end + delta) & 0xffff) > end - start) {
addRange(coverage, start, end + 1);
} else {
for (uint32_t j = start; j < end + 1; j++) {
if (((j + delta) & 0xffff) != 0) {
addRange(coverage, j, j + 1);
}
}
}
} else {
for (uint32_t j = start; j < end + 1; j++) {
uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset +
(i + j - start) * 2;
if (actualRangeOffset + 2 > size) {
continue;
}
uint32_t glyphId = readU16(data, actualRangeOffset);
if (glyphId != 0) {
addRange(coverage, j, j + 1);
}
}
}
}
return true;
}
Commit Message: Add error logging on invalid cmap - DO NOT MERGE
This patch logs instances of fonts with invalid cmap tables.
Bug: 25645298
Bug: 26413177
Change-Id: I183985e9784a97a2b4307a22e036382b1fc90e5e
CWE ID: CWE-20
Target: 1
Example 2:
Code: void QuotaTaskObserver::RegisterTask(QuotaTask* task) {
running_quota_tasks_.insert(task);
}
Commit Message: Quota double-delete fix
BUG=142310
Review URL: https://chromiumcodereview.appspot.com/10832407
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152532 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 void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx)
{
struct Vmxnet3_TxDesc txd;
uint32_t txd_idx;
uint32_t data_len;
hwaddr data_pa;
for (;;) {
if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) {
break;
}
vmxnet3_dump_tx_descr(&txd);
if (!s->skip_current_tx_pkt) {
data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE;
data_pa = le64_to_cpu(txd.addr);
if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt,
data_pa,
data_len)) {
s->skip_current_tx_pkt = true;
}
}
if (s->tx_sop) {
vmxnet3_tx_retrieve_metadata(s, &txd);
s->tx_sop = false;
}
if (txd.eop) {
if (!s->skip_current_tx_pkt) {
vmxnet_tx_pkt_parse(s->tx_pkt);
if (s->needs_vlan) {
vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);
}
vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);
}
vmxnet3_send_packet(s, qidx);
} else {
vmxnet3_on_tx_done_update_stats(s, qidx,
VMXNET3_PKT_STATUS_ERROR);
}
vmxnet3_complete_packet(s, qidx, txd_idx);
s->tx_sop = true;
s->skip_current_tx_pkt = false;
vmxnet_tx_pkt_reset(s->tx_pkt);
}
}
Commit Message:
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 ide_dma_cb(void *opaque, int ret)
{
IDEState *s = opaque;
int n;
int64_t sector_num;
bool stay_active = false;
if (ret == -ECANCELED) {
return;
}
if (ret < 0) {
int op = IDE_RETRY_DMA;
if (s->dma_cmd == IDE_DMA_READ)
op |= IDE_RETRY_READ;
else if (s->dma_cmd == IDE_DMA_TRIM)
op |= IDE_RETRY_TRIM;
if (ide_handle_rw_error(s, -ret, op)) {
return;
}
}
n = s->io_buffer_size >> 9;
if (n > s->nsector) {
/* The PRDs were longer than needed for this request. Shorten them so
* we don't get a negative remainder. The Active bit must remain set
* after the request completes. */
n = s->nsector;
stay_active = true;
}
sector_num = ide_get_sector(s);
if (n > 0) {
assert(s->io_buffer_size == s->sg.size);
dma_buf_commit(s, s->io_buffer_size);
sector_num += n;
ide_set_sector(s, sector_num);
s->nsector -= n;
}
/* end of transfer ? */
if (s->nsector == 0) {
s->status = READY_STAT | SEEK_STAT;
ide_set_irq(s->bus);
goto eot;
}
/* launch next transfer */
n = s->nsector;
s->io_buffer_index = 0;
s->io_buffer_size = n * 512;
if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) == 0) {
/* The PRDs were too short. Reset the Active bit, but don't raise an
* interrupt. */
s->status = READY_STAT | SEEK_STAT;
goto eot;
}
printf("ide_dma_cb: sector_num=%" PRId64 " n=%d, cmd_cmd=%d\n",
sector_num, n, s->dma_cmd);
#endif
if ((s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) &&
!ide_sect_range_ok(s, sector_num, n)) {
ide_dma_error(s);
return;
}
switch (s->dma_cmd) {
case IDE_DMA_READ:
s->bus->dma->aiocb = dma_blk_read(s->blk, &s->sg, sector_num,
ide_dma_cb, s);
break;
case IDE_DMA_WRITE:
s->bus->dma->aiocb = dma_blk_write(s->blk, &s->sg, sector_num,
ide_dma_cb, s);
break;
case IDE_DMA_TRIM:
s->bus->dma->aiocb = dma_blk_io(s->blk, &s->sg, sector_num,
ide_issue_trim, ide_dma_cb, s,
DMA_DIRECTION_TO_DEVICE);
break;
}
return;
eot:
if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {
block_acct_done(blk_get_stats(s->blk), &s->acct);
}
ide_set_inactive(s, stay_active);
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool effects_enabled()
{
struct listnode *out_node;
list_for_each(out_node, &active_outputs_list) {
struct listnode *fx_node;
output_context_t *out_ctxt = node_to_item(out_node,
output_context_t,
outputs_list_node);
list_for_each(fx_node, &out_ctxt->effects_list) {
effect_context_t *fx_ctxt = node_to_item(fx_node,
effect_context_t,
output_node);
if ((fx_ctxt->state == EFFECT_STATE_ACTIVE) &&
(fx_ctxt->ops.process != NULL))
return true;
}
}
return false;
}
Commit Message: DO NOT MERGE Fix AudioEffect reply overflow
Bug: 28173666
Change-Id: I055af37a721b20c5da0f1ec4b02f630dcd5aee02
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 imap_status(char *path, int queue)
{
static int queued = 0;
struct ImapData *idata = NULL;
char buf[LONG_STRING];
char mbox[LONG_STRING];
struct ImapStatus *status = NULL;
if (get_mailbox(path, &idata, buf, sizeof(buf)) < 0)
return -1;
/* We are in the folder we're polling - just return the mailbox count.
*
* Note that imap_mxcmp() converts NULL to "INBOX", so we need to
* make sure the idata really is open to a folder. */
if (idata->ctx && !imap_mxcmp(buf, idata->mailbox))
return idata->ctx->msgcount;
else if (mutt_bit_isset(idata->capabilities, IMAP4REV1) ||
mutt_bit_isset(idata->capabilities, STATUS))
{
imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf);
snprintf(buf, sizeof(buf), "STATUS %s (%s)", mbox, "MESSAGES");
imap_unmunge_mbox_name(idata, mbox);
}
else
{
/* Server does not support STATUS, and this is not the current mailbox.
* There is no lightweight way to check recent arrivals */
return -1;
}
if (queue)
{
imap_exec(idata, buf, IMAP_CMD_QUEUE);
queued = 1;
return 0;
}
else if (!queued)
imap_exec(idata, buf, 0);
queued = 0;
status = imap_mboxcache_get(idata, mbox, 0);
if (status)
return status->messages;
return 0;
}
Commit Message: quote imap strings more carefully
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-77
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 JSON_INLINE size_t num_buckets(hashtable_t *hashtable)
{
return primes[hashtable->num_buckets];
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310
Target: 1
Example 2:
Code: static int do_add_mount(struct mount *newmnt, struct path *path, int mnt_flags)
{
struct mountpoint *mp;
struct mount *parent;
int err;
mnt_flags &= ~MNT_INTERNAL_FLAGS;
mp = lock_mount(path);
if (IS_ERR(mp))
return PTR_ERR(mp);
parent = real_mount(path->mnt);
err = -EINVAL;
if (unlikely(!check_mnt(parent))) {
/* that's acceptable only for automounts done in private ns */
if (!(mnt_flags & MNT_SHRINKABLE))
goto unlock;
/* ... and for those we'd better have mountpoint still alive */
if (!parent->mnt_ns)
goto unlock;
}
/* Refuse the same filesystem on the same mount point */
err = -EBUSY;
if (path->mnt->mnt_sb == newmnt->mnt.mnt_sb &&
path->mnt->mnt_root == path->dentry)
goto unlock;
err = -EINVAL;
if (S_ISLNK(newmnt->mnt.mnt_root->d_inode->i_mode))
goto unlock;
newmnt->mnt.mnt_flags = mnt_flags;
err = graft_tree(newmnt, parent, mp);
unlock:
unlock_mount(mp);
return 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: 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 gx_ttfReader__Read(ttfReader *self, void *p, int n)
{
gx_ttfReader *r = (gx_ttfReader *)self;
const byte *q;
if (!r->error) {
if (r->extra_glyph_index != -1) {
q = r->glyph_data.bits.data + r->pos;
r->error = (r->glyph_data.bits.size - r->pos < n ?
gs_note_error(gs_error_invalidfont) : 0);
if (r->error == 0)
memcpy(p, q, n);
unsigned int cnt;
for (cnt = 0; cnt < (uint)n; cnt += r->error) {
r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q);
if (r->error < 0)
break;
else if ( r->error == 0) {
memcpy((char *)p + cnt, q, n - cnt);
break;
} else {
memcpy((char *)p + cnt, q, r->error);
}
}
}
}
if (r->error) {
memset(p, 0, n);
return;
}
r->pos += n;
}
Commit Message:
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: exsltCryptoRc4EncryptFunction (xmlXPathParserContextPtr ctxt, int nargs) {
int key_len = 0, key_size = 0;
int str_len = 0, bin_len = 0, hex_len = 0;
xmlChar *key = NULL, *str = NULL, *padkey = NULL;
xmlChar *bin = NULL, *hex = NULL;
xsltTransformContextPtr tctxt = NULL;
if (nargs != 2) {
xmlXPathSetArityError (ctxt);
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
str = xmlXPathPopString (ctxt);
str_len = xmlUTF8Strlen (str);
if (str_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (str);
return;
}
key = xmlXPathPopString (ctxt);
key_len = xmlUTF8Strlen (key);
if (key_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (key);
xmlFree (str);
return;
}
padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1);
if (padkey == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memset(padkey, 0, RC4_KEY_LENGTH + 1);
key_size = xmlUTF8Strsize (key, key_len);
if ((key_size > RC4_KEY_LENGTH) || (key_size < 0)) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: key size too long or key broken\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
memcpy (padkey, key, key_size);
/* encrypt it */
bin_len = str_len;
bin = xmlStrdup (str);
if (bin == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate string\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
PLATFORM_RC4_ENCRYPT (ctxt, padkey, str, str_len, bin, bin_len);
/* encode it */
hex_len = str_len * 2 + 1;
hex = xmlMallocAtomic (hex_len);
if (hex == NULL) {
xsltTransformError(tctxt, NULL, tctxt->inst,
"exsltCryptoRc4EncryptFunction: Failed to allocate result\n");
tctxt->state = XSLT_STATE_STOPPED;
xmlXPathReturnEmptyString (ctxt);
goto done;
}
exsltCryptoBin2Hex (bin, str_len, hex, hex_len);
xmlXPathReturnString (ctxt, hex);
done:
if (key != NULL)
xmlFree (key);
if (str != NULL)
xmlFree (str);
if (padkey != NULL)
xmlFree (padkey);
if (bin != NULL)
xmlFree (bin);
}
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
Target: 1
Example 2:
Code: void RenderWidgetHostImpl::PauseForPendingResizeOrRepaints() {
TRACE_EVENT0("browser",
"RenderWidgetHostImpl::PauseForPendingResizeOrRepaints");
if (!CanPauseForPendingResizeOrRepaints())
return;
WaitForSurface();
}
Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI
BUG=590284
Review URL: https://codereview.chromium.org/1747183002
Cr-Commit-Position: refs/heads/master@{#378844}
CWE ID:
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 skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_skcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
atomic_set(&ctx->inflight, 0);
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
skcipher_request_set_tfm(&ctx->req, private);
skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
Commit Message: crypto: algif_skcipher - Require setkey before accept(2)
Some cipher implementations will crash if you try to use them
without calling setkey first. This patch adds a check so that
the accept(2) call will fail with -ENOKEY if setkey hasn't been
done on the socket yet.
Cc: [email protected]
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Tested-by: Dmitry Vyukov <[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: long SimpleBlock::Parse()
{
return m_block.Parse(m_pCluster);
}
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: cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;}
Commit Message: fix buffer overflow (#30)
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: static void add_probe(const char *name)
{
struct module_entry *m;
m = get_or_add_modentry(name);
if (!(option_mask32 & (OPT_REMOVE | OPT_SHOW_DEPS))
&& (m->flags & MODULE_FLAG_LOADED)
&& strncmp(m->modname, "symbol:", 7) == 0
) {
G.need_symbols = 1;
}
}
Commit Message:
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: forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
Commit Message: fix #58 : access to invalid address by reg->dmin value
CWE ID: CWE-125
Target: 1
Example 2:
Code: status_t OMXNodeInstance::createGraphicBufferSource(
OMX_U32 portIndex, sp<IGraphicBufferConsumer> bufferConsumer, MetadataBufferType *type) {
status_t err;
if (portIndex != kPortIndexInput) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_VALUE;
} else if (mNumPortBuffers[portIndex] > 0) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
const sp<GraphicBufferSource> surfaceCheck = getGraphicBufferSource();
if (surfaceCheck != NULL) {
if (portIndex < NELEM(mMetadataType) && type != NULL) {
*type = mMetadataType[portIndex];
}
return ALREADY_EXISTS;
}
if (type != NULL) {
*type = kMetadataBufferTypeANWBuffer;
}
err = storeMetaDataInBuffers_l(portIndex, OMX_TRUE, type);
if (err != OK) {
return err;
}
OMX_PARAM_PORTDEFINITIONTYPE def;
InitOMXParams(&def);
def.nPortIndex = portIndex;
OMX_ERRORTYPE oerr = OMX_GetParameter(
mHandle, OMX_IndexParamPortDefinition, &def);
if (oerr != OMX_ErrorNone) {
OMX_INDEXTYPE index = OMX_IndexParamPortDefinition;
CLOG_ERROR(getParameter, oerr, "%s(%#x): %s:%u",
asString(index), index, portString(portIndex), portIndex);
return UNKNOWN_ERROR;
}
if (def.format.video.eColorFormat != OMX_COLOR_FormatAndroidOpaque) {
CLOGW("createInputSurface requires COLOR_FormatSurface "
"(AndroidOpaque) color format instead of %s(%#x)",
asString(def.format.video.eColorFormat), def.format.video.eColorFormat);
return INVALID_OPERATION;
}
uint32_t usageBits;
oerr = OMX_GetParameter(
mHandle, (OMX_INDEXTYPE)OMX_IndexParamConsumerUsageBits, &usageBits);
if (oerr != OMX_ErrorNone) {
usageBits = 0;
}
sp<GraphicBufferSource> bufferSource = new GraphicBufferSource(this,
def.format.video.nFrameWidth,
def.format.video.nFrameHeight,
def.nBufferCountActual,
usageBits,
bufferConsumer);
if ((err = bufferSource->initCheck()) != OK) {
return err;
}
setGraphicBufferSource(bufferSource);
return OK;
}
Commit Message: IOMX: allow configuration after going to loaded state
This was disallowed recently but we still use it as MediaCodcec.stop
only goes to loaded state, and does not free component.
Bug: 31450460
Change-Id: I72e092e4e55c9f23b1baee3e950d76e84a5ef28d
(cherry picked from commit e03b22839d78c841ce0a1a0a1ee1960932188b0b)
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: write_header( FT_Error error_code )
{
FT_Face face;
const char* basename;
error = FTC_Manager_LookupFace( handle->cache_manager,
handle->scaler.face_id, &face );
if ( error )
PanicZ( "can't access font file" );
if ( !status.header )
{
basename = ft_basename( handle->current_font->filepathname );
switch ( error_code )
{
case FT_Err_Ok:
sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name,
face->style_name, basename );
break;
case FT_Err_Invalid_Pixel_Size:
sprintf( status.header_buffer, "Invalid pixel size (file `%s')",
basename );
break;
case FT_Err_Invalid_PPem:
sprintf( status.header_buffer, "Invalid ppem value (file `%s')",
basename );
break;
default:
sprintf( status.header_buffer, "File `%s': error 0x%04x", basename,
(FT_UShort)error_code );
break;
}
status.header = status.header_buffer;
}
grWriteCellString( display->bitmap, 0, 0,
status.header, display->fore_color );
sprintf( status.header_buffer, "at %g points, angle = %d",
status.ptsize/64.0, status.angle );
grWriteCellString( display->bitmap, 0, CELLSTRING_HEIGHT,
status.header_buffer, display->fore_color );
grRefreshSurface( display->surface );
}
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 gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
{
int c;
int x, y;
int tox, toy;
int ydest;
int i;
int colorMap[gdMaxColors];
/* Stretch vectors */
int *stx, *sty;
if (overflow2(sizeof(int), srcW)) {
return;
}
if (overflow2(sizeof(int), srcH)) {
return;
}
stx = (int *) gdMalloc (sizeof (int) * srcW);
sty = (int *) gdMalloc (sizeof (int) * srcH);
/* Fixed by Mao Morimoto 2.0.16 */
for (i = 0; (i < srcW); i++) {
stx[i] = dstW * (i+1) / srcW - dstW * i / srcW ;
}
for (i = 0; (i < srcH); i++) {
sty[i] = dstH * (i+1) / srcH - dstH * i / srcH ;
}
for (i = 0; (i < gdMaxColors); i++) {
colorMap[i] = (-1);
}
toy = dstY;
for (y = srcY; (y < (srcY + srcH)); y++) {
for (ydest = 0; (ydest < sty[y - srcY]); ydest++) {
tox = dstX;
for (x = srcX; (x < (srcX + srcW)); x++) {
int nc = 0;
int mapTo;
if (!stx[x - srcX]) {
continue;
}
if (dst->trueColor) {
/* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */
if (!src->trueColor) {
int tmp = gdImageGetPixel (src, x, y);
mapTo = gdImageGetTrueColorPixel (src, x, y);
if (gdImageGetTransparent (src) == tmp) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
} else {
/* TK: old code follows */
mapTo = gdImageGetTrueColorPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == mapTo) {
/* 2.0.21, TK: not tox++ */
tox += stx[x - srcX];
continue;
}
}
} else {
c = gdImageGetPixel (src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent (src) == c) {
tox += stx[x - srcX];
continue;
}
if (src->trueColor) {
/* Remap to the palette available in the destination image. This is slow and works badly. */
mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c),
gdTrueColorGetGreen(c),
gdTrueColorGetBlue(c),
gdTrueColorGetAlpha (c));
} else {
/* Have we established a mapping for this color? */
if (colorMap[c] == (-1)) {
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
/* Find or create the best match */
/* 2.0.5: can't use gdTrueColorGetRed, etc with palette */
nc = gdImageColorResolveAlpha(dst, gdImageRed(src, c),
gdImageGreen(src, c),
gdImageBlue(src, c),
gdImageAlpha(src, c));
}
colorMap[c] = nc;
}
mapTo = colorMap[c];
}
}
for (i = 0; (i < stx[x - srcX]); i++) {
gdImageSetPixel (dst, tox, toy, mapTo);
tox++;
}
}
toy++;
}
}
gdFree (stx);
gdFree (sty);
}
Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow
CWE ID: CWE-190
Target: 1
Example 2:
Code: bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
{
bool eligible;
eligible = !vcpu->spin_loop.in_spin_loop ||
(vcpu->spin_loop.in_spin_loop &&
vcpu->spin_loop.dy_eligible);
if (vcpu->spin_loop.in_spin_loop)
kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
return eligible;
}
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: static CURLcode nss_init_core(struct Curl_easy *data, const char *cert_dir)
{
NSSInitParameters initparams;
if(nss_context != NULL)
return CURLE_OK;
memset((void *) &initparams, '\0', sizeof(initparams));
initparams.length = sizeof(initparams);
if(cert_dir) {
char *certpath = aprintf("sql:%s", cert_dir);
if(!certpath)
return CURLE_OUT_OF_MEMORY;
infof(data, "Initializing NSS with certpath: %s\n", certpath);
nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
free(certpath);
if(nss_context != NULL)
return CURLE_OK;
infof(data, "Unable to initialize NSS database\n");
}
infof(data, "Initializing NSS with certpath: none\n");
nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
| NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
| NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
if(nss_context != NULL)
return CURLE_OK;
infof(data, "Unable to initialize NSS\n");
return CURLE_SSL_CACERT_BADFILE;
}
Commit Message: nss: refuse previously loaded certificate from file
... when we are not asked to use a certificate from file
CWE ID: CWE-287
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 long restore_tm_sigcontexts(struct pt_regs *regs,
struct sigcontext __user *sc,
struct sigcontext __user *tm_sc)
{
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs, *tm_v_regs;
#endif
unsigned long err = 0;
unsigned long msr;
#ifdef CONFIG_VSX
int i;
#endif
/* copy the GPRs */
err |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr));
err |= __copy_from_user(¤t->thread.ckpt_regs, sc->gp_regs,
sizeof(regs->gpr));
/*
* TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP.
* TEXASR was set by the signal delivery reclaim, as was TFIAR.
* Users doing anything abhorrent like thread-switching w/ signals for
* TM-Suspended code will have to back TEXASR/TFIAR up themselves.
* For the case of getting a signal and simply returning from it,
* we don't need to re-copy them here.
*/
err |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]);
err |= __get_user(current->thread.tm_tfhar, &sc->gp_regs[PT_NIP]);
/* get MSR separately, transfer the LE bit if doing signal return */
err |= __get_user(msr, &sc->gp_regs[PT_MSR]);
/* pull in MSR TM from user context */
regs->msr = (regs->msr & ~MSR_TS_MASK) | (msr & MSR_TS_MASK);
/* pull in MSR LE from user context */
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
/* The following non-GPR non-FPR non-VR state is also checkpointed: */
err |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]);
err |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]);
err |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]);
err |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]);
err |= __get_user(current->thread.ckpt_regs.ctr,
&sc->gp_regs[PT_CTR]);
err |= __get_user(current->thread.ckpt_regs.link,
&sc->gp_regs[PT_LNK]);
err |= __get_user(current->thread.ckpt_regs.xer,
&sc->gp_regs[PT_XER]);
err |= __get_user(current->thread.ckpt_regs.ccr,
&sc->gp_regs[PT_CCR]);
/* These regs are not checkpointed; they can go in 'regs'. */
err |= __get_user(regs->trap, &sc->gp_regs[PT_TRAP]);
err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);
err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);
err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr. That way, if we get preempted
* and another task grabs the FPU/Altivec, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
/*
* Force reload of FP/VEC.
* This has to be done before copying stuff into current->thread.fpr/vr
* for the reasons explained in the previous comment.
*/
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX);
#ifdef CONFIG_ALTIVEC
err |= __get_user(v_regs, &sc->v_regs);
err |= __get_user(tm_v_regs, &tm_sc->v_regs);
if (err)
return err;
if (v_regs && !access_ok(VERIFY_READ, v_regs, 34 * sizeof(vector128)))
return -EFAULT;
if (tm_v_regs && !access_ok(VERIFY_READ,
tm_v_regs, 34 * sizeof(vector128)))
return -EFAULT;
/* Copy 33 vec registers (vr0..31 and vscr) from the stack */
if (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) {
err |= __copy_from_user(¤t->thread.vr_state, v_regs,
33 * sizeof(vector128));
err |= __copy_from_user(¤t->thread.transact_vr, tm_v_regs,
33 * sizeof(vector128));
}
else if (current->thread.used_vr) {
memset(¤t->thread.vr_state, 0, 33 * sizeof(vector128));
memset(¤t->thread.transact_vr, 0, 33 * sizeof(vector128));
}
/* Always get VRSAVE back */
if (v_regs != NULL && tm_v_regs != NULL) {
err |= __get_user(current->thread.vrsave,
(u32 __user *)&v_regs[33]);
err |= __get_user(current->thread.transact_vrsave,
(u32 __user *)&tm_v_regs[33]);
}
else {
current->thread.vrsave = 0;
current->thread.transact_vrsave = 0;
}
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
/* restore floating point */
err |= copy_fpr_from_user(current, &sc->fp_regs);
err |= copy_transact_fpr_from_user(current, &tm_sc->fp_regs);
#ifdef CONFIG_VSX
/*
* Get additional VSX data. Update v_regs to point after the
* VMX data. Copy VSX low doubleword from userspace to local
* buffer for formatting, then into the taskstruct.
*/
if (v_regs && ((msr & MSR_VSX) != 0)) {
v_regs += ELF_NVRREG;
tm_v_regs += ELF_NVRREG;
err |= copy_vsx_from_user(current, v_regs);
err |= copy_transact_vsx_from_user(current, tm_v_regs);
} else {
for (i = 0; i < 32 ; i++) {
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;
}
}
#endif
tm_enable();
/* Make sure the transaction is marked as failed */
current->thread.tm_texasr |= TEXASR_FS;
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(¤t->thread, msr);
/* This loads the speculative FP/VEC state, if used */
if (msr & MSR_FP) {
do_load_up_transact_fpu(¤t->thread);
regs->msr |= (MSR_FP | current->thread.fpexc_mode);
}
#ifdef CONFIG_ALTIVEC
if (msr & MSR_VEC) {
do_load_up_transact_altivec(¤t->thread);
regs->msr |= MSR_VEC;
}
#endif
return err;
}
Commit Message: powerpc/tm: Block signal return setting invalid MSR state
Currently we allow both the MSR T and S bits to be set by userspace on
a signal return. Unfortunately this is a reserved configuration and
will cause a TM Bad Thing exception if attempted (via rfid).
This patch checks for this case in both the 32 and 64 bit signals
code. If both T and S are set, we mark the context as invalid.
Found using a syscall fuzzer.
Fixes: 2b0a576d15e0 ("powerpc: Add new transactional memory state to the signal context")
Cc: [email protected] # v3.9+
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: SWFInput_getUInt32(SWFInput input)
{
unsigned long num = SWFInput_getChar(input);
num += SWFInput_getChar(input) << 8;
num += SWFInput_getChar(input) << 16;
num += SWFInput_getChar(input) << 24;
return num;
}
Commit Message: Fix left shift of a negative value in SWFInput_readSBits. Check for number before before left-shifting by (number-1).
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: my_object_uppercase (MyObject *obj, const char *str, char **ret, GError **error)
{
*ret = g_ascii_strup (str, -1);
return TRUE;
}
Commit Message:
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: LIBOPENMPT_MODPLUG_API unsigned int ModPlug_SampleName(ModPlugFile* file, unsigned int qual, char* buff)
{
const char* str;
unsigned int retval;
size_t tmpretval;
if(!file) return 0;
str = openmpt_module_get_sample_name(file->mod,qual-1);
if(!str){
if(buff){
*buff = '\0';
}
return 0;
}
tmpretval = strlen(str);
if(tmpretval>=INT_MAX){
tmpretval = INT_MAX-1;
}
retval = (int)tmpretval;
if(buff){
memcpy(buff,str,retval+1);
buff[retval] = '\0';
}
openmpt_free_string(str);
return retval;
}
Commit Message: [Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team)
git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27
CWE ID: CWE-120
Target: 1
Example 2:
Code: gs_lib_ctx_get_real_stdio(FILE **in, FILE **out, FILE **err)
{
*in = stdin;
*out = stdout;
*err = stderr;
}
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: static void block_socket(SOCKETTYPE fd)
{
#ifndef WIN32
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
#else
u_long flags = 0;
ioctlsocket(fd, FIONBIO, &flags);
#endif
}
Commit Message: stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime.
Might have introduced a memory leak, don't have time to check. :(
Should the other hex2bin()'s be checked?
Thanks to Mick Ayzenberg <mick.dejavusecurity.com> for finding this.
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: bool SessionRestore::IsRestoring(const Profile* profile) {
return (profiles_getting_restored &&
profiles_getting_restored->find(profile) !=
profiles_getting_restored->end());
}
Commit Message: Lands http://codereview.chromium.org/9316065/ for Marja. I reviewed
this, so I'm using TBR to land it.
Don't crash if multiple SessionRestoreImpl:s refer to the same
Profile.
It shouldn't ever happen but it seems to happen anyway.
BUG=111238
TEST=NONE
[email protected]
[email protected]
Review URL: https://chromiumcodereview.appspot.com/9343005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120648 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: static future_t *start_up(void) {
LOG_INFO("%s", __func__);
command_credits = 1;
firmware_is_configured = false;
pthread_mutex_init(&commands_pending_response_lock, NULL);
period_ms_t startup_timeout_ms;
char timeout_prop[PROPERTY_VALUE_MAX];
if (!property_get("bluetooth.enable_timeout_ms", timeout_prop, STRING_VALUE_OF(DEFAULT_STARTUP_TIMEOUT_MS))
|| (startup_timeout_ms = atoi(timeout_prop)) < 100)
startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;
startup_timer = non_repeating_timer_new(startup_timeout_ms, startup_timer_expired, NULL);
if (!startup_timer) {
LOG_ERROR("%s unable to create startup timer.", __func__);
goto error;
}
non_repeating_timer_restart(startup_timer);
epilog_timer = non_repeating_timer_new(EPILOG_TIMEOUT_MS, epilog_timer_expired, NULL);
if (!epilog_timer) {
LOG_ERROR("%s unable to create epilog timer.", __func__);
goto error;
}
command_response_timer = non_repeating_timer_new(COMMAND_PENDING_TIMEOUT, command_timed_out, NULL);
if (!command_response_timer) {
LOG_ERROR("%s unable to create command response timer.", __func__);
goto error;
}
command_queue = fixed_queue_new(SIZE_MAX);
if (!command_queue) {
LOG_ERROR("%s unable to create pending command queue.", __func__);
goto error;
}
packet_queue = fixed_queue_new(SIZE_MAX);
if (!packet_queue) {
LOG_ERROR("%s unable to create pending packet queue.", __func__);
goto error;
}
thread = thread_new("hci_thread");
if (!thread) {
LOG_ERROR("%s unable to create thread.", __func__);
goto error;
}
commands_pending_response = list_new(NULL);
if (!commands_pending_response) {
LOG_ERROR("%s unable to create list for commands pending response.", __func__);
goto error;
}
memset(incoming_packets, 0, sizeof(incoming_packets));
packet_fragmenter->init(&packet_fragmenter_callbacks);
fixed_queue_register_dequeue(command_queue, thread_get_reactor(thread), event_command_ready, NULL);
fixed_queue_register_dequeue(packet_queue, thread_get_reactor(thread), event_packet_ready, NULL);
vendor->open(btif_local_bd_addr.address, &interface);
hal->init(&hal_callbacks, thread);
low_power_manager->init(thread);
vendor->set_callback(VENDOR_CONFIGURE_FIRMWARE, firmware_config_callback);
vendor->set_callback(VENDOR_CONFIGURE_SCO, sco_config_callback);
vendor->set_callback(VENDOR_DO_EPILOG, epilog_finished_callback);
if (!hci_inject->open(&interface)) {
}
int power_state = BT_VND_PWR_OFF;
#if (defined (BT_CLEAN_TURN_ON_DISABLED) && BT_CLEAN_TURN_ON_DISABLED == TRUE)
LOG_WARN("%s not turning off the chip before turning on.", __func__);
#else
vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
#endif
power_state = BT_VND_PWR_ON;
vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
startup_future = future_new();
LOG_DEBUG("%s starting async portion", __func__);
thread_post(thread, event_finish_startup, NULL);
return startup_future;
error:;
shut_down(); // returns NULL so no need to wait for it
return future_new_immediate(FUTURE_FAIL);
}
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: 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 GF_Err gf_isom_avc_config_update_ex(GF_ISOFile *the_file, u32 trackNumber, u32 DescriptionIndex, GF_AVCConfig *cfg, u32 op_type)
{
GF_TrackBox *trak;
GF_Err e;
GF_MPEGVisualSampleEntryBox *entry;
e = CanAccessMovie(the_file, GF_ISOM_OPEN_WRITE);
if (e) return e;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !trak->Media || !DescriptionIndex) return GF_BAD_PARAM;
entry = (GF_MPEGVisualSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, DescriptionIndex-1);
if (!entry) return GF_BAD_PARAM;
switch (entry->type) {
case GF_ISOM_BOX_TYPE_AVC1:
case GF_ISOM_BOX_TYPE_AVC2:
case GF_ISOM_BOX_TYPE_AVC3:
case GF_ISOM_BOX_TYPE_AVC4:
case GF_ISOM_BOX_TYPE_SVC1:
case GF_ISOM_BOX_TYPE_MVC1:
break;
default:
return GF_BAD_PARAM;
}
switch (op_type) {
/*AVCC replacement*/
case 0:
if (!cfg) return GF_BAD_PARAM;
if (!entry->avc_config) entry->avc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_AVCC);
if (entry->avc_config->config) gf_odf_avc_cfg_del(entry->avc_config->config);
entry->avc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_AVC1;
break;
/*SVCC replacement*/
case 1:
if (!cfg) return GF_BAD_PARAM;
if (!entry->svc_config) entry->svc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_SVCC);
if (entry->svc_config->config) gf_odf_avc_cfg_del(entry->svc_config->config);
entry->svc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_AVC1;
break;
/*SVCC replacement and AVC removal*/
case 2:
if (!cfg) return GF_BAD_PARAM;
if (entry->avc_config) {
gf_isom_box_del((GF_Box*)entry->avc_config);
entry->avc_config = NULL;
}
if (!entry->svc_config) entry->svc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_SVCC);
if (entry->svc_config->config) gf_odf_avc_cfg_del(entry->svc_config->config);
entry->svc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_SVC1;
break;
/*AVCC removal and switch to avc3*/
case 3:
if (!entry->avc_config || !entry->avc_config->config)
return GF_BAD_PARAM;
if (entry->svc_config) {
gf_isom_box_del((GF_Box*)entry->svc_config);
entry->svc_config = NULL;
}
if (entry->mvc_config) {
gf_isom_box_del((GF_Box*)entry->mvc_config);
entry->mvc_config = NULL;
}
while (gf_list_count(entry->avc_config->config->sequenceParameterSets)) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot*)gf_list_get(entry->avc_config->config->sequenceParameterSets, 0);
gf_list_rem(entry->avc_config->config->sequenceParameterSets, 0);
if (sl->data) gf_free(sl->data);
gf_free(sl);
}
while (gf_list_count(entry->avc_config->config->pictureParameterSets)) {
GF_AVCConfigSlot *sl = (GF_AVCConfigSlot*)gf_list_get(entry->avc_config->config->pictureParameterSets, 0);
gf_list_rem(entry->avc_config->config->pictureParameterSets, 0);
if (sl->data) gf_free(sl->data);
gf_free(sl);
}
if (entry->type == GF_ISOM_BOX_TYPE_AVC1)
entry->type = GF_ISOM_BOX_TYPE_AVC3;
else if (entry->type == GF_ISOM_BOX_TYPE_AVC2)
entry->type = GF_ISOM_BOX_TYPE_AVC4;
break;
/*MVCC replacement*/
case 4:
if (!cfg) return GF_BAD_PARAM;
if (!entry->mvc_config) entry->mvc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_MVCC);
if (entry->mvc_config->config) gf_odf_avc_cfg_del(entry->mvc_config->config);
entry->mvc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_AVC1;
break;
/*MVCC replacement and AVC removal*/
case 5:
if (!cfg) return GF_BAD_PARAM;
if (entry->avc_config) {
gf_isom_box_del((GF_Box*)entry->avc_config);
entry->avc_config = NULL;
}
if (!entry->mvc_config) entry->mvc_config = (GF_AVCConfigurationBox*)gf_isom_box_new(GF_ISOM_BOX_TYPE_MVCC);
if (entry->mvc_config->config) gf_odf_avc_cfg_del(entry->mvc_config->config);
entry->mvc_config->config = AVC_DuplicateConfig(cfg);
entry->type = GF_ISOM_BOX_TYPE_MVC1;
break;
}
AVC_RewriteESDescriptor(entry);
return GF_OK;
}
Commit Message: fix some exploitable overflows (#994, #997)
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: lexer_process_char_literal (parser_context_t *context_p, /**< context */
const uint8_t *char_p, /**< characters */
size_t length, /**< length of string */
uint8_t literal_type, /**< final literal type */
bool has_escape) /**< has escape sequences */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
uint32_t literal_index = 0;
JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL
|| literal_type == LEXER_STRING_LITERAL);
JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);
JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == literal_type
&& literal_p->prop.length == length
&& memcmp (literal_p->u.char_p, char_p, length) == 0)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);
return;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = literal_type;
literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;
if (has_escape)
{
literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);
memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);
}
else
{
literal_p->u.char_p = char_p;
}
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->literal_count++;
} /* lexer_process_char_literal */
Commit Message: Do not allocate memory for zero length strings.
Fixes #1821.
JerryScript-DCO-1.0-Signed-off-by: Zoltan Herczeg [email protected]
CWE ID: CWE-476
Target: 1
Example 2:
Code: void NavigationControllerImpl::LoadIfNecessary() {
if (!needs_reload_)
return;
if (pending_entry_) {
NavigateToPendingEntry(ReloadType::NONE);
} else if (last_committed_entry_index_ != -1) {
pending_entry_index_ = last_committed_entry_index_;
NavigateToPendingEntry(ReloadType::NONE);
} else {
needs_reload_ = false;
}
}
Commit Message: Add DumpWithoutCrashing in RendererDidNavigateToExistingPage
This is intended to be reverted after investigating the linked bug.
BUG=688425
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2701523004
Cr-Commit-Position: refs/heads/master@{#450900}
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 int em_call(struct x86_emulate_ctxt *ctxt)
{
long rel = ctxt->src.val;
ctxt->src.val = (unsigned long)ctxt->_eip;
jmp_rel(ctxt, rel);
return em_push(ctxt);
}
Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches
Before changing rip (during jmp, call, ret, etc.) the target should be asserted
to be canonical one, as real CPUs do. During sysret, both target rsp and rip
should be canonical. If any of these values is noncanonical, a #GP exception
should occur. The exception to this rule are syscall and sysenter instructions
in which the assigned rip is checked during the assignment to the relevant
MSRs.
This patch fixes the emulator to behave as real CPUs do for near branches.
Far branches are handled by the next patch.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
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: __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
static u32 ip6_proxy_idents_hashrnd __read_mostly;
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return 0;
net_get_random_once(&ip6_proxy_idents_hashrnd,
sizeof(ip6_proxy_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,
&addrs[1], &addrs[0]);
return htonl(id);
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: Program* GetProgramInfoNotShader(
GLuint client_id, const char* function_name) {
Program* program = GetProgram(client_id);
if (!program) {
if (GetShader(client_id)) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "shader passed for program");
} else {
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "unknown program");
}
}
LogClientServiceForInfo(program, client_id, function_name);
return program;
}
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: SchedulerObject::setAttribute(std::string key,
std::string name,
std::string value,
std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (isSubmissionChange(name.c_str())) {
text = "Changes to submission name not allowed";
return false;
}
if (isKeyword(name.c_str())) {
text = "Attribute name is reserved: " + name;
return false;
}
if (!isValidAttributeName(name,text)) {
return false;
}
if (::SetAttribute(id.cluster,
id.proc,
name.c_str(),
value.c_str())) {
text = "Failed to set attribute " + name + " to " + value;
return false;
}
return true;
}
Commit Message:
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 ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name)
{
WLog_DBG(TAG, "%s (Len: %"PRIu16" MaxLen: %"PRIu16" BufferOffset: %"PRIu32")",
name, fields->Len, fields->MaxLen, fields->BufferOffset);
if (fields->Len > 0)
winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len);
}
Commit Message: Fixed CVE-2018-8789
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int __mlx5_ib_modify_qp(struct ib_qp *ibqp,
const struct ib_qp_attr *attr, int attr_mask,
enum ib_qp_state cur_state, enum ib_qp_state new_state,
const struct mlx5_ib_modify_qp *ucmd)
{
static const u16 optab[MLX5_QP_NUM_STATE][MLX5_QP_NUM_STATE] = {
[MLX5_QP_STATE_RST] = {
[MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP,
[MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP,
[MLX5_QP_STATE_INIT] = MLX5_CMD_OP_RST2INIT_QP,
},
[MLX5_QP_STATE_INIT] = {
[MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP,
[MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP,
[MLX5_QP_STATE_INIT] = MLX5_CMD_OP_INIT2INIT_QP,
[MLX5_QP_STATE_RTR] = MLX5_CMD_OP_INIT2RTR_QP,
},
[MLX5_QP_STATE_RTR] = {
[MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP,
[MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP,
[MLX5_QP_STATE_RTS] = MLX5_CMD_OP_RTR2RTS_QP,
},
[MLX5_QP_STATE_RTS] = {
[MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP,
[MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP,
[MLX5_QP_STATE_RTS] = MLX5_CMD_OP_RTS2RTS_QP,
},
[MLX5_QP_STATE_SQD] = {
[MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP,
[MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP,
},
[MLX5_QP_STATE_SQER] = {
[MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP,
[MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP,
[MLX5_QP_STATE_RTS] = MLX5_CMD_OP_SQERR2RTS_QP,
},
[MLX5_QP_STATE_ERR] = {
[MLX5_QP_STATE_RST] = MLX5_CMD_OP_2RST_QP,
[MLX5_QP_STATE_ERR] = MLX5_CMD_OP_2ERR_QP,
}
};
struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
struct mlx5_ib_qp *qp = to_mqp(ibqp);
struct mlx5_ib_qp_base *base = &qp->trans_qp.base;
struct mlx5_ib_cq *send_cq, *recv_cq;
struct mlx5_qp_context *context;
struct mlx5_ib_pd *pd;
struct mlx5_ib_port *mibport = NULL;
enum mlx5_qp_state mlx5_cur, mlx5_new;
enum mlx5_qp_optpar optpar;
int mlx5_st;
int err;
u16 op;
u8 tx_affinity = 0;
mlx5_st = to_mlx5_st(ibqp->qp_type == IB_QPT_DRIVER ?
qp->qp_sub_type : ibqp->qp_type);
if (mlx5_st < 0)
return -EINVAL;
context = kzalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return -ENOMEM;
context->flags = cpu_to_be32(mlx5_st << 16);
if (!(attr_mask & IB_QP_PATH_MIG_STATE)) {
context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11);
} else {
switch (attr->path_mig_state) {
case IB_MIG_MIGRATED:
context->flags |= cpu_to_be32(MLX5_QP_PM_MIGRATED << 11);
break;
case IB_MIG_REARM:
context->flags |= cpu_to_be32(MLX5_QP_PM_REARM << 11);
break;
case IB_MIG_ARMED:
context->flags |= cpu_to_be32(MLX5_QP_PM_ARMED << 11);
break;
}
}
if ((cur_state == IB_QPS_RESET) && (new_state == IB_QPS_INIT)) {
if ((ibqp->qp_type == IB_QPT_RC) ||
(ibqp->qp_type == IB_QPT_UD &&
!(qp->flags & MLX5_IB_QP_SQPN_QP1)) ||
(ibqp->qp_type == IB_QPT_UC) ||
(ibqp->qp_type == IB_QPT_RAW_PACKET) ||
(ibqp->qp_type == IB_QPT_XRC_INI) ||
(ibqp->qp_type == IB_QPT_XRC_TGT)) {
if (mlx5_lag_is_active(dev->mdev)) {
u8 p = mlx5_core_native_port_num(dev->mdev);
tx_affinity = (unsigned int)atomic_add_return(1,
&dev->roce[p].next_port) %
MLX5_MAX_PORTS + 1;
context->flags |= cpu_to_be32(tx_affinity << 24);
}
}
}
if (is_sqp(ibqp->qp_type)) {
context->mtu_msgmax = (IB_MTU_256 << 5) | 8;
} else if ((ibqp->qp_type == IB_QPT_UD &&
!(qp->flags & MLX5_IB_QP_UNDERLAY)) ||
ibqp->qp_type == MLX5_IB_QPT_REG_UMR) {
context->mtu_msgmax = (IB_MTU_4096 << 5) | 12;
} else if (attr_mask & IB_QP_PATH_MTU) {
if (attr->path_mtu < IB_MTU_256 ||
attr->path_mtu > IB_MTU_4096) {
mlx5_ib_warn(dev, "invalid mtu %d\n", attr->path_mtu);
err = -EINVAL;
goto out;
}
context->mtu_msgmax = (attr->path_mtu << 5) |
(u8)MLX5_CAP_GEN(dev->mdev, log_max_msg);
}
if (attr_mask & IB_QP_DEST_QPN)
context->log_pg_sz_remote_qpn = cpu_to_be32(attr->dest_qp_num);
if (attr_mask & IB_QP_PKEY_INDEX)
context->pri_path.pkey_index = cpu_to_be16(attr->pkey_index);
/* todo implement counter_index functionality */
if (is_sqp(ibqp->qp_type))
context->pri_path.port = qp->port;
if (attr_mask & IB_QP_PORT)
context->pri_path.port = attr->port_num;
if (attr_mask & IB_QP_AV) {
err = mlx5_set_path(dev, qp, &attr->ah_attr, &context->pri_path,
attr_mask & IB_QP_PORT ? attr->port_num : qp->port,
attr_mask, 0, attr, false);
if (err)
goto out;
}
if (attr_mask & IB_QP_TIMEOUT)
context->pri_path.ackto_lt |= attr->timeout << 3;
if (attr_mask & IB_QP_ALT_PATH) {
err = mlx5_set_path(dev, qp, &attr->alt_ah_attr,
&context->alt_path,
attr->alt_port_num,
attr_mask | IB_QP_PKEY_INDEX | IB_QP_TIMEOUT,
0, attr, true);
if (err)
goto out;
}
pd = get_pd(qp);
get_cqs(qp->ibqp.qp_type, qp->ibqp.send_cq, qp->ibqp.recv_cq,
&send_cq, &recv_cq);
context->flags_pd = cpu_to_be32(pd ? pd->pdn : to_mpd(dev->devr.p0)->pdn);
context->cqn_send = send_cq ? cpu_to_be32(send_cq->mcq.cqn) : 0;
context->cqn_recv = recv_cq ? cpu_to_be32(recv_cq->mcq.cqn) : 0;
context->params1 = cpu_to_be32(MLX5_IB_ACK_REQ_FREQ << 28);
if (attr_mask & IB_QP_RNR_RETRY)
context->params1 |= cpu_to_be32(attr->rnr_retry << 13);
if (attr_mask & IB_QP_RETRY_CNT)
context->params1 |= cpu_to_be32(attr->retry_cnt << 16);
if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC) {
if (attr->max_rd_atomic)
context->params1 |=
cpu_to_be32(fls(attr->max_rd_atomic - 1) << 21);
}
if (attr_mask & IB_QP_SQ_PSN)
context->next_send_psn = cpu_to_be32(attr->sq_psn);
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC) {
if (attr->max_dest_rd_atomic)
context->params2 |=
cpu_to_be32(fls(attr->max_dest_rd_atomic - 1) << 21);
}
if (attr_mask & (IB_QP_ACCESS_FLAGS | IB_QP_MAX_DEST_RD_ATOMIC))
context->params2 |= to_mlx5_access_flags(qp, attr, attr_mask);
if (attr_mask & IB_QP_MIN_RNR_TIMER)
context->rnr_nextrecvpsn |= cpu_to_be32(attr->min_rnr_timer << 24);
if (attr_mask & IB_QP_RQ_PSN)
context->rnr_nextrecvpsn |= cpu_to_be32(attr->rq_psn);
if (attr_mask & IB_QP_QKEY)
context->qkey = cpu_to_be32(attr->qkey);
if (qp->rq.wqe_cnt && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT)
context->db_rec_addr = cpu_to_be64(qp->db.dma);
if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) {
u8 port_num = (attr_mask & IB_QP_PORT ? attr->port_num :
qp->port) - 1;
/* Underlay port should be used - index 0 function per port */
if (qp->flags & MLX5_IB_QP_UNDERLAY)
port_num = 0;
mibport = &dev->port[port_num];
context->qp_counter_set_usr_page |=
cpu_to_be32((u32)(mibport->cnts.set_id) << 24);
}
if (!ibqp->uobject && cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT)
context->sq_crq_size |= cpu_to_be16(1 << 4);
if (qp->flags & MLX5_IB_QP_SQPN_QP1)
context->deth_sqpn = cpu_to_be32(1);
mlx5_cur = to_mlx5_state(cur_state);
mlx5_new = to_mlx5_state(new_state);
if (mlx5_cur >= MLX5_QP_NUM_STATE || mlx5_new >= MLX5_QP_NUM_STATE ||
!optab[mlx5_cur][mlx5_new]) {
err = -EINVAL;
goto out;
}
op = optab[mlx5_cur][mlx5_new];
optpar = ib_mask_to_mlx5_opt(attr_mask);
optpar &= opt_mask[mlx5_cur][mlx5_new][mlx5_st];
if (qp->ibqp.qp_type == IB_QPT_RAW_PACKET ||
qp->flags & MLX5_IB_QP_UNDERLAY) {
struct mlx5_modify_raw_qp_param raw_qp_param = {};
raw_qp_param.operation = op;
if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT) {
raw_qp_param.rq_q_ctr_id = mibport->cnts.set_id;
raw_qp_param.set_mask |= MLX5_RAW_QP_MOD_SET_RQ_Q_CTR_ID;
}
if (attr_mask & IB_QP_RATE_LIMIT) {
raw_qp_param.rl.rate = attr->rate_limit;
if (ucmd->burst_info.max_burst_sz) {
if (attr->rate_limit &&
MLX5_CAP_QOS(dev->mdev, packet_pacing_burst_bound)) {
raw_qp_param.rl.max_burst_sz =
ucmd->burst_info.max_burst_sz;
} else {
err = -EINVAL;
goto out;
}
}
if (ucmd->burst_info.typical_pkt_sz) {
if (attr->rate_limit &&
MLX5_CAP_QOS(dev->mdev, packet_pacing_typical_size)) {
raw_qp_param.rl.typical_pkt_sz =
ucmd->burst_info.typical_pkt_sz;
} else {
err = -EINVAL;
goto out;
}
}
raw_qp_param.set_mask |= MLX5_RAW_QP_RATE_LIMIT;
}
err = modify_raw_packet_qp(dev, qp, &raw_qp_param, tx_affinity);
} else {
err = mlx5_core_qp_modify(dev->mdev, op, optpar, context,
&base->mqp);
}
if (err)
goto out;
qp->state = new_state;
if (attr_mask & IB_QP_ACCESS_FLAGS)
qp->trans_qp.atomic_rd_en = attr->qp_access_flags;
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
qp->trans_qp.resp_depth = attr->max_dest_rd_atomic;
if (attr_mask & IB_QP_PORT)
qp->port = attr->port_num;
if (attr_mask & IB_QP_ALT_PATH)
qp->trans_qp.alt_port = attr->alt_port_num;
/*
* If we moved a kernel QP to RESET, clean up all old CQ
* entries and reinitialize the QP.
*/
if (new_state == IB_QPS_RESET &&
!ibqp->uobject && ibqp->qp_type != IB_QPT_XRC_TGT) {
mlx5_ib_cq_clean(recv_cq, base->mqp.qpn,
ibqp->srq ? to_msrq(ibqp->srq) : NULL);
if (send_cq != recv_cq)
mlx5_ib_cq_clean(send_cq, base->mqp.qpn, NULL);
qp->rq.head = 0;
qp->rq.tail = 0;
qp->sq.head = 0;
qp->sq.tail = 0;
qp->sq.cur_post = 0;
qp->sq.last_poll = 0;
qp->db.db[MLX5_RCV_DBR] = 0;
qp->db.db[MLX5_SND_DBR] = 0;
}
out:
kfree(context);
return err;
}
Commit Message: IB/mlx5: Fix leaking stack memory to userspace
mlx5_ib_create_qp_resp was never initialized and only the first 4 bytes
were written.
Fixes: 41d902cb7c32 ("RDMA/mlx5: Fix definition of mlx5_ib_create_qp_resp")
Cc: <[email protected]>
Acked-by: Leon Romanovsky <[email protected]>
Signed-off-by: Jason Gunthorpe <[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: sshkey_load_private_type_fd(int fd, int type, const char *passphrase,
struct sshkey **keyp, char **commentp)
{
struct sshbuf *buffer = NULL;
int r;
if (keyp != NULL)
*keyp = NULL;
if ((buffer = sshbuf_new()) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshkey_load_file(fd, buffer)) != 0 ||
(r = sshkey_parse_private_fileblob_type(buffer, type,
passphrase, keyp, commentp)) != 0)
goto out;
/* success */
r = 0;
out:
sshbuf_free(buffer);
return r;
}
Commit Message: use sshbuf_allocate() to pre-allocate the buffer used for loading
keys. This avoids implicit realloc inside the buffer code, which
might theoretically leave fragments of the key on the heap. This
doesn't appear to happen in practice for normal sized keys, but
was observed for novelty oversize ones.
Pointed out by Jann Horn of Project Zero; ok markus@
CWE ID: CWE-320
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 DocumentLoader::DidInstallNewDocument(Document* document) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(content_security_policy_.Release());
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(HTTPNames::X_DNS_Prefetch_Control);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(HTTPNames::Content_Language);
if (!header_content_language.IsEmpty()) {
size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(HTTPNames::Referrer_Policy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
Commit Message: Inherit CSP when self-navigating to local-scheme URL
As the linked bug example shows, we should inherit CSP when we navigate
to a local-scheme URL (even if we are in a main browsing context).
Bug: 799747
Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02
Reviewed-on: https://chromium-review.googlesource.com/c/1234337
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597889}
CWE ID:
Target: 1
Example 2:
Code: void RenderWidgetHostImpl::OnMsgClose() {
Shutdown();
}
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: 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 sig_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg)
{
if(operation == ASN1_OP_NEW_PRE) {
DSA_SIG *sig;
sig = OPENSSL_malloc(sizeof(DSA_SIG));
if (!sig)
{
DSAerr(DSA_F_SIG_CB, ERR_R_MALLOC_FAILURE);
return 0;
}
sig->r = NULL;
sig->s = NULL;
*pval = (ASN1_VALUE *)sig;
return 2;
}
return 1;
}
Commit Message: Fix various certificate fingerprint issues.
By using non-DER or invalid encodings outside the signed portion of a
certificate the fingerprint can be changed without breaking the signature.
Although no details of the signed portion of the certificate can be changed
this can cause problems with some applications: e.g. those using the
certificate fingerprint for blacklists.
1. Reject signatures with non zero unused bits.
If the BIT STRING containing the signature has non zero unused bits reject
the signature. All current signature algorithms require zero unused bits.
2. Check certificate algorithm consistency.
Check the AlgorithmIdentifier inside TBS matches the one in the
certificate signature. NB: this will result in signature failure
errors for some broken certificates.
3. Check DSA/ECDSA signatures use DER.
Reencode DSA/ECDSA signatures and compare with the original received
signature. Return an error if there is a mismatch.
This will reject various cases including garbage after signature
(thanks to Antti Karjalainen and Tuomo Untinen from the Codenomicon CROSS
program for discovering this case) and use of BER or invalid ASN.1 INTEGERs
(negative or with leading zeroes).
CVE-2014-8275
Reviewed-by: Emilia Käsper <[email protected]>
CWE ID: CWE-310
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 vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
{
int i;
VncDisplay *vd = ds->opaque;
struct VncSurface *s = &vd->guest;
h += y;
two 16-pixel blocks but we only mark the first as dirty
*/
w += (x % 16);
x -= (x % 16);
w += (x % 16);
x -= (x % 16);
x = MIN(x, s->ds->width);
y = MIN(y, s->ds->height);
w = MIN(x + w, s->ds->width) - x;
h = MIN(h, s->ds->height);
for (; y < h; y++)
for (i = 0; i < w; i += 16)
void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
int32_t encoding)
{
vnc_write_u16(vs, x);
vnc_write_u16(vs, y);
vnc_write_u16(vs, w);
vnc_write_u16(vs, h);
vnc_write_s32(vs, encoding);
}
void buffer_reserve(Buffer *buffer, size_t len)
{
if ((buffer->capacity - buffer->offset) < len) {
buffer->capacity += (len + 1024);
buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
if (buffer->buffer == NULL) {
fprintf(stderr, "vnc: out of memory\n");
exit(1);
}
}
}
int buffer_empty(Buffer *buffer)
{
return buffer->offset == 0;
}
uint8_t *buffer_end(Buffer *buffer)
{
return buffer->buffer + buffer->offset;
}
void buffer_reset(Buffer *buffer)
{
buffer->offset = 0;
}
void buffer_free(Buffer *buffer)
{
g_free(buffer->buffer);
buffer->offset = 0;
buffer->capacity = 0;
buffer->buffer = NULL;
}
void buffer_append(Buffer *buffer, const void *data, size_t len)
{
memcpy(buffer->buffer + buffer->offset, data, len);
buffer->offset += len;
}
static void vnc_desktop_resize(VncState *vs)
{
DisplayState *ds = vs->ds;
if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
return;
}
if (vs->client_width == ds_get_width(ds) &&
vs->client_height == ds_get_height(ds)) {
return;
}
vs->client_width = ds_get_width(ds);
vs->client_height = ds_get_height(ds);
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1); /* number of rects */
vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
VNC_ENCODING_DESKTOPRESIZE);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void vnc_abort_display_jobs(VncDisplay *vd)
{
VncState *vs;
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_lock_output(vs);
vs->abort = true;
vnc_unlock_output(vs);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_jobs_join(vs);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_lock_output(vs);
vs->abort = false;
vnc_unlock_output(vs);
}
}
}
Commit Message:
CWE ID: CWE-125
Target: 1
Example 2:
Code: ExtensionRegistry::ExtensionRegistry(content::BrowserContext* browser_context)
: browser_context_(browser_context) {}
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: 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 ThresholdMap *GetThresholdMapFile(const char *xml,
const char *filename,const char *map_id,ExceptionInfo *exception)
{
const char
*attribute,
*content;
double
value;
ThresholdMap
*map;
XMLTreeInfo
*description,
*levels,
*threshold,
*thresholds;
map = (ThresholdMap *) NULL;
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *) NULL )
return(map);
for (threshold = GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *) NULL;
threshold = GetNextXMLTreeTag(threshold) )
{
attribute=GetXMLTreeAttribute(threshold, "map");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
attribute=GetXMLTreeAttribute(threshold, "alias");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
}
if (threshold == (XMLTreeInfo *) NULL)
{
thresholds=DestroyXMLTree(thresholds);
return(map);
}
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
levels=GetXMLTreeChild(threshold,"levels");
if (levels == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
/*
The map has been found -- allocate a Threshold Map to return
*/
map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap));
if (map == (ThresholdMap *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
map->map_id=(char *) NULL;
map->description=(char *) NULL;
map->levels=(ssize_t *) NULL;
/*
Assign basic attributeibutes.
*/
attribute=GetXMLTreeAttribute(threshold,"map");
if (attribute != (char *) NULL)
map->map_id=ConstantString(attribute);
content=GetXMLTreeContent(description);
if (content != (char *) NULL)
map->description=ConstantString(content);
attribute=GetXMLTreeAttribute(levels,"width");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->width=StringToUnsignedLong(attribute);
if (map->width == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"height");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels height>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->height=StringToUnsignedLong(attribute);
if (map->height == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels, "divisor");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->divisor=(ssize_t) StringToLong(attribute);
if (map->divisor < 2)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
/*
Allocate theshold levels array.
*/
content=GetXMLTreeContent(levels);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height*
sizeof(*map->levels));
if (map->levels == (ssize_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
{
char
*p;
register ssize_t
i;
/*
Parse levels into integer array.
*/
for (i=0; i< (ssize_t) (map->width*map->height); i++)
{
map->levels[i]=(ssize_t) strtol(content,&p,10);
if (p == content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too few values, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
if ((map->levels[i] < 0) || (map->levels[i] > map->divisor))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> %.20g out of range, map \"%s\"",
(double) map->levels[i],map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=p;
}
value=(double) strtol(content,&p,10);
(void) value;
if (p != content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too many values, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
}
thresholds=DestroyXMLTree(thresholds);
return(map);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1609
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: static int xfrm6_tunnel_rcv(struct sk_buff *skb)
{
struct ipv6hdr *iph = ipv6_hdr(skb);
__be32 spi;
spi = xfrm6_tunnel_spi_lookup((xfrm_address_t *)&iph->saddr);
return xfrm6_rcv_spi(skb, spi);
}
Commit Message: [IPV6]: Fix slab corruption running ip6sic
From: Eric Sesterhenn <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: event_wait(void *eventhdl)
{
struct posix_event *ev = (struct posix_event *)eventhdl;
pthread_mutex_lock(&(ev->mutex));
pthread_cond_wait(&(ev->cond), &(ev->mutex));
pthread_mutex_unlock(&(ev->mutex));
return 1;
}
Commit Message: Check length of memcmp
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: esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (snpal == 6)
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal)));
if (netal != 0)
ND_PRINT((ndo, "\n\t NET (length: %u) %s",
netal,
isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
Commit Message: CVE-2017-13047/ES-IS: put an existing bounds check right
The bounds check in esis_print() tested one pointer at the beginning of
a loop that incremented another, make the trivial fix. While at it, make
the function print a standard marker when it detects truncated data and
update some existing ES-IS tests respectively.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
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 int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np)
{
struct platform_device *pdev = cqspi->pdev;
struct device *dev = &pdev->dev;
struct cqspi_flash_pdata *f_pdata;
struct spi_nor *nor;
struct mtd_info *mtd;
unsigned int cs;
int i, ret;
/* Get flash device data */
for_each_available_child_of_node(dev->of_node, np) {
if (of_property_read_u32(np, "reg", &cs)) {
dev_err(dev, "Couldn't determine chip select.\n");
goto err;
}
if (cs > CQSPI_MAX_CHIPSELECT) {
dev_err(dev, "Chip select %d out of range.\n", cs);
goto err;
}
f_pdata = &cqspi->f_pdata[cs];
f_pdata->cqspi = cqspi;
f_pdata->cs = cs;
ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np);
if (ret)
goto err;
nor = &f_pdata->nor;
mtd = &nor->mtd;
mtd->priv = nor;
nor->dev = dev;
spi_nor_set_flash_node(nor, np);
nor->priv = f_pdata;
nor->read_reg = cqspi_read_reg;
nor->write_reg = cqspi_write_reg;
nor->read = cqspi_read;
nor->write = cqspi_write;
nor->erase = cqspi_erase;
nor->prepare = cqspi_prep;
nor->unprepare = cqspi_unprep;
mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d",
dev_name(dev), cs);
if (!mtd->name) {
ret = -ENOMEM;
goto err;
}
ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD);
if (ret)
goto err;
ret = mtd_device_register(mtd, NULL, 0);
if (ret)
goto err;
f_pdata->registered = true;
}
return 0;
err:
for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++)
if (cqspi->f_pdata[i].registered)
mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd);
return ret;
}
Commit Message: mtd: spi-nor: Off by one in cqspi_setup_flash()
There are CQSPI_MAX_CHIPSELECT elements in the ->f_pdata array so the >
should be >=.
Fixes: 140623410536 ('mtd: spi-nor: Add driver for Cadence Quad SPI Flash Controller')
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: Marek Vasut <[email protected]>
Signed-off-by: Cyrille Pitchen <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void SyncTest::TearDown() {
InProcessBrowserTest::TearDown();
TearDownLocalPythonTestServer();
TearDownLocalTestServer();
}
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
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 Visualizer_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
VisualizerContext * pContext = (VisualizerContext *)self;
int retsize;
if (pContext == NULL || pContext->mState == VISUALIZER_STATE_UNINITIALIZED) {
return -EINVAL;
}
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Visualizer_init(pContext);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Visualizer_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL || replySize == NULL ||
*replySize != sizeof(effect_config_t)) {
return -EINVAL;
}
Visualizer_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Visualizer_reset(pContext);
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pContext->mState != VISUALIZER_STATE_INITIALIZED) {
return -ENOSYS;
}
pContext->mState = VISUALIZER_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pContext->mState != VISUALIZER_STATE_ACTIVE) {
return -ENOSYS;
}
pContext->mState = VISUALIZER_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_GET_PARAM: {
if (pCmdData == NULL ||
cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t)) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t))) {
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(uint32_t));
effect_param_t *p = (effect_param_t *)pReplyData;
p->status = 0;
*replySize = sizeof(effect_param_t) + sizeof(uint32_t);
if (p->psize != sizeof(uint32_t)) {
p->status = -EINVAL;
break;
}
switch (*(uint32_t *)p->data) {
case VISUALIZER_PARAM_CAPTURE_SIZE:
ALOGV("get mCaptureSize = %" PRIu32, pContext->mCaptureSize);
*((uint32_t *)p->data + 1) = pContext->mCaptureSize;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
case VISUALIZER_PARAM_SCALING_MODE:
ALOGV("get mScalingMode = %" PRIu32, pContext->mScalingMode);
*((uint32_t *)p->data + 1) = pContext->mScalingMode;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
case VISUALIZER_PARAM_MEASUREMENT_MODE:
ALOGV("get mMeasurementMode = %" PRIu32, pContext->mMeasurementMode);
*((uint32_t *)p->data + 1) = pContext->mMeasurementMode;
p->vsize = sizeof(uint32_t);
*replySize += sizeof(uint32_t);
break;
default:
p->status = -EINVAL;
}
} break;
case EFFECT_CMD_SET_PARAM: {
if (pCmdData == NULL ||
cmdSize != (int)(sizeof(effect_param_t) + sizeof(uint32_t) + sizeof(uint32_t)) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
return -EINVAL;
}
*(int32_t *)pReplyData = 0;
effect_param_t *p = (effect_param_t *)pCmdData;
if (p->psize != sizeof(uint32_t) || p->vsize != sizeof(uint32_t)) {
*(int32_t *)pReplyData = -EINVAL;
break;
}
switch (*(uint32_t *)p->data) {
case VISUALIZER_PARAM_CAPTURE_SIZE:
pContext->mCaptureSize = *((uint32_t *)p->data + 1);
ALOGV("set mCaptureSize = %" PRIu32, pContext->mCaptureSize);
break;
case VISUALIZER_PARAM_SCALING_MODE:
pContext->mScalingMode = *((uint32_t *)p->data + 1);
ALOGV("set mScalingMode = %" PRIu32, pContext->mScalingMode);
break;
case VISUALIZER_PARAM_LATENCY:
pContext->mLatency = *((uint32_t *)p->data + 1);
ALOGV("set mLatency = %" PRIu32, pContext->mLatency);
break;
case VISUALIZER_PARAM_MEASUREMENT_MODE:
pContext->mMeasurementMode = *((uint32_t *)p->data + 1);
ALOGV("set mMeasurementMode = %" PRIu32, pContext->mMeasurementMode);
break;
default:
*(int32_t *)pReplyData = -EINVAL;
}
} break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_VOLUME:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
case VISUALIZER_CMD_CAPTURE: {
uint32_t captureSize = pContext->mCaptureSize;
if (pReplyData == NULL || replySize == NULL || *replySize != captureSize) {
ALOGV("VISUALIZER_CMD_CAPTURE() error *replySize %" PRIu32 " captureSize %" PRIu32,
*replySize, captureSize);
return -EINVAL;
}
if (pContext->mState == VISUALIZER_STATE_ACTIVE) {
const uint32_t deltaMs = Visualizer_getDeltaTimeMsFromUpdatedTime(pContext);
if ((pContext->mLastCaptureIdx == pContext->mCaptureIdx) &&
(pContext->mBufferUpdateTime.tv_sec != 0) &&
(deltaMs > MAX_STALL_TIME_MS)) {
ALOGV("capture going to idle");
pContext->mBufferUpdateTime.tv_sec = 0;
memset(pReplyData, 0x80, captureSize);
} else {
int32_t latencyMs = pContext->mLatency;
latencyMs -= deltaMs;
if (latencyMs < 0) {
latencyMs = 0;
}
const uint32_t deltaSmpl =
pContext->mConfig.inputCfg.samplingRate * latencyMs / 1000;
int32_t capturePoint = pContext->mCaptureIdx - captureSize - deltaSmpl;
if (capturePoint < 0) {
uint32_t size = -capturePoint;
if (size > captureSize) {
size = captureSize;
}
memcpy(pReplyData,
pContext->mCaptureBuf + CAPTURE_BUF_SIZE + capturePoint,
size);
pReplyData = (char *)pReplyData + size;
captureSize -= size;
capturePoint = 0;
}
memcpy(pReplyData,
pContext->mCaptureBuf + capturePoint,
captureSize);
}
pContext->mLastCaptureIdx = pContext->mCaptureIdx;
} else {
memset(pReplyData, 0x80, captureSize);
}
} break;
case VISUALIZER_CMD_MEASURE: {
if (pReplyData == NULL || replySize == NULL ||
*replySize < (sizeof(int32_t) * MEASUREMENT_COUNT)) {
if (replySize == NULL) {
ALOGV("VISUALIZER_CMD_MEASURE() error replySize NULL");
} else {
ALOGV("VISUALIZER_CMD_MEASURE() error *replySize %" PRIu32
" < (sizeof(int32_t) * MEASUREMENT_COUNT) %" PRIu32,
*replySize,
uint32_t(sizeof(int32_t)) * MEASUREMENT_COUNT);
}
android_errorWriteLog(0x534e4554, "30229821");
return -EINVAL;
}
uint16_t peakU16 = 0;
float sumRmsSquared = 0.0f;
uint8_t nbValidMeasurements = 0;
const int32_t delayMs = Visualizer_getDeltaTimeMsFromUpdatedTime(pContext);
if (delayMs > DISCARD_MEASUREMENTS_TIME_MS) {
ALOGV("Discarding measurements, last measurement is %" PRId32 "ms old", delayMs);
for (uint32_t i=0 ; i<pContext->mMeasurementWindowSizeInBuffers ; i++) {
pContext->mPastMeasurements[i].mIsValid = false;
pContext->mPastMeasurements[i].mPeakU16 = 0;
pContext->mPastMeasurements[i].mRmsSquared = 0;
}
pContext->mMeasurementBufferIdx = 0;
} else {
for (uint32_t i=0 ; i < pContext->mMeasurementWindowSizeInBuffers ; i++) {
if (pContext->mPastMeasurements[i].mIsValid) {
if (pContext->mPastMeasurements[i].mPeakU16 > peakU16) {
peakU16 = pContext->mPastMeasurements[i].mPeakU16;
}
sumRmsSquared += pContext->mPastMeasurements[i].mRmsSquared;
nbValidMeasurements++;
}
}
}
float rms = nbValidMeasurements == 0 ? 0.0f : sqrtf(sumRmsSquared / nbValidMeasurements);
int32_t* pIntReplyData = (int32_t*)pReplyData;
if (rms < 0.000016f) {
pIntReplyData[MEASUREMENT_IDX_RMS] = -9600; //-96dB
} else {
pIntReplyData[MEASUREMENT_IDX_RMS] = (int32_t) (2000 * log10(rms / 32767.0f));
}
if (peakU16 == 0) {
pIntReplyData[MEASUREMENT_IDX_PEAK] = -9600; //-96dB
} else {
pIntReplyData[MEASUREMENT_IDX_PEAK] = (int32_t) (2000 * log10(peakU16 / 32767.0f));
}
ALOGV("VISUALIZER_CMD_MEASURE peak=%" PRIu16 " (%" PRId32 "mB), rms=%.1f (%" PRId32 "mB)",
peakU16, pIntReplyData[MEASUREMENT_IDX_PEAK],
rms, pIntReplyData[MEASUREMENT_IDX_RMS]);
}
break;
default:
ALOGW("Visualizer_command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
return 0;
}
Commit Message: Visualizer: Check capture size and latency parameters
Bug: 31781965
Change-Id: I1c439a0d0f6aa0057b3c651499f28426e1e1f5e4
(cherry picked from commit 9a2732ba0a8d609ab040d2c1ddee28577ead9772)
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 ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al)
{
unsigned short type;
unsigned short size;
unsigned short len;
unsigned char *data = *p;
int renegotiate_seen = 0;
int sigalg_seen = 0;
s->servername_done = 0;
s->tlsext_status_type = -1;
#ifndef OPENSSL_NO_NEXTPROTONEG
s->s3->next_proto_neg_seen = 0;
#endif
#ifndef OPENSSL_NO_HEARTBEATS
s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED |
SSL_TLSEXT_HB_DONT_SEND_REQUESTS);
#endif
#ifndef OPENSSL_NO_EC
if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
ssl_check_for_safari(s, data, d, n);
#endif /* !OPENSSL_NO_EC */
if (data >= (d+n-2))
goto ri_check;
n2s(data,len);
if (data > (d+n-len))
goto ri_check;
while (data <= (d+n-4))
{
n2s(data,type);
n2s(data,size);
if (data+size > (d+n))
goto ri_check;
#if 0
fprintf(stderr,"Received extension type %d size %d\n",type,size);
#endif
if (s->tlsext_debug_cb)
s->tlsext_debug_cb(s, 0, type, data, size,
s->tlsext_debug_arg);
/* The servername extension is treated as follows:
- Only the hostname type is supported with a maximum length of 255.
- The servername is rejected if too long or if it contains zeros,
in which case an fatal alert is generated.
- The servername field is maintained together with the session cache.
- When a session is resumed, the servername call back invoked in order
to allow the application to position itself to the right context.
- The servername is acknowledged if it is new for a session or when
it is identical to a previously used for the same session.
Applications can control the behaviour. They can at any time
set a 'desirable' servername for a new SSL object. This can be the
case for example with HTTPS when a Host: header field is received and
a renegotiation is requested. In this case, a possible servername
presented in the new client hello is only acknowledged if it matches
the value of the Host: field.
- Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
if they provide for changing an explicit servername context for the session,
i.e. when the session has been established with a servername extension.
- On session reconnect, the servername extension may be absent.
*/
if (type == TLSEXT_TYPE_server_name)
{
unsigned char *sdata;
int servname_type;
int dsize;
if (size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(data,dsize);
size -= 2;
if (dsize > size )
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
sdata = data;
while (dsize > 3)
{
servname_type = *(sdata++);
n2s(sdata,len);
dsize -= 3;
if (len > dsize)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->servername_done == 0)
switch (servname_type)
{
case TLSEXT_NAMETYPE_host_name:
if (!s->hit)
{
if(s->session->tlsext_hostname)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (len > TLSEXT_MAXLEN_host_name)
{
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
if ((s->session->tlsext_hostname = OPENSSL_malloc(len+1)) == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
memcpy(s->session->tlsext_hostname, sdata, len);
s->session->tlsext_hostname[len]='\0';
if (strlen(s->session->tlsext_hostname) != len) {
OPENSSL_free(s->session->tlsext_hostname);
s->session->tlsext_hostname = NULL;
*al = TLS1_AD_UNRECOGNIZED_NAME;
return 0;
}
s->servername_done = 1;
}
else
s->servername_done = s->session->tlsext_hostname
&& strlen(s->session->tlsext_hostname) == len
&& strncmp(s->session->tlsext_hostname, (char *)sdata, len) == 0;
break;
default:
break;
}
dsize -= len;
}
if (dsize != 0)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
#ifndef OPENSSL_NO_SRP
else if (type == TLSEXT_TYPE_srp)
{
if (size <= 0 || ((len = data[0])) != (size -1))
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->srp_ctx.login != NULL)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if ((s->srp_ctx.login = OPENSSL_malloc(len+1)) == NULL)
return -1;
memcpy(s->srp_ctx.login, &data[1], len);
s->srp_ctx.login[len]='\0';
if (strlen(s->srp_ctx.login) != len)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
#endif
#ifndef OPENSSL_NO_EC
else if (type == TLSEXT_TYPE_ec_point_formats)
{
unsigned char *sdata = data;
int ecpointformatlist_length = *(sdata++);
if (ecpointformatlist_length != size - 1)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (!s->hit)
{
if(s->session->tlsext_ecpointformatlist)
{
OPENSSL_free(s->session->tlsext_ecpointformatlist);
s->session->tlsext_ecpointformatlist = NULL;
}
s->session->tlsext_ecpointformatlist_length = 0;
if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length;
memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length);
}
#if 0
fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) ", s->session->tlsext_ecpointformatlist_length);
sdata = s->session->tlsext_ecpointformatlist;
for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++)
fprintf(stderr,"%i ",*(sdata++));
fprintf(stderr,"\n");
#endif
}
else if (type == TLSEXT_TYPE_elliptic_curves)
{
unsigned char *sdata = data;
int ellipticcurvelist_length = (*(sdata++) << 8);
ellipticcurvelist_length += (*(sdata++));
if (ellipticcurvelist_length != size - 2 ||
ellipticcurvelist_length < 1)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
if (!s->hit)
{
if(s->session->tlsext_ellipticcurvelist)
{
*al = TLS1_AD_DECODE_ERROR;
return 0;
}
s->session->tlsext_ellipticcurvelist_length = 0;
if ((s->session->tlsext_ellipticcurvelist = OPENSSL_malloc(ellipticcurvelist_length)) == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
s->session->tlsext_ellipticcurvelist_length = ellipticcurvelist_length;
memcpy(s->session->tlsext_ellipticcurvelist, sdata, ellipticcurvelist_length);
}
#if 0
fprintf(stderr,"ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) ", s->session->tlsext_ellipticcurvelist_length);
sdata = s->session->tlsext_ellipticcurvelist;
for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++)
fprintf(stderr,"%i ",*(sdata++));
fprintf(stderr,"\n");
#endif
}
#endif /* OPENSSL_NO_EC */
#ifdef TLSEXT_TYPE_opaque_prf_input
else if (type == TLSEXT_TYPE_opaque_prf_input &&
s->version != DTLS1_VERSION)
{
unsigned char *sdata = data;
if (size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(sdata, s->s3->client_opaque_prf_input_len);
if (s->s3->client_opaque_prf_input_len != size - 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (s->s3->client_opaque_prf_input != NULL) /* shouldn't really happen */
OPENSSL_free(s->s3->client_opaque_prf_input);
if (s->s3->client_opaque_prf_input_len == 0)
s->s3->client_opaque_prf_input = OPENSSL_malloc(1); /* dummy byte just to get non-NULL */
else
s->s3->client_opaque_prf_input = BUF_memdup(sdata, s->s3->client_opaque_prf_input_len);
if (s->s3->client_opaque_prf_input == NULL)
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
#endif
else if (type == TLSEXT_TYPE_session_ticket)
{
if (s->tls_session_ticket_ext_cb &&
!s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg))
{
*al = TLS1_AD_INTERNAL_ERROR;
return 0;
}
}
else if (type == TLSEXT_TYPE_renegotiate)
{
if(!ssl_parse_clienthello_renegotiate_ext(s, data, size, al))
return 0;
renegotiate_seen = 1;
}
else if (type == TLSEXT_TYPE_signature_algorithms)
{
int dsize;
if (sigalg_seen || size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
sigalg_seen = 1;
n2s(data,dsize);
size -= 2;
if (dsize != size || dsize & 1)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (!tls1_process_sigalgs(s, data, dsize))
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
else if (type == TLSEXT_TYPE_status_request &&
s->version != DTLS1_VERSION)
{
if (size < 5)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
s->tlsext_status_type = *data++;
size--;
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp)
{
const unsigned char *sdata;
int dsize;
/* Read in responder_id_list */
n2s(data,dsize);
size -= 2;
if (dsize > size )
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
while (dsize > 0)
{
OCSP_RESPID *id;
int idsize;
if (dsize < 4)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(data, idsize);
dsize -= 2 + idsize;
size -= 2 + idsize;
if (dsize < 0)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
sdata = data;
data += idsize;
id = d2i_OCSP_RESPID(NULL,
&sdata, idsize);
if (!id)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (data != sdata)
{
OCSP_RESPID_free(id);
*al = SSL_AD_DECODE_ERROR;
return 0;
}
if (!s->tlsext_ocsp_ids
&& !(s->tlsext_ocsp_ids =
sk_OCSP_RESPID_new_null()))
{
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
if (!sk_OCSP_RESPID_push(
s->tlsext_ocsp_ids, id))
{
OCSP_RESPID_free(id);
*al = SSL_AD_INTERNAL_ERROR;
return 0;
}
}
/* Read in request_extensions */
if (size < 2)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
n2s(data,dsize);
size -= 2;
if (dsize != size)
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
sdata = data;
if (dsize > 0)
{
if (s->tlsext_ocsp_exts)
{
sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts,
X509_EXTENSION_free);
}
s->tlsext_ocsp_exts =
d2i_X509_EXTENSIONS(NULL,
&sdata, dsize);
if (!s->tlsext_ocsp_exts
|| (data + dsize != sdata))
{
*al = SSL_AD_DECODE_ERROR;
return 0;
}
}
}
/* We don't know what to do with any other type
* so ignore it.
*/
else
s->tlsext_status_type = -1;
}
#ifndef OPENSSL_NO_HEARTBEATS
else if (type == TLSEXT_TYPE_heartbeat)
{
switch(data[0])
{
case 0x01: /* Client allows us to send HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
break;
case 0x02: /* Client doesn't accept HB requests */
s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED;
s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
break;
default: *al = SSL_AD_ILLEGAL_PARAMETER;
return 0;
}
}
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
else if (type == TLSEXT_TYPE_next_proto_neg &&
s->s3->tmp.finish_md_len == 0)
{
/* We shouldn't accept this extension on a
* renegotiation.
*
* s->new_session will be set on renegotiation, but we
* probably shouldn't rely that it couldn't be set on
* the initial renegotation too in certain cases (when
* there's some other reason to disallow resuming an
* earlier session -- the current code won't be doing
* anything like that, but this might change).
* A valid sign that there's been a previous handshake
* in this connection is if s->s3->tmp.finish_md_len >
* 0. (We are talking about a check that will happen
* in the Hello protocol round, well before a new
* Finished message could have been computed.) */
s->s3->next_proto_neg_seen = 1;
}
#endif
/* session ticket processed earlier */
#ifndef OPENSSL_NO_SRTP
else if (type == TLSEXT_TYPE_use_srtp)
{
if(ssl_parse_clienthello_use_srtp_ext(s, data, size,
al))
}
#endif
data+=size;
}
*p = data;
ri_check:
/* Need RI if renegotiating */
if (!renegotiate_seen && s->renegotiate &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
{
*al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT,
SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
return 0;
}
return 1;
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: void Document::RemoveFocusedElementOfSubtree(Node* node,
bool among_children_only) {
if (!focused_element_)
return;
if (!node->isConnected())
return;
bool contains =
node->IsShadowIncludingInclusiveAncestorOf(focused_element_.Get());
if (contains && (focused_element_ != node || !among_children_only))
ClearFocusedElement();
}
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 BiquadDSPKernel::getFrequencyResponse(int nFrequencies,
const float* frequencyHz,
float* magResponse,
float* phaseResponse)
{
bool isGood = nFrequencies > 0 && frequencyHz && magResponse && phaseResponse;
ASSERT(isGood);
if (!isGood)
return;
Vector<float> frequency(nFrequencies);
double nyquist = this->nyquist();
for (int k = 0; k < nFrequencies; ++k)
frequency[k] = narrowPrecisionToFloat(frequencyHz[k] / nyquist);
updateCoefficientsIfNecessary(false, true);
m_biquad.getFrequencyResponse(nFrequencies, frequency.data(), magResponse, phaseResponse);
}
Commit Message: Initialize value since calculateFinalValues may fail to do so.
Fix threading issue where updateCoefficientsIfNecessary was not always
called from the audio thread. This causes the value not to be
initialized.
Thus,
o Initialize the variable to some value, just in case.
o Split updateCoefficientsIfNecessary into two functions with the code
that sets the coefficients pulled out in to the new function
updateCoefficients.
o Simplify updateCoefficientsIfNecessary since useSmoothing was always
true, and forceUpdate is not longer needed.
o Add process lock to prevent the audio thread from updating the
coefficients while they are being read in the main thread. The audio
thread will update them the next time around.
o Make getFrequencyResponse set the lock while reading the
coefficients of the biquad in preparation for computing the
frequency response.
BUG=389219
Review URL: https://codereview.chromium.org/354213002
git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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 ecdsa_sign_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret, key_tries, sign_tries;
int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
mbedtls_mpi *pk = &k, *pr = r;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
ECDSA_RS_ENTER( sig );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
{
/* redirect to our context */
p_sign_tries = &rs_ctx->sig->sign_tries;
p_key_tries = &rs_ctx->sig->key_tries;
pk = &rs_ctx->sig->k;
pr = &rs_ctx->sig->r;
/* jump to current step */
if( rs_ctx->sig->state == ecdsa_sig_mul )
goto mul;
if( rs_ctx->sig->state == ecdsa_sig_modn )
goto modn;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
*p_sign_tries = 0;
do
{
if( *p_sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
*p_key_tries = 0;
do
{
if( *p_key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_mul;
mul:
#endif
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G,
f_rng, p_rng, ECDSA_RS_ECP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_modn;
modn:
#endif
/*
* Accounting for everything up to the end of the loop
* (step 6, but checking now avoids saving e and t)
*/
ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng, p_rng ) );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
mbedtls_mpi_copy( r, pr );
#endif
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
ECDSA_RS_LEAVE( sig );
return( ret );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted
CWE ID: CWE-200
Target: 1
Example 2:
Code: ScopedAvoidIdentityHashForTesting::ScopedAvoidIdentityHashForTesting(
content::V8ValueConverterImpl* converter)
: converter_(converter) {
CHECK(converter_);
converter_->avoid_identity_hash_for_testing_ = true;
}
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: static void disk_seqf_stop(struct seq_file *seqf, void *v)
{
struct class_dev_iter *iter = seqf->private;
/* stop is called even after start failed :-( */
if (iter) {
class_dev_iter_exit(iter);
kfree(iter);
}
}
Commit Message: block: fix use-after-free in seq file
I got a KASAN report of use-after-free:
==================================================================
BUG: KASAN: use-after-free in klist_iter_exit+0x61/0x70 at addr ffff8800b6581508
Read of size 8 by task trinity-c1/315
=============================================================================
BUG kmalloc-32 (Not tainted): kasan: bad access detected
-----------------------------------------------------------------------------
Disabling lock debugging due to kernel taint
INFO: Allocated in disk_seqf_start+0x66/0x110 age=144 cpu=1 pid=315
___slab_alloc+0x4f1/0x520
__slab_alloc.isra.58+0x56/0x80
kmem_cache_alloc_trace+0x260/0x2a0
disk_seqf_start+0x66/0x110
traverse+0x176/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
INFO: Freed in disk_seqf_stop+0x42/0x50 age=160 cpu=1 pid=315
__slab_free+0x17a/0x2c0
kfree+0x20a/0x220
disk_seqf_stop+0x42/0x50
traverse+0x3b5/0x860
seq_read+0x7e3/0x11a0
proc_reg_read+0xbc/0x180
do_loop_readv_writev+0x134/0x210
do_readv_writev+0x565/0x660
vfs_readv+0x67/0xa0
do_preadv+0x126/0x170
SyS_preadv+0xc/0x10
do_syscall_64+0x1a1/0x460
return_from_SYSCALL_64+0x0/0x6a
CPU: 1 PID: 315 Comm: trinity-c1 Tainted: G B 4.7.0+ #62
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Ubuntu-1.8.2-1ubuntu1 04/01/2014
ffffea0002d96000 ffff880119b9f918 ffffffff81d6ce81 ffff88011a804480
ffff8800b6581500 ffff880119b9f948 ffffffff8146c7bd ffff88011a804480
ffffea0002d96000 ffff8800b6581500 fffffffffffffff4 ffff880119b9f970
Call Trace:
[<ffffffff81d6ce81>] dump_stack+0x65/0x84
[<ffffffff8146c7bd>] print_trailer+0x10d/0x1a0
[<ffffffff814704ff>] object_err+0x2f/0x40
[<ffffffff814754d1>] kasan_report_error+0x221/0x520
[<ffffffff8147590e>] __asan_report_load8_noabort+0x3e/0x40
[<ffffffff83888161>] klist_iter_exit+0x61/0x70
[<ffffffff82404389>] class_dev_iter_exit+0x9/0x10
[<ffffffff81d2e8ea>] disk_seqf_stop+0x3a/0x50
[<ffffffff8151f812>] seq_read+0x4b2/0x11a0
[<ffffffff815f8fdc>] proc_reg_read+0xbc/0x180
[<ffffffff814b24e4>] do_loop_readv_writev+0x134/0x210
[<ffffffff814b4c45>] do_readv_writev+0x565/0x660
[<ffffffff814b8a17>] vfs_readv+0x67/0xa0
[<ffffffff814b8de6>] do_preadv+0x126/0x170
[<ffffffff814b92ec>] SyS_preadv+0xc/0x10
This problem can occur in the following situation:
open()
- pread()
- .seq_start()
- iter = kmalloc() // succeeds
- seqf->private = iter
- .seq_stop()
- kfree(seqf->private)
- pread()
- .seq_start()
- iter = kmalloc() // fails
- .seq_stop()
- class_dev_iter_exit(seqf->private) // boom! old pointer
As the comment in disk_seqf_stop() says, stop is called even if start
failed, so we need to reinitialise the private pointer to NULL when seq
iteration stops.
An alternative would be to set the private pointer to NULL when the
kmalloc() in disk_seqf_start() fails.
Cc: [email protected]
Signed-off-by: Vegard Nossum <[email protected]>
Acked-by: Tejun Heo <[email protected]>
Signed-off-by: Jens Axboe <[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: static bool svc_rdma_prealloc_maps(struct svcxprt_rdma *xprt)
{
unsigned int i;
/* One for each receive buffer on this connection. */
i = xprt->sc_max_requests;
while (i--) {
struct svc_rdma_req_map *map;
map = alloc_req_map(GFP_KERNEL);
if (!map) {
dprintk("svcrdma: No memory for request map\n");
return false;
}
list_add(&map->free, &xprt->sc_maps);
}
return true;
}
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: static void tg3_init_coal(struct tg3 *tp)
{
struct ethtool_coalesce *ec = &tp->coal;
memset(ec, 0, sizeof(*ec));
ec->cmd = ETHTOOL_GCOALESCE;
ec->rx_coalesce_usecs = LOW_RXCOL_TICKS;
ec->tx_coalesce_usecs = LOW_TXCOL_TICKS;
ec->rx_max_coalesced_frames = LOW_RXMAX_FRAMES;
ec->tx_max_coalesced_frames = LOW_TXMAX_FRAMES;
ec->rx_coalesce_usecs_irq = DEFAULT_RXCOAL_TICK_INT;
ec->tx_coalesce_usecs_irq = DEFAULT_TXCOAL_TICK_INT;
ec->rx_max_coalesced_frames_irq = DEFAULT_RXCOAL_MAXF_INT;
ec->tx_max_coalesced_frames_irq = DEFAULT_TXCOAL_MAXF_INT;
ec->stats_block_coalesce_usecs = DEFAULT_STAT_COAL_TICKS;
if (tp->coalesce_mode & (HOSTCC_MODE_CLRTICK_RXBD |
HOSTCC_MODE_CLRTICK_TXBD)) {
ec->rx_coalesce_usecs = LOW_RXCOL_TICKS_CLRTCKS;
ec->rx_coalesce_usecs_irq = DEFAULT_RXCOAL_TICK_INT_CLRTCKS;
ec->tx_coalesce_usecs = LOW_TXCOL_TICKS_CLRTCKS;
ec->tx_coalesce_usecs_irq = DEFAULT_TXCOAL_TICK_INT_CLRTCKS;
}
if (tg3_flag(tp, 5705_PLUS)) {
ec->rx_coalesce_usecs_irq = 0;
ec->tx_coalesce_usecs_irq = 0;
ec->stats_block_coalesce_usecs = 0;
}
}
Commit Message: tg3: fix length overflow in VPD firmware parsing
Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version
when present") introduced VPD parsing that contained a potential length
overflow.
Limit the hardware's reported firmware string length (max 255 bytes) to
stay inside the driver's firmware string length (32 bytes). On overflow,
truncate the formatted firmware string instead of potentially overwriting
portions of the tg3 struct.
http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf
Signed-off-by: Kees Cook <[email protected]>
Reported-by: Oded Horovitz <[email protected]>
Reported-by: Brad Spengler <[email protected]>
Cc: [email protected]
Cc: Matt Carlson <[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: static int au1200fb_drv_resume(struct device *dev)
{
struct au1200fb_platdata *pd = dev_get_drvdata(dev);
struct fb_info *fbi;
int i;
/* Kickstart the panel */
au1200_setpanel(panel, pd);
for (i = 0; i < device_count; i++) {
fbi = _au1200fb_infos[i];
au1200fb_fb_set_par(fbi);
}
return 0;
}
Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls
Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that
really should use the vm_iomap_memory() helper. This trivially converts
two of them to the helper, and comments about why the third one really
needs to continue to use remap_pfn_range(), and adds the missing size
check.
Reported-by: Nico Golde <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[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: bool WebPagePrivate::dispatchTouchEventToFullScreenPlugin(PluginView* plugin, const Platform::TouchEvent& event)
{
if (!event.neverHadMultiTouch())
return false;
if (event.isDoubleTap() || event.isTouchHold() || event.m_type == Platform::TouchEvent::TouchCancel) {
NPTouchEvent npTouchEvent;
if (event.isDoubleTap())
npTouchEvent.type = TOUCH_EVENT_DOUBLETAP;
else if (event.isTouchHold())
npTouchEvent.type = TOUCH_EVENT_TOUCHHOLD;
else if (event.m_type == Platform::TouchEvent::TouchCancel)
npTouchEvent.type = TOUCH_EVENT_CANCEL;
npTouchEvent.points = 0;
npTouchEvent.size = event.m_points.size();
if (npTouchEvent.size) {
npTouchEvent.points = new NPTouchPoint[npTouchEvent.size];
for (int i = 0; i < npTouchEvent.size; i++) {
npTouchEvent.points[i].touchId = event.m_points[i].m_id;
npTouchEvent.points[i].clientX = event.m_points[i].m_screenPos.x();
npTouchEvent.points[i].clientY = event.m_points[i].m_screenPos.y();
npTouchEvent.points[i].screenX = event.m_points[i].m_screenPos.x();
npTouchEvent.points[i].screenY = event.m_points[i].m_screenPos.y();
npTouchEvent.points[i].pageX = event.m_points[i].m_pos.x();
npTouchEvent.points[i].pageY = event.m_points[i].m_pos.y();
}
}
NPEvent npEvent;
npEvent.type = NP_TouchEvent;
npEvent.data = &npTouchEvent;
plugin->dispatchFullScreenNPEvent(npEvent);
delete[] npTouchEvent.points;
return true;
}
dispatchTouchPointAsMouseEventToFullScreenPlugin(plugin, event.m_points[0]);
return true;
}
Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API
https://bugs.webkit.org/show_bug.cgi?id=105143
RIM PR 171941
Reviewed by Rob Buis.
Internally reviewed by George Staikos.
Source/WebCore:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit.
Also adapt to new method names and encapsulation of TouchPoint data
members.
No change in behavior, no new tests.
* platform/blackberry/PlatformTouchPointBlackBerry.cpp:
(WebCore::PlatformTouchPoint::PlatformTouchPoint):
Source/WebKit/blackberry:
TouchPoint instances now provide document coordinates for the viewport
and content position of the touch event. The pixel coordinates stored
in the TouchPoint should no longer be needed in WebKit. One exception
is when passing events to a full screen plugin.
Also adapt to new method names and encapsulation of TouchPoint data
members.
* Api/WebPage.cpp:
(BlackBerry::WebKit::WebPage::touchEvent):
(BlackBerry::WebKit::WebPage::touchPointAsMouseEvent):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin):
(BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin):
* WebKitSupport/InputHandler.cpp:
(BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint):
* WebKitSupport/InputHandler.h:
(InputHandler):
* WebKitSupport/TouchEventHandler.cpp:
(BlackBerry::WebKit::TouchEventHandler::doFatFingers):
(BlackBerry::WebKit::TouchEventHandler::handleTouchPoint):
* WebKitSupport/TouchEventHandler.h:
(TouchEventHandler):
Tools:
Adapt to new method names and encapsulation of TouchPoint data members.
* DumpRenderTree/blackberry/EventSender.cpp:
(addTouchPointCallback):
(updateTouchPointCallback):
(touchEndCallback):
(releaseTouchPointCallback):
(sendTouchEvent):
git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 1
Example 2:
Code: FakeVoiceInteractionController* voice_interaction_controller() {
return voice_interaction_controller_.get();
}
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: PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(RenderStyle* style) const
{
if (style->filter().operations().isEmpty())
return cssValuePool().createIdentifierValue(CSSValueNone);
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
RefPtr<WebKitCSSFilterValue> filterValue;
Vector<RefPtr<FilterOperation> >::const_iterator end = style->filter().operations().end();
for (Vector<RefPtr<FilterOperation> >::const_iterator it = style->filter().operations().begin(); it != end; ++it) {
FilterOperation* filterOperation = (*it).get();
switch (filterOperation->getOperationType()) {
case FilterOperation::REFERENCE: {
ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::ReferenceFilterOperation);
filterValue->append(cssValuePool().createValue(referenceOperation->reference(), CSSPrimitiveValue::CSS_STRING));
break;
}
case FilterOperation::GRAYSCALE: {
BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::GrayscaleFilterOperation);
filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
}
case FilterOperation::SEPIA: {
BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::SepiaFilterOperation);
filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
}
case FilterOperation::SATURATE: {
BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::SaturateFilterOperation);
filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
}
case FilterOperation::HUE_ROTATE: {
BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::HueRotateFilterOperation);
filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_DEG));
break;
}
case FilterOperation::INVERT: {
BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::InvertFilterOperation);
filterValue->append(cssValuePool().createValue(componentTransferOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
}
case FilterOperation::OPACITY: {
BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::OpacityFilterOperation);
filterValue->append(cssValuePool().createValue(componentTransferOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
}
case FilterOperation::BRIGHTNESS: {
BasicComponentTransferFilterOperation* brightnessOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::BrightnessFilterOperation);
filterValue->append(cssValuePool().createValue(brightnessOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
}
case FilterOperation::CONTRAST: {
BasicComponentTransferFilterOperation* contrastOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::ContrastFilterOperation);
filterValue->append(cssValuePool().createValue(contrastOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
}
case FilterOperation::BLUR: {
BlurFilterOperation* blurOperation = static_cast<BlurFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::BlurFilterOperation);
filterValue->append(zoomAdjustedPixelValue(blurOperation->stdDeviation().value(), style));
break;
}
case FilterOperation::DROP_SHADOW: {
DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::DropShadowFilterOperation);
ShadowData shadowData = ShadowData(dropShadowOperation->location(), dropShadowOperation->stdDeviation(), 0, Normal, false, dropShadowOperation->color());
filterValue->append(valueForShadow(&shadowData, CSSPropertyTextShadow, style));
break;
}
#if ENABLE(CSS_SHADERS)
case FilterOperation::CUSTOM: {
CustomFilterOperation* customOperation = static_cast<CustomFilterOperation*>(filterOperation);
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::CustomFilterOperation);
ASSERT(customOperation->program());
StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customOperation->program());
RefPtr<CSSValueList> shadersList = CSSValueList::createSpaceSeparated();
if (program->vertexShader())
shadersList->append(program->vertexShader()->cssValue());
else
shadersList->append(cssValuePool().createIdentifierValue(CSSValueNone));
if (program->fragmentShader())
shadersList->append(program->fragmentShader()->cssValue());
else
shadersList->append(cssValuePool().createIdentifierValue(CSSValueNone));
filterValue->append(shadersList.release());
RefPtr<CSSValueList> meshParameters = CSSValueList::createSpaceSeparated();
meshParameters->append(cssValuePool().createValue(customOperation->meshRows(), CSSPrimitiveValue::CSS_NUMBER));
meshParameters->append(cssValuePool().createValue(customOperation->meshColumns(), CSSPrimitiveValue::CSS_NUMBER));
meshParameters->append(cssValuePool().createValue(customOperation->meshBoxType()));
if (customOperation->meshType() == CustomFilterOperation::DETACHED)
meshParameters->append(cssValuePool().createIdentifierValue(CSSValueDetached));
filterValue->append(meshParameters.release());
const CustomFilterParameterList& parameters = customOperation->parameters();
size_t parametersSize = parameters.size();
if (!parametersSize)
break;
RefPtr<CSSValueList> parametersCSSValue = CSSValueList::createCommaSeparated();
for (size_t i = 0; i < parametersSize; ++i) {
const CustomFilterParameter* parameter = parameters.at(i).get();
RefPtr<CSSValueList> parameterCSSNameAndValue = CSSValueList::createSpaceSeparated();
parameterCSSNameAndValue->append(cssValuePool().createValue(parameter->name(), CSSPrimitiveValue::CSS_STRING));
parameterCSSNameAndValue->append(valueForCustomFilterParameter(parameter));
parametersCSSValue->append(parameterCSSNameAndValue.release());
}
filterValue->append(parametersCSSValue.release());
break;
}
#endif
default:
filterValue = WebKitCSSFilterValue::create(WebKitCSSFilterValue::UnknownFilterOperation);
break;
}
list->append(filterValue);
}
return list.release();
}
Commit Message: Rename isPositioned to isOutOfFlowPositioned for clarity
https://bugs.webkit.org/show_bug.cgi?id=89836
Reviewed by Antti Koivisto.
RenderObject and RenderStyle had an isPositioned() method that was
confusing, because it excluded relative positioning. Rename to
isOutOfFlowPositioned(), which makes it clearer that it only applies
to absolute and fixed positioning.
Simple rename; no behavior change.
Source/WebCore:
* css/CSSComputedStyleDeclaration.cpp:
(WebCore::getPositionOffsetValue):
* css/StyleResolver.cpp:
(WebCore::StyleResolver::collectMatchingRulesForList):
* dom/Text.cpp:
(WebCore::Text::rendererIsNeeded):
* editing/DeleteButtonController.cpp:
(WebCore::isDeletableElement):
* editing/TextIterator.cpp:
(WebCore::shouldEmitNewlinesBeforeAndAfterNode):
* rendering/AutoTableLayout.cpp:
(WebCore::shouldScaleColumns):
* rendering/InlineFlowBox.cpp:
(WebCore::InlineFlowBox::addToLine):
(WebCore::InlineFlowBox::placeBoxesInInlineDirection):
(WebCore::InlineFlowBox::requiresIdeographicBaseline):
(WebCore::InlineFlowBox::adjustMaxAscentAndDescent):
(WebCore::InlineFlowBox::computeLogicalBoxHeights):
(WebCore::InlineFlowBox::placeBoxesInBlockDirection):
(WebCore::InlineFlowBox::flipLinesInBlockDirection):
(WebCore::InlineFlowBox::computeOverflow):
(WebCore::InlineFlowBox::computeOverAnnotationAdjustment):
(WebCore::InlineFlowBox::computeUnderAnnotationAdjustment):
* rendering/InlineIterator.h:
(WebCore::isIteratorTarget):
* rendering/LayoutState.cpp:
(WebCore::LayoutState::LayoutState):
* rendering/RenderBlock.cpp:
(WebCore::RenderBlock::MarginInfo::MarginInfo):
(WebCore::RenderBlock::styleWillChange):
(WebCore::RenderBlock::styleDidChange):
(WebCore::RenderBlock::addChildToContinuation):
(WebCore::RenderBlock::addChildToAnonymousColumnBlocks):
(WebCore::RenderBlock::containingColumnsBlock):
(WebCore::RenderBlock::columnsBlockForSpanningElement):
(WebCore::RenderBlock::addChildIgnoringAnonymousColumnBlocks):
(WebCore::getInlineRun):
(WebCore::RenderBlock::isSelfCollapsingBlock):
(WebCore::RenderBlock::layoutBlock):
(WebCore::RenderBlock::addOverflowFromBlockChildren):
(WebCore::RenderBlock::expandsToEncloseOverhangingFloats):
(WebCore::RenderBlock::handlePositionedChild):
(WebCore::RenderBlock::moveRunInUnderSiblingBlockIfNeeded):
(WebCore::RenderBlock::collapseMargins):
(WebCore::RenderBlock::clearFloatsIfNeeded):
(WebCore::RenderBlock::simplifiedNormalFlowLayout):
(WebCore::RenderBlock::isSelectionRoot):
(WebCore::RenderBlock::blockSelectionGaps):
(WebCore::RenderBlock::clearFloats):
(WebCore::RenderBlock::markAllDescendantsWithFloatsForLayout):
(WebCore::RenderBlock::markSiblingsWithFloatsForLayout):
(WebCore::isChildHitTestCandidate):
(WebCore::InlineMinMaxIterator::next):
(WebCore::RenderBlock::computeBlockPreferredLogicalWidths):
(WebCore::RenderBlock::firstLineBoxBaseline):
(WebCore::RenderBlock::lastLineBoxBaseline):
(WebCore::RenderBlock::updateFirstLetter):
(WebCore::shouldCheckLines):
(WebCore::getHeightForLineCount):
(WebCore::RenderBlock::adjustForBorderFit):
(WebCore::inNormalFlow):
(WebCore::RenderBlock::adjustLinePositionForPagination):
(WebCore::RenderBlock::adjustBlockChildForPagination):
(WebCore::RenderBlock::renderName):
* rendering/RenderBlock.h:
(WebCore::RenderBlock::shouldSkipCreatingRunsForObject):
* rendering/RenderBlockLineLayout.cpp:
(WebCore::RenderBlock::setMarginsForRubyRun):
(WebCore::RenderBlock::computeInlineDirectionPositionsForLine):
(WebCore::RenderBlock::computeBlockDirectionPositionsForLine):
(WebCore::RenderBlock::layoutInlineChildren):
(WebCore::requiresLineBox):
(WebCore::RenderBlock::LineBreaker::skipTrailingWhitespace):
(WebCore::RenderBlock::LineBreaker::skipLeadingWhitespace):
(WebCore::RenderBlock::LineBreaker::nextLineBreak):
* rendering/RenderBox.cpp:
(WebCore::RenderBox::removeFloatingOrPositionedChildFromBlockLists):
(WebCore::RenderBox::styleWillChange):
(WebCore::RenderBox::styleDidChange):
(WebCore::RenderBox::updateBoxModelInfoFromStyle):
(WebCore::RenderBox::offsetFromContainer):
(WebCore::RenderBox::positionLineBox):
(WebCore::RenderBox::computeRectForRepaint):
(WebCore::RenderBox::computeLogicalWidthInRegion):
(WebCore::RenderBox::renderBoxRegionInfo):
(WebCore::RenderBox::computeLogicalHeight):
(WebCore::RenderBox::computePercentageLogicalHeight):
(WebCore::RenderBox::computeReplacedLogicalWidthUsing):
(WebCore::RenderBox::computeReplacedLogicalHeightUsing):
(WebCore::RenderBox::availableLogicalHeightUsing):
(WebCore::percentageLogicalHeightIsResolvable):
* rendering/RenderBox.h:
(WebCore::RenderBox::stretchesToViewport):
(WebCore::RenderBox::isDeprecatedFlexItem):
* rendering/RenderBoxModelObject.cpp:
(WebCore::RenderBoxModelObject::adjustedPositionRelativeToOffsetParent):
(WebCore::RenderBoxModelObject::mapAbsoluteToLocalPoint):
* rendering/RenderBoxModelObject.h:
(WebCore::RenderBoxModelObject::requiresLayer):
* rendering/RenderDeprecatedFlexibleBox.cpp:
(WebCore::childDoesNotAffectWidthOrFlexing):
(WebCore::RenderDeprecatedFlexibleBox::layoutBlock):
(WebCore::RenderDeprecatedFlexibleBox::layoutHorizontalBox):
(WebCore::RenderDeprecatedFlexibleBox::layoutVerticalBox):
(WebCore::RenderDeprecatedFlexibleBox::renderName):
* rendering/RenderFieldset.cpp:
(WebCore::RenderFieldset::findLegend):
* rendering/RenderFlexibleBox.cpp:
(WebCore::RenderFlexibleBox::computePreferredLogicalWidths):
(WebCore::RenderFlexibleBox::autoMarginOffsetInMainAxis):
(WebCore::RenderFlexibleBox::availableAlignmentSpaceForChild):
(WebCore::RenderFlexibleBox::computeMainAxisPreferredSizes):
(WebCore::RenderFlexibleBox::computeNextFlexLine):
(WebCore::RenderFlexibleBox::resolveFlexibleLengths):
(WebCore::RenderFlexibleBox::prepareChildForPositionedLayout):
(WebCore::RenderFlexibleBox::layoutAndPlaceChildren):
(WebCore::RenderFlexibleBox::layoutColumnReverse):
(WebCore::RenderFlexibleBox::adjustAlignmentForChild):
(WebCore::RenderFlexibleBox::flipForRightToLeftColumn):
* rendering/RenderGrid.cpp:
(WebCore::RenderGrid::renderName):
* rendering/RenderImage.cpp:
(WebCore::RenderImage::computeIntrinsicRatioInformation):
* rendering/RenderInline.cpp:
(WebCore::RenderInline::addChildIgnoringContinuation):
(WebCore::RenderInline::addChildToContinuation):
(WebCore::RenderInline::generateCulledLineBoxRects):
(WebCore):
(WebCore::RenderInline::culledInlineFirstLineBox):
(WebCore::RenderInline::culledInlineLastLineBox):
(WebCore::RenderInline::culledInlineVisualOverflowBoundingBox):
(WebCore::RenderInline::computeRectForRepaint):
(WebCore::RenderInline::dirtyLineBoxes):
* rendering/RenderLayer.cpp:
(WebCore::checkContainingBlockChainForPagination):
(WebCore::RenderLayer::updateLayerPosition):
(WebCore::isPositionedContainer):
(WebCore::RenderLayer::calculateClipRects):
(WebCore::RenderLayer::shouldBeNormalFlowOnly):
* rendering/RenderLayerCompositor.cpp:
(WebCore::RenderLayerCompositor::requiresCompositingForPosition):
* rendering/RenderLineBoxList.cpp:
(WebCore::RenderLineBoxList::dirtyLinesFromChangedChild):
* rendering/RenderListItem.cpp:
(WebCore::getParentOfFirstLineBox):
* rendering/RenderMultiColumnBlock.cpp:
(WebCore::RenderMultiColumnBlock::renderName):
* rendering/RenderObject.cpp:
(WebCore::RenderObject::markContainingBlocksForLayout):
(WebCore::RenderObject::setPreferredLogicalWidthsDirty):
(WebCore::RenderObject::invalidateContainerPreferredLogicalWidths):
(WebCore::RenderObject::styleWillChange):
(WebCore::RenderObject::offsetParent):
* rendering/RenderObject.h:
(WebCore::RenderObject::isOutOfFlowPositioned):
(WebCore::RenderObject::isInFlowPositioned):
(WebCore::RenderObject::hasClip):
(WebCore::RenderObject::isFloatingOrOutOfFlowPositioned):
* rendering/RenderObjectChildList.cpp:
(WebCore::RenderObjectChildList::removeChildNode):
* rendering/RenderReplaced.cpp:
(WebCore::hasAutoHeightOrContainingBlockWithAutoHeight):
* rendering/RenderRubyRun.cpp:
(WebCore::RenderRubyRun::rubyText):
* rendering/RenderTable.cpp:
(WebCore::RenderTable::addChild):
(WebCore::RenderTable::computeLogicalWidth):
(WebCore::RenderTable::layout):
* rendering/style/RenderStyle.h:
Source/WebKit/blackberry:
* Api/WebPage.cpp:
(BlackBerry::WebKit::isPositionedContainer):
(BlackBerry::WebKit::isNonRenderViewFixedPositionedContainer):
(BlackBerry::WebKit::isFixedPositionedContainer):
Source/WebKit2:
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::updateOffsetFromViewportForSelf):
git-svn-id: svn://svn.chromium.org/blink/trunk@121123 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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: const service_manager::Manifest& GetChromeContentBrowserOverlayManifest() {
static base::NoDestructor<service_manager::Manifest> manifest {
service_manager::ManifestBuilder()
.ExposeCapability("gpu",
service_manager::Manifest::InterfaceList<
metrics::mojom::CallStackProfileCollector>())
.ExposeCapability("renderer",
service_manager::Manifest::InterfaceList<
chrome::mojom::AvailableOfflineContentProvider,
chrome::mojom::CacheStatsRecorder,
chrome::mojom::NetBenchmarking,
data_reduction_proxy::mojom::DataReductionProxy,
metrics::mojom::CallStackProfileCollector,
#if defined(OS_WIN)
mojom::ModuleEventSink,
#endif
rappor::mojom::RapporRecorder,
safe_browsing::mojom::SafeBrowsing>())
.RequireCapability("ash", "system_ui")
.RequireCapability("ash", "test")
.RequireCapability("ash", "display")
.RequireCapability("assistant", "assistant")
.RequireCapability("assistant_audio_decoder", "assistant:audio_decoder")
.RequireCapability("chrome", "input_device_controller")
.RequireCapability("chrome_printing", "converter")
.RequireCapability("cups_ipp_parser", "ipp_parser")
.RequireCapability("device", "device:fingerprint")
.RequireCapability("device", "device:geolocation_config")
.RequireCapability("device", "device:geolocation_control")
.RequireCapability("device", "device:ip_geolocator")
.RequireCapability("ime", "input_engine")
.RequireCapability("mirroring", "mirroring")
.RequireCapability("nacl_broker", "browser")
.RequireCapability("nacl_loader", "browser")
.RequireCapability("noop", "noop")
.RequireCapability("patch", "patch_file")
.RequireCapability("preferences", "pref_client")
.RequireCapability("preferences", "pref_control")
.RequireCapability("profile_import", "import")
.RequireCapability("removable_storage_writer",
"removable_storage_writer")
.RequireCapability("secure_channel", "secure_channel")
.RequireCapability("ui", "ime_registrar")
.RequireCapability("ui", "input_device_controller")
.RequireCapability("ui", "window_manager")
.RequireCapability("unzip", "unzip_file")
.RequireCapability("util_win", "util_win")
.RequireCapability("xr_device_service", "xr_device_provider")
.RequireCapability("xr_device_service", "xr_device_test_hook")
#if defined(OS_CHROMEOS)
.RequireCapability("multidevice_setup", "multidevice_setup")
#endif
.ExposeInterfaceFilterCapability_Deprecated(
"navigation:frame", "renderer",
service_manager::Manifest::InterfaceList<
autofill::mojom::AutofillDriver,
autofill::mojom::PasswordManagerDriver,
chrome::mojom::OfflinePageAutoFetcher,
#if defined(OS_CHROMEOS)
chromeos_camera::mojom::CameraAppHelper,
chromeos::cellular_setup::mojom::CellularSetup,
chromeos::crostini_installer::mojom::PageHandlerFactory,
chromeos::crostini_upgrader::mojom::PageHandlerFactory,
chromeos::ime::mojom::InputEngineManager,
chromeos::machine_learning::mojom::PageHandler,
chromeos::media_perception::mojom::MediaPerception,
chromeos::multidevice_setup::mojom::MultiDeviceSetup,
chromeos::multidevice_setup::mojom::PrivilegedHostDeviceSetter,
chromeos::network_config::mojom::CrosNetworkConfig,
cros::mojom::CameraAppDeviceProvider,
#endif
contextual_search::mojom::ContextualSearchJsApiService,
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::KeepAlive,
#endif
media::mojom::MediaEngagementScoreDetailsProvider,
media_router::mojom::MediaRouter,
page_load_metrics::mojom::PageLoadMetrics,
translate::mojom::ContentTranslateDriver,
downloads::mojom::PageHandlerFactory,
feed_internals::mojom::PageHandler,
new_tab_page::mojom::PageHandlerFactory,
#if defined(OS_ANDROID)
explore_sites_internals::mojom::PageHandler,
#else
app_management::mojom::PageHandlerFactory,
#endif
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
defined(OS_CHROMEOS)
discards::mojom::DetailsProvider, discards::mojom::GraphDump,
#endif
#if defined(OS_CHROMEOS)
add_supervision::mojom::AddSupervisionHandler,
#endif
mojom::BluetoothInternalsHandler,
mojom::InterventionsInternalsPageHandler,
mojom::OmniboxPageHandler, mojom::ResetPasswordHandler,
mojom::SiteEngagementDetailsProvider,
mojom::UsbInternalsPageHandler,
snippets_internals::mojom::PageHandlerFactory>())
.PackageService(prefs::GetManifest())
#if defined(OS_CHROMEOS)
.PackageService(chromeos::multidevice_setup::GetManifest())
#endif // defined(OS_CHROMEOS)
.Build()
};
return *manifest;
}
Commit Message: Revert "Creates a WebUI-based Crostini Upgrader"
This reverts commit 29c8bb394dd8b8c03e006efb39ec77fc42f96900.
Reason for revert:
Findit (https://goo.gl/kROfz5) identified CL at revision 717476 as the
culprit for failures in the build cycles as shown on:
https://analysis.chromium.org/waterfall/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyRAsSDVdmU3VzcGVjdGVkQ0wiMWNocm9taXVtLzI5YzhiYjM5NGRkOGI4YzAzZTAwNmVmYjM5ZWM3N2ZjNDJmOTY5MDAM
Sample Failed Build: https://ci.chromium.org/b/8896211200981346592
Sample Failed Step: compile
Original change's description:
> Creates a WebUI-based Crostini Upgrader
>
> The UI is behind the new crostini-webui-upgrader flag
> (currently disabled by default)
>
> The main areas for review are
>
> calamity@:
> html/js - chrome/browser/chromeos/crostini_upgrader/
> mojo and webui glue classes - chrome/browser/ui/webui/crostini_upgrader/
>
> davidmunro@
> crostini business logic - chrome/browser/chromeos/crostini/
>
> In this CL, the optional container backup stage is stubbed, and will be
> in a subsequent CL.
>
> A suite of unit/browser tests are also currently lacking. I intend them for
> follow-up CLs.
>
>
> Bug: 930901
> Change-Id: Ic52c5242e6c57232ffa6be5d6af65aaff5e8f4ff
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1900520
> Commit-Queue: Nicholas Verne <[email protected]>
> Reviewed-by: Sam McNally <[email protected]>
> Reviewed-by: calamity <[email protected]>
> Reviewed-by: Ken Rockot <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#717476}
Change-Id: I704f549216a7d1dc21942fbf6cf4ab9a1d600380
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 930901
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1928159
Cr-Commit-Position: refs/heads/master@{#717481}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void WebContentsImpl::CreateNewWidget(int32_t render_process_id,
int32_t route_id,
blink::WebPopupType popup_type) {
CreateNewWidget(render_process_id, route_id, false, popup_type);
}
Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted
BUG=583718
Review URL: https://codereview.chromium.org/1685343004
Cr-Commit-Position: refs/heads/master@{#375700}
CWE ID:
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: icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)
{
const struct icmp6_router_renum *rr6;
const char *cp;
const struct rr_pco_match *match;
const struct rr_pco_use *use;
char hbuf[NI_MAXHOST];
int n;
if (ep < bp)
return;
rr6 = (const struct icmp6_router_renum *)bp;
cp = (const char *)(rr6 + 1);
ND_TCHECK(rr6->rr_reserved);
switch (rr6->rr_code) {
case ICMP6_ROUTER_RENUMBERING_COMMAND:
ND_PRINT((ndo,"router renum: command"));
break;
case ICMP6_ROUTER_RENUMBERING_RESULT:
ND_PRINT((ndo,"router renum: result"));
break;
case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:
ND_PRINT((ndo,"router renum: sequence number reset"));
break;
default:
ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code));
break;
}
ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum)));
if (ndo->ndo_vflag) {
#define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"[")); /*]*/
if (rr6->rr_flags) {
ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"),
F(ICMP6_RR_FLAGS_REQRESULT, "R"),
F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"),
F(ICMP6_RR_FLAGS_SPECSITE, "S"),
F(ICMP6_RR_FLAGS_PREVDONE, "P")));
}
ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum));
ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay)));
if (rr6->rr_reserved)
ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved)));
/*[*/
ND_PRINT((ndo,"]"));
#undef F
}
if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {
match = (const struct rr_pco_match *)cp;
cp = (const char *)(match + 1);
ND_TCHECK(match->rpm_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"match(")); /*)*/
switch (match->rpm_code) {
case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break;
case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break;
case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break;
default: ND_PRINT((ndo,"#%u", match->rpm_code)); break;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,",ord=%u", match->rpm_ordinal));
ND_PRINT((ndo,",min=%u", match->rpm_minlen));
ND_PRINT((ndo,",max=%u", match->rpm_maxlen));
}
if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen));
else
ND_PRINT((ndo,",?/%u", match->rpm_matchlen));
/*(*/
ND_PRINT((ndo,")"));
n = match->rpm_len - 3;
if (n % 4)
goto trunc;
n /= 4;
while (n-- > 0) {
use = (const struct rr_pco_use *)cp;
cp = (const char *)(use + 1);
ND_TCHECK(use->rpu_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"use(")); /*)*/
if (use->rpu_flags) {
#define F(x, y) ((use->rpu_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"%s%s,",
F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"),
F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P")));
#undef F
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask));
ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags));
if (~use->rpu_vltime == 0)
ND_PRINT((ndo,"vltime=infty,"));
else
ND_PRINT((ndo,"vltime=%u,",
EXTRACT_32BITS(&use->rpu_vltime)));
if (~use->rpu_pltime == 0)
ND_PRINT((ndo,"pltime=infty,"));
else
ND_PRINT((ndo,"pltime=%u,",
EXTRACT_32BITS(&use->rpu_pltime)));
}
if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen,
use->rpu_keeplen));
else
ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen,
use->rpu_keeplen));
/*(*/
ND_PRINT((ndo,")"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
}
Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
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: write_one_file(Image *output, Image *image, int convert_to_8bit)
{
if (image->opts & FAST_WRITE)
image->image.flags |= PNG_IMAGE_FLAG_FAST;
if (image->opts & USE_STDIO)
{
FILE *f = tmpfile();
if (f != NULL)
{
if (png_image_write_to_stdio(&image->image, f, convert_to_8bit,
image->buffer+16, (png_int_32)image->stride, image->colormap))
{
if (fflush(f) == 0)
{
rewind(f);
initimage(output, image->opts, "tmpfile", image->stride_extra);
output->input_file = f;
if (!checkopaque(image))
return 0;
}
else
return logclose(image, f, "tmpfile", ": flush: ");
}
else
{
fclose(f);
return logerror(image, "tmpfile", ": write failed", "");
}
}
else
return logerror(image, "tmpfile", ": open: ", strerror(errno));
}
else
{
static int counter = 0;
char name[32];
sprintf(name, "%s%d.png", tmpf, ++counter);
if (png_image_write_to_file(&image->image, name, convert_to_8bit,
image->buffer+16, (png_int_32)image->stride, image->colormap))
{
initimage(output, image->opts, output->tmpfile_name,
image->stride_extra);
/* Afterwards, or freeimage will delete it! */
strcpy(output->tmpfile_name, name);
if (!checkopaque(image))
return 0;
}
else
return logerror(image, name, ": write failed", "");
}
/* 'output' has an initialized temporary image, read this back in and compare
* this against the original: there should be no change since the original
* format was written unmodified unless 'convert_to_8bit' was specified.
* However, if the original image was color-mapped, a simple read will zap
* the linear, color and maybe alpha flags, this will cause spurious failures
* under some circumstances.
*/
if (read_file(output, image->image.format | FORMAT_NO_CHANGE, NULL))
{
png_uint_32 original_format = image->image.format;
if (convert_to_8bit)
original_format &= ~PNG_FORMAT_FLAG_LINEAR;
if ((output->image.format & BASE_FORMATS) !=
(original_format & BASE_FORMATS))
return logerror(image, image->file_name, ": format changed on read: ",
output->file_name);
return compare_two_images(image, output, 0/*via linear*/, NULL);
}
else
return logerror(output, output->tmpfile_name,
": read of new file failed", "");
}
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: RenderProcessImpl::~RenderProcessImpl() {
#ifndef NDEBUG
webkit_glue::CheckForLeaks();
#endif
GetShutDownEvent()->Signal();
ClearTransportDIBCache();
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
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 CURLcode smtp_state_data_resp(struct connectdata *conn, int smtpcode,
smtpstate instate)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
(void)instate; /* no use for this yet */
if(smtpcode != 354) {
failf(data, "DATA failed: %d", smtpcode);
result = CURLE_SEND_ERROR;
}
else {
/* Set the progress upload size */
Curl_pgrsSetUploadSize(data, data->state.infilesize);
/* SMTP upload */
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, FIRSTSOCKET, NULL);
/* End of DO phase */
state(conn, SMTP_STOP);
}
return result;
}
Commit Message: smtp: use the upload buffer size for scratch buffer malloc
... not the read buffer size, as that can be set smaller and thus cause
a buffer overflow! CVE-2018-0500
Reported-by: Peter Wu
Bug: https://curl.haxx.se/docs/adv_2018-70a2.html
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: void RenderFrameObserverNatives::OnDocumentElementCreated(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK(args.Length() == 2);
CHECK(args[0]->IsInt32());
CHECK(args[1]->IsFunction());
int frame_id = args[0]->Int32Value();
content::RenderFrame* frame = content::RenderFrame::FromRoutingID(frame_id);
if (!frame) {
LOG(WARNING) << "No render frame found to register LoadWatcher.";
return;
}
new LoadWatcher(context(), frame, args[1].As<v8::Function>());
args.GetReturnValue().Set(true);
}
Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated
BUG=585268,568130
Review URL: https://codereview.chromium.org/1684953002
Cr-Commit-Position: refs/heads/master@{#374758}
CWE ID:
Target: 1
Example 2:
Code: void Instance::EnableAutoscroll(const pp::Point& origin) {
if (is_autoscroll_)
return;
pp::Size client_size = plugin_size_;
if (v_scrollbar_.get())
client_size.Enlarge(-GetScrollbarThickness(), 0);
if (h_scrollbar_.get())
client_size.Enlarge(0, -GetScrollbarThickness());
if (autoscroll_anchor_.size().width() > client_size.width() ||
autoscroll_anchor_.size().height() > client_size.height())
return;
autoscroll_rect_ = pp::Rect(
pp::Point(origin.x() - autoscroll_anchor_.size().width() / 2,
origin.y() - autoscroll_anchor_.size().height() / 2),
autoscroll_anchor_.size());
if (autoscroll_rect_.right() > client_size.width()) {
autoscroll_rect_.set_x(
client_size.width() - autoscroll_anchor_.size().width());
}
if (autoscroll_rect_.bottom() > client_size.height()) {
autoscroll_rect_.set_y(
client_size.height() - autoscroll_anchor_.size().height());
}
if (autoscroll_rect_.x() < 0)
autoscroll_rect_.set_x(0);
if (autoscroll_rect_.y() < 0)
autoscroll_rect_.set_y(0);
is_autoscroll_ = true;
Invalidate(kAutoScrollId, autoscroll_rect_);
ScheduleTimer(kAutoScrollId, kAutoScrollTimeoutMs);
}
Commit Message: Let PDFium handle event when there is not yet a visible page.
Speculative fix for 415307. CF will confirm.
The stack trace for that bug indicates an attempt to index by -1, which is consistent with no visible page.
BUG=415307
Review URL: https://codereview.chromium.org/560133004
Cr-Commit-Position: refs/heads/master@{#295421}
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: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)
{ psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_be_8byte */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
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 void registerStreamURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerStreamURL(blobRegistryContext->url, blobRegistryContext->type);
}
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: header_afiol(struct archive_read *a, struct cpio *cpio,
struct archive_entry *entry, size_t *namelength, size_t *name_pad)
{
const void *h;
const char *header;
a->archive.archive_format = ARCHIVE_FORMAT_CPIO_AFIO_LARGE;
a->archive.archive_format_name = "afio large ASCII";
/* Read fixed-size portion of header. */
h = __archive_read_ahead(a, afiol_header_size, NULL);
if (h == NULL)
return (ARCHIVE_FATAL);
/* Parse out octal fields. */
header = (const char *)h;
archive_entry_set_dev(entry,
(dev_t)atol16(header + afiol_dev_offset, afiol_dev_size));
archive_entry_set_ino(entry, atol16(header + afiol_ino_offset, afiol_ino_size));
archive_entry_set_mode(entry,
(mode_t)atol8(header + afiol_mode_offset, afiol_mode_size));
archive_entry_set_uid(entry, atol16(header + afiol_uid_offset, afiol_uid_size));
archive_entry_set_gid(entry, atol16(header + afiol_gid_offset, afiol_gid_size));
archive_entry_set_nlink(entry,
(unsigned int)atol16(header + afiol_nlink_offset, afiol_nlink_size));
archive_entry_set_rdev(entry,
(dev_t)atol16(header + afiol_rdev_offset, afiol_rdev_size));
archive_entry_set_mtime(entry, atol16(header + afiol_mtime_offset, afiol_mtime_size), 0);
*namelength = (size_t)atol16(header + afiol_namesize_offset, afiol_namesize_size);
*name_pad = 0; /* No padding of filename. */
cpio->entry_bytes_remaining =
atol16(header + afiol_filesize_offset, afiol_filesize_size);
archive_entry_set_size(entry, cpio->entry_bytes_remaining);
cpio->entry_padding = 0;
__archive_read_consume(a, afiol_header_size);
return (ARCHIVE_OK);
}
Commit Message: Reject cpio symlinks that exceed 1MB
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 inline bool vfio_vga_disabled(void)
{
#ifdef CONFIG_VFIO_PCI_VGA
return disable_vga;
#else
return true;
#endif
}
Commit Message: vfio/pci: Fix integer overflows, bitmask check
The VFIO_DEVICE_SET_IRQS ioctl did not sufficiently sanitize
user-supplied integers, potentially allowing memory corruption. This
patch adds appropriate integer overflow checks, checks the range bounds
for VFIO_IRQ_SET_DATA_NONE, and also verifies that only single element
in the VFIO_IRQ_SET_DATA_TYPE_MASK bitmask is set.
VFIO_IRQ_SET_ACTION_TYPE_MASK is already correctly checked later in
vfio_pci_set_irqs_ioctl().
Furthermore, a kzalloc is changed to a kcalloc because the use of a
kzalloc with an integer multiplication allowed an integer overflow
condition to be reached without this patch. kcalloc checks for overflow
and should prevent a similar occurrence.
Signed-off-by: Vlad Tsyrklevich <[email protected]>
Signed-off-by: Alex Williamson <[email protected]>
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 int ext4_convert_unwritten_extents_endio(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path)
{
struct ext4_extent *ex;
int depth;
int err = 0;
depth = ext_depth(inode);
ex = path[depth].p_ext;
ext_debug("ext4_convert_unwritten_extents_endio: inode %lu, logical"
"block %llu, max_blocks %u\n", inode->i_ino,
(unsigned long long)le32_to_cpu(ex->ee_block),
ext4_ext_get_actual_len(ex));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
/* first mark the extent as initialized */
ext4_ext_mark_initialized(ex);
/* note: ext4_ext_correct_indexes() isn't needed here because
* borders are not changed
*/
ext4_ext_try_to_merge(handle, inode, path, ex);
/* Mark modified extent as dirty */
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
out:
ext4_ext_show_leaf(inode, path);
return err;
}
Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio
We assumed that at the time we call ext4_convert_unwritten_extents_endio()
extent in question is fully inside [map.m_lblk, map->m_len] because
it was already split during submission. But this may not be true due to
a race between writeback vs fallocate.
If extent in question is larger than requested we will split it again.
Special precautions should being done if zeroout required because
[map.m_lblk, map->m_len] already contains valid data.
Signed-off-by: Dmitry Monakhov <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int nr_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
void __user *argp = (void __user *)arg;
int ret;
switch (cmd) {
case TIOCOUTQ: {
long amount;
lock_sock(sk);
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
release_sock(sk);
return put_user(amount, (int __user *)argp);
}
case TIOCINQ: {
struct sk_buff *skb;
long amount = 0L;
lock_sock(sk);
/* These two are safe on a single CPU system as only user tasks fiddle here */
if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL)
amount = skb->len;
release_sock(sk);
return put_user(amount, (int __user *)argp);
}
case SIOCGSTAMP:
lock_sock(sk);
ret = sock_get_timestamp(sk, argp);
release_sock(sk);
return ret;
case SIOCGSTAMPNS:
lock_sock(sk);
ret = sock_get_timestampns(sk, argp);
release_sock(sk);
return ret;
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
return -EINVAL;
case SIOCADDRT:
case SIOCDELRT:
case SIOCNRDECOBS:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return nr_rt_ioctl(cmd, argp);
default:
return -ENOIOCTLCMD;
}
return 0;
}
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: 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 CuePoint* Cues::GetLast() const {
if (m_cue_points == NULL)
return NULL;
if (m_count <= 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
const size_t index = count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
pCP->Load(m_pSegment->m_pReader);
assert(pCP->GetTimeCode() >= 0);
#else
const long index = m_count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
#endif
return pCP;
}
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 bnep_add_connection(struct bnep_connadd_req *req, struct socket *sock)
{
struct net_device *dev;
struct bnep_session *s, *ss;
u8 dst[ETH_ALEN], src[ETH_ALEN];
int err;
BT_DBG("");
baswap((void *) dst, &l2cap_pi(sock->sk)->chan->dst);
baswap((void *) src, &l2cap_pi(sock->sk)->chan->src);
/* session struct allocated as private part of net_device */
dev = alloc_netdev(sizeof(struct bnep_session),
(*req->device) ? req->device : "bnep%d",
NET_NAME_UNKNOWN,
bnep_net_setup);
if (!dev)
return -ENOMEM;
down_write(&bnep_session_sem);
ss = __bnep_get_session(dst);
if (ss && ss->state == BT_CONNECTED) {
err = -EEXIST;
goto failed;
}
s = netdev_priv(dev);
/* This is rx header therefore addresses are swapped.
* ie. eh.h_dest is our local address. */
memcpy(s->eh.h_dest, &src, ETH_ALEN);
memcpy(s->eh.h_source, &dst, ETH_ALEN);
memcpy(dev->dev_addr, s->eh.h_dest, ETH_ALEN);
s->dev = dev;
s->sock = sock;
s->role = req->role;
s->state = BT_CONNECTED;
s->msg.msg_flags = MSG_NOSIGNAL;
#ifdef CONFIG_BT_BNEP_MC_FILTER
/* Set default mc filter */
set_bit(bnep_mc_hash(dev->broadcast), (ulong *) &s->mc_filter);
#endif
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
/* Set default protocol filter */
bnep_set_default_proto_filter(s);
#endif
SET_NETDEV_DEV(dev, bnep_get_device(s));
SET_NETDEV_DEVTYPE(dev, &bnep_type);
err = register_netdev(dev);
if (err)
goto failed;
__bnep_link_session(s);
__module_get(THIS_MODULE);
s->task = kthread_run(bnep_session, s, "kbnepd %s", dev->name);
if (IS_ERR(s->task)) {
/* Session thread start failed, gotta cleanup. */
module_put(THIS_MODULE);
unregister_netdev(dev);
__bnep_unlink_session(s);
err = PTR_ERR(s->task);
goto failed;
}
up_write(&bnep_session_sem);
strcpy(req->device, dev->name);
return 0;
failed:
up_write(&bnep_session_sem);
free_netdev(dev);
return err;
}
Commit Message: Bluetooth: bnep: bnep_add_connection() should verify that it's dealing with l2cap socket
same story as cmtp
Signed-off-by: Al Viro <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: asmlinkage void sparc_lvl15_nmi(struct pt_regs *regs, unsigned long serr,
unsigned long svaddr, unsigned long aerr,
unsigned long avaddr)
{
sun4c_complete_all_stores();
printk("FAULT: NMI received\n");
printk("SREGS: Synchronous Error %08lx\n", serr);
printk(" Synchronous Vaddr %08lx\n", svaddr);
printk(" Asynchronous Error %08lx\n", aerr);
printk(" Asynchronous Vaddr %08lx\n", avaddr);
if (sun4c_memerr_reg)
printk(" Memory Parity Error %08lx\n", *sun4c_memerr_reg);
printk("REGISTER DUMP:\n");
show_regs(regs);
prom_halt();
}
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: __mem_cgroup_commit_charge_lrucare(struct page *page, struct mem_cgroup *memcg,
enum charge_type ctype)
{
struct page_cgroup *pc = lookup_page_cgroup(page);
struct zone *zone = page_zone(page);
unsigned long flags;
bool removed = false;
/*
* In some case, SwapCache, FUSE(splice_buf->radixtree), the page
* is already on LRU. It means the page may on some other page_cgroup's
* LRU. Take care of it.
*/
spin_lock_irqsave(&zone->lru_lock, flags);
if (PageLRU(page)) {
del_page_from_lru_list(zone, page, page_lru(page));
ClearPageLRU(page);
removed = true;
}
__mem_cgroup_commit_charge(memcg, page, 1, pc, ctype);
if (removed) {
add_page_to_lru_list(zone, page, page_lru(page));
SetPageLRU(page);
}
spin_unlock_irqrestore(&zone->lru_lock, flags);
return;
}
Commit Message: mm: memcg: Correct unregistring of events attached to the same eventfd
There is an issue when memcg unregisters events that were attached to
the same eventfd:
- On the first call mem_cgroup_usage_unregister_event() removes all
events attached to a given eventfd, and if there were no events left,
thresholds->primary would become NULL;
- Since there were several events registered, cgroups core will call
mem_cgroup_usage_unregister_event() again, but now kernel will oops,
as the function doesn't expect that threshold->primary may be NULL.
That's a good question whether mem_cgroup_usage_unregister_event()
should actually remove all events in one go, but nowadays it can't
do any better as cftype->unregister_event callback doesn't pass
any private event-associated cookie. So, let's fix the issue by
simply checking for threshold->primary.
FWIW, w/o the patch the following oops may be observed:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000004
IP: [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0
Pid: 574, comm: kworker/0:2 Not tainted 3.3.0-rc4+ #9 Bochs Bochs
RIP: 0010:[<ffffffff810be32c>] [<ffffffff810be32c>] mem_cgroup_usage_unregister_event+0x9c/0x1f0
RSP: 0018:ffff88001d0b9d60 EFLAGS: 00010246
Process kworker/0:2 (pid: 574, threadinfo ffff88001d0b8000, task ffff88001de91cc0)
Call Trace:
[<ffffffff8107092b>] cgroup_event_remove+0x2b/0x60
[<ffffffff8103db94>] process_one_work+0x174/0x450
[<ffffffff8103e413>] worker_thread+0x123/0x2d0
Cc: stable <[email protected]>
Signed-off-by: Anton Vorontsov <[email protected]>
Acked-by: KAMEZAWA Hiroyuki <[email protected]>
Cc: Kirill A. Shutemov <[email protected]>
Cc: Michal Hocko <[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: void MediaStreamManager::OpenDevice(int render_process_id,
int render_frame_id,
int page_request_id,
const std::string& device_id,
MediaStreamType type,
MediaDeviceSaltAndOrigin salt_and_origin,
OpenDeviceCallback open_device_cb,
DeviceStoppedCallback device_stopped_cb) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(type == MEDIA_DEVICE_AUDIO_CAPTURE ||
type == MEDIA_DEVICE_VIDEO_CAPTURE);
DVLOG(1) << "OpenDevice ({page_request_id = " << page_request_id << "})";
StreamControls controls;
if (IsAudioInputMediaType(type)) {
controls.audio.requested = true;
controls.audio.stream_type = type;
controls.audio.device_id = device_id;
} else if (IsVideoInputMediaType(type)) {
controls.video.requested = true;
controls.video.stream_type = type;
controls.video.device_id = device_id;
} else {
NOTREACHED();
}
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, page_request_id,
false /* user gesture */, MEDIA_OPEN_DEVICE_PEPPER_ONLY, controls,
std::move(salt_and_origin), std::move(device_stopped_cb));
const std::string& label = AddRequest(request);
request->open_device_cb = std::move(open_device_cb);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
}
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
Target: 1
Example 2:
Code: void fuse_request_send_background_locked(struct fuse_conn *fc,
struct fuse_req *req)
{
req->isreply = 1;
fuse_request_send_nowait_locked(fc, req);
}
Commit Message: fuse: check size of FUSE_NOTIFY_INVAL_ENTRY message
FUSE_NOTIFY_INVAL_ENTRY didn't check the length of the write so the
message processing could overrun and result in a "kernel BUG at
fs/fuse/dev.c:629!"
Reported-by: Han-Wen Nienhuys <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
CC: [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: long do_io_submit(aio_context_t ctx_id, long nr,
struct iocb __user *__user *iocbpp, bool compat)
{
struct kioctx *ctx;
long ret = 0;
int i = 0;
struct blk_plug plug;
struct kiocb_batch batch;
if (unlikely(nr < 0))
return -EINVAL;
if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
nr = LONG_MAX/sizeof(*iocbpp);
if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
return -EFAULT;
ctx = lookup_ioctx(ctx_id);
if (unlikely(!ctx)) {
pr_debug("EINVAL: io_submit: invalid context id\n");
return -EINVAL;
}
kiocb_batch_init(&batch, nr);
blk_start_plug(&plug);
/*
* AKPM: should this return a partial result if some of the IOs were
* successfully submitted?
*/
for (i=0; i<nr; i++) {
struct iocb __user *user_iocb;
struct iocb tmp;
if (unlikely(__get_user(user_iocb, iocbpp + i))) {
ret = -EFAULT;
break;
}
if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
ret = -EFAULT;
break;
}
ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat);
if (ret)
break;
}
blk_finish_plug(&plug);
kiocb_batch_free(&batch);
put_ioctx(ctx);
return i ? i : ret;
}
Commit Message: Unused iocbs in a batch should not be accounted as active.
commit 69e4747ee9727d660b88d7e1efe0f4afcb35db1b upstream.
Since commit 080d676de095 ("aio: allocate kiocbs in batches") iocbs are
allocated in a batch during processing of first iocbs. All iocbs in a
batch are automatically added to ctx->active_reqs list and accounted in
ctx->reqs_active.
If one (not the last one) of iocbs submitted by an user fails, further
iocbs are not processed, but they are still present in ctx->active_reqs
and accounted in ctx->reqs_active. This causes process to stuck in a D
state in wait_for_all_aios() on exit since ctx->reqs_active will never
go down to zero. Furthermore since kiocb_batch_free() frees iocb
without removing it from active_reqs list the list become corrupted
which may cause oops.
Fix this by removing iocb from ctx->active_reqs and updating
ctx->reqs_active in kiocb_batch_free().
Signed-off-by: Gleb Natapov <[email protected]>
Reviewed-by: Jeff Moyer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
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: static int ctdb_tcp_listen_automatic(struct ctdb_context *ctdb)
{
struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data,
struct ctdb_tcp);
ctdb_sock_addr sock;
int lock_fd, i;
const char *lock_path = "/tmp/.ctdb_socket_lock";
struct flock lock;
int one = 1;
int sock_size;
struct tevent_fd *fde;
/* If there are no nodes, then it won't be possible to find
* the first one. Log a failure and short circuit the whole
* process.
*/
if (ctdb->num_nodes == 0) {
DEBUG(DEBUG_CRIT,("No nodes available to attempt bind to - is the nodes file empty?\n"));
return -1;
}
/* in order to ensure that we don't get two nodes with the
same adddress, we must make the bind() and listen() calls
atomic. The SO_REUSEADDR setsockopt only prevents double
binds if the first socket is in LISTEN state */
lock_fd = open(lock_path, O_RDWR|O_CREAT, 0666);
if (lock_fd == -1) {
DEBUG(DEBUG_CRIT,("Unable to open %s\n", lock_path));
return -1;
}
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 1;
lock.l_pid = 0;
if (fcntl(lock_fd, F_SETLKW, &lock) != 0) {
DEBUG(DEBUG_CRIT,("Unable to lock %s\n", lock_path));
close(lock_fd);
return -1;
}
for (i=0; i < ctdb->num_nodes; i++) {
if (ctdb->nodes[i]->flags & NODE_FLAGS_DELETED) {
continue;
}
ZERO_STRUCT(sock);
if (ctdb_tcp_get_address(ctdb,
ctdb->nodes[i]->address.address,
&sock) != 0) {
continue;
}
switch (sock.sa.sa_family) {
case AF_INET:
sock.ip.sin_port = htons(ctdb->nodes[i]->address.port);
sock_size = sizeof(sock.ip);
break;
case AF_INET6:
sock.ip6.sin6_port = htons(ctdb->nodes[i]->address.port);
sock_size = sizeof(sock.ip6);
break;
default:
DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n",
sock.sa.sa_family));
continue;
}
#ifdef HAVE_SOCK_SIN_LEN
sock.ip.sin_len = sock_size;
#endif
ctcp->listen_fd = socket(sock.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
if (ctcp->listen_fd == -1) {
ctdb_set_error(ctdb, "socket failed\n");
continue;
}
set_close_on_exec(ctcp->listen_fd);
setsockopt(ctcp->listen_fd,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one));
if (bind(ctcp->listen_fd, (struct sockaddr * )&sock, sock_size) == 0) {
break;
}
if (errno == EADDRNOTAVAIL) {
DEBUG(DEBUG_DEBUG,(__location__ " Failed to bind() to socket. %s(%d)\n",
strerror(errno), errno));
} else {
DEBUG(DEBUG_ERR,(__location__ " Failed to bind() to socket. %s(%d)\n",
strerror(errno), errno));
}
}
if (i == ctdb->num_nodes) {
DEBUG(DEBUG_CRIT,("Unable to bind to any of the node addresses - giving up\n"));
goto failed;
}
ctdb->address.address = talloc_strdup(ctdb, ctdb->nodes[i]->address.address);
ctdb->address.port = ctdb->nodes[i]->address.port;
ctdb->name = talloc_asprintf(ctdb, "%s:%u",
ctdb->address.address,
ctdb->address.port);
ctdb->pnn = ctdb->nodes[i]->pnn;
DEBUG(DEBUG_INFO,("ctdb chose network address %s:%u pnn %u\n",
ctdb->address.address,
ctdb->address.port,
ctdb->pnn));
if (listen(ctcp->listen_fd, 10) == -1) {
goto failed;
}
fde = event_add_fd(ctdb->ev, ctcp, ctcp->listen_fd, EVENT_FD_READ,
ctdb_listen_event, ctdb);
tevent_fd_set_auto_close(fde);
close(lock_fd);
return 0;
failed:
close(lock_fd);
close(ctcp->listen_fd);
ctcp->listen_fd = -1;
return -1;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool GLES2DecoderPassthroughImpl::MakeCurrent() {
if (!context_.get())
return false;
if (WasContextLost()) {
LOG(ERROR) << " GLES2DecoderPassthroughImpl: Trying to make lost context "
"current.";
return false;
}
if (!context_->MakeCurrent(surface_.get())) {
LOG(ERROR)
<< " GLES2DecoderPassthroughImpl: Context lost during MakeCurrent.";
MarkContextLost(error::kMakeCurrentFailed);
group_->LoseContexts(error::kUnknown);
return false;
}
DCHECK_EQ(api(), gl::g_current_gl_context);
if (CheckResetStatus()) {
LOG(ERROR) << " GLES2DecoderPassthroughImpl: Context reset detected after "
"MakeCurrent.";
group_->LoseContexts(error::kUnknown);
return false;
}
ProcessReadPixels(false);
ProcessQueries(false);
resources_->DestroyPendingTextures(/*has_context=*/true);
return true;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
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 __exit fini(void)
{
crypto_unregister_algs(camellia_algs, ARRAY_SIZE(camellia_algs));
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[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: static unsigned int unix_dgram_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk, *other;
unsigned int mask, writable;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR |
(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if (sk->sk_type == SOCK_SEQPACKET) {
if (sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/* connection hasn't started yet? */
if (sk->sk_state == TCP_SYN_SENT)
return mask;
}
/* No write status requested, avoid expensive OUT tests. */
if (!(poll_requested_events(wait) & (POLLWRBAND|POLLWRNORM|POLLOUT)))
return mask;
writable = unix_writable(sk);
other = unix_peer_get(sk);
if (other) {
if (unix_peer(other) != sk) {
sock_poll_wait(file, &unix_sk(other)->peer_wait, wait);
if (unix_recvq_full(other))
writable = 0;
}
sock_put(other);
}
if (writable)
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
return mask;
}
Commit Message: unix: avoid use-after-free in ep_remove_wait_queue
Rainer Weikusat <[email protected]> writes:
An AF_UNIX datagram socket being the client in an n:1 association with
some server socket is only allowed to send messages to the server if the
receive queue of this socket contains at most sk_max_ack_backlog
datagrams. This implies that prospective writers might be forced to go
to sleep despite none of the message presently enqueued on the server
receive queue were sent by them. In order to ensure that these will be
woken up once space becomes again available, the present unix_dgram_poll
routine does a second sock_poll_wait call with the peer_wait wait queue
of the server socket as queue argument (unix_dgram_recvmsg does a wake
up on this queue after a datagram was received). This is inherently
problematic because the server socket is only guaranteed to remain alive
for as long as the client still holds a reference to it. In case the
connection is dissolved via connect or by the dead peer detection logic
in unix_dgram_sendmsg, the server socket may be freed despite "the
polling mechanism" (in particular, epoll) still has a pointer to the
corresponding peer_wait queue. There's no way to forcibly deregister a
wait queue with epoll.
Based on an idea by Jason Baron, the patch below changes the code such
that a wait_queue_t belonging to the client socket is enqueued on the
peer_wait queue of the server whenever the peer receive queue full
condition is detected by either a sendmsg or a poll. A wake up on the
peer queue is then relayed to the ordinary wait queue of the client
socket via wake function. The connection to the peer wait queue is again
dissolved if either a wake up is about to be relayed or the client
socket reconnects or a dead peer is detected or the client socket is
itself closed. This enables removing the second sock_poll_wait from
unix_dgram_poll, thus avoiding the use-after-free, while still ensuring
that no blocked writer sleeps forever.
Signed-off-by: Rainer Weikusat <[email protected]>
Fixes: ec0d215f9420 ("af_unix: fix 'poll for write'/connected DGRAM sockets")
Reviewed-by: Jason Baron <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void SiteInstanceImpl::SetSite(const GURL& url) {
TRACE_EVENT2("navigation", "SiteInstanceImpl::SetSite",
"site id", id_, "url", url.possibly_invalid_spec());
DCHECK(!has_site_);
has_site_ = true;
BrowserContext* browser_context = browsing_instance_->browser_context();
site_ = GetSiteForURL(browser_context, url);
original_url_ = url;
browsing_instance_->RegisterSiteInstance(this);
bool should_use_process_per_site =
RenderProcessHost::ShouldUseProcessPerSite(browser_context, site_);
if (should_use_process_per_site) {
process_reuse_policy_ = ProcessReusePolicy::PROCESS_PER_SITE;
}
if (process_) {
LockToOriginIfNeeded();
if (should_use_process_per_site) {
RenderProcessHostImpl::RegisterProcessHostForSite(
browser_context, process_, site_);
}
}
}
Commit Message: Use unique processes for data URLs on restore.
Data URLs are usually put into the process that created them, but this
info is not tracked after a tab restore. Ensure that they do not end up
in the parent frame's process (or each other's process), in case they
are malicious.
BUG=863069
Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b
Reviewed-on: https://chromium-review.googlesource.com/1150767
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#581023}
CWE ID: CWE-285
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 AppCacheGroup::AddUpdateObserver(UpdateObserver* observer) {
if (queued_updates_.find(observer) != queued_updates_.end())
queued_observers_.AddObserver(observer);
else
observers_.AddObserver(observer);
}
Commit Message: Refcount AppCacheGroup correctly.
Bug: 888926
Change-Id: Iab0d82d272e2f24a5e91180d64bc8e2aa8a8238d
Reviewed-on: https://chromium-review.googlesource.com/1246827
Reviewed-by: Marijn Kruisselbrink <[email protected]>
Reviewed-by: Joshua Bell <[email protected]>
Commit-Queue: Chris Palmer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#594475}
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 struct key *construct_key_and_link(struct keyring_search_context *ctx,
const char *callout_info,
size_t callout_len,
void *aux,
struct key *dest_keyring,
unsigned long flags)
{
struct key_user *user;
struct key *key;
int ret;
kenter("");
user = key_user_lookup(current_fsuid());
if (!user)
return ERR_PTR(-ENOMEM);
construct_get_dest_keyring(&dest_keyring);
ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
key_user_put(user);
if (ret == 0) {
ret = construct_key(key, callout_info, callout_len, aux,
dest_keyring);
if (ret < 0) {
kdebug("cons failed");
goto construction_failed;
}
} else if (ret == -EINPROGRESS) {
ret = 0;
} else {
goto couldnt_alloc_key;
}
key_put(dest_keyring);
kleave(" = key %d", key_serial(key));
return key;
construction_failed:
key_negate_and_link(key, key_negative_timeout, NULL, NULL);
key_put(key);
couldnt_alloc_key:
key_put(dest_keyring);
kleave(" = %d", ret);
return ERR_PTR(ret);
}
Commit Message: Merge branch 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs
Pull key handling fixes from David Howells:
"Here are two patches, the first of which at least should go upstream
immediately:
(1) Prevent a user-triggerable crash in the keyrings destructor when a
negatively instantiated keyring is garbage collected. I have also
seen this triggered for user type keys.
(2) Prevent the user from using requesting that a keyring be created
and instantiated through an upcall. Doing so is probably safe
since the keyring type ignores the arguments to its instantiation
function - but we probably shouldn't let keyrings be created in
this manner"
* 'keys-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/dhowells/linux-fs:
KEYS: Don't permit request_key() to construct a new keyring
KEYS: Fix crash when attempt to garbage collect an uninstantiated keyring
CWE ID: CWE-20
Target: 1
Example 2:
Code: void SoftAVC::logVersion() {
ivd_ctl_getversioninfo_ip_t s_ctl_ip;
ivd_ctl_getversioninfo_op_t s_ctl_op;
UWORD8 au1_buf[512];
IV_API_CALL_STATUS_T status;
s_ctl_ip.e_cmd = IVD_CMD_VIDEO_CTL;
s_ctl_ip.e_sub_cmd = IVD_CMD_CTL_GETVERSION;
s_ctl_ip.u4_size = sizeof(ivd_ctl_getversioninfo_ip_t);
s_ctl_op.u4_size = sizeof(ivd_ctl_getversioninfo_op_t);
s_ctl_ip.pv_version_buffer = au1_buf;
s_ctl_ip.u4_version_buffer_size = sizeof(au1_buf);
status =
ivdec_api_function(mCodecCtx, (void *)&s_ctl_ip, (void *)&s_ctl_op);
if (status != IV_SUCCESS) {
ALOGE("Error in getting version number: 0x%x",
s_ctl_op.u4_error_code);
} else {
ALOGV("Ittiam decoder version number: %s",
(char *)s_ctl_ip.pv_version_buffer);
}
return;
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
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 ctypeof(JF, js_Ast *exp)
{
if (exp->type == EXP_IDENTIFIER)
emitlocal(J, F, OP_GETLOCAL, OP_HASVAR, exp);
else
cexp(J, F, exp);
emit(J, F, OP_TYPEOF);
}
Commit Message:
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: void CmdBufferImageTransportFactory::DestroySharedSurfaceHandle(
const gfx::GLSurfaceHandle& handle) {
if (!context_->makeContextCurrent()) {
NOTREACHED() << "Failed to make shared graphics context current";
return;
}
context_->deleteTexture(handle.parent_texture_id[0]);
context_->deleteTexture(handle.parent_texture_id[1]);
context_->finish();
}
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: const btav_source_interface_t* btif_av_get_src_interface(void) {
BTIF_TRACE_EVENT("%s", __func__);
return &bt_av_src_interface;
}
Commit Message: DO NOT MERGE AVRC: Copy browse.p_browse_data in btif_av_event_deep_copy
p_msg_src->browse.p_browse_data is not copied, but used after the
original pointer is freed
Bug: 109699112
Test: manual
Change-Id: I1d014eb9a8911da6913173a9b11218bf1c89e16e
(cherry picked from commit 1d9a58768e6573899c7e80c2b3f52e22f2d8f58b)
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 iov_fault_in_pages_read(struct iovec *iov, unsigned long len)
{
while (!iov->iov_len)
iov++;
while (len > 0) {
unsigned long this_len;
this_len = min_t(unsigned long, len, iov->iov_len);
fault_in_pages_readable(iov->iov_base, this_len);
len -= this_len;
iov++;
}
}
Commit Message: new helper: copy_page_from_iter()
parallel to copy_page_to_iter(). pipe_write() switched to it (and became
->write_iter()).
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: bool adapter_enable_disable() {
int error;
CALL_AND_WAIT(error = bt_interface->enable(), adapter_state_changed);
TASSERT(error == BT_STATUS_SUCCESS, "Error enabling Bluetooth: %d", error);
TASSERT(adapter_get_state() == BT_STATE_ON, "Adapter did not turn on.");
CALL_AND_WAIT(error = bt_interface->disable(), adapter_state_changed);
TASSERT(error == BT_STATUS_SUCCESS, "Error disabling Bluetooth: %d", error);
TASSERT(adapter_get_state() == BT_STATE_OFF, "Adapter did not turn off.");
return true;
}
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
CWE ID: CWE-20
Target: 1
Example 2:
Code: MainThreadTaskRunner(WTF::MainThreadFunction* function, void* context)
: m_function(function)
, m_context(context) { }
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: static void uipc_read_task(void *arg)
{
int ch_id;
int result;
UNUSED(arg);
prctl(PR_SET_NAME, (unsigned long)"uipc-main", 0, 0, 0);
raise_priority_a2dp(TASK_UIPC_READ);
while (uipc_main.running)
{
uipc_main.read_set = uipc_main.active_set;
result = select(uipc_main.max_fd+1, &uipc_main.read_set, NULL, NULL, NULL);
if (result == 0)
{
BTIF_TRACE_EVENT("select timeout");
continue;
}
else if (result < 0)
{
BTIF_TRACE_EVENT("select failed %s", strerror(errno));
continue;
}
UIPC_LOCK();
/* clear any wakeup interrupt */
uipc_check_interrupt_locked();
/* check pending task events */
uipc_check_task_flags_locked();
/* make sure we service audio channel first */
uipc_check_fd_locked(UIPC_CH_ID_AV_AUDIO);
/* check for other connections */
for (ch_id = 0; ch_id < UIPC_CH_NUM; ch_id++)
{
if (ch_id != UIPC_CH_ID_AV_AUDIO)
uipc_check_fd_locked(ch_id);
}
UIPC_UNLOCK();
}
BTIF_TRACE_EVENT("UIPC READ THREAD EXITING");
uipc_main_cleanup();
uipc_main.tid = 0;
BTIF_TRACE_EVENT("UIPC READ THREAD DONE");
}
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
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 VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVAPicture(
VAPictureH264* va_pic,
scoped_refptr<H264Picture> pic) {
VASurfaceID va_surface_id = VA_INVALID_SURFACE;
if (!pic->nonexisting) {
scoped_refptr<VaapiDecodeSurface> dec_surface =
H264PictureToVaapiDecodeSurface(pic);
va_surface_id = dec_surface->va_surface()->id();
}
va_pic->picture_id = va_surface_id;
va_pic->frame_idx = pic->frame_num;
va_pic->flags = 0;
switch (pic->field) {
case H264Picture::FIELD_NONE:
break;
case H264Picture::FIELD_TOP:
va_pic->flags |= VA_PICTURE_H264_TOP_FIELD;
break;
case H264Picture::FIELD_BOTTOM:
va_pic->flags |= VA_PICTURE_H264_BOTTOM_FIELD;
break;
}
if (pic->ref) {
va_pic->flags |= pic->long_term ? VA_PICTURE_H264_LONG_TERM_REFERENCE
: VA_PICTURE_H264_SHORT_TERM_REFERENCE;
}
va_pic->TopFieldOrderCnt = pic->top_field_order_cnt;
va_pic->BottomFieldOrderCnt = pic->bottom_field_order_cnt;
}
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
Target: 1
Example 2:
Code: bool PropertyChanged() const { return property_changed_; }
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
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 inline void report_tpr_access(struct kvm_lapic *apic, bool write)
{
if (apic->vcpu->arch.tpr_access_reporting)
__report_tpr_access(apic, write);
}
Commit Message: KVM: x86: fix guest-initiated crash with x2apic (CVE-2013-6376)
A guest can cause a BUG_ON() leading to a host kernel crash.
When the guest writes to the ICR to request an IPI, while in x2apic
mode the following things happen, the destination is read from
ICR2, which is a register that the guest can control.
kvm_irq_delivery_to_apic_fast uses the high 16 bits of ICR2 as the
cluster id. A BUG_ON is triggered, which is a protection against
accessing map->logical_map with an out-of-bounds access and manages
to avoid that anything really unsafe occurs.
The logic in the code is correct from real HW point of view. The problem
is that KVM supports only one cluster with ID 0 in clustered mode, but
the code that has the bug does not take this into account.
Reported-by: Lars Bull <[email protected]>
Cc: [email protected]
Signed-off-by: Gleb Natapov <[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 AppCache::RemoveEntry(const GURL& url) {
auto found = entries_.find(url);
DCHECK(found != entries_.end());
cache_size_ -= found->second.response_size();
entries_.erase(found);
}
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
Target: 1
Example 2:
Code: base::SharedMemoryHandle MockRenderThread::HostAllocateSharedMemoryBuffer(
uint32 buffer_size) {
base::SharedMemory shared_buf;
if (!shared_buf.CreateAndMapAnonymous(buffer_size)) {
NOTREACHED() << "Cannot map shared memory buffer";
return base::SharedMemory::NULLHandle();
}
base::SharedMemoryHandle handle;
shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), &handle);
return handle;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
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: _warc_rdtyp(const char *buf, size_t bsz)
{
static const char _key[] = "\r\nWARC-Type:";
const char *val, *eol;
if ((val = xmemmem(buf, bsz, _key, sizeof(_key) - 1U)) == NULL) {
/* no bother */
return WT_NONE;
}
val += sizeof(_key) - 1U;
if ((eol = _warc_find_eol(val, buf + bsz - val)) == NULL) {
/* no end of line */
return WT_NONE;
}
/* overread whitespace */
while (val < eol && (*val == ' ' || *val == '\t'))
++val;
if (val + 8U == eol) {
if (memcmp(val, "resource", 8U) == 0)
return WT_RSRC;
else if (memcmp(val, "response", 8U) == 0)
return WT_RSP;
}
return WT_NONE;
}
Commit Message: warc: consume data once read
The warc decoder only used read ahead, it wouldn't actually consume
data that had previously been printed. This means that if you specify
an invalid content length, it will just reprint the same data over
and over and over again until it hits the desired length.
This means that a WARC resource with e.g.
Content-Length: 666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666665
but only a few hundred bytes of data, causes a quasi-infinite loop.
Consume data in subsequent calls to _warc_read.
Found with an AFL + afl-rb + qsym setup.
CWE ID: CWE-415
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: native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) err = BAD_VALUE;
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
Commit Message: Verify that the native handle was created
The inputs to native_handle_create can cause an overflowed allocation,
so check the return value of native_handle_create before accessing
the memory it returns.
Bug:19334482
Change-Id: I1f489382776c2a1390793a79dc27ea17baa9b2a2
(cherry picked from commit eaac99a7172da52a76ba48c26413778a74951b1a)
CWE ID: CWE-189
Target: 1
Example 2:
Code: void Gfx::doFunctionShFill(GfxFunctionShading *shading) {
double x0, y0, x1, y1;
GfxColor colors[4];
if (out->useShadedFills() &&
out->functionShadedFill(state, shading)) {
return;
}
shading->getDomain(&x0, &y0, &x1, &y1);
shading->getColor(x0, y0, &colors[0]);
shading->getColor(x0, y1, &colors[1]);
shading->getColor(x1, y0, &colors[2]);
shading->getColor(x1, y1, &colors[3]);
doFunctionShFill1(shading, x0, y0, x1, y1, colors, 0);
}
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: gfx::Size LayerTreeHost::GetUIResourceSize(UIResourceId uid) const {
UIResourceClientMap::const_iterator iter = ui_resource_client_map_.find(uid);
if (iter == ui_resource_client_map_.end())
return gfx::Size();
const UIResourceClientData& data = iter->second;
return data.size;
}
Commit Message: Removed pinch viewport scroll offset distribution
The associated change in Blink makes the pinch viewport a proper
ScrollableArea meaning the normal path for synchronizing layer scroll
offsets is used.
This is a 2 sided patch, the other CL:
https://codereview.chromium.org/199253002/
BUG=349941
Review URL: https://codereview.chromium.org/210543002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98
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: xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix,
const xmlChar *URI, int line, int nsNr, int tlen) {
const xmlChar *name;
GROW;
if ((RAW != '<') || (NXT(1) != '/')) {
xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL);
return;
}
SKIP(2);
if ((tlen > 0) && (xmlStrncmp(ctxt->input->cur, ctxt->name, tlen) == 0)) {
if (ctxt->input->cur[tlen] == '>') {
ctxt->input->cur += tlen + 1;
goto done;
}
ctxt->input->cur += tlen;
name = (xmlChar*)1;
} else {
if (prefix == NULL)
name = xmlParseNameAndCompare(ctxt, ctxt->name);
else
name = xmlParseQNameAndCompare(ctxt, ctxt->name, prefix);
}
/*
* We should definitely be at the ending "S? '>'" part
*/
GROW;
SKIP_BLANKS;
if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) {
xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
} else
NEXT1;
/*
* [ WFC: Element Type Match ]
* The Name in an element's end-tag must match the element type in the
* start-tag.
*
*/
if (name != (xmlChar*)1) {
if (name == NULL) name = BAD_CAST "unparseable";
if ((line == 0) && (ctxt->node != NULL))
line = ctxt->node->line;
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
"Opening and ending tag mismatch: %s line %d and %s\n",
ctxt->name, line, name);
}
/*
* SAX: End of Tag
*/
done:
if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, ctxt->name, prefix, URI);
spacePop(ctxt);
if (nsNr != 0)
nsPop(ctxt, nsNr);
return;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); }
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: 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 __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
switch (hdev->product) {
case USB_DEVICE_ID_KYE_ERGO_525V:
/* the fixups that need to be done:
* - change led usage page to button for extra buttons
* - report size 8 count 1 must be size 1 count 8 for button
* bitfield
* - change the button usage range to 4-7 for the extra
* buttons
*/
if (*rsize >= 74 &&
rdesc[61] == 0x05 && rdesc[62] == 0x08 &&
rdesc[63] == 0x19 && rdesc[64] == 0x08 &&
rdesc[65] == 0x29 && rdesc[66] == 0x0f &&
rdesc[71] == 0x75 && rdesc[72] == 0x08 &&
rdesc[73] == 0x95 && rdesc[74] == 0x01) {
hid_info(hdev,
"fixing up Kye/Genius Ergo Mouse "
"report descriptor\n");
rdesc[62] = 0x09;
rdesc[64] = 0x04;
rdesc[66] = 0x07;
rdesc[72] = 0x01;
rdesc[74] = 0x08;
}
break;
case USB_DEVICE_ID_KYE_EASYPEN_I405X:
if (*rsize == EASYPEN_I405X_RDESC_ORIG_SIZE) {
rdesc = easypen_i405x_rdesc_fixed;
*rsize = sizeof(easypen_i405x_rdesc_fixed);
}
break;
case USB_DEVICE_ID_KYE_MOUSEPEN_I608X:
if (*rsize == MOUSEPEN_I608X_RDESC_ORIG_SIZE) {
rdesc = mousepen_i608x_rdesc_fixed;
*rsize = sizeof(mousepen_i608x_rdesc_fixed);
}
break;
case USB_DEVICE_ID_KYE_EASYPEN_M610X:
if (*rsize == EASYPEN_M610X_RDESC_ORIG_SIZE) {
rdesc = easypen_m610x_rdesc_fixed;
*rsize = sizeof(easypen_m610x_rdesc_fixed);
}
break;
case USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE:
rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104,
"Genius Gila Gaming Mouse");
break;
case USB_DEVICE_ID_GENIUS_GX_IMPERATOR:
rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 83,
"Genius Gx Imperator Keyboard");
break;
case USB_DEVICE_ID_GENIUS_MANTICORE:
rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104,
"Genius Manticore Keyboard");
break;
}
return rdesc;
}
Commit Message: HID: fix a couple of off-by-ones
There are a few very theoretical off-by-one bugs in report descriptor size
checking when performing a pre-parsing fixup. Fix those.
Cc: [email protected]
Reported-by: Ben Hawkes <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
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: png_get_uint_31(png_structp png_ptr, png_bytep buf)
{
#ifdef PNG_READ_BIG_ENDIAN_SUPPORTED
png_uint_32 i = png_get_uint_32(buf);
#else
/* Avoid an extra function call by inlining the result. */
png_uint_32 i = ((png_uint_32)(*buf) << 24) +
((png_uint_32)(*(buf + 1)) << 16) +
((png_uint_32)(*(buf + 2)) << 8) +
(png_uint_32)(*(buf + 3));
#endif
if (i > PNG_UINT_31_MAX)
png_error(png_ptr, "PNG unsigned integer out of range.");
return (i);
}
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: 1
Example 2:
Code: bool BluetoothDeviceChromeOS::IsConnecting() const {
return num_connecting_calls_ > 0;
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 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: static void red_channel_client_send_migrate(RedChannelClient *rcc)
{
SpiceMsgMigrate migrate;
red_channel_client_init_send_data(rcc, SPICE_MSG_MIGRATE, NULL);
migrate.flags = rcc->channel->migration_flags;
spice_marshall_msg_migrate(rcc->send_data.marshaller, &migrate);
if (rcc->channel->migration_flags & SPICE_MIGRATE_NEED_FLUSH) {
rcc->wait_migrate_flush_mark = TRUE;
}
red_channel_client_begin_send_message(rcc);
}
Commit Message:
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: hstore_from_record(PG_FUNCTION_ARGS)
{
HeapTupleHeader rec;
int32 buflen;
HStore *out;
Pairs *pairs;
Oid tupType;
int32 tupTypmod;
TupleDesc tupdesc;
HeapTupleData tuple;
RecordIOData *my_extra;
int ncolumns;
int i,
j;
Datum *values;
bool *nulls;
if (PG_ARGISNULL(0))
{
Oid argtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
/*
* have no tuple to look at, so the only source of type info is the
* argtype. The lookup_rowtype_tupdesc call below will error out if we
* don't have a known composite type oid here.
*/
tupType = argtype;
tupTypmod = -1;
rec = NULL;
}
else
{
rec = PG_GETARG_HEAPTUPLEHEADER(0);
/* Extract type info from the tuple itself */
tupType = HeapTupleHeaderGetTypeId(rec);
tupTypmod = HeapTupleHeaderGetTypMod(rec);
}
tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
ncolumns = tupdesc->natts;
/*
* We arrange to look up the needed I/O info just once per series of
* calls, assuming the record type doesn't change underneath us.
*/
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
if (my_extra == NULL ||
my_extra->ncolumns != ncolumns)
{
fcinfo->flinfo->fn_extra =
MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
my_extra->record_type = InvalidOid;
my_extra->record_typmod = 0;
}
if (my_extra->record_type != tupType ||
my_extra->record_typmod != tupTypmod)
{
MemSet(my_extra, 0,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra->record_type = tupType;
my_extra->record_typmod = tupTypmod;
my_extra->ncolumns = ncolumns;
}
pairs = palloc(ncolumns * sizeof(Pairs));
if (rec)
{
/* Build a temporary HeapTuple control structure */
tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
ItemPointerSetInvalid(&(tuple.t_self));
tuple.t_tableOid = InvalidOid;
tuple.t_data = rec;
values = (Datum *) palloc(ncolumns * sizeof(Datum));
nulls = (bool *) palloc(ncolumns * sizeof(bool));
/* Break down the tuple into fields */
heap_deform_tuple(&tuple, tupdesc, values, nulls);
}
else
{
values = NULL;
nulls = NULL;
}
for (i = 0, j = 0; i < ncolumns; ++i)
{
ColumnIOData *column_info = &my_extra->columns[i];
Oid column_type = tupdesc->attrs[i]->atttypid;
char *value;
/* Ignore dropped columns in datatype */
if (tupdesc->attrs[i]->attisdropped)
continue;
pairs[j].key = NameStr(tupdesc->attrs[i]->attname);
pairs[j].keylen = hstoreCheckKeyLen(strlen(NameStr(tupdesc->attrs[i]->attname)));
if (!nulls || nulls[i])
{
pairs[j].val = NULL;
pairs[j].vallen = 4;
pairs[j].isnull = true;
pairs[j].needfree = false;
++j;
continue;
}
/*
* Convert the column value to text
*/
if (column_info->column_type != column_type)
{
bool typIsVarlena;
getTypeOutputInfo(column_type,
&column_info->typiofunc,
&typIsVarlena);
fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
fcinfo->flinfo->fn_mcxt);
column_info->column_type = column_type;
}
value = OutputFunctionCall(&column_info->proc, values[i]);
pairs[j].val = value;
pairs[j].vallen = hstoreCheckValLen(strlen(value));
pairs[j].isnull = false;
pairs[j].needfree = false;
++j;
}
ncolumns = hstoreUniquePairs(pairs, j, &buflen);
out = hstorePairs(pairs, ncolumns, buflen);
ReleaseTupleDesc(tupdesc);
PG_RETURN_POINTER(out);
}
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: CronTab::sort( ExtArray<int> &list )
{
int ctr, ctr2, value;
for ( ctr = 1; ctr <= list.getlast(); ctr++ ) {
value = list[ctr];
ctr2 = ctr;
while ( ( ctr2 > 0 ) && ( list[ctr2 - 1] > value ) ) {
list[ctr2] = list[ctr2 - 1];
ctr2--;
} // WHILE
list[ctr2] = value;
} // FOR
return;
}
Commit Message:
CWE ID: CWE-134
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 hns_ppe_cnt_clr_ce(struct hns_ppe_cb *ppe_cb)
{
dsaf_set_dev_bit(ppe_cb, PPE_TNL_0_5_CNT_CLR_CE_REG,
PPE_CNT_CLR_CE_B, 1);
}
Commit Message: net: hns: fix ethtool_get_strings overflow in hns driver
hns_get_sset_count() returns HNS_NET_STATS_CNT and the data space allocated
is not enough for ethtool_get_strings(), which will cause random memory
corruption.
When SLAB and DEBUG_SLAB are both enabled, memory corruptions like the
the following can be observed without this patch:
[ 43.115200] Slab corruption (Not tainted): Acpi-ParseExt start=ffff801fb0b69030, len=80
[ 43.115206] Redzone: 0x9f911029d006462/0x5f78745f31657070.
[ 43.115208] Last user: [<5f7272655f746b70>](0x5f7272655f746b70)
[ 43.115214] 010: 70 70 65 31 5f 74 78 5f 70 6b 74 00 6b 6b 6b 6b ppe1_tx_pkt.kkkk
[ 43.115217] 030: 70 70 65 31 5f 74 78 5f 70 6b 74 5f 6f 6b 00 6b ppe1_tx_pkt_ok.k
[ 43.115218] Next obj: start=ffff801fb0b69098, len=80
[ 43.115220] Redzone: 0x706d655f6f666966/0x9f911029d74e35b.
[ 43.115229] Last user: [<ffff0000084b11b0>](acpi_os_release_object+0x28/0x38)
[ 43.115231] 000: 74 79 00 6b 6b 6b 6b 6b 70 70 65 31 5f 74 78 5f ty.kkkkkppe1_tx_
[ 43.115232] 010: 70 6b 74 5f 65 72 72 5f 63 73 75 6d 5f 66 61 69 pkt_err_csum_fai
Signed-off-by: Timmy Li <[email protected]>
Signed-off-by: David S. Miller <[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: AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len)
{
guint8 key_version;
guint8 *key_data;
guint8 *szEncryptedKey;
guint16 key_bytes_len = 0; /* Length of the total key data field */
guint16 key_len; /* Actual group key length */
static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
/* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */
/* Preparation for decrypting the group key - determine group key data length */
/* depending on whether the pairwise key is TKIP or AES encryption key */
key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]);
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
/* TKIP */
key_bytes_len = pntoh16(pEAPKey->key_length);
}else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES */
key_bytes_len = pntoh16(pEAPKey->key_data_len);
/* AES keys must be at least 128 bits = 16 bytes. */
if (key_bytes_len < 16) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
}
if (key_bytes_len < GROUP_KEY_MIN_LEN || key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY)) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Encrypted key is in the information element field of the EAPOL key packet */
key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY);
szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len);
DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len);
DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16);
DEBUG_DUMP("decryption_key:", decryption_key, 16);
/* We are rekeying, save old sa */
tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION));
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
/* As we have no concept of the prior association request at this point, we need to deduce the */
/* group key cipher from the length of the key bytes. In WPA this is straightforward as the */
/* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */
/* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */
/* does not. Also there are other (variable length) items in the keybytes which we need to account */
/* for to determine the true key length, and thus the group cipher. */
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
guint8 new_key[32];
guint8 dummy[256];
/* TKIP key */
/* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */
/* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */
rc4_state_struct rc4_state;
/* The WPA group key just contains the GTK bytes so deducing the type is straightforward */
/* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */
sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP;
/* Build the full decryption key based on the IV and part of the pairwise key */
memcpy(new_key, pEAPKey->key_iv, 16);
memcpy(new_key+16, decryption_key, 16);
DEBUG_DUMP("FullDecrKey:", new_key, 32);
crypt_rc4_init(&rc4_state, new_key, sizeof(new_key));
/* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */
crypt_rc4(&rc4_state, dummy, 256);
crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len);
} else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES CCMP key */
guint8 key_found;
guint8 key_length;
guint16 key_index;
guint8 *decrypted_data;
/* Unwrap the key; the result is key_bytes_len in length */
decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len);
/* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure.
The key itself is stored as a GTK KDE
WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to
pass pointer to the actual key with 8 bytes offset */
key_found = FALSE;
key_index = 0;
/* Parse Key data until we found GTK KDE */
/* GTK KDE = 00-0F-AC 01 */
while(key_index < (key_bytes_len - 6) && !key_found){
guint8 rsn_id;
guint32 type;
/* Get RSN ID */
rsn_id = decrypted_data[key_index];
type = ((decrypted_data[key_index + 2] << 24) +
(decrypted_data[key_index + 3] << 16) +
(decrypted_data[key_index + 4] << 8) +
(decrypted_data[key_index + 5]));
if (rsn_id == 0xdd && type == 0x000fac01) {
key_found = TRUE;
} else {
key_index += decrypted_data[key_index+1]+2;
}
}
if (key_found){
key_length = decrypted_data[key_index+1] - 6;
if (key_index+8 >= key_bytes_len ||
key_length > key_bytes_len - key_index - 8) {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Skip over the GTK header info, and don't copy past the end of the encrypted data */
memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length);
} else {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
if (key_length == TKIP_GROUP_KEY_LEN)
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP;
else
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
g_free(decrypted_data);
}
key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN;
if (key_len > key_bytes_len) {
/* the key required for this protocol is longer than the key that we just calculated */
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Decrypted key is now in szEncryptedKey with len of key_len */
DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len);
/* Load the proper key material info into the SA */
sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */
sa->validKey = TRUE;
/* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */
/* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */
memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk));
memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len);
g_free(szEncryptedKey);
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
Commit Message: Sanity check eapol_len in AirPDcapDecryptWPABroadcastKey
Bug: 12175
Change-Id: Iaf977ba48f8668bf8095800a115ff9a3472dd893
Reviewed-on: https://code.wireshark.org/review/15326
Petri-Dish: Michael Mann <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Alexis La Goutte <[email protected]>
Reviewed-by: Peter Wu <[email protected]>
Tested-by: Peter Wu <[email protected]>
CWE ID: CWE-125
Target: 1
Example 2:
Code: int brnf_sysctl_call_tables(ctl_table * ctl, int write,
void __user * buffer, size_t * lenp, loff_t * ppos)
{
int ret;
ret = proc_dointvec(ctl, write, buffer, lenp, ppos);
if (write && *(int *)(ctl->data))
*(int *)(ctl->data) = 1;
return ret;
}
Commit Message: bridge: reset IPCB in br_parse_ip_options
Commit 462fb2af9788a82 (bridge : Sanitize skb before it enters the IP
stack), missed one IPCB init before calling ip_options_compile()
Thanks to Scot Doyle for his tests and bug reports.
Reported-by: Scot Doyle <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Hiroaki SHIMODA <[email protected]>
Acked-by: Bandan Das <[email protected]>
Acked-by: Stephen Hemminger <[email protected]>
Cc: Jan Lübbe <[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: ext2_xattr_cmp(struct ext2_xattr_header *header1,
struct ext2_xattr_header *header2)
{
struct ext2_xattr_entry *entry1, *entry2;
entry1 = ENTRY(header1+1);
entry2 = ENTRY(header2+1);
while (!IS_LAST_ENTRY(entry1)) {
if (IS_LAST_ENTRY(entry2))
return 1;
if (entry1->e_hash != entry2->e_hash ||
entry1->e_name_index != entry2->e_name_index ||
entry1->e_name_len != entry2->e_name_len ||
entry1->e_value_size != entry2->e_value_size ||
memcmp(entry1->e_name, entry2->e_name, entry1->e_name_len))
return 1;
if (entry1->e_value_block != 0 || entry2->e_value_block != 0)
return -EIO;
if (memcmp((char *)header1 + le16_to_cpu(entry1->e_value_offs),
(char *)header2 + le16_to_cpu(entry2->e_value_offs),
le32_to_cpu(entry1->e_value_size)))
return 1;
entry1 = EXT2_XATTR_NEXT(entry1);
entry2 = EXT2_XATTR_NEXT(entry2);
}
if (!IS_LAST_ENTRY(entry2))
return 1;
return 0;
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
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: static void encode_frame(vpx_codec_ctx_t *ctx,
const vpx_image_t *img,
vpx_codec_pts_t pts,
unsigned int duration,
vpx_enc_frame_flags_t flags,
unsigned int deadline,
VpxVideoWriter *writer) {
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags,
deadline);
if (res != VPX_CODEC_OK)
die_codec(ctx, "Failed to encode frame.");
while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) {
if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf,
pkt->data.frame.sz,
pkt->data.frame.pts))
die_codec(ctx, "Failed to write compressed frame.");
printf(keyframe ? "K" : ".");
fflush(stdout);
}
}
}
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 inline bool is_gp_fault(u32 intr_info)
{
return is_exception_n(intr_info, GP_VECTOR);
}
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 void ConvertHexadecimalToIDAlphabet(std::string* id) {
for (size_t i = 0; i < id->size(); ++i) {
int val;
if (base::HexStringToInt(id->begin() + i, id->begin() + i + 1, &val))
(*id)[i] = val + 'a';
else
(*id)[i] = 'a';
}
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
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: zsethalftone5(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
uint count;
gs_halftone_component *phtc = 0;
gs_halftone_component *pc;
int code = 0;
int j;
bool have_default;
gs_halftone *pht = 0;
gx_device_halftone *pdht = 0;
ref sprocs[GS_CLIENT_COLOR_MAX_COMPONENTS + 1];
ref tprocs[GS_CLIENT_COLOR_MAX_COMPONENTS + 1];
gs_memory_t *mem;
uint edepth = ref_stack_count(&e_stack);
int npop = 2;
int dict_enum = dict_first(op);
ref rvalue[2];
int cname, colorant_number;
byte * pname;
uint name_size;
int halftonetype, type = 0;
gs_gstate *pgs = igs;
int space_index = r_space_index(op - 1);
mem = (gs_memory_t *) idmemory->spaces_indexed[space_index];
* the device color space, so we need to mark them
* with a different internal halftone type.
*/
code = dict_int_param(op - 1, "HalftoneType", 1, 100, 0, &type);
if (code < 0)
return code;
halftonetype = (type == 2 || type == 4)
? ht_type_multiple_colorscreen
: ht_type_multiple;
/* Count how many components that we will actually use. */
have_default = false;
for (count = 0; ;) {
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/*
* Verify that we have a valid component. We may have a
* /HalfToneType entry.
*/
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component verify that we will use it. */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue;
else if (colorant_number == GX_DEVICE_COLOR_MAX_COMPONENTS) {
/* If here then we have the "Default" component */
if (have_default)
return_error(gs_error_rangecheck);
have_default = true;
}
count++;
/*
* Check to see if we have already reached the legal number of
* components.
*/
if (count > GS_CLIENT_COLOR_MAX_COMPONENTS + 1) {
code = gs_note_error(gs_error_rangecheck);
break;
}
}
if (count == 0 || (halftonetype == ht_type_multiple && ! have_default))
code = gs_note_error(gs_error_rangecheck);
if (code >= 0) {
check_estack(5); /* for sampling Type 1 screens */
refset_null(sprocs, count);
refset_null(tprocs, count);
rc_alloc_struct_0(pht, gs_halftone, &st_halftone,
imemory, pht = 0, ".sethalftone5");
phtc = gs_alloc_struct_array(mem, count, gs_halftone_component,
&st_ht_component_element,
".sethalftone5");
rc_alloc_struct_0(pdht, gx_device_halftone, &st_device_halftone,
imemory, pdht = 0, ".sethalftone5");
if (pht == 0 || phtc == 0 || pdht == 0) {
j = 0; /* Quiet the compiler:
gs_note_error isn't necessarily identity,
so j could be left ununitialized. */
code = gs_note_error(gs_error_VMerror);
}
}
if (code >= 0) {
dict_enum = dict_first(op);
for (j = 0, pc = phtc; ;) {
int type;
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/*
* Verify that we have a valid component. We may have a
* /HalfToneType entry.
*/
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue; /* Do not use this component */
pc->cname = cname;
pc->comp_number = colorant_number;
/* Now process the component dictionary */
check_dict_read(rvalue[1]);
if (dict_int_param(&rvalue[1], "HalftoneType", 1, 7, 0, &type) < 0) {
code = gs_note_error(gs_error_typecheck);
break;
}
switch (type) {
default:
code = gs_note_error(gs_error_rangecheck);
break;
case 1:
code = dict_spot_params(&rvalue[1], &pc->params.spot,
sprocs + j, tprocs + j, mem);
pc->params.spot.screen.spot_function = spot1_dummy;
pc->type = ht_type_spot;
break;
case 3:
code = dict_threshold_params(&rvalue[1], &pc->params.threshold,
tprocs + j);
pc->type = ht_type_threshold;
break;
case 7:
code = dict_threshold2_params(&rvalue[1], &pc->params.threshold2,
tprocs + j, imemory);
pc->type = ht_type_threshold2;
break;
}
if (code < 0)
break;
pc++;
j++;
}
}
if (code >= 0) {
pht->type = halftonetype;
pht->params.multiple.components = phtc;
pht->params.multiple.num_comp = j;
pht->params.multiple.get_colorname_string = gs_get_colorname_string;
code = gs_sethalftone_prepare(igs, pht, pdht);
}
if (code >= 0) {
/*
* Put the actual frequency and angle in the spot function component dictionaries.
*/
dict_enum = dict_first(op);
for (pc = phtc; ; ) {
/* Move to next element in the dictionary */
if ((dict_enum = dict_next(op, dict_enum, rvalue)) == -1)
break;
/* Verify that we have a valid component */
if (!r_has_type(&rvalue[0], t_name))
continue;
if (!r_has_type(&rvalue[1], t_dictionary))
continue;
/* Get the name of the component and verify that we will use it. */
cname = name_index(mem, &rvalue[0]);
code = gs_get_colorname_string(mem, cname, &pname, &name_size);
if (code < 0)
break;
colorant_number = gs_cname_to_colorant_number(pgs, pname, name_size,
halftonetype);
if (colorant_number < 0)
continue;
if (pc->type == ht_type_spot) {
code = dict_spot_results(i_ctx_p, &rvalue[1], &pc->params.spot);
if (code < 0)
break;
}
pc++;
}
}
if (code >= 0) {
/*
* Schedule the sampling of any Type 1 screens,
* and any (Type 1 or Type 3) TransferFunctions.
* Save the stack depths in case we have to back out.
*/
uint odepth = ref_stack_count(&o_stack);
ref odict, odict5;
odict = op[-1];
odict5 = *op;
pop(2);
op = osp;
esp += 5;
make_mark_estack(esp - 4, es_other, sethalftone_cleanup);
esp[-3] = odict;
make_istruct(esp - 2, 0, pht);
make_istruct(esp - 1, 0, pdht);
make_op_estack(esp, sethalftone_finish);
for (j = 0; j < count; j++) {
gx_ht_order *porder = NULL;
if (pdht->components == 0)
porder = &pdht->order;
else {
/* Find the component in pdht that matches component j in
the pht; gs_sethalftone_prepare() may permute these. */
int k;
int comp_number = phtc[j].comp_number;
for (k = 0; k < count; k++) {
if (pdht->components[k].comp_number == comp_number) {
porder = &pdht->components[k].corder;
break;
}
}
}
switch (phtc[j].type) {
case ht_type_spot:
code = zscreen_enum_init(i_ctx_p, porder,
&phtc[j].params.spot.screen,
&sprocs[j], 0, 0, space_index);
if (code < 0)
break;
/* falls through */
case ht_type_threshold:
if (!r_has_type(tprocs + j, t__invalid)) {
/* Schedule TransferFunction sampling. */
/****** check_xstack IS WRONG ******/
check_ostack(zcolor_remap_one_ostack);
check_estack(zcolor_remap_one_estack);
code = zcolor_remap_one(i_ctx_p, tprocs + j,
porder->transfer, igs,
zcolor_remap_one_finish);
op = osp;
}
break;
default: /* not possible here, but to keep */
/* the compilers happy.... */
;
}
if (code < 0) { /* Restore the stack. */
ref_stack_pop_to(&o_stack, odepth);
ref_stack_pop_to(&e_stack, edepth);
op = osp;
op[-1] = odict;
*op = odict5;
break;
}
npop = 0;
}
}
if (code < 0) {
gs_free_object(mem, pdht, ".sethalftone5");
gs_free_object(mem, phtc, ".sethalftone5");
gs_free_object(mem, pht, ".sethalftone5");
return code;
}
pop(npop);
return (ref_stack_count(&e_stack) > edepth ? o_push_estack : 0);
}
Commit Message:
CWE ID: CWE-704
Target: 1
Example 2:
Code: static int btrfs_getattr(struct vfsmount *mnt,
struct dentry *dentry, struct kstat *stat)
{
u64 delalloc_bytes;
struct inode *inode = d_inode(dentry);
u32 blocksize = inode->i_sb->s_blocksize;
generic_fillattr(inode, stat);
stat->dev = BTRFS_I(inode)->root->anon_dev;
stat->blksize = PAGE_CACHE_SIZE;
spin_lock(&BTRFS_I(inode)->lock);
delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
spin_unlock(&BTRFS_I(inode)->lock);
stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
ALIGN(delalloc_bytes, blocksize)) >> 9;
return 0;
}
Commit Message: Btrfs: fix truncation of compressed and inlined extents
When truncating a file to a smaller size which consists of an inline
extent that is compressed, we did not discard (or made unusable) the
data between the new file size and the old file size, wasting metadata
space and allowing for the truncated data to be leaked and the data
corruption/loss mentioned below.
We were also not correctly decrementing the number of bytes used by the
inode, we were setting it to zero, giving a wrong report for callers of
the stat(2) syscall. The fsck tool also reported an error about a mismatch
between the nbytes of the file versus the real space used by the file.
Now because we weren't discarding the truncated region of the file, it
was possible for a caller of the clone ioctl to actually read the data
that was truncated, allowing for a security breach without requiring root
access to the system, using only standard filesystem operations. The
scenario is the following:
1) User A creates a file which consists of an inline and compressed
extent with a size of 2000 bytes - the file is not accessible to
any other users (no read, write or execution permission for anyone
else);
2) The user truncates the file to a size of 1000 bytes;
3) User A makes the file world readable;
4) User B creates a file consisting of an inline extent of 2000 bytes;
5) User B issues a clone operation from user A's file into its own
file (using a length argument of 0, clone the whole range);
6) User B now gets to see the 1000 bytes that user A truncated from
its file before it made its file world readbale. User B also lost
the bytes in the range [1000, 2000[ bytes from its own file, but
that might be ok if his/her intention was reading stale data from
user A that was never supposed to be public.
Note that this contrasts with the case where we truncate a file from 2000
bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In
this case reading any byte from the range [1000, 2000[ will return a value
of 0x00, instead of the original data.
This problem exists since the clone ioctl was added and happens both with
and without my recent data loss and file corruption fixes for the clone
ioctl (patch "Btrfs: fix file corruption and data loss after cloning
inline extents").
So fix this by truncating the compressed inline extents as we do for the
non-compressed case, which involves decompressing, if the data isn't already
in the page cache, compressing the truncated version of the extent, writing
the compressed content into the inline extent and then truncate it.
The following test case for fstests reproduces the problem. In order for
the test to pass both this fix and my previous fix for the clone ioctl
that forbids cloning a smaller inline extent into a larger one,
which is titled "Btrfs: fix file corruption and data loss after cloning
inline extents", are needed. Without that other fix the test fails in a
different way that does not leak the truncated data, instead part of
destination file gets replaced with zeroes (because the destination file
has a larger inline extent than the source).
seq=`basename $0`
seqres=$RESULT_DIR/$seq
echo "QA output created by $seq"
tmp=/tmp/$$
status=1 # failure is the default!
trap "_cleanup; exit \$status" 0 1 2 3 15
_cleanup()
{
rm -f $tmp.*
}
# get standard environment, filters and checks
. ./common/rc
. ./common/filter
# real QA test starts here
_need_to_be_root
_supported_fs btrfs
_supported_os Linux
_require_scratch
_require_cloner
rm -f $seqres.full
_scratch_mkfs >>$seqres.full 2>&1
_scratch_mount "-o compress"
# Create our test files. File foo is going to be the source of a clone operation
# and consists of a single inline extent with an uncompressed size of 512 bytes,
# while file bar consists of a single inline extent with an uncompressed size of
# 256 bytes. For our test's purpose, it's important that file bar has an inline
# extent with a size smaller than foo's inline extent.
$XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \
-c "pwrite -S 0x2a 128 384" \
$SCRATCH_MNT/foo | _filter_xfs_io
$XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io
# Now durably persist all metadata and data. We do this to make sure that we get
# on disk an inline extent with a size of 512 bytes for file foo.
sync
# Now truncate our file foo to a smaller size. Because it consists of a
# compressed and inline extent, btrfs did not shrink the inline extent to the
# new size (if the extent was not compressed, btrfs would shrink it to 128
# bytes), it only updates the inode's i_size to 128 bytes.
$XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo
# Now clone foo's inline extent into bar.
# This clone operation should fail with errno EOPNOTSUPP because the source
# file consists only of an inline extent and the file's size is smaller than
# the inline extent of the destination (128 bytes < 256 bytes). However the
# clone ioctl was not prepared to deal with a file that has a size smaller
# than the size of its inline extent (something that happens only for compressed
# inline extents), resulting in copying the full inline extent from the source
# file into the destination file.
#
# Note that btrfs' clone operation for inline extents consists of removing the
# inline extent from the destination inode and copy the inline extent from the
# source inode into the destination inode, meaning that if the destination
# inode's inline extent is larger (N bytes) than the source inode's inline
# extent (M bytes), some bytes (N - M bytes) will be lost from the destination
# file. Btrfs could copy the source inline extent's data into the destination's
# inline extent so that we would not lose any data, but that's currently not
# done due to the complexity that would be needed to deal with such cases
# (specially when one or both extents are compressed), returning EOPNOTSUPP, as
# it's normally not a very common case to clone very small files (only case
# where we get inline extents) and copying inline extents does not save any
# space (unlike for normal, non-inlined extents).
$CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar
# Now because the above clone operation used to succeed, and due to foo's inline
# extent not being shinked by the truncate operation, our file bar got the whole
# inline extent copied from foo, making us lose the last 128 bytes from bar
# which got replaced by the bytes in range [128, 256[ from foo before foo was
# truncated - in other words, data loss from bar and being able to read old and
# stale data from foo that should not be possible to read anymore through normal
# filesystem operations. Contrast with the case where we truncate a file from a
# size N to a smaller size M, truncate it back to size N and then read the range
# [M, N[, we should always get the value 0x00 for all the bytes in that range.
# We expected the clone operation to fail with errno EOPNOTSUPP and therefore
# not modify our file's bar data/metadata. So its content should be 256 bytes
# long with all bytes having the value 0xbb.
#
# Without the btrfs bug fix, the clone operation succeeded and resulted in
# leaking truncated data from foo, the bytes that belonged to its range
# [128, 256[, and losing data from bar in that same range. So reading the
# file gave us the following content:
#
# 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1
# *
# 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a
# *
# 0000400
echo "File bar's content after the clone operation:"
od -t x1 $SCRATCH_MNT/bar
# Also because the foo's inline extent was not shrunk by the truncate
# operation, btrfs' fsck, which is run by the fstests framework everytime a
# test completes, failed reporting the following error:
#
# root 5 inode 257 errors 400, nbytes wrong
status=0
exit
Cc: [email protected]
Signed-off-by: Filipe Manana <[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: static void ep_ptable_queue_proc(struct file *file, wait_queue_head_t *whead,
poll_table *pt)
{
struct epitem *epi = ep_item_from_epqueue(pt);
struct eppoll_entry *pwq;
if (epi->nwait >= 0 && (pwq = kmem_cache_alloc(pwq_cache, GFP_KERNEL))) {
init_waitqueue_func_entry(&pwq->wait, ep_poll_callback);
pwq->whead = whead;
pwq->base = epi;
add_wait_queue(whead, &pwq->wait);
list_add_tail(&pwq->llink, &epi->pwqlist);
epi->nwait++;
} else {
/* We have to signal that an error occurred */
epi->nwait = -1;
}
}
Commit Message: epoll: clear the tfile_check_list on -ELOOP
An epoll_ctl(,EPOLL_CTL_ADD,,) operation can return '-ELOOP' to prevent
circular epoll dependencies from being created. However, in that case we
do not properly clear the 'tfile_check_list'. Thus, add a call to
clear_tfile_check_list() for the -ELOOP case.
Signed-off-by: Jason Baron <[email protected]>
Reported-by: Yurij M. Plotnikov <[email protected]>
Cc: Nelson Elhage <[email protected]>
Cc: Davide Libenzi <[email protected]>
Tested-by: Alexandra N. Kossovsky <[email protected]>
Signed-off-by: Andrew Morton <[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: OMX_ERRORTYPE SoftAMRNBEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPortFormat:
{
OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
formatParams->eEncoding =
(formatParams->nPortIndex == 0)
? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAMR;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAmr:
{
OMX_AUDIO_PARAM_AMRTYPE *amrParams =
(OMX_AUDIO_PARAM_AMRTYPE *)params;
if (amrParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
amrParams->nChannels = 1;
amrParams->nBitRate = mBitRate;
amrParams->eAMRBandMode = (OMX_AUDIO_AMRBANDMODETYPE)(mMode + 1);
amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelCF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = kSampleRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(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: static int send_cmd(struct usb_device *dev, __u8 command,
__u8 moduleid, __u16 value, u8 *data,
int size)
{
return ti_vsend_sync(dev, command, value, moduleid, data, size);
}
Commit Message: USB: io_ti: Fix NULL dereference in chase_port()
The tty is NULL when the port is hanging up.
chase_port() needs to check for this.
This patch is intended for stable series.
The behavior was observed and tested in Linux 3.2 and 3.7.1.
Johan Hovold submitted a more elaborate patch for the mainline kernel.
[ 56.277883] usb 1-1: edge_bulk_in_callback - nonzero read bulk status received: -84
[ 56.278811] usb 1-1: USB disconnect, device number 3
[ 56.278856] usb 1-1: edge_bulk_in_callback - stopping read!
[ 56.279562] BUG: unable to handle kernel NULL pointer dereference at 00000000000001c8
[ 56.280536] IP: [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35
[ 56.281212] PGD 1dc1b067 PUD 1e0f7067 PMD 0
[ 56.282085] Oops: 0002 [#1] SMP
[ 56.282744] Modules linked in:
[ 56.283512] CPU 1
[ 56.283512] Pid: 25, comm: khubd Not tainted 3.7.1 #1 innotek GmbH VirtualBox/VirtualBox
[ 56.283512] RIP: 0010:[<ffffffff8144e62a>] [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35
[ 56.283512] RSP: 0018:ffff88001fa99ab0 EFLAGS: 00010046
[ 56.283512] RAX: 0000000000000046 RBX: 00000000000001c8 RCX: 0000000000640064
[ 56.283512] RDX: 0000000000010000 RSI: ffff88001fa99b20 RDI: 00000000000001c8
[ 56.283512] RBP: ffff88001fa99b20 R08: 0000000000000000 R09: 0000000000000000
[ 56.283512] R10: 0000000000000000 R11: ffffffff812fcb4c R12: ffff88001ddf53c0
[ 56.283512] R13: 0000000000000000 R14: 00000000000001c8 R15: ffff88001e19b9f4
[ 56.283512] FS: 0000000000000000(0000) GS:ffff88001fd00000(0000) knlGS:0000000000000000
[ 56.283512] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[ 56.283512] CR2: 00000000000001c8 CR3: 000000001dc51000 CR4: 00000000000006e0
[ 56.283512] DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
[ 56.283512] DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
[ 56.283512] Process khubd (pid: 25, threadinfo ffff88001fa98000, task ffff88001fa94f80)
[ 56.283512] Stack:
[ 56.283512] 0000000000000046 00000000000001c8 ffffffff810578ec ffffffff812fcb4c
[ 56.283512] ffff88001e19b980 0000000000002710 ffffffff812ffe81 0000000000000001
[ 56.283512] ffff88001fa94f80 0000000000000202 ffffffff00000001 0000000000000296
[ 56.283512] Call Trace:
[ 56.283512] [<ffffffff810578ec>] ? add_wait_queue+0x12/0x3c
[ 56.283512] [<ffffffff812fcb4c>] ? usb_serial_port_work+0x28/0x28
[ 56.283512] [<ffffffff812ffe81>] ? chase_port+0x84/0x2d6
[ 56.283512] [<ffffffff81063f27>] ? try_to_wake_up+0x199/0x199
[ 56.283512] [<ffffffff81263a5c>] ? tty_ldisc_hangup+0x222/0x298
[ 56.283512] [<ffffffff81300171>] ? edge_close+0x64/0x129
[ 56.283512] [<ffffffff810612f7>] ? __wake_up+0x35/0x46
[ 56.283512] [<ffffffff8106135b>] ? should_resched+0x5/0x23
[ 56.283512] [<ffffffff81264916>] ? tty_port_shutdown+0x39/0x44
[ 56.283512] [<ffffffff812fcb4c>] ? usb_serial_port_work+0x28/0x28
[ 56.283512] [<ffffffff8125d38c>] ? __tty_hangup+0x307/0x351
[ 56.283512] [<ffffffff812e6ddc>] ? usb_hcd_flush_endpoint+0xde/0xed
[ 56.283512] [<ffffffff8144e625>] ? _raw_spin_lock_irqsave+0x14/0x35
[ 56.283512] [<ffffffff812fd361>] ? usb_serial_disconnect+0x57/0xc2
[ 56.283512] [<ffffffff812ea99b>] ? usb_unbind_interface+0x5c/0x131
[ 56.283512] [<ffffffff8128d738>] ? __device_release_driver+0x7f/0xd5
[ 56.283512] [<ffffffff8128d9cd>] ? device_release_driver+0x1a/0x25
[ 56.283512] [<ffffffff8128d393>] ? bus_remove_device+0xd2/0xe7
[ 56.283512] [<ffffffff8128b7a3>] ? device_del+0x119/0x167
[ 56.283512] [<ffffffff812e8d9d>] ? usb_disable_device+0x6a/0x180
[ 56.283512] [<ffffffff812e2ae0>] ? usb_disconnect+0x81/0xe6
[ 56.283512] [<ffffffff812e4435>] ? hub_thread+0x577/0xe82
[ 56.283512] [<ffffffff8144daa7>] ? __schedule+0x490/0x4be
[ 56.283512] [<ffffffff8105798f>] ? abort_exclusive_wait+0x79/0x79
[ 56.283512] [<ffffffff812e3ebe>] ? usb_remote_wakeup+0x2f/0x2f
[ 56.283512] [<ffffffff812e3ebe>] ? usb_remote_wakeup+0x2f/0x2f
[ 56.283512] [<ffffffff810570b4>] ? kthread+0x81/0x89
[ 56.283512] [<ffffffff81057033>] ? __kthread_parkme+0x5c/0x5c
[ 56.283512] [<ffffffff8145387c>] ? ret_from_fork+0x7c/0xb0
[ 56.283512] [<ffffffff81057033>] ? __kthread_parkme+0x5c/0x5c
[ 56.283512] Code: 8b 7c 24 08 e8 17 0b c3 ff 48 8b 04 24 48 83 c4 10 c3 53 48 89 fb 41 50 e8 e0 0a c3 ff 48 89 04 24 e8 e7 0a c3 ff ba 00 00 01 00
<f0> 0f c1 13 48 8b 04 24 89 d1 c1 ea 10 66 39 d1 74 07 f3 90 66
[ 56.283512] RIP [<ffffffff8144e62a>] _raw_spin_lock_irqsave+0x19/0x35
[ 56.283512] RSP <ffff88001fa99ab0>
[ 56.283512] CR2: 00000000000001c8
[ 56.283512] ---[ end trace 49714df27e1679ce ]---
Signed-off-by: Wolfgang Frisch <[email protected]>
Cc: Johan Hovold <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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: jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
int i, j;
int w, h;
int leftbyte, rightbyte;
int shift;
uint8_t *s, *ss;
uint8_t *d, *dd;
uint8_t mask, rightmask;
if (op != JBIG2_COMPOSE_OR) {
/* hand off the the general routine */
return jbig2_image_compose_unopt(ctx, dst, src, x, y, op);
}
/* clip */
w = src->width;
h = src->height;
ss = src->data;
if (x < 0) {
w += x;
x = 0;
}
if (y < 0) {
h += y;
y = 0;
}
w = (x + w < dst->width) ? w : dst->width - x;
h = (y + h < dst->height) ? h : dst->height - y;
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping\n", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
#if 0
/* special case complete/strip replacement */
/* disabled because it's only safe to do when the destination
buffer is all-blank. */
if ((x == 0) && (w == src->width)) {
memcpy(dst->data + y * dst->stride, src->data, h * src->stride);
return 0;
}
#endif
leftbyte = x >> 3;
rightbyte = (x + w - 1) >> 3;
shift = x & 7;
/* general OR case */
s = ss;
d = dd = dst->data + y * dst->stride + leftbyte;
if (d < dst->data || leftbyte > dst->stride || h * dst->stride < 0 || d - leftbyte + h * dst->stride > dst->data + dst->height * dst->stride) {
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "preventing heap overflow in jbig2_image_compose");
}
if (leftbyte == rightbyte) {
mask = 0x100 - (0x100 >> w);
for (j = 0; j < h; j++) {
*d |= (*s & mask) >> shift;
d += dst->stride;
s += src->stride;
}
} else if (shift == 0) {
rightmask = (w & 7) ? 0x100 - (1 << (8 - (w & 7))) : 0xFF;
for (j = 0; j < h; j++) {
for (i = leftbyte; i < rightbyte; i++)
*d++ |= *s++;
*d |= *s & rightmask;
d = (dd += dst->stride);
s = (ss += src->stride);
}
} else {
bool overlap = (((w + 7) >> 3) < ((x + w + 7) >> 3) - (x >> 3));
mask = 0x100 - (1 << shift);
if (overlap)
rightmask = (0x100 - (0x100 >> ((x + w) & 7))) >> (8 - shift);
else
rightmask = 0x100 - (0x100 >> (w & 7));
for (j = 0; j < h; j++) {
*d++ |= (*s & mask) >> shift;
for (i = leftbyte; i < rightbyte - 1; i++) {
*d |= ((*s++ & ~mask) << (8 - shift));
*d++ |= ((*s & mask) >> shift);
}
if (overlap)
*d |= (*s & rightmask) << (8 - shift);
else
*d |= ((s[0] & ~mask) << (8 - shift)) | ((s[1] & rightmask) >> shift);
d = (dd += dst->stride);
s = (ss += src->stride);
}
}
return 0;
}
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 UpdateProperty(IBusProperty* ibus_prop) {
DLOG(INFO) << "UpdateProperty";
DCHECK(ibus_prop);
ImePropertyList prop_list; // our representation.
if (!FlattenProperty(ibus_prop, &prop_list)) {
LOG(ERROR) << "Malformed properties are detected";
return;
}
if (!prop_list.empty()) {
update_ime_property_(language_library_, prop_list);
}
}
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: badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack)
{
unsigned long long sector;
int length;
char newline;
#ifdef DO_DEBUG
/* Allow clearing via sysfs *only* for testing/debugging.
* Normally only a successful write may clear a badblock
*/
int clear = 0;
if (page[0] == '-') {
clear = 1;
page++;
}
#endif /* DO_DEBUG */
switch (sscanf(page, "%llu %d%c", §or, &length, &newline)) {
case 3:
if (newline != '\n')
return -EINVAL;
case 2:
if (length <= 0)
return -EINVAL;
break;
default:
return -EINVAL;
}
#ifdef DO_DEBUG
if (clear) {
md_clear_badblocks(bb, sector, length);
return len;
}
#endif /* DO_DEBUG */
if (md_set_badblocks(bb, sector, length, !unack))
return len;
else
return -ENOSPC;
}
Commit Message: md: use kzalloc() when bitmap is disabled
In drivers/md/md.c get_bitmap_file() uses kmalloc() for creating a
mdu_bitmap_file_t called "file".
5769 file = kmalloc(sizeof(*file), GFP_NOIO);
5770 if (!file)
5771 return -ENOMEM;
This structure is copied to user space at the end of the function.
5786 if (err == 0 &&
5787 copy_to_user(arg, file, sizeof(*file)))
5788 err = -EFAULT
But if bitmap is disabled only the first byte of "file" is initialized
with zero, so it's possible to read some bytes (up to 4095) of kernel
space memory from user space. This is an information leak.
5775 /* bitmap disabled, zero the first byte and copy out */
5776 if (!mddev->bitmap_info.file)
5777 file->pathname[0] = '\0';
Signed-off-by: Benjamin Randazzo <[email protected]>
Signed-off-by: NeilBrown <[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: status_t BnSoundTriggerHwService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case LIST_MODULES: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
unsigned int numModulesReq = data.readInt32();
unsigned int numModules = numModulesReq;
struct sound_trigger_module_descriptor *modules =
(struct sound_trigger_module_descriptor *)calloc(numModulesReq,
sizeof(struct sound_trigger_module_descriptor));
status_t status = listModules(modules, &numModules);
reply->writeInt32(status);
reply->writeInt32(numModules);
ALOGV("LIST_MODULES status %d got numModules %d", status, numModules);
if (status == NO_ERROR) {
if (numModulesReq > numModules) {
numModulesReq = numModules;
}
reply->write(modules,
numModulesReq * sizeof(struct sound_trigger_module_descriptor));
}
free(modules);
return NO_ERROR;
}
case ATTACH: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
sound_trigger_module_handle_t handle;
data.read(&handle, sizeof(sound_trigger_module_handle_t));
sp<ISoundTriggerClient> client =
interface_cast<ISoundTriggerClient>(data.readStrongBinder());
sp<ISoundTrigger> module;
status_t status = attach(handle, client, module);
reply->writeInt32(status);
if (module != 0) {
reply->writeInt32(1);
reply->writeStrongBinder(IInterface::asBinder(module));
} else {
reply->writeInt32(0);
}
return NO_ERROR;
} break;
case SET_CAPTURE_STATE: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
reply->writeInt32(setCaptureState((bool)data.readInt32()));
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: Check memory allocation in ISoundTriggerHwService
Add memory allocation check in ISoundTriggerHwService::listModules().
Bug: 19385640.
Change-Id: Iaf74b6f154c3437e1bfc9da78b773d64b16a7604
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 CreatePersistentHistogramAllocator() {
allocator_memory_.reset(new char[kAllocatorMemorySize]);
GlobalHistogramAllocator::ReleaseForTesting();
memset(allocator_memory_.get(), 0, kAllocatorMemorySize);
GlobalHistogramAllocator::GetCreateHistogramResultHistogram();
GlobalHistogramAllocator::CreateWithPersistentMemory(
allocator_memory_.get(), kAllocatorMemorySize, 0, 0,
"PersistentHistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264
Target: 1
Example 2:
Code: ZSTD_selectEncodingType(
FSE_repeat* repeatMode, unsigned const* count, unsigned const max,
size_t const mostFrequent, size_t nbSeq, unsigned const FSELog,
FSE_CTable const* prevCTable,
short const* defaultNorm, U32 defaultNormLog,
ZSTD_defaultPolicy_e const isDefaultAllowed,
ZSTD_strategy const strategy)
{
ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0);
if (mostFrequent == nbSeq) {
*repeatMode = FSE_repeat_none;
if (isDefaultAllowed && nbSeq <= 2) {
/* Prefer set_basic over set_rle when there are 2 or less symbols,
* since RLE uses 1 byte, but set_basic uses 5-6 bits per symbol.
* If basic encoding isn't possible, always choose RLE.
*/
DEBUGLOG(5, "Selected set_basic");
return set_basic;
}
DEBUGLOG(5, "Selected set_rle");
return set_rle;
}
if (strategy < ZSTD_lazy) {
if (isDefaultAllowed) {
size_t const staticFse_nbSeq_max = 1000;
size_t const mult = 10 - strategy;
size_t const baseLog = 3;
size_t const dynamicFse_nbSeq_min = (((size_t)1 << defaultNormLog) * mult) >> baseLog; /* 28-36 for offset, 56-72 for lengths */
assert(defaultNormLog >= 5 && defaultNormLog <= 6); /* xx_DEFAULTNORMLOG */
assert(mult <= 9 && mult >= 7);
if ( (*repeatMode == FSE_repeat_valid)
&& (nbSeq < staticFse_nbSeq_max) ) {
DEBUGLOG(5, "Selected set_repeat");
return set_repeat;
}
if ( (nbSeq < dynamicFse_nbSeq_min)
|| (mostFrequent < (nbSeq >> (defaultNormLog-1))) ) {
DEBUGLOG(5, "Selected set_basic");
/* The format allows default tables to be repeated, but it isn't useful.
* When using simple heuristics to select encoding type, we don't want
* to confuse these tables with dictionaries. When running more careful
* analysis, we don't need to waste time checking both repeating tables
* and default tables.
*/
*repeatMode = FSE_repeat_none;
return set_basic;
}
}
} else {
size_t const basicCost = isDefaultAllowed ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, count, max) : ERROR(GENERIC);
size_t const repeatCost = *repeatMode != FSE_repeat_none ? ZSTD_fseBitCost(prevCTable, count, max) : ERROR(GENERIC);
size_t const NCountCost = ZSTD_NCountCost(count, max, nbSeq, FSELog);
size_t const compressedCost = (NCountCost << 3) + ZSTD_entropyCost(count, max, nbSeq);
if (isDefaultAllowed) {
assert(!ZSTD_isError(basicCost));
assert(!(*repeatMode == FSE_repeat_valid && ZSTD_isError(repeatCost)));
}
assert(!ZSTD_isError(NCountCost));
assert(compressedCost < ERROR(maxCode));
DEBUGLOG(5, "Estimated bit costs: basic=%u\trepeat=%u\tcompressed=%u",
(U32)basicCost, (U32)repeatCost, (U32)compressedCost);
if (basicCost <= repeatCost && basicCost <= compressedCost) {
DEBUGLOG(5, "Selected set_basic");
assert(isDefaultAllowed);
*repeatMode = FSE_repeat_none;
return set_basic;
}
if (repeatCost <= compressedCost) {
DEBUGLOG(5, "Selected set_repeat");
assert(!ZSTD_isError(repeatCost));
return set_repeat;
}
assert(compressedCost < basicCost && compressedCost < repeatCost);
}
DEBUGLOG(5, "Selected set_compressed");
*repeatMode = FSE_repeat_check;
return set_compressed;
}
Commit Message: fixed T36302429
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 filter_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
const int kInterp_Extend = 4;
const unsigned int intermediate_height =
(kInterp_Extend - 1) + output_height + kInterp_Extend;
/* Size of intermediate_buffer is max_intermediate_height * filter_max_width,
* where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height
* + kInterp_Extend
* = 3 + 16 + 4
* = 23
* and filter_max_width = 16
*/
uint8_t intermediate_buffer[71 * 64];
const int intermediate_next_stride = 1 - intermediate_height * output_width;
{
uint8_t *output_ptr = intermediate_buffer;
const int src_next_row_stride = src_stride - output_width;
unsigned int i, j;
src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1);
for (i = 0; i < intermediate_height; ++i) {
for (j = 0; j < output_width; ++j) {
const int temp = (src_ptr[0] * HFilter[0]) +
(src_ptr[1] * HFilter[1]) +
(src_ptr[2] * HFilter[2]) +
(src_ptr[3] * HFilter[3]) +
(src_ptr[4] * HFilter[4]) +
(src_ptr[5] * HFilter[5]) +
(src_ptr[6] * HFilter[6]) +
(src_ptr[7] * HFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
*output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT);
++src_ptr;
output_ptr += intermediate_height;
}
src_ptr += src_next_row_stride;
output_ptr += intermediate_next_stride;
}
}
{
uint8_t *src_ptr = intermediate_buffer;
const int dst_next_row_stride = dst_stride - output_width;
unsigned int i, j;
for (i = 0; i < output_height; ++i) {
for (j = 0; j < output_width; ++j) {
const int temp = (src_ptr[0] * VFilter[0]) +
(src_ptr[1] * VFilter[1]) +
(src_ptr[2] * VFilter[2]) +
(src_ptr[3] * VFilter[3]) +
(src_ptr[4] * VFilter[4]) +
(src_ptr[5] * VFilter[5]) +
(src_ptr[6] * VFilter[6]) +
(src_ptr[7] * VFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
*dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT);
src_ptr += intermediate_height;
}
src_ptr += intermediate_next_stride;
dst_ptr += dst_next_row_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
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 RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
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: void RunTransactionTestWithLog(net::HttpCache* cache,
const MockTransaction& trans_info,
const net::BoundNetLog& log) {
RunTransactionTestWithRequestAndLog(
cache, trans_info, MockHttpRequest(trans_info), NULL, log);
}
Commit Message: Http cache: Test deleting an entry with a pending_entry when
adding the truncated flag.
BUG=125159
TEST=net_unittests
Review URL: https://chromiumcodereview.appspot.com/10356113
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139331 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: dissect_FORM_1(tvbuff_t *tvb, int offset, packet_info *pinfo,
proto_tree *tree, dcerpc_info *di, guint8 *drep)
{
proto_tree *subtree;
guint32 flags;
subtree = proto_tree_add_subtree(tree, tvb, offset, 0, ett_FORM_1, NULL, "Form level 1");
offset = dissect_ndr_str_pointer_item(
tvb, offset, pinfo, subtree, di, drep, NDR_POINTER_UNIQUE,
"Name", hf_form_name, 0);
/* Eek - we need to know whether this pointer was NULL or not.
Currently there is not any way to do this. */
if (tvb_reported_length_remaining(tvb, offset) <= 0)
goto done;
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep, hf_form_flags, &flags);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_form_unknown, NULL);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_form_width, NULL);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_form_height, NULL);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_form_left_margin, NULL);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_form_top_margin, NULL);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_form_horiz_len, NULL);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_form_vert_len, NULL);
done:
return offset;
}
Commit Message: SPOOLSS: Try to avoid an infinite loop.
Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make
sure our offset always increments in dissect_spoolss_keybuffer.
Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793
Reviewed-on: https://code.wireshark.org/review/14687
Reviewed-by: Gerald Combs <[email protected]>
Petri-Dish: Gerald Combs <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[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: 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[0].dx == 0) || (jp2_image->comps[0].dy == 0) ||
(jp2_image->comps[0].dx != jp2_image->comps[i].dx) ||
(jp2_image->comps[0].dy != jp2_image->comps[i].dy) ||
(jp2_image->comps[0].prec != jp2_image->comps[i].prec) ||
(jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) ||
(jp2_image->comps[i].data == NULL))
{
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: https://github.com/ImageMagick/ImageMagick/issues/501
CWE ID: CWE-20
Target: 1
Example 2:
Code: PHP_MINIT_FUNCTION(phar) /* {{{ */
{
REGISTER_INI_ENTRIES();
phar_orig_compile_file = zend_compile_file;
zend_compile_file = phar_compile_file;
phar_save_resolve_path = zend_resolve_path;
zend_resolve_path = phar_resolve_path;
phar_object_init(TSRMLS_C);
phar_intercept_functions_init(TSRMLS_C);
phar_save_orig_functions(TSRMLS_C);
return php_register_url_stream_wrapper("phar", &php_stream_phar_wrapper TSRMLS_CC);
}
/* }}} */
Commit Message:
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 ChromeOSChangeInputMethod(
InputMethodStatusConnection* connection, const char* name) {
DCHECK(name);
DLOG(INFO) << "ChangeInputMethod: " << name;
g_return_val_if_fail(connection, false);
return connection->ChangeInputMethod(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
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: MediaControlsProgressView::MediaControlsProgressView(
base::RepeatingCallback<void(double)> seek_callback)
: seek_callback_(std::move(seek_callback)) {
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical, kProgressViewInsets));
progress_bar_ = AddChildView(std::make_unique<views::ProgressBar>(5, false));
progress_bar_->SetBorder(views::CreateEmptyBorder(kProgressBarInsets));
gfx::Font default_font;
int font_size_delta = kProgressTimeFontSize - 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 time_view = std::make_unique<views::View>();
auto* time_view_layout =
time_view->SetLayoutManager(std::make_unique<views::FlexLayout>());
time_view_layout->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetMainAxisAlignment(views::LayoutAlignment::kCenter)
.SetCrossAxisAlignment(views::LayoutAlignment::kCenter)
.SetCollapseMargins(true);
auto progress_time = std::make_unique<views::Label>();
progress_time->SetFontList(font_list);
progress_time->SetEnabledColor(SK_ColorWHITE);
progress_time->SetAutoColorReadabilityEnabled(false);
progress_time_ = time_view->AddChildView(std::move(progress_time));
auto time_spacing = std::make_unique<views::View>();
time_spacing->SetPreferredSize(kTimeSpacingSize);
time_spacing->SetProperty(views::kFlexBehaviorKey,
views::FlexSpecification::ForSizeRule(
views::MinimumFlexSizeRule::kPreferred,
views::MaximumFlexSizeRule::kUnbounded));
time_view->AddChildView(std::move(time_spacing));
auto duration = std::make_unique<views::Label>();
duration->SetFontList(font_list);
duration->SetEnabledColor(SK_ColorWHITE);
duration->SetAutoColorReadabilityEnabled(false);
duration_ = time_view->AddChildView(std::move(duration));
AddChildView(std::move(time_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: aspath_snmp_pathseg (struct aspath *as, size_t *varlen)
{
#define SNMP_PATHSEG_MAX 1024
if (!snmp_stream)
snmp_stream = stream_new (SNMP_PATHSEG_MAX);
else
stream_reset (snmp_stream);
if (!as)
{
*varlen = 0;
return NULL;
}
aspath_put (snmp_stream, as, 0); /* use 16 bit for now here */
*varlen = stream_get_endp (snmp_stream);
return stream_pnt(snmp_stream);
}
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: magic_check(struct magic_set *ms, const char *magicfile)
{
if (ms == NULL)
return -1;
return file_apprentice(ms, magicfile, FILE_CHECK);
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
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: static int v9fs_xattr_set_acl(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *name, const void *value,
size_t size, int flags)
{
int retval;
struct posix_acl *acl;
struct v9fs_session_info *v9ses;
v9ses = v9fs_dentry2v9ses(dentry);
/*
* set the attribute on the remote. Without even looking at the
* xattr value. We leave it to the server to validate
*/
if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT)
return v9fs_xattr_set(dentry, handler->name, value, size,
flags);
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (value) {
/* update the cached acl value */
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
return PTR_ERR(acl);
else if (acl) {
retval = posix_acl_valid(inode->i_sb->s_user_ns, acl);
if (retval)
goto err_out;
}
} else
acl = NULL;
switch (handler->flags) {
case ACL_TYPE_ACCESS:
if (acl) {
umode_t mode = inode->i_mode;
retval = posix_acl_equiv_mode(acl, &mode);
if (retval < 0)
goto err_out;
else {
struct iattr iattr;
if (retval == 0) {
/*
* ACL can be represented
* by the mode bits. So don't
* update ACL.
*/
acl = NULL;
value = NULL;
size = 0;
}
/* Updte the mode bits */
iattr.ia_mode = ((mode & S_IALLUGO) |
(inode->i_mode & ~S_IALLUGO));
iattr.ia_valid = ATTR_MODE;
/* FIXME should we update ctime ?
* What is the following setxattr update the
* mode ?
*/
v9fs_vfs_setattr_dotl(dentry, &iattr);
}
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
retval = acl ? -EINVAL : 0;
goto err_out;
}
break;
default:
BUG();
}
retval = v9fs_xattr_set(dentry, handler->name, value, size, flags);
if (!retval)
set_cached_acl(inode, handler->flags, acl);
err_out:
posix_acl_release(acl);
return retval;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285
Target: 1
Example 2:
Code: gfx::Size ShellSurface::GetPreferredSize() const {
if (!geometry_.IsEmpty())
return geometry_.size();
return surface_ ? surface_->window()->layer()->size() : gfx::Size();
}
Commit Message: exo: Reduce side-effects of dynamic activation code.
This code exists for clients that need to managed their own system
modal dialogs. Since the addition of the remote surface API we
can limit the impact of this to surfaces created for system modal
container.
BUG=29528396
Review-Url: https://codereview.chromium.org/2084023003
Cr-Commit-Position: refs/heads/master@{#401115}
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 RenderProcessHostImpl::CreateSharedRendererHistogramAllocator() {
if (!base::GlobalHistogramAllocator::Get()) {
if (is_initialized_) {
HistogramController::GetInstance()->SetHistogramMemory<RenderProcessHost>(
this, mojo::ScopedSharedBufferHandle());
}
return;
}
base::ProcessHandle destination = GetHandle();
if (destination == base::kNullProcessHandle)
return;
if (!metrics_allocator_) {
std::unique_ptr<base::SharedMemory> shm(new base::SharedMemory());
if (!shm->CreateAndMapAnonymous(2 << 20)) // 2 MiB
return;
metrics_allocator_.reset(new base::SharedPersistentMemoryAllocator(
std::move(shm), GetID(), "RendererMetrics", /*readonly=*/false));
}
HistogramController::GetInstance()->SetHistogramMemory<RenderProcessHost>(
this, mojo::WrapSharedMemoryHandle(
metrics_allocator_->shared_memory()->handle().Duplicate(),
metrics_allocator_->shared_memory()->mapped_size(), false));
}
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
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: EntrySync* EntrySync::copyTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->copy(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AcceleratedSurfaceBuffersSwappedCompleted(int host_id,
int route_id,
bool alive) {
if (BrowserThread::CurrentlyOn(BrowserThread::IO)) {
GpuProcessHost* host = GpuProcessHost::FromID(host_id);
if (host) {
if (alive)
host->Send(new AcceleratedSurfaceMsg_BuffersSwappedACK(route_id));
else {
host->ForceShutdown();
}
}
} else {
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id,
route_id,
alive));
}
}
Commit Message: Revert 137988 - VAVDA is the hardware video decode accelerator for Chrome on Linux and ChromeOS for Intel CPUs (Sandy Bridge and newer).
This CL enables VAVDA acceleration for ChromeOS, both for HTML5 video and Flash.
The feature is currently hidden behind a command line flag and can be enabled by adding the --enable-vaapi parameter to command line.
BUG=117062
TEST=Manual runs of test streams.
Change-Id: I386e16739e2ef2230f52a0a434971b33d8654699
Review URL: https://chromiumcodereview.appspot.com/9814001
This is causing crbug.com/129103
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10411066
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@138208 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: explicit FastElementsAccessor(const char* name)
: ElementsAccessorBase<Subclass, KindTraits>(name) {}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
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 swevent_hlist_get_cpu(struct perf_event *event, int cpu)
{
struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
int err = 0;
mutex_lock(&swhash->hlist_mutex);
if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
struct swevent_hlist *hlist;
hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
if (!hlist) {
err = -ENOMEM;
goto exit;
}
rcu_assign_pointer(swhash->swevent_hlist, hlist);
}
swhash->hlist_refcount++;
exit:
mutex_unlock(&swhash->hlist_mutex);
return err;
}
Commit Message: perf: Fix race in swevent hash
There's a race on CPU unplug where we free the swevent hash array
while it can still have events on. This will result in a
use-after-free which is BAD.
Simply do not free the hash array on unplug. This leaves the thing
around and no use-after-free takes place.
When the last swevent dies, we do a for_each_possible_cpu() iteration
anyway to clean these up, at which time we'll free it, so no leakage
will occur.
Reported-by: Sasha Levin <[email protected]>
Tested-by: Sasha Levin <[email protected]>
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Stephane Eranian <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: Vince Weaver <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int check_block_validity(struct inode *inode, const char *msg,
sector_t logical, sector_t phys, int len)
{
if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), phys, len)) {
__ext4_error(inode->i_sb, msg,
"inode #%lu logical block %llu mapped to %llu "
"(size %d)", inode->i_ino,
(unsigned long long) logical,
(unsigned long long) phys, len);
return -EIO;
}
return 0;
}
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: 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 ScriptProcessorHandler::Process(size_t frames_to_process) {
AudioBus* input_bus = Input(0).Bus();
AudioBus* output_bus = Output(0).Bus();
unsigned double_buffer_index = this->DoubleBufferIndex();
bool is_double_buffer_index_good =
double_buffer_index < 2 && double_buffer_index < input_buffers_.size() &&
double_buffer_index < output_buffers_.size();
DCHECK(is_double_buffer_index_good);
if (!is_double_buffer_index_good)
return;
AudioBuffer* input_buffer = input_buffers_[double_buffer_index].Get();
AudioBuffer* output_buffer = output_buffers_[double_buffer_index].Get();
unsigned number_of_input_channels = internal_input_bus_->NumberOfChannels();
bool buffers_are_good =
output_buffer && BufferSize() == output_buffer->length() &&
buffer_read_write_index_ + frames_to_process <= BufferSize();
if (internal_input_bus_->NumberOfChannels())
buffers_are_good = buffers_are_good && input_buffer &&
BufferSize() == input_buffer->length();
DCHECK(buffers_are_good);
if (!buffers_are_good)
return;
bool is_frames_to_process_good = frames_to_process &&
BufferSize() >= frames_to_process &&
!(BufferSize() % frames_to_process);
DCHECK(is_frames_to_process_good);
if (!is_frames_to_process_good)
return;
unsigned number_of_output_channels = output_bus->NumberOfChannels();
bool channels_are_good =
(number_of_input_channels == number_of_input_channels_) &&
(number_of_output_channels == number_of_output_channels_);
DCHECK(channels_are_good);
if (!channels_are_good)
return;
for (unsigned i = 0; i < number_of_input_channels; ++i)
internal_input_bus_->SetChannelMemory(
i,
input_buffer->getChannelData(i).View()->Data() +
buffer_read_write_index_,
frames_to_process);
if (number_of_input_channels)
internal_input_bus_->CopyFrom(*input_bus);
for (unsigned i = 0; i < number_of_output_channels; ++i) {
memcpy(output_bus->Channel(i)->MutableData(),
output_buffer->getChannelData(i).View()->Data() +
buffer_read_write_index_,
sizeof(float) * frames_to_process);
}
buffer_read_write_index_ =
(buffer_read_write_index_ + frames_to_process) % BufferSize();
if (!buffer_read_write_index_) {
MutexTryLocker try_locker(process_event_lock_);
if (!try_locker.Locked()) {
output_buffer->Zero();
} else if (Context()->GetExecutionContext()) {
if (Context()->HasRealtimeConstraint()) {
TaskRunnerHelper::Get(TaskType::kMediaElementEvent,
Context()->GetExecutionContext())
->PostTask(BLINK_FROM_HERE,
CrossThreadBind(
&ScriptProcessorHandler::FireProcessEvent,
CrossThreadUnretained(this), double_buffer_index_));
} else {
std::unique_ptr<WaitableEvent> waitable_event =
WTF::MakeUnique<WaitableEvent>();
TaskRunnerHelper::Get(TaskType::kMediaElementEvent,
Context()->GetExecutionContext())
->PostTask(BLINK_FROM_HERE,
CrossThreadBind(
&ScriptProcessorHandler::
FireProcessEventForOfflineAudioContext,
CrossThreadUnretained(this), double_buffer_index_,
CrossThreadUnretained(waitable_event.get())));
waitable_event->Wait();
}
}
SwapBuffers();
}
}
Commit Message: Keep ScriptProcessorHandler alive across threads
When posting a task from the ScriptProcessorHandler::Process to fire a
process event, we need to keep the handler alive in case the
ScriptProcessorNode goes away (because it has no onaudioprocess
handler) and removes the its handler.
Bug: 765495
Test:
Change-Id: Ib4fa39d7b112c7051897700a1eff9f59a4a7a054
Reviewed-on: https://chromium-review.googlesource.com/677137
Reviewed-by: Hongchan Choi <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Commit-Queue: Raymond Toy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#503629}
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 int decode_dds1(GetByteContext *gb, uint8_t *frame, int width, int height)
{
const uint8_t *frame_start = frame;
const uint8_t *frame_end = frame + width * height;
int mask = 0x10000, bitbuf = 0;
int i, v, offset, count, segments;
segments = bytestream2_get_le16(gb);
while (segments--) {
if (bytestream2_get_bytes_left(gb) < 2)
return AVERROR_INVALIDDATA;
if (mask == 0x10000) {
bitbuf = bytestream2_get_le16u(gb);
mask = 1;
}
if (bitbuf & mask) {
v = bytestream2_get_le16(gb);
offset = (v & 0x1FFF) << 2;
count = ((v >> 13) + 2) << 1;
if (frame - frame_start < offset || frame_end - frame < count*2 + width)
return AVERROR_INVALIDDATA;
for (i = 0; i < count; i++) {
frame[0] = frame[1] =
frame[width] = frame[width + 1] = frame[-offset];
frame += 2;
}
} else if (bitbuf & (mask << 1)) {
v = bytestream2_get_le16(gb)*2;
if (frame - frame_end < v)
return AVERROR_INVALIDDATA;
frame += v;
} else {
if (frame_end - frame < width + 3)
return AVERROR_INVALIDDATA;
frame[0] = frame[1] =
frame[width] = frame[width + 1] = bytestream2_get_byte(gb);
frame += 2;
frame[0] = frame[1] =
frame[width] = frame[width + 1] = bytestream2_get_byte(gb);
frame += 2;
}
mask <<= 2;
}
return 0;
}
Commit Message: avcodec/dfa: Fix off by 1 error
Fixes out of array access
Fixes: 1345/clusterfuzz-testcase-minimized-6062963045695488
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static js_Ast *jsP_newnode(js_State *J, enum js_AstType type, js_Ast *a, js_Ast *b, js_Ast *c, js_Ast *d)
{
js_Ast *node = js_malloc(J, sizeof *node);
node->type = type;
node->line = J->astline;
node->a = a;
node->b = b;
node->c = c;
node->d = d;
node->number = 0;
node->string = NULL;
node->jumps = NULL;
node->casejump = 0;
node->parent = NULL;
if (a) a->parent = node;
if (b) b->parent = node;
if (c) c->parent = node;
if (d) d->parent = node;
node->gcnext = J->gcast;
J->gcast = node;
return node;
}
Commit Message:
CWE ID: CWE-674
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: PassOwnPtr<LifecycleNotifier> Document::createLifecycleNotifier()
{
return DocumentLifecycleNotifier::create(this);
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
[email protected], abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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: std::unique_ptr<FakeMediaStreamUIProxy> CreateMockUI(bool expect_started) {
std::unique_ptr<MockMediaStreamUIProxy> fake_ui =
std::make_unique<MockMediaStreamUIProxy>();
if (expect_started)
EXPECT_CALL(*fake_ui, MockOnStarted(_));
return fake_ui;
}
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
Target: 1
Example 2:
Code: static unsigned int psk_server_cb(SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len)
{
unsigned int psk_len = 0;
int ret;
BIGNUM *bn = NULL;
if (s_debug)
BIO_printf(bio_s_out, "psk_server_cb\n");
if (!identity) {
BIO_printf(bio_err, "Error: client did not send PSK identity\n");
goto out_err;
}
if (s_debug)
BIO_printf(bio_s_out, "identity_len=%d identity=%s\n",
(int)strlen(identity), identity);
/* here we could lookup the given identity e.g. from a database */
if (strcmp(identity, psk_identity) != 0) {
BIO_printf(bio_s_out, "PSK error: client identity not found"
" (got '%s' expected '%s')\n", identity, psk_identity);
goto out_err;
}
if (s_debug)
BIO_printf(bio_s_out, "PSK client identity found\n");
/* convert the PSK key to binary */
ret = BN_hex2bn(&bn, psk_key);
if (!ret) {
BIO_printf(bio_err, "Could not convert PSK key '%s' to BIGNUM\n",
psk_key);
if (bn)
BN_free(bn);
return 0;
}
if (BN_num_bytes(bn) > (int)max_psk_len) {
BIO_printf(bio_err,
"psk buffer of callback is too small (%d) for key (%d)\n",
max_psk_len, BN_num_bytes(bn));
BN_free(bn);
return 0;
}
ret = BN_bn2bin(bn, psk);
BN_free(bn);
if (ret < 0)
goto out_err;
psk_len = (unsigned int)ret;
if (s_debug)
BIO_printf(bio_s_out, "fetched PSK len=%d\n", psk_len);
return psk_len;
out_err:
if (s_debug)
BIO_printf(bio_err, "Error in PSK server callback\n");
return 0;
}
Commit Message:
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 int ftrc(struct sh_fpu_soft_struct *fregs, int n)
{
FP_DECL_EX;
if (FPSCR_PR)
EMU_FTRC_X(D, DRn);
else
EMU_FTRC_X(S, FRn);
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
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: i915_gem_do_execbuffer(struct drm_device *dev, void *data,
struct drm_file *file,
struct drm_i915_gem_execbuffer2 *args,
struct drm_i915_gem_exec_object2 *exec)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct list_head objects;
struct eb_objects *eb;
struct drm_i915_gem_object *batch_obj;
struct drm_clip_rect *cliprects = NULL;
struct intel_ring_buffer *ring;
u32 exec_start, exec_len;
u32 seqno;
u32 mask;
int ret, mode, i;
if (!i915_gem_check_execbuffer(args)) {
DRM_DEBUG("execbuf with invalid offset/length\n");
return -EINVAL;
}
ret = validate_exec_list(exec, args->buffer_count);
if (ret)
return ret;
switch (args->flags & I915_EXEC_RING_MASK) {
case I915_EXEC_DEFAULT:
case I915_EXEC_RENDER:
ring = &dev_priv->ring[RCS];
break;
case I915_EXEC_BSD:
if (!HAS_BSD(dev)) {
DRM_DEBUG("execbuf with invalid ring (BSD)\n");
return -EINVAL;
}
ring = &dev_priv->ring[VCS];
break;
case I915_EXEC_BLT:
if (!HAS_BLT(dev)) {
DRM_DEBUG("execbuf with invalid ring (BLT)\n");
return -EINVAL;
}
ring = &dev_priv->ring[BCS];
break;
default:
DRM_DEBUG("execbuf with unknown ring: %d\n",
(int)(args->flags & I915_EXEC_RING_MASK));
return -EINVAL;
}
mode = args->flags & I915_EXEC_CONSTANTS_MASK;
mask = I915_EXEC_CONSTANTS_MASK;
switch (mode) {
case I915_EXEC_CONSTANTS_REL_GENERAL:
case I915_EXEC_CONSTANTS_ABSOLUTE:
case I915_EXEC_CONSTANTS_REL_SURFACE:
if (ring == &dev_priv->ring[RCS] &&
mode != dev_priv->relative_constants_mode) {
if (INTEL_INFO(dev)->gen < 4)
return -EINVAL;
if (INTEL_INFO(dev)->gen > 5 &&
mode == I915_EXEC_CONSTANTS_REL_SURFACE)
return -EINVAL;
/* The HW changed the meaning on this bit on gen6 */
if (INTEL_INFO(dev)->gen >= 6)
mask &= ~I915_EXEC_CONSTANTS_REL_SURFACE;
}
break;
default:
DRM_DEBUG("execbuf with unknown constants: %d\n", mode);
return -EINVAL;
}
if (args->buffer_count < 1) {
DRM_DEBUG("execbuf with %d buffers\n", args->buffer_count);
return -EINVAL;
}
if (args->num_cliprects != 0) {
if (ring != &dev_priv->ring[RCS]) {
DRM_DEBUG("clip rectangles are only valid with the render ring\n");
return -EINVAL;
}
cliprects = kmalloc(args->num_cliprects * sizeof(*cliprects),
GFP_KERNEL);
if (cliprects == NULL) {
ret = -ENOMEM;
goto pre_mutex_err;
}
if (copy_from_user(cliprects,
(struct drm_clip_rect __user *)(uintptr_t)
args->cliprects_ptr,
sizeof(*cliprects)*args->num_cliprects)) {
ret = -EFAULT;
goto pre_mutex_err;
}
}
ret = i915_mutex_lock_interruptible(dev);
if (ret)
goto pre_mutex_err;
if (dev_priv->mm.suspended) {
mutex_unlock(&dev->struct_mutex);
ret = -EBUSY;
goto pre_mutex_err;
}
eb = eb_create(args->buffer_count);
if (eb == NULL) {
mutex_unlock(&dev->struct_mutex);
ret = -ENOMEM;
goto pre_mutex_err;
}
/* Look up object handles */
INIT_LIST_HEAD(&objects);
for (i = 0; i < args->buffer_count; i++) {
struct drm_i915_gem_object *obj;
obj = to_intel_bo(drm_gem_object_lookup(dev, file,
exec[i].handle));
if (&obj->base == NULL) {
DRM_DEBUG("Invalid object handle %d at index %d\n",
exec[i].handle, i);
/* prevent error path from reading uninitialized data */
ret = -ENOENT;
goto err;
}
if (!list_empty(&obj->exec_list)) {
DRM_DEBUG("Object %p [handle %d, index %d] appears more than once in object list\n",
obj, exec[i].handle, i);
ret = -EINVAL;
goto err;
}
list_add_tail(&obj->exec_list, &objects);
obj->exec_handle = exec[i].handle;
obj->exec_entry = &exec[i];
eb_add_object(eb, obj);
}
/* take note of the batch buffer before we might reorder the lists */
batch_obj = list_entry(objects.prev,
struct drm_i915_gem_object,
exec_list);
/* Move the objects en-masse into the GTT, evicting if necessary. */
ret = i915_gem_execbuffer_reserve(ring, file, &objects);
if (ret)
goto err;
/* The objects are in their final locations, apply the relocations. */
ret = i915_gem_execbuffer_relocate(dev, eb, &objects);
if (ret) {
if (ret == -EFAULT) {
ret = i915_gem_execbuffer_relocate_slow(dev, file, ring,
&objects, eb,
exec,
args->buffer_count);
BUG_ON(!mutex_is_locked(&dev->struct_mutex));
}
if (ret)
goto err;
}
/* Set the pending read domains for the batch buffer to COMMAND */
if (batch_obj->base.pending_write_domain) {
DRM_DEBUG("Attempting to use self-modifying batch buffer\n");
ret = -EINVAL;
goto err;
}
batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
ret = i915_gem_execbuffer_move_to_gpu(ring, &objects);
if (ret)
goto err;
seqno = i915_gem_next_request_seqno(ring);
for (i = 0; i < ARRAY_SIZE(ring->sync_seqno); i++) {
if (seqno < ring->sync_seqno[i]) {
/* The GPU can not handle its semaphore value wrapping,
* so every billion or so execbuffers, we need to stall
* the GPU in order to reset the counters.
*/
ret = i915_gpu_idle(dev, true);
if (ret)
goto err;
BUG_ON(ring->sync_seqno[i]);
}
}
if (ring == &dev_priv->ring[RCS] &&
mode != dev_priv->relative_constants_mode) {
ret = intel_ring_begin(ring, 4);
if (ret)
goto err;
intel_ring_emit(ring, MI_NOOP);
intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
intel_ring_emit(ring, INSTPM);
intel_ring_emit(ring, mask << 16 | mode);
intel_ring_advance(ring);
dev_priv->relative_constants_mode = mode;
}
if (args->flags & I915_EXEC_GEN7_SOL_RESET) {
ret = i915_reset_gen7_sol_offsets(dev, ring);
if (ret)
goto err;
}
trace_i915_gem_ring_dispatch(ring, seqno);
exec_start = batch_obj->gtt_offset + args->batch_start_offset;
exec_len = args->batch_len;
if (cliprects) {
for (i = 0; i < args->num_cliprects; i++) {
ret = i915_emit_box(dev, &cliprects[i],
args->DR1, args->DR4);
if (ret)
goto err;
ret = ring->dispatch_execbuffer(ring,
exec_start, exec_len);
if (ret)
goto err;
}
} else {
ret = ring->dispatch_execbuffer(ring, exec_start, exec_len);
if (ret)
goto err;
}
i915_gem_execbuffer_move_to_active(&objects, ring, seqno);
i915_gem_execbuffer_retire_commands(dev, file, ring);
err:
eb_destroy(eb);
while (!list_empty(&objects)) {
struct drm_i915_gem_object *obj;
obj = list_first_entry(&objects,
struct drm_i915_gem_object,
exec_list);
list_del_init(&obj->exec_list);
drm_gem_object_unreference(&obj->base);
}
mutex_unlock(&dev->struct_mutex);
pre_mutex_err:
kfree(cliprects);
return ret;
}
Commit Message: drm/i915: fix integer overflow in i915_gem_do_execbuffer()
On 32-bit systems, a large args->num_cliprects from userspace via ioctl
may overflow the allocation size, leading to out-of-bounds access.
This vulnerability was introduced in commit 432e58ed ("drm/i915: Avoid
allocation for execbuffer object list").
Signed-off-by: Xi Wang <[email protected]>
Reviewed-by: Chris Wilson <[email protected]>
Cc: [email protected]
Signed-off-by: Daniel Vetter <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MagickPathExtent],
text[MagickPathExtent];
Image
*image;
long
x_offset,
y_offset;
PixelInfo
pixel;
MagickBooleanType
status;
QuantumAny
range;
register ssize_t
i,
x;
register Quantum
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->alpha_trait=UndefinedPixelTrait;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->alpha_trait=BlendPixelTrait;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) SetImageBackgroundColor(image,exception);
(void) SetImageColorspace(image,(ColorspaceType) type,exception);
GetPixelInfo(image,&pixel);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
alpha,
black,
blue,
green,
red;
red=0.0;
green=0.0;
blue=0.0;
black=0.0;
alpha=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&alpha);
green=red;
blue=red;
break;
}
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,
&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&black,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&black);
break;
}
default:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
black*=0.01*range;
alpha*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5),
range);
pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5),
range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (Quantum *) NULL)
continue;
SetPixelViaPixelInfo(image,&pixel,q);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/298
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: static unsigned long long *dbg_redzone1(struct kmem_cache *cachep, void *objp)
{
BUG_ON(!(cachep->flags & SLAB_RED_ZONE));
return (unsigned long long*) (objp + obj_offset(cachep) -
sizeof(unsigned long long));
}
Commit Message: mm/slab.c: fix SLAB freelist randomization duplicate entries
This patch fixes a bug in the freelist randomization code. When a high
random number is used, the freelist will contain duplicate entries. It
will result in different allocations sharing the same chunk.
It will result in odd behaviours and crashes. It should be uncommon but
it depends on the machines. We saw it happening more often on some
machines (every few hours of running tests).
Fixes: c7ce4f60ac19 ("mm: SLAB freelist randomization")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: John Sperbeck <[email protected]>
Signed-off-by: Thomas Garnier <[email protected]>
Cc: Christoph Lameter <[email protected]>
Cc: Pekka Enberg <[email protected]>
Cc: David Rientjes <[email protected]>
Cc: Joonsoo Kim <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[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: void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %lu, expected %zu", outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
Commit Message: Fix build
Change-Id: I96a9c437eec53a285ac96794cc1ad0c8954b27e0
CWE ID: CWE-264
Target: 1
Example 2:
Code: static uint8_t arcmsr_hbaC_wait_msgint_ready(struct AdapterControlBlock *pACB)
{
struct MessageUnit_C __iomem *phbcmu = pACB->pmuC;
int i;
for (i = 0; i < 2000; i++) {
if (readl(&phbcmu->outbound_doorbell)
& ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE) {
writel(ARCMSR_HBCMU_IOP2DRV_MESSAGE_CMD_DONE_DOORBELL_CLEAR,
&phbcmu->outbound_doorbell_clear); /*clear interrupt*/
return true;
}
msleep(10);
} /* max 20 seconds */
return false;
}
Commit Message: scsi: arcmsr: Buffer overflow in arcmsr_iop_message_xfer()
We need to put an upper bound on "user_len" so the memcpy() doesn't
overflow.
Cc: <[email protected]>
Reported-by: Marco Grassi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: Tomas Henzl <[email protected]>
Signed-off-by: Martin K. Petersen <[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 int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pmd_access_permitted(orig, write))
return 0;
if (pmd_devmap(orig))
return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
refs = 0;
page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = compound_head(pmd_page(orig));
if (!page_cache_add_speculative(head, refs)) {
*nr -= refs;
return 0;
}
if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
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: void DownloadResourceHandler::OnRequestRedirected(
const net::RedirectInfo& redirect_info,
network::ResourceResponse* response,
std::unique_ptr<ResourceController> controller) {
url::Origin new_origin(url::Origin::Create(redirect_info.new_url));
if (!follow_cross_origin_redirects_ &&
!first_origin_.IsSameOriginWith(new_origin)) {
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(
&NavigateOnUIThread, redirect_info.new_url, request()->url_chain(),
Referrer(GURL(redirect_info.new_referrer),
Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
redirect_info.new_referrer_policy)),
GetRequestInfo()->HasUserGesture(),
GetRequestInfo()->GetWebContentsGetterForRequest()));
controller->Cancel();
return;
}
if (core_.OnRequestRedirected()) {
controller->Resume();
} else {
controller->Cancel();
}
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284
Target: 1
Example 2:
Code: void LoadingDataCollector::RecordMainFrameLoadComplete(
const NavigationID& navigation_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (predictor_)
predictor_->StartInitialization();
auto nav_it = inflight_navigations_.find(navigation_id);
if (nav_it == inflight_navigations_.end())
return;
std::unique_ptr<PageRequestSummary> summary = std::move(nav_it->second);
inflight_navigations_.erase(nav_it);
if (stats_collector_)
stats_collector_->RecordPageRequestSummary(*summary);
if (predictor_)
predictor_->RecordPageRequestSummary(std::move(summary));
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
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 registerMockedChromeURLLoad(const std::string& fileName)
{
URLTestHelpers::registerMockedURLFromBaseURL(WebString::fromUTF8(m_chromeURL.c_str()), WebString::fromUTF8(fileName.c_str()));
}
Commit Message: Call didAccessInitialDocument when javascript: URLs are used.
BUG=265221
TEST=See bug for repro.
Review URL: https://chromiumcodereview.appspot.com/22572004
git-svn-id: svn://svn.chromium.org/blink/trunk@155790 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: QuotaTask::QuotaTask(QuotaTaskObserver* observer)
: observer_(observer),
original_task_runner_(base::MessageLoopProxy::current()) {
}
Commit Message: Quota double-delete fix
BUG=142310
Review URL: https://chromiumcodereview.appspot.com/10832407
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152532 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static unsigned int unix_skb_len(const struct sk_buff *skb)
{
return skb->len - UNIXCB(skb).consumed;
}
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: void ChromeContentRendererClient::RenderViewCreated(RenderView* render_view) {
ContentSettingsObserver* content_settings =
new ContentSettingsObserver(render_view);
new DevToolsAgent(render_view);
new ExtensionHelper(render_view, extension_dispatcher_.get());
new PageLoadHistograms(render_view, histogram_snapshots_.get());
new PrintWebViewHelper(render_view);
new SearchBox(render_view);
new SpellCheckProvider(render_view, spellcheck_.get());
#if defined(ENABLE_SAFE_BROWSING)
safe_browsing::MalwareDOMDetails::Create(render_view);
#endif
#if defined(OS_MACOSX)
new TextInputClientObserver(render_view);
#endif // defined(OS_MACOSX)
PasswordAutofillManager* password_autofill_manager =
new PasswordAutofillManager(render_view);
AutofillAgent* autofill_agent = new AutofillAgent(render_view,
password_autofill_manager);
PageClickTracker* page_click_tracker = new PageClickTracker(render_view);
page_click_tracker->AddListener(password_autofill_manager);
page_click_tracker->AddListener(autofill_agent);
TranslateHelper* translate = new TranslateHelper(render_view, autofill_agent);
new ChromeRenderViewObserver(
render_view, content_settings, extension_dispatcher_.get(), translate);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
new AutomationRendererHelper(render_view);
}
}
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
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: WORD32 ih264d_parse_bslice(dec_struct_t * ps_dec, UWORD16 u2_first_mb_in_slice)
{
dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps;
dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice;
dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm;
UWORD8 u1_ref_idx_re_flag_lx;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 u4_temp, ui_temp1;
WORD32 i_temp;
WORD32 ret;
/*--------------------------------------------------------------------*/
/* Read remaining contents of the slice header */
/*--------------------------------------------------------------------*/
{
WORD8 *pi1_buf;
WORD16 *pi2_mv = ps_dec->s_default_mv_pred.i2_mv;
WORD32 *pi4_mv = (WORD32*)pi2_mv;
WORD16 *pi16_refFrame;
pi1_buf = ps_dec->s_default_mv_pred.i1_ref_frame;
pi16_refFrame = (WORD16*)pi1_buf;
*pi4_mv = 0;
*(pi4_mv + 1) = 0;
*pi16_refFrame = OUT_OF_RANGE_REF;
ps_dec->s_default_mv_pred.u1_col_ref_pic_idx = (UWORD8)-1;
ps_dec->s_default_mv_pred.u1_pic_type = (UWORD8)-1;
}
ps_slice->u1_num_ref_idx_active_override_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: num_ref_idx_override_flag",
ps_slice->u1_num_ref_idx_active_override_flag);
u4_temp = ps_dec->ps_cur_pps->u1_num_ref_idx_lx_active[0];
ui_temp1 = ps_dec->ps_cur_pps->u1_num_ref_idx_lx_active[1];
if(ps_slice->u1_num_ref_idx_active_override_flag)
{
u4_temp = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: num_ref_idx_l0_active_minus1",
u4_temp - 1);
ui_temp1 = 1 + ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: num_ref_idx_l1_active_minus1",
ui_temp1 - 1);
}
{
UWORD8 u1_max_ref_idx = MAX_FRAMES;
if(ps_slice->u1_field_pic_flag)
{
u1_max_ref_idx = MAX_FRAMES << 1;
}
if((u4_temp > u1_max_ref_idx) || (ui_temp1 > u1_max_ref_idx))
{
return ERROR_NUM_REF;
}
ps_slice->u1_num_ref_idx_lx_active[0] = u4_temp;
ps_slice->u1_num_ref_idx_lx_active[1] = ui_temp1;
}
/* Initialize the Reference list once in Picture if the slice type */
/* of first slice is between 5 to 9 defined in table 7.3 of standard */
/* If picture contains both P & B slices then Initialize the Reference*/
/* List only when it switches from P to B and B to P */
{
UWORD8 init_idx_flg = (ps_dec->u1_pr_sl_type
!= ps_dec->ps_cur_slice->u1_slice_type);
if(ps_dec->u1_first_pb_nal_in_pic
|| (init_idx_flg & !ps_dec->u1_sl_typ_5_9)
|| ps_dec->u1_num_ref_idx_lx_active_prev
!= ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0])
ih264d_init_ref_idx_lx_b(ps_dec);
if(ps_dec->u1_first_pb_nal_in_pic & ps_dec->u1_sl_typ_5_9)
ps_dec->u1_first_pb_nal_in_pic = 0;
}
/* Store the value for future slices in the same picture */
ps_dec->u1_num_ref_idx_lx_active_prev =
ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0];
u1_ref_idx_re_flag_lx = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: ref_pic_list_reordering_flag_l0",u1_ref_idx_re_flag_lx);
/* Modified temporarily */
if(u1_ref_idx_re_flag_lx)
{
WORD8 ret;
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_mod_dpb[0];
ret = ih264d_ref_idx_reordering(ps_dec, 0);
if(ret == -1)
return ERROR_REFIDX_ORDER_T;
}
else
ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0];
u1_ref_idx_re_flag_lx = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: ref_pic_list_reordering_flag_l1",u1_ref_idx_re_flag_lx);
/* Modified temporarily */
if(u1_ref_idx_re_flag_lx)
{
WORD8 ret;
ps_dec->ps_ref_pic_buf_lx[1] = ps_dec->ps_dpb_mgr->ps_mod_dpb[1];
ret = ih264d_ref_idx_reordering(ps_dec, 1);
if(ret == -1)
return ERROR_REFIDX_ORDER_T;
}
else
ps_dec->ps_ref_pic_buf_lx[1] = ps_dec->ps_dpb_mgr->ps_init_dpb[1];
/* Create refIdx to POC mapping */
{
void **ppv_map_ref_idx_to_poc_lx;
WORD8 idx;
struct pic_buffer_t *ps_pic;
ppv_map_ref_idx_to_poc_lx = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L0;
ppv_map_ref_idx_to_poc_lx[0] = 0;
ppv_map_ref_idx_to_poc_lx++;
for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0];
idx++)
{
ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx];
ppv_map_ref_idx_to_poc_lx[idx] = (ps_pic->pu1_buf1);
}
ppv_map_ref_idx_to_poc_lx = ps_dec->ppv_map_ref_idx_to_poc + FRM_LIST_L1;
ppv_map_ref_idx_to_poc_lx[0] = 0;
ppv_map_ref_idx_to_poc_lx++;
for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[1];
idx++)
{
ps_pic = ps_dec->ps_ref_pic_buf_lx[1][idx];
ppv_map_ref_idx_to_poc_lx[idx] = (ps_pic->pu1_buf1);
}
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
{
void **ppv_map_ref_idx_to_poc_lx_t, **ppv_map_ref_idx_to_poc_lx_b;
ppv_map_ref_idx_to_poc_lx_t = ps_dec->ppv_map_ref_idx_to_poc
+ TOP_LIST_FLD_L0;
ppv_map_ref_idx_to_poc_lx_b = ps_dec->ppv_map_ref_idx_to_poc
+ BOT_LIST_FLD_L0;
ppv_map_ref_idx_to_poc_lx_t[0] = 0;
ppv_map_ref_idx_to_poc_lx_t++;
ppv_map_ref_idx_to_poc_lx_b[0] = 0;
ppv_map_ref_idx_to_poc_lx_b++;
for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[0];
idx++)
{
ps_pic = ps_dec->ps_ref_pic_buf_lx[0][idx];
ppv_map_ref_idx_to_poc_lx_t[0] = (ps_pic->pu1_buf1);
ppv_map_ref_idx_to_poc_lx_b[1] = (ps_pic->pu1_buf1);
ppv_map_ref_idx_to_poc_lx_b[0] = (ps_pic->pu1_buf1) + 1;
ppv_map_ref_idx_to_poc_lx_t[1] = (ps_pic->pu1_buf1) + 1;
ppv_map_ref_idx_to_poc_lx_t += 2;
ppv_map_ref_idx_to_poc_lx_b += 2;
}
ppv_map_ref_idx_to_poc_lx_t = ps_dec->ppv_map_ref_idx_to_poc
+ TOP_LIST_FLD_L1;
ppv_map_ref_idx_to_poc_lx_b = ps_dec->ppv_map_ref_idx_to_poc
+ BOT_LIST_FLD_L1;
ppv_map_ref_idx_to_poc_lx_t[0] = 0;
ppv_map_ref_idx_to_poc_lx_t++;
ppv_map_ref_idx_to_poc_lx_b[0] = 0;
ppv_map_ref_idx_to_poc_lx_b++;
for(idx = 0; idx < ps_dec->ps_cur_slice->u1_num_ref_idx_lx_active[1];
idx++)
{
UWORD8 u1_tmp_idx = idx << 1;
ps_pic = ps_dec->ps_ref_pic_buf_lx[1][idx];
ppv_map_ref_idx_to_poc_lx_t[u1_tmp_idx] = (ps_pic->pu1_buf1);
ppv_map_ref_idx_to_poc_lx_b[u1_tmp_idx + 1] = (ps_pic->pu1_buf1);
ppv_map_ref_idx_to_poc_lx_b[u1_tmp_idx] = (ps_pic->pu1_buf1) + 1;
ppv_map_ref_idx_to_poc_lx_t[u1_tmp_idx + 1] = (ps_pic->pu1_buf1) + 1;
}
}
if(ps_dec->u4_num_cores >= 3)
{
WORD32 num_entries;
WORD32 size;
num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init);
num_entries = 2 * ((2 * num_entries) + 1);
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
memcpy((void *)ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc,
ps_dec->ppv_map_ref_idx_to_poc,
size);
}
}
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag
&& (ps_dec->ps_cur_slice->u1_field_pic_flag == 0))
{
ih264d_convert_frm_mbaff_list(ps_dec);
}
if(ps_pps->u1_wted_bipred_idc == 1)
{
ret = ih264d_parse_pred_weight_table(ps_slice, ps_bitstrm);
if(ret != OK)
return ret;
ih264d_form_pred_weight_matrix(ps_dec);
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
}
else if(ps_pps->u1_wted_bipred_idc == 2)
{
/* Implicit Weighted prediction */
ps_slice->u2_log2Y_crwd = 0x0505;
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
ih264d_get_implicit_weights(ps_dec);
}
else
ps_dec->ps_cur_slice->u2_log2Y_crwd = 0;
ps_dec->ps_parse_cur_slice->u2_log2Y_crwd =
ps_dec->ps_cur_slice->u2_log2Y_crwd;
/* G050 */
if(ps_slice->u1_nal_ref_idc != 0)
{
if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read)
ps_dec->u4_bitoffset = ih264d_read_mmco_commands(ps_dec);
else
ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset;
}
/* G050 */
if(ps_pps->u1_entropy_coding_mode == CABAC)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > MAX_CABAC_INIT_IDC)
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->u1_cabac_init_idc = u4_temp;
COPYTHECONTEXT("SH: cabac_init_idc",ps_slice->u1_cabac_init_idc);
}
/* Read slice_qp_delta */
i_temp = ps_pps->u1_pic_init_qp
+ ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if((i_temp < 0) || (i_temp > 51))
{
return ERROR_INV_RANGE_QP_T;
}
ps_slice->u1_slice_qp = i_temp;
COPYTHECONTEXT("SH: slice_qp_delta",
(WORD8)(ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp));
if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED)
{
return ERROR_INV_SLICE_HDR_T;
} COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp);
ps_slice->u1_disable_dblk_filter_idc = u4_temp;
if(u4_temp != 1)
{
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->i1_slice_alpha_c0_offset = i_temp;
COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2",
ps_slice->i1_slice_alpha_c0_offset >> 1);
i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf)
<< 1;
if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF))
{
return ERROR_INV_SLICE_HDR_T;
}
ps_slice->i1_slice_beta_offset = i_temp;
COPYTHECONTEXT("SH: slice_beta_offset_div2",
ps_slice->i1_slice_beta_offset >> 1);
}
else
{
ps_slice->i1_slice_alpha_c0_offset = 0;
ps_slice->i1_slice_beta_offset = 0;
}
}
else
{
ps_slice->u1_disable_dblk_filter_idc = 0;
ps_slice->i1_slice_alpha_c0_offset = 0;
ps_slice->i1_slice_beta_offset = 0;
}
ps_dec->u1_slice_header_done = 2;
if(ps_pps->u1_entropy_coding_mode)
{
SWITCHOFFTRACE; SWITCHONTRACECABAC;
ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cabac;
ps_dec->pf_parse_inter_mb = ih264d_parse_bmb_cabac;
ih264d_init_cabac_contexts(B_SLICE, ps_dec);
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff;
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff;
}
else
{
SWITCHONTRACE; SWITCHOFFTRACECABAC;
ps_dec->pf_parse_inter_slice = ih264d_parse_inter_slice_data_cavlc;
ps_dec->pf_parse_inter_mb = ih264d_parse_bmb_cavlc;
if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag)
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff;
else
ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff;
}
ret = ih264d_cal_col_pic(ps_dec);
if(ret != OK)
return ret;
ps_dec->u1_B = 1;
ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_bmb;
ret = ps_dec->pf_parse_inter_slice(ps_dec, ps_slice, u2_first_mb_in_slice);
if(ret != OK)
return ret;
return OK;
}
Commit Message: Return error when there are more mmco params than allocated size
Bug: 25818142
Change-Id: I5c1b23985eeca5192b42703c627ca3d060e4e13d
CWE ID: CWE-119
Target: 1
Example 2:
Code: async_job_start (NautilusDirectory *directory,
const char *job)
{
#ifdef DEBUG_ASYNC_JOBS
char *key;
#endif
#ifdef DEBUG_START_STOP
g_message ("starting %s in %p", job, directory->details->location);
#endif
g_assert (async_job_count >= 0);
g_assert (async_job_count <= MAX_ASYNC_JOBS);
if (async_job_count >= MAX_ASYNC_JOBS)
{
if (waiting_directories == NULL)
{
waiting_directories = g_hash_table_new (NULL, NULL);
}
g_hash_table_insert (waiting_directories,
directory,
directory);
return FALSE;
}
#ifdef DEBUG_ASYNC_JOBS
{
char *uri;
if (async_jobs == NULL)
{
async_jobs = g_hash_table_new (g_str_hash, g_str_equal);
}
uri = nautilus_directory_get_uri (directory);
key = g_strconcat (uri, ": ", job, NULL);
if (g_hash_table_lookup (async_jobs, key) != NULL)
{
g_warning ("same job twice: %s in %s",
job, uri);
}
g_free (uri);
g_hash_table_insert (async_jobs, key, directory);
}
#endif
async_job_count += 1;
return TRUE;
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
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 decode_level3_header(LHAFileHeader **header, LHAInputStream *stream)
{
unsigned int header_len;
if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) {
return 0;
}
if (!extend_raw_data(header, stream,
LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) {
return 0;
}
header_len = lha_decode_uint32(&RAW_DATA(header, 24));
if (header_len > LEVEL_3_MAX_HEADER_LEN) {
return 0;
}
if (!extend_raw_data(header, stream,
header_len - RAW_DATA_LEN(header))) {
return 0;
}
memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5);
(*header)->compress_method[5] = '\0';
(*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7));
(*header)->length = lha_decode_uint32(&RAW_DATA(header, 11));
(*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15));
(*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21));
(*header)->os_type = RAW_DATA(header, 23);
if (!decode_extended_headers(header, 28)) {
return 0;
}
return 1;
}
Commit Message: Fix integer underflow vulnerability in L3 decode.
Marcin 'Icewall' Noga of Cisco TALOS discovered that the level 3 header
decoding routines were vulnerable to an integer underflow, if the 32-bit
header length was less than the base level 3 header length. This could
lead to an exploitable heap corruption condition.
Thanks go to Marcin Noga and Regina Wilson of Cisco TALOS for reporting
this vulnerability.
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 void print_maps(struct pid_info_t* info)
{
FILE *maps;
size_t offset;
char device[10];
long int inode;
char file[PATH_MAX];
strlcat(info->path, "maps", sizeof(info->path));
maps = fopen(info->path, "r");
if (!maps)
goto out;
while (fscanf(maps, "%*x-%*x %*s %zx %s %ld %s\n", &offset, device, &inode,
file) == 4) {
if (inode == 0 || !strcmp(device, "00:00"))
continue;
printf("%-9s %5d %10s %4s %9s %18s %9zd %10ld %s\n",
info->cmdline, info->pid, info->user, "mem",
"???", device, offset, inode, file);
}
fclose(maps);
out:
info->path[info->parent_length] = '\0';
}
Commit Message: Fix scanf %s in lsof.
Bug: http://b/28175237
Change-Id: Ief0ba299b09693ad9afc0e3d17a8f664c2fbb8c2
CWE ID: CWE-20
Target: 1
Example 2:
Code: PHP_FUNCTION(pg_insert)
{
zval *pgsql_link, *values;
char *table;
size_t table_len;
zend_ulong option = PGSQL_DML_EXEC, return_sql;
PGconn *pg_link;
PGresult *pg_result;
ExecStatusType status;
pgsql_result_handle *pgsql_handle;
zend_string *sql = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc, "rsa|l",
&pgsql_link, &table, &table_len, &values, &option) == FAILURE) {
return;
}
if (option & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) {
php_error_docref(NULL, E_WARNING, "Invalid option is specified");
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pg_link, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (php_pgsql_flush_query(pg_link)) {
php_error_docref(NULL, E_NOTICE, "Detected unhandled result(s) in connection");
}
return_sql = option & PGSQL_DML_STRING;
if (option & PGSQL_DML_EXEC) {
/* return resource when executed */
option = option & ~PGSQL_DML_EXEC;
if (php_pgsql_insert(pg_link, table, values, option|PGSQL_DML_STRING, &sql) == FAILURE) {
RETURN_FALSE;
}
pg_result = PQexec(pg_link, sql->val);
if ((PGG(auto_reset_persistent) & 2) && PQstatus(pg_link) != CONNECTION_OK) {
PQclear(pg_result);
PQreset(pg_link);
pg_result = PQexec(pg_link, sql->val);
}
efree(sql);
if (pg_result) {
status = PQresultStatus(pg_result);
} else {
status = (ExecStatusType) PQstatus(pg_link);
}
switch (status) {
case PGRES_EMPTY_QUERY:
case PGRES_BAD_RESPONSE:
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
PHP_PQ_ERROR("Query failed: %s", pg_link);
PQclear(pg_result);
RETURN_FALSE;
break;
case PGRES_COMMAND_OK: /* successful command that did not return rows */
default:
if (pg_result) {
pgsql_handle = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
pgsql_handle->conn = pg_link;
pgsql_handle->result = pg_result;
pgsql_handle->row = 0;
ZEND_REGISTER_RESOURCE(return_value, pgsql_handle, le_result);
return;
} else {
PQclear(pg_result);
RETURN_FALSE;
}
break;
}
} else if (php_pgsql_insert(pg_link, table, values, option, &sql) == FAILURE) {
RETURN_FALSE;
}
if (return_sql) {
RETURN_STR(sql);
return;
}
RETURN_TRUE;
}
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 RTCPeerConnectionHandler::SetRemoteDescription(
const blink::WebRTCVoidRequest& request,
const blink::WebRTCSessionDescription& description) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::setRemoteDescription");
std::string sdp = description.Sdp().Utf8();
std::string type = description.GetType().Utf8();
if (peer_connection_tracker_) {
peer_connection_tracker_->TrackSetSessionDescription(
this, sdp, type, PeerConnectionTracker::SOURCE_REMOTE);
}
webrtc::SdpParseError error;
std::unique_ptr<webrtc::SessionDescriptionInterface> native_desc(
CreateNativeSessionDescription(sdp, type, &error));
if (!native_desc) {
std::string reason_str = "Failed to parse SessionDescription. ";
reason_str.append(error.line);
reason_str.append(" ");
reason_str.append(error.description);
LOG(ERROR) << reason_str;
request.RequestFailed(webrtc::RTCError(
webrtc::RTCErrorType::UNSUPPORTED_OPERATION, std::move(reason_str)));
if (peer_connection_tracker_) {
peer_connection_tracker_->TrackSessionDescriptionCallback(
this, PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION,
"OnFailure", reason_str);
}
return;
}
if (!first_remote_description_ && IsOfferOrAnswer(native_desc.get())) {
first_remote_description_.reset(
new FirstSessionDescription(native_desc.get()));
if (first_local_description_) {
ReportFirstSessionDescriptions(
*first_local_description_,
*first_remote_description_);
}
}
scoped_refptr<WebRtcSetDescriptionObserverImpl> content_observer(
new WebRtcSetDescriptionObserverImpl(
weak_factory_.GetWeakPtr(), request, peer_connection_tracker_,
task_runner_, PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION,
configuration_.sdp_semantics));
bool surface_receivers_only =
(configuration_.sdp_semantics == webrtc::SdpSemantics::kPlanB);
rtc::scoped_refptr<webrtc::SetRemoteDescriptionObserverInterface>
webrtc_observer(WebRtcSetRemoteDescriptionObserverHandler::Create(
task_runner_, signaling_thread(),
native_peer_connection_, track_adapter_map_,
content_observer, surface_receivers_only)
.get());
signaling_thread()->PostTask(
FROM_HERE,
base::BindOnce(
&RunClosureWithTrace,
base::Bind(
static_cast<void (webrtc::PeerConnectionInterface::*)(
std::unique_ptr<webrtc::SessionDescriptionInterface>,
rtc::scoped_refptr<
webrtc::SetRemoteDescriptionObserverInterface>)>(
&webrtc::PeerConnectionInterface::SetRemoteDescription),
native_peer_connection_, base::Passed(&native_desc),
webrtc_observer),
"SetRemoteDescription"));
}
Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl
Bug: 912074
Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8
Reviewed-on: https://chromium-review.googlesource.com/c/1411916
Commit-Queue: Guido Urdaneta <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#622945}
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 void php_wddx_serialize_object(wddx_packet *packet, zval *obj)
{
/* OBJECTS_FIXME */
zval **ent, *fname, **varname;
zval *retval = NULL;
const char *key;
ulong idx;
char tmp_buf[WDDX_BUF_LEN];
HashTable *objhash, *sleephash;
TSRMLS_FETCH();
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__sleep", 1);
/*
* We try to call __sleep() method on object. It's supposed to return an
* array of property names to be serialized.
*/
if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) {
if (retval && (sleephash = HASH_OF(retval))) {
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(sleephash);
zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS;
zend_hash_move_forward(sleephash)) {
if (Z_TYPE_PP(varname) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
continue;
}
if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) {
php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
} else {
uint key_len;
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(objhash);
zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(objhash)) {
if (*ent == obj) {
continue;
}
if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) {
const char *class_name, *prop_name;
zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name);
php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
Commit Message: Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle
Proper soltion would be to call serialize/unserialize and deal with the result,
but this requires more work that should be done by wddx maintainer (not me).
CWE ID: CWE-476
Target: 1
Example 2:
Code: BufferManager::BufferInfo* GetBufferInfoForTarget(GLenum target) {
DCHECK(target == GL_ARRAY_BUFFER || target == GL_ELEMENT_ARRAY_BUFFER);
BufferManager::BufferInfo* info = target == GL_ARRAY_BUFFER ?
bound_array_buffer_ : bound_element_array_buffer_;
return info;
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
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: ft_bitmap_assure_buffer( FT_Memory memory,
FT_Bitmap* bitmap,
FT_UInt xpixels,
FT_UInt ypixels )
{
FT_Error error;
int pitch;
int new_pitch;
FT_UInt bpp;
FT_Int i, width, height;
unsigned char* buffer = NULL;
width = bitmap->width;
height = bitmap->rows;
pitch = bitmap->pitch;
if ( pitch < 0 )
pitch = -pitch;
switch ( bitmap->pixel_mode )
{
case FT_PIXEL_MODE_MONO:
bpp = 1;
new_pitch = ( width + xpixels + 7 ) >> 3;
break;
case FT_PIXEL_MODE_GRAY2:
bpp = 2;
new_pitch = ( width + xpixels + 3 ) >> 2;
break;
case FT_PIXEL_MODE_GRAY4:
bpp = 4;
new_pitch = ( width + xpixels + 1 ) >> 1;
break;
case FT_PIXEL_MODE_GRAY:
case FT_PIXEL_MODE_LCD:
case FT_PIXEL_MODE_LCD_V:
bpp = 8;
new_pitch = ( width + xpixels );
break;
default:
return FT_THROW( Invalid_Glyph_Format );
}
/* if no need to allocate memory */
if ( ypixels == 0 && new_pitch <= pitch )
{
/* zero the padding */
FT_Int bit_width = pitch * 8;
FT_Int bit_last = ( width + xpixels ) * bpp;
if ( bit_last < bit_width )
{
FT_Byte* line = bitmap->buffer + ( bit_last >> 3 );
FT_Byte* end = bitmap->buffer + pitch;
FT_Int shift = bit_last & 7;
FT_UInt mask = 0xFF00U >> shift;
FT_Int count = height;
for ( ; count > 0; count--, line += pitch, end += pitch )
{
FT_Byte* write = line;
if ( shift > 0 )
{
write[0] = (FT_Byte)( write[0] & mask );
write++;
}
if ( write < end )
FT_MEM_ZERO( write, end - write );
}
}
return FT_Err_Ok;
}
/* otherwise allocate new buffer */
if ( FT_QALLOC_MULT( buffer, new_pitch, bitmap->rows + ypixels ) )
return error;
/* new rows get added at the top of the bitmap, */
/* thus take care of the flow direction */
if ( bitmap->pitch > 0 )
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * ( ypixels + i ),
bitmap->buffer + pitch * i, len );
}
else
{
FT_Int len = ( width * bpp + 7 ) >> 3;
for ( i = 0; i < bitmap->rows; i++ )
FT_MEM_COPY( buffer + new_pitch * i,
bitmap->buffer + pitch * i, len );
}
FT_FREE( bitmap->buffer );
bitmap->buffer = buffer;
if ( bitmap->pitch < 0 )
new_pitch = -new_pitch;
/* set pitch only, width and height are left untouched */
bitmap->pitch = new_pitch;
return FT_Err_Ok;
}
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: static void buffer_pipe_buf_get(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
struct buffer_ref *ref = (struct buffer_ref *)buf->private;
ref->ref++;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void voidMethodArrayBufferArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
throwTypeError(ExceptionMessages::failedToExecute("voidMethodArrayBufferArg", "TestObjectPython", ExceptionMessages::notEnoughArguments(1, info.Length())), info.GetIsolate());
return;
}
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
V8TRYCATCH_VOID(ArrayBuffer*, arrayBufferArg, info[0]->IsArrayBuffer() ? V8ArrayBuffer::toNative(v8::Handle<v8::ArrayBuffer>::Cast(info[0])) : 0);
imp->voidMethodArrayBufferArg(arrayBufferArg);
}
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
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 hpet_post_load(void *opaque, int version_id)
{
HPETState *s = opaque;
s->flags |= 1 << HPET_MSI_SUPPORT;
}
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: static void enable_nmi_window(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
== HF_NMI_MASK)
return; /* IRET will cause a vm exit */
/*
* Something prevents NMI from been injected. Single step over possible
* problem (IRET or exception injection or interrupt shadow)
*/
svm->nmi_singlestep = true;
svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
update_db_bp_intercept(vcpu);
}
Commit Message: KVM: svm: unconditionally intercept #DB
This is needed to avoid the possibility that the guest triggers
an infinite stream of #DB exceptions (CVE-2015-8104).
VMX is not affected: because it does not save DR6 in the VMCS,
it already intercepts #DB unconditionally.
Reported-by: Jan Beulich <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b,
BN_CTX *ctx)
{
if (group->meth->point_cmp == 0) {
ECerr(EC_F_EC_POINT_CMP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return -1;
}
if ((group->meth != a->meth) || (a->meth != b->meth)) {
ECerr(EC_F_EC_POINT_CMP, EC_R_INCOMPATIBLE_OBJECTS);
return -1;
}
return group->meth->point_cmp(group, a, b, ctx);
}
Commit Message:
CWE ID: CWE-311
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 mem_seek(jas_stream_obj_t *obj, long offset, int origin)
{
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
long newpos;
JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin));
switch (origin) {
case SEEK_SET:
newpos = offset;
break;
case SEEK_END:
newpos = m->len_ - offset;
break;
case SEEK_CUR:
newpos = m->pos_ + offset;
break;
default:
abort();
break;
}
if (newpos < 0) {
return -1;
}
m->pos_ = newpos;
return m->pos_;
}
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 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; 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;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
Commit Message: Fix #8743 - Crash in ELF version parser on 32bit systems
CWE ID: CWE-125
Target: 1
Example 2:
Code: int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
AVFrame *frame,
int *got_frame_ptr,
const AVPacket *avpkt)
{
AVCodecInternal *avci = avctx->internal;
int ret = 0;
*got_frame_ptr = 0;
if (!avctx->codec)
return AVERROR(EINVAL);
if (!avctx->codec->decode) {
av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n");
return AVERROR(ENOSYS);
}
if (!avpkt->data && avpkt->size) {
av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
return AVERROR(EINVAL);
}
if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
return AVERROR(EINVAL);
}
av_frame_unref(frame);
if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
uint8_t *side;
int side_size;
uint32_t discard_padding = 0;
uint8_t skip_reason = 0;
uint8_t discard_reason = 0;
AVPacket tmp = *avpkt;
int did_split = av_packet_split_side_data(&tmp);
ret = apply_param_change(avctx, &tmp);
if (ret < 0)
goto fail;
avctx->internal->pkt = &tmp;
if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);
else {
ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
av_assert0(ret <= tmp.size);
frame->pkt_dts = avpkt->dts;
}
if (ret >= 0 && *got_frame_ptr) {
avctx->frame_number++;
av_frame_set_best_effort_timestamp(frame,
guess_correct_pts(avctx,
frame->pts,
frame->pkt_dts));
if (frame->format == AV_SAMPLE_FMT_NONE)
frame->format = avctx->sample_fmt;
if (!frame->channel_layout)
frame->channel_layout = avctx->channel_layout;
if (!av_frame_get_channels(frame))
av_frame_set_channels(frame, avctx->channels);
if (!frame->sample_rate)
frame->sample_rate = avctx->sample_rate;
}
side= av_packet_get_side_data(avctx->internal->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
if(side && side_size>=10) {
avctx->internal->skip_samples = AV_RL32(side);
discard_padding = AV_RL32(side + 4);
av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
avctx->internal->skip_samples, (int)discard_padding);
skip_reason = AV_RL8(side + 8);
discard_reason = AV_RL8(side + 9);
}
if ((frame->flags & AV_FRAME_FLAG_DISCARD) && *got_frame_ptr &&
!(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
*got_frame_ptr = 0;
}
if (avctx->internal->skip_samples > 0 && *got_frame_ptr &&
!(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
if(frame->nb_samples <= avctx->internal->skip_samples){
*got_frame_ptr = 0;
avctx->internal->skip_samples -= frame->nb_samples;
av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
avctx->internal->skip_samples);
} else {
av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
if(avctx->pkt_timebase.num && avctx->sample_rate) {
int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
(AVRational){1, avctx->sample_rate},
avctx->pkt_timebase);
if(frame->pts!=AV_NOPTS_VALUE)
frame->pts += diff_ts;
#if FF_API_PKT_PTS
FF_DISABLE_DEPRECATION_WARNINGS
if(frame->pkt_pts!=AV_NOPTS_VALUE)
frame->pkt_pts += diff_ts;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
if(frame->pkt_dts!=AV_NOPTS_VALUE)
frame->pkt_dts += diff_ts;
if (av_frame_get_pkt_duration(frame) >= diff_ts)
av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
} else {
av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
}
av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
avctx->internal->skip_samples, frame->nb_samples);
frame->nb_samples -= avctx->internal->skip_samples;
avctx->internal->skip_samples = 0;
}
}
if (discard_padding > 0 && discard_padding <= frame->nb_samples && *got_frame_ptr &&
!(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
if (discard_padding == frame->nb_samples) {
*got_frame_ptr = 0;
} else {
if(avctx->pkt_timebase.num && avctx->sample_rate) {
int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
(AVRational){1, avctx->sample_rate},
avctx->pkt_timebase);
av_frame_set_pkt_duration(frame, diff_ts);
} else {
av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
}
av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
(int)discard_padding, frame->nb_samples);
frame->nb_samples -= discard_padding;
}
}
if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && *got_frame_ptr) {
AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
if (fside) {
AV_WL32(fside->data, avctx->internal->skip_samples);
AV_WL32(fside->data + 4, discard_padding);
AV_WL8(fside->data + 8, skip_reason);
AV_WL8(fside->data + 9, discard_reason);
avctx->internal->skip_samples = 0;
}
}
fail:
avctx->internal->pkt = NULL;
if (did_split) {
av_packet_free_side_data(&tmp);
if(ret == tmp.size)
ret = avpkt->size;
}
if (ret >= 0 && *got_frame_ptr) {
if (!avctx->refcounted_frames) {
int err = unrefcount_frame(avci, frame);
if (err < 0)
return err;
}
} else
av_frame_unref(frame);
}
av_assert0(ret <= avpkt->size);
if (!avci->showed_multi_packet_warning &&
ret >= 0 && ret != avpkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
avci->showed_multi_packet_warning = 1;
}
return ret;
}
Commit Message: avcodec/utils: correct align value for interplay
Fixes out of array access
Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
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 unsigned long mmap_legacy_base(unsigned long rnd)
{
if (mmap_is_ia32())
return TASK_UNMAPPED_BASE;
else
return TASK_UNMAPPED_BASE + rnd;
}
Commit Message: x86/mm/32: Enable full randomization on i386 and X86_32
Currently on i386 and on X86_64 when emulating X86_32 in legacy mode, only
the stack and the executable are randomized but not other mmapped files
(libraries, vDSO, etc.). This patch enables randomization for the
libraries, vDSO and mmap requests on i386 and in X86_32 in legacy mode.
By default on i386 there are 8 bits for the randomization of the libraries,
vDSO and mmaps which only uses 1MB of VA.
This patch preserves the original randomness, using 1MB of VA out of 3GB or
4GB. We think that 1MB out of 3GB is not a big cost for having the ASLR.
The first obvious security benefit is that all objects are randomized (not
only the stack and the executable) in legacy mode which highly increases
the ASLR effectiveness, otherwise the attackers may use these
non-randomized areas. But also sensitive setuid/setgid applications are
more secure because currently, attackers can disable the randomization of
these applications by setting the ulimit stack to "unlimited". This is a
very old and widely known trick to disable the ASLR in i386 which has been
allowed for too long.
Another trick used to disable the ASLR was to set the ADDR_NO_RANDOMIZE
personality flag, but fortunately this doesn't work on setuid/setgid
applications because there is security checks which clear Security-relevant
flags.
This patch always randomizes the mmap_legacy_base address, removing the
possibility to disable the ASLR by setting the stack to "unlimited".
Signed-off-by: Hector Marco-Gisbert <[email protected]>
Acked-by: Ismael Ripoll Ripoll <[email protected]>
Acked-by: Kees Cook <[email protected]>
Acked-by: Arjan van de Ven <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: [email protected]
Cc: kees Cook <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-254
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 dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp)
{
BN_CTX *ctx;
BIGNUM k, kq, *K, *kinv = NULL, *r = NULL;
BIGNUM l, m;
int ret = 0;
int q_bits;
if (!dsa->p || !dsa->q || !dsa->g) {
DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS);
return 0;
}
BN_init(&k);
BN_init(&kq);
BN_init(&l);
BN_init(&m);
if (ctx_in == NULL) {
if ((ctx = BN_CTX_new()) == NULL)
goto err;
} else
ctx = ctx_in;
if ((r = BN_new()) == NULL)
goto err;
/* Preallocate space */
q_bits = BN_num_bits(dsa->q);
if (!BN_set_bit(&k, q_bits)
|| !BN_set_bit(&l, q_bits)
|| !BN_set_bit(&m, q_bits))
goto err;
/* Get random k */
do
if (!BN_rand_range(&k, dsa->q))
goto err;
while (BN_is_zero(&k));
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
BN_set_flags(&k, BN_FLG_CONSTTIME);
}
if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p,
CRYPTO_LOCK_DSA, dsa->p, ctx))
goto err;
}
/* Compute r = (g^k mod p) mod q */
if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) {
/*
* We do not want timing information to leak the length of k, so we
* compute G^k using an equivalent scalar of fixed bit-length.
*
* We unconditionally perform both of these additions to prevent a
* small timing information leakage. We then choose the sum that is
* one bit longer than the modulus.
*
* TODO: revisit the BN_copy aiming for a memory access agnostic
* conditional copy.
*/
if (!BN_add(&l, &k, dsa->q)
|| !BN_add(&m, &l, dsa->q)
|| !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m))
goto err;
BN_set_flags(&kq, BN_FLG_CONSTTIME);
K = &kq;
} else {
K = &k;
}
DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx,
dsa->method_mont_p);
if (!BN_mod(r, r, dsa->q, ctx))
goto err;
/* Compute part of 's = inv(k) (m + xr) mod q' */
if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL)
goto err;
if (*kinvp != NULL)
BN_clear_free(*kinvp);
*kinvp = kinv;
kinv = NULL;
if (*rp != NULL)
BN_clear_free(*rp);
*rp = r;
ret = 1;
err:
if (!ret) {
DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB);
if (r != NULL)
BN_clear_free(r);
}
if (ctx_in == NULL)
BN_CTX_free(ctx);
BN_clear_free(&k);
BN_clear_free(&kq);
BN_clear_free(&l);
BN_clear_free(&m);
return ret;
}
Commit Message:
CWE ID: CWE-320
Target: 1
Example 2:
Code: int wc_ecc_free(ecc_key* key)
{
if (key == NULL) {
return 0;
}
#ifdef WOLFSSL_ASYNC_CRYPT
#ifdef WC_ASYNC_ENABLE_ECC
wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC);
#endif
wc_ecc_free_async(key);
#endif
#ifdef WOLFSSL_ATECC508A
atmel_ecc_free(key->slot);
key->slot = -1;
#else
mp_clear(key->pubkey.x);
mp_clear(key->pubkey.y);
mp_clear(key->pubkey.z);
mp_forcezero(&key->k);
#endif /* WOLFSSL_ATECC508A */
#ifdef WOLFSSL_CUSTOM_CURVES
if (key->deallocSet && key->dp != NULL)
wc_ecc_free_curve(key->dp, key->heap);
#endif
return 0;
}
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: tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
u32 prior_snd_una)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
const unsigned char *ptr = (skb_transport_header(ack_skb) +
TCP_SKB_CB(ack_skb)->sacked);
struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
struct tcp_sack_block sp[TCP_NUM_SACKS];
struct tcp_sack_block *cache;
struct tcp_sacktag_state state;
struct sk_buff *skb;
int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
int used_sacks;
int found_dup_sack = 0;
int i, j;
int first_sack_index;
state.flag = 0;
state.reord = tp->packets_out;
if (!tp->sacked_out) {
if (WARN_ON(tp->fackets_out))
tp->fackets_out = 0;
tcp_highest_sack_reset(sk);
}
found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
num_sacks, prior_snd_una);
if (found_dup_sack)
state.flag |= FLAG_DSACKING_ACK;
/* Eliminate too old ACKs, but take into
* account more or less fresh ones, they can
* contain valid SACK info.
*/
if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
return 0;
if (!tp->packets_out)
goto out;
used_sacks = 0;
first_sack_index = 0;
for (i = 0; i < num_sacks; i++) {
int dup_sack = !i && found_dup_sack;
sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq);
sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq);
if (!tcp_is_sackblock_valid(tp, dup_sack,
sp[used_sacks].start_seq,
sp[used_sacks].end_seq)) {
int mib_idx;
if (dup_sack) {
if (!tp->undo_marker)
mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO;
else
mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD;
} else {
/* Don't count olds caused by ACK reordering */
if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
!after(sp[used_sacks].end_seq, tp->snd_una))
continue;
mib_idx = LINUX_MIB_TCPSACKDISCARD;
}
NET_INC_STATS_BH(sock_net(sk), mib_idx);
if (i == 0)
first_sack_index = -1;
continue;
}
/* Ignore very old stuff early */
if (!after(sp[used_sacks].end_seq, prior_snd_una))
continue;
used_sacks++;
}
/* order SACK blocks to allow in order walk of the retrans queue */
for (i = used_sacks - 1; i > 0; i--) {
for (j = 0; j < i; j++) {
if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
swap(sp[j], sp[j + 1]);
/* Track where the first SACK block goes to */
if (j == first_sack_index)
first_sack_index = j + 1;
}
}
}
skb = tcp_write_queue_head(sk);
state.fack_count = 0;
i = 0;
if (!tp->sacked_out) {
/* It's already past, so skip checking against it */
cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
} else {
cache = tp->recv_sack_cache;
/* Skip empty blocks in at head of the cache */
while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
!cache->end_seq)
cache++;
}
while (i < used_sacks) {
u32 start_seq = sp[i].start_seq;
u32 end_seq = sp[i].end_seq;
int dup_sack = (found_dup_sack && (i == first_sack_index));
struct tcp_sack_block *next_dup = NULL;
if (found_dup_sack && ((i + 1) == first_sack_index))
next_dup = &sp[i + 1];
/* Event "B" in the comment above. */
if (after(end_seq, tp->high_seq))
state.flag |= FLAG_DATA_LOST;
/* Skip too early cached blocks */
while (tcp_sack_cache_ok(tp, cache) &&
!before(start_seq, cache->end_seq))
cache++;
/* Can skip some work by looking recv_sack_cache? */
if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
after(end_seq, cache->start_seq)) {
/* Head todo? */
if (before(start_seq, cache->start_seq)) {
skb = tcp_sacktag_skip(skb, sk, &state,
start_seq);
skb = tcp_sacktag_walk(skb, sk, next_dup,
&state,
start_seq,
cache->start_seq,
dup_sack);
}
/* Rest of the block already fully processed? */
if (!after(end_seq, cache->end_seq))
goto advance_sp;
skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
&state,
cache->end_seq);
/* ...tail remains todo... */
if (tcp_highest_sack_seq(tp) == cache->end_seq) {
/* ...but better entrypoint exists! */
skb = tcp_highest_sack(sk);
if (skb == NULL)
break;
state.fack_count = tp->fackets_out;
cache++;
goto walk;
}
skb = tcp_sacktag_skip(skb, sk, &state, cache->end_seq);
/* Check overlap against next cached too (past this one already) */
cache++;
continue;
}
if (!before(start_seq, tcp_highest_sack_seq(tp))) {
skb = tcp_highest_sack(sk);
if (skb == NULL)
break;
state.fack_count = tp->fackets_out;
}
skb = tcp_sacktag_skip(skb, sk, &state, start_seq);
walk:
skb = tcp_sacktag_walk(skb, sk, next_dup, &state,
start_seq, end_seq, dup_sack);
advance_sp:
/* SACK enhanced FRTO (RFC4138, Appendix B): Clearing correct
* due to in-order walk
*/
if (after(end_seq, tp->frto_highmark))
state.flag &= ~FLAG_ONLY_ORIG_SACKED;
i++;
}
/* Clear the head of the cache sack blocks so we can skip it next time */
for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
tp->recv_sack_cache[i].start_seq = 0;
tp->recv_sack_cache[i].end_seq = 0;
}
for (j = 0; j < used_sacks; j++)
tp->recv_sack_cache[i++] = sp[j];
tcp_mark_lost_retrans(sk);
tcp_verify_left_out(tp);
if ((state.reord < tp->fackets_out) &&
((icsk->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker) &&
(!tp->frto_highmark || after(tp->snd_una, tp->frto_highmark)))
tcp_update_reordering(sk, tp->fackets_out - state.reord, 0);
out:
#if FASTRETRANS_DEBUG > 0
WARN_ON((int)tp->sacked_out < 0);
WARN_ON((int)tp->lost_out < 0);
WARN_ON((int)tp->retrans_out < 0);
WARN_ON((int)tcp_packets_in_flight(tp) < 0);
#endif
return state.flag;
}
Commit Message: tcp: drop SYN+FIN messages
Denys Fedoryshchenko reported that SYN+FIN attacks were bringing his
linux machines to their limits.
Dont call conn_request() if the TCP flags includes SYN flag
Reported-by: Denys Fedoryshchenko <[email protected]>
Signed-off-by: Eric Dumazet <[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: status_t MediaPlayer::setDataSource(
const sp<IMediaHTTPService> &httpService,
const char *url, const KeyedVector<String8, String8> *headers)
{
ALOGV("setDataSource(%s)", url);
status_t err = BAD_VALUE;
if (url != NULL) {
const sp<IMediaPlayerService>& service(getMediaPlayerService());
if (service != 0) {
sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
(NO_ERROR != player->setDataSource(httpService, url, headers))) {
player.clear();
}
err = attachNewPlayer(player);
}
}
return err;
}
Commit Message: Don't use sp<>&
because they may end up pointing to NULL after a NULL check was performed.
Bug: 28166152
Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe
CWE ID: CWE-476
Target: 1
Example 2:
Code: format_256(const u_char *data)
{
static char buf[4][sizeof("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64,
EXTRACT_64BITS(data),
EXTRACT_64BITS(data + 8),
EXTRACT_64BITS(data + 16),
EXTRACT_64BITS(data + 24)
);
return buf[i];
}
Commit Message: CVE-2017-13044/HNCP: add DHCPv4-Data bounds checks
dhcpv4_print() in print-hncp.c had the same bug as dhcpv6_print(), apply
a fix along the same lines.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
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 re_yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yycolumn;
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
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 bool ShouldAutofocus(const HTMLFormControlElement* element) {
if (!element->isConnected())
return false;
if (!element->IsAutofocusable())
return false;
Document& doc = element->GetDocument();
if (doc.IsSandboxed(WebSandboxFlags::kAutomaticFeatures)) {
doc.AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
"Blocked autofocusing on a form control because the form's frame is "
"sandboxed and the 'allow-scripts' permission is not set."));
return false;
}
if (!doc.IsInMainFrame() &&
!doc.TopFrameOrigin()->CanAccess(doc.GetSecurityOrigin())) {
doc.AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
"Blocked autofocusing on a form control in a cross-origin subframe."));
return false;
}
return true;
}
Commit Message: autofocus: Fix a crash with an autofocus element in a document without browsing context.
ShouldAutofocus() should check existence of the browsing context.
Otherwise, doc.TopFrameOrigin() returns null.
Before crrev.com/695830, ShouldAutofocus() was called only for
rendered elements. That is to say, the document always had
browsing context.
Bug: 1003228
Change-Id: I2a941c34e9707d44869a6d7585dc7fb9f06e3bf4
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1800902
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Keishi Hattori <[email protected]>
Cr-Commit-Position: refs/heads/master@{#696291}
CWE ID: CWE-704
Target: 1
Example 2:
Code: static IndexPacket *GetAuthenticIndexesFromCache(const Image *image)
{
CacheInfo
*restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickSignature);
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->indexes);
}
Commit Message:
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: main (int argc, char *argv[])
{
struct gengetopt_args_info args_info;
char *line = NULL;
size_t linelen = 0;
char *p, *r;
uint32_t *q;
unsigned cmdn = 0;
int rc;
setlocale (LC_ALL, "");
set_program_name (argv[0]);
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
if (cmdline_parser (argc, argv, &args_info) != 0)
return EXIT_FAILURE;
if (args_info.version_given)
{
version_etc (stdout, "idn", PACKAGE_NAME, VERSION,
"Simon Josefsson", (char *) NULL);
return EXIT_SUCCESS;
}
if (args_info.help_given)
usage (EXIT_SUCCESS);
/* Backwards compatibility: -n has always been the documented short
form for --nfkc but, before v1.10, -k was the implemented short
form. We now accept both to avoid documentation changes. */
if (args_info.hidden_nfkc_given)
args_info.nfkc_given = 1;
if (!args_info.stringprep_given &&
!args_info.punycode_encode_given && !args_info.punycode_decode_given &&
!args_info.idna_to_ascii_given && !args_info.idna_to_unicode_given &&
!args_info.nfkc_given)
args_info.idna_to_ascii_given = 1;
if ((args_info.stringprep_given ? 1 : 0) +
(args_info.punycode_encode_given ? 1 : 0) +
(args_info.punycode_decode_given ? 1 : 0) +
(args_info.idna_to_ascii_given ? 1 : 0) +
(args_info.idna_to_unicode_given ? 1 : 0) +
(args_info.nfkc_given ? 1 : 0) != 1)
{
error (0, 0, _("only one of -s, -e, -d, -a, -u or -n can be specified"));
usage (EXIT_FAILURE);
}
if (!args_info.quiet_given
&& args_info.inputs_num == 0
&& isatty (fileno (stdin)))
fprintf (stderr, "%s %s\n" GREETING, PACKAGE, VERSION);
if (args_info.debug_given)
fprintf (stderr, _("Charset `%s'.\n"), stringprep_locale_charset ());
if (!args_info.quiet_given
&& args_info.inputs_num == 0
&& isatty (fileno (stdin)))
fprintf (stderr, _("Type each input string on a line by itself, "
"terminated by a newline character.\n"));
do
{
if (cmdn < args_info.inputs_num)
line = strdup (args_info.inputs[cmdn++]);
else if (getline (&line, &linelen, stdin) == -1)
{
if (feof (stdin))
break;
error (EXIT_FAILURE, errno, _("input error"));
}
if (line[strlen (line) - 1] == '\n')
line[strlen (line) - 1] = '\0';
if (args_info.stringprep_given)
{
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
q = stringprep_utf8_to_ucs4 (p, -1, NULL);
if (!q)
{
free (p);
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
}
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
free (q);
rc = stringprep_profile (p, &r,
args_info.profile_given ?
args_info.profile_arg : "Nameprep", 0);
free (p);
if (rc != STRINGPREP_OK)
error (EXIT_FAILURE, 0, _("stringprep_profile: %s"),
stringprep_strerror (rc));
q = stringprep_utf8_to_ucs4 (r, -1, NULL);
if (!q)
{
free (r);
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
}
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
free (q);
p = stringprep_utf8_to_locale (r);
free (r);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.punycode_encode_given)
{
char encbuf[BUFSIZ];
size_t len, len2;
p = stringprep_locale_to_utf8 (line);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
q = stringprep_utf8_to_ucs4 (p, -1, &len);
free (p);
if (!q)
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
if (args_info.debug_given)
{
size_t i;
for (i = 0; i < len; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
len2 = BUFSIZ - 1;
rc = punycode_encode (len, q, NULL, &len2, encbuf);
free (q);
if (rc != PUNYCODE_SUCCESS)
error (EXIT_FAILURE, 0, _("punycode_encode: %s"),
punycode_strerror (rc));
encbuf[len2] = '\0';
p = stringprep_utf8_to_locale (encbuf);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.punycode_decode_given)
{
size_t len;
len = BUFSIZ;
q = (uint32_t *) malloc (len * sizeof (q[0]));
if (!q)
error (EXIT_FAILURE, ENOMEM, N_("malloc"));
rc = punycode_decode (strlen (line), line, &len, q, NULL);
if (rc != PUNYCODE_SUCCESS)
{
free (q);
error (EXIT_FAILURE, 0, _("punycode_decode: %s"),
punycode_strerror (rc));
}
if (args_info.debug_given)
{
size_t i;
for (i = 0; i < len; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
q[len] = 0;
r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL);
free (q);
if (!r)
error (EXIT_FAILURE, 0,
_("could not convert from UCS-4 to UTF-8"));
p = stringprep_utf8_to_locale (r);
free (r);
if (!r)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.idna_to_ascii_given)
{
p = stringprep_locale_to_utf8 (line);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
q = stringprep_utf8_to_ucs4 (p, -1, NULL);
free (p);
if (!q)
error (EXIT_FAILURE, 0,
_("could not convert from UCS-4 to UTF-8"));
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
rc = idna_to_ascii_4z (q, &p,
(args_info.allow_unassigned_given ?
IDNA_ALLOW_UNASSIGNED : 0) |
(args_info.usestd3asciirules_given ?
IDNA_USE_STD3_ASCII_RULES : 0));
free (q);
if (rc != IDNA_SUCCESS)
error (EXIT_FAILURE, 0, _("idna_to_ascii_4z: %s"),
idna_strerror (rc));
#ifdef WITH_TLD
if (args_info.tld_flag && !args_info.no_tld_flag)
{
size_t errpos;
rc = idna_to_unicode_8z4z (p, &q,
(args_info.allow_unassigned_given ?
IDNA_ALLOW_UNASSIGNED : 0) |
(args_info.usestd3asciirules_given ?
IDNA_USE_STD3_ASCII_RULES : 0));
if (rc != IDNA_SUCCESS)
error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z (TLD): %s"),
idna_strerror (rc));
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "tld[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
rc = tld_check_4z (q, &errpos, NULL);
free (q);
if (rc == TLD_INVALID)
error (EXIT_FAILURE, 0, _("tld_check_4z (position %lu): %s"),
(unsigned long) errpos, tld_strerror (rc));
if (rc != TLD_SUCCESS)
error (EXIT_FAILURE, 0, _("tld_check_4z: %s"),
tld_strerror (rc));
}
#endif
if (args_info.debug_given)
{
size_t i;
for (i = 0; p[i]; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, p[i]);
}
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.idna_to_unicode_given)
{
p = stringprep_locale_to_utf8 (line);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
q = stringprep_utf8_to_ucs4 (p, -1, NULL);
if (!q)
{
free (p);
error (EXIT_FAILURE, 0,
_("could not convert from UCS-4 to UTF-8"));
}
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
free (q);
rc = idna_to_unicode_8z4z (p, &q,
(args_info.allow_unassigned_given ?
IDNA_ALLOW_UNASSIGNED : 0) |
(args_info.usestd3asciirules_given ?
IDNA_USE_STD3_ASCII_RULES : 0));
free (p);
if (rc != IDNA_SUCCESS)
error (EXIT_FAILURE, 0, _("idna_to_unicode_8z4z: %s"),
idna_strerror (rc));
if (args_info.debug_given)
{
size_t i;
for (i = 0; q[i]; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
}
#ifdef WITH_TLD
if (args_info.tld_flag)
{
size_t errpos;
rc = tld_check_4z (q, &errpos, NULL);
if (rc == TLD_INVALID)
{
free (q);
error (EXIT_FAILURE, 0,
_("tld_check_4z (position %lu): %s"),
(unsigned long) errpos, tld_strerror (rc));
}
if (rc != TLD_SUCCESS)
{
free (q);
error (EXIT_FAILURE, 0, _("tld_check_4z: %s"),
tld_strerror (rc));
}
}
#endif
r = stringprep_ucs4_to_utf8 (q, -1, NULL, NULL);
free (q);
if (!r)
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
p = stringprep_utf8_to_locale (r);
free (r);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
if (args_info.nfkc_given)
{
p = stringprep_locale_to_utf8 (line);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from %s to UTF-8"),
stringprep_locale_charset ());
if (args_info.debug_given)
{
size_t i;
q = stringprep_utf8_to_ucs4 (p, -1, NULL);
if (!q)
{
free (p);
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
}
for (i = 0; q[i]; i++)
fprintf (stderr, "input[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
free (q);
}
r = stringprep_utf8_nfkc_normalize (p, -1);
free (p);
if (!r)
error (EXIT_FAILURE, 0, _("could not do NFKC normalization"));
if (args_info.debug_given)
{
size_t i;
q = stringprep_utf8_to_ucs4 (r, -1, NULL);
if (!q)
{
free (r);
error (EXIT_FAILURE, 0,
_("could not convert from UTF-8 to UCS-4"));
}
for (i = 0; q[i]; i++)
fprintf (stderr, "output[%lu] = U+%04x\n",
(unsigned long) i, q[i]);
free (q);
}
p = stringprep_utf8_to_locale (r);
free (r);
if (!p)
error (EXIT_FAILURE, 0, _("could not convert from UTF-8 to %s"),
stringprep_locale_charset ());
fprintf (stdout, "%s\n", p);
free (p);
}
fflush (stdout);
}
while (!feof (stdin) && !ferror (stdin) && (args_info.inputs_num == 0 ||
cmdn < args_info.inputs_num));
free (line);
return EXIT_SUCCESS;
}
Commit Message:
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: cf2_hintmap_build( CF2_HintMap hintmap,
CF2_ArrStack hStemHintArray,
CF2_ArrStack vStemHintArray,
CF2_HintMask hintMask,
CF2_Fixed hintOrigin,
FT_Bool initialMap )
{
FT_Byte* maskPtr;
CF2_Font font = hintmap->font;
CF2_HintMaskRec tempHintMask;
size_t bitCount, i;
FT_Byte maskByte;
/* check whether initial map is constructed */
if ( !initialMap && !cf2_hintmap_isValid( hintmap->initialHintMap ) )
{
/* make recursive call with initialHintMap and temporary mask; */
/* temporary mask will get all bits set, below */
cf2_hintmask_init( &tempHintMask, hintMask->error );
cf2_hintmap_build( hintmap->initialHintMap,
hStemHintArray,
vStemHintArray,
&tempHintMask,
hintOrigin,
TRUE );
}
if ( !cf2_hintmask_isValid( hintMask ) )
{
/* without a hint mask, assume all hints are active */
cf2_hintmask_setAll( hintMask,
cf2_arrstack_size( hStemHintArray ) +
cf2_arrstack_size( vStemHintArray ) );
if ( !cf2_hintmask_isValid( hintMask ) )
return; /* too many stem hints */
}
/* begin by clearing the map */
hintmap->count = 0;
hintmap->lastIndex = 0;
/* make a copy of the hint mask so we can modify it */
tempHintMask = *hintMask;
maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
/* use the hStem hints only, which are first in the mask */
/* TODO: compare this to cffhintmaskGetBitCount */
bitCount = cf2_arrstack_size( hStemHintArray );
/* synthetic embox hints get highest priority */
if ( font->blues.doEmBoxHints )
{
cf2_hint_initZero( &dummy ); /* invalid hint map element */
/* ghost bottom */
cf2_hintmap_insertHint( hintmap,
&font->blues.emBoxBottomEdge,
&dummy );
/* ghost top */
cf2_hintmap_insertHint( hintmap,
&dummy,
&font->blues.emBoxTopEdge );
}
/* insert hints captured by a blue zone or already locked (higher */
/* priority) */
for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
{
if ( maskByte & *maskPtr )
{
/* expand StemHint into two `CF2_Hint' elements */
CF2_HintRec bottomHintEdge, topHintEdge;
cf2_hint_init( &bottomHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
TRUE /* bottom */ );
cf2_hint_init( &topHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
FALSE /* top */ );
if ( cf2_hint_isLocked( &bottomHintEdge ) ||
cf2_hint_isLocked( &topHintEdge ) ||
cf2_blues_capture( &font->blues,
&bottomHintEdge,
&topHintEdge ) )
{
/* insert captured hint into map */
cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
*maskPtr &= ~maskByte; /* turn off the bit for this hint */
}
}
if ( ( i & 7 ) == 7 )
{
/* move to next mask byte */
maskPtr++;
maskByte = 0x80;
}
else
maskByte >>= 1;
}
/* initial hint map includes only captured hints plus maybe one at 0 */
/*
* TODO: There is a problem here because we are trying to build a
* single hint map containing all captured hints. It is
* possible for there to be conflicts between captured hints,
* either because of darkening or because the hints are in
* separate hint zones (we are ignoring hint zones for the
* initial map). An example of the latter is MinionPro-Regular
* v2.030 glyph 883 (Greek Capital Alpha with Psili) at 15ppem.
* A stem hint for the psili conflicts with the top edge hint
* for the base character. The stem hint gets priority because
* of its sort order. In glyph 884 (Greek Capital Alpha with
* Psili and Oxia), the top of the base character gets a stem
* hint, and the psili does not. This creates different initial
* maps for the two glyphs resulting in different renderings of
* the base character. Will probably defer this either as not
* worth the cost or as a font bug. I don't think there is any
* good reason for an accent to be captured by an alignment
* zone. -darnold 2/12/10
*/
if ( initialMap )
{
/* Apply a heuristic that inserts a point for (0,0), unless it's */
/* already covered by a mapping. This locks the baseline for glyphs */
/* that have no baseline hints. */
if ( hintmap->count == 0 ||
hintmap->edge[0].csCoord > 0 ||
hintmap->edge[hintmap->count - 1].csCoord < 0 )
{
/* all edges are above 0 or all edges are below 0; */
/* construct a locked edge hint at 0 */
CF2_HintRec edge, invalid;
cf2_hint_initZero( &edge );
edge.flags = CF2_GhostBottom |
CF2_Locked |
CF2_Synthetic;
edge.scale = hintmap->scale;
cf2_hint_initZero( &invalid );
cf2_hintmap_insertHint( hintmap, &edge, &invalid );
}
}
else
{
/* insert remaining hints */
maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
{
if ( maskByte & *maskPtr )
{
CF2_HintRec bottomHintEdge, topHintEdge;
cf2_hint_init( &bottomHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
TRUE /* bottom */ );
cf2_hint_init( &topHintEdge,
hStemHintArray,
i,
font,
hintOrigin,
hintmap->scale,
FALSE /* top */ );
cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
}
if ( ( i & 7 ) == 7 )
{
/* move to next mask byte */
maskPtr++;
maskByte = 0x80;
}
else
maskByte >>= 1;
}
}
/*
* Note: The following line is a convenient place to break when
* debugging hinting. Examine `hintmap->edge' for the list of
* enabled hints, then step over the call to see the effect of
* adjustment. We stop here first on the recursive call that
* creates the initial map, and then on each counter group and
* hint zone.
*/
/* adjust positions of hint edges that are not locked to blue zones */
cf2_hintmap_adjustHints( hintmap );
/* save the position of all hints that were used in this hint map; */
/* if we use them again, we'll locate them in the same position */
if ( !initialMap )
{
for ( i = 0; i < hintmap->count; i++ )
{
if ( !cf2_hint_isSynthetic( &hintmap->edge[i] ) )
{
/* Note: include both valid and invalid edges */
/* Note: top and bottom edges are copied back separately */
CF2_StemHint stemhint = (CF2_StemHint)
cf2_arrstack_getPointer( hStemHintArray,
hintmap->edge[i].index );
if ( cf2_hint_isTop( &hintmap->edge[i] ) )
stemhint->maxDS = hintmap->edge[i].dsCoord;
else
stemhint->minDS = hintmap->edge[i].dsCoord;
stemhint->used = TRUE;
}
}
}
/* hint map is ready to use */
hintmap->isValid = TRUE;
/* remember this mask has been used */
cf2_hintmask_setNew( hintMask, FALSE );
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderFrameImpl::CommitSyncNavigation(
std::unique_ptr<blink::WebNavigationInfo> info) {
auto navigation_params = WebNavigationParams::CreateFromInfo(*info);
navigation_params->service_worker_network_provider =
BuildServiceWorkerNetworkProviderForNavigation(
nullptr /* request_params */,
nullptr /* controller_service_worker_info */);
frame_->CommitNavigation(std::move(navigation_params), BuildDocumentState());
}
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: bool ChromotingInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
CHECK(!initialized_);
initialized_ = true;
VLOG(1) << "Started ChromotingInstance::Init";
if (!media::IsMediaLibraryInitialized()) {
LOG(ERROR) << "Media library not initialized.";
return false;
}
net::EnableSSLServerSockets();
context_.Start();
scoped_refptr<FrameConsumerProxy> consumer_proxy =
new FrameConsumerProxy(plugin_task_runner_);
rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(),
context_.decode_task_runner(),
consumer_proxy);
view_.reset(new PepperView(this, &context_, rectangle_decoder_.get()));
consumer_proxy->Attach(view_->AsWeakPtr());
return true;
}
Commit Message: Restrict the Chromoting client plugin to use by extensions & apps.
BUG=160456
Review URL: https://chromiumcodereview.appspot.com/11365276
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168289 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: sd2_parse_rsrc_fork (SF_PRIVATE *psf)
{ SD2_RSRC rsrc ;
int k, marker, error = 0 ;
psf_use_rsrc (psf, SF_TRUE) ;
memset (&rsrc, 0, sizeof (rsrc)) ;
rsrc.rsrc_len = psf_get_filelen (psf) ;
psf_log_printf (psf, "Resource length : %d (0x%04X)\n", rsrc.rsrc_len, rsrc.rsrc_len) ;
if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header))
{ rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ;
rsrc.need_to_free_rsrc_data = SF_TRUE ;
}
else
{
rsrc.rsrc_data = psf->header ;
rsrc.need_to_free_rsrc_data = SF_FALSE ;
} ;
/* Read in the whole lot. */
psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ;
/* Reset the header storage because we have changed to the rsrcdes. */
psf->headindex = psf->headend = rsrc.rsrc_len ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0) ;
rsrc.map_offset = read_rsrc_int (&rsrc, 4) ;
rsrc.data_length = read_rsrc_int (&rsrc, 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 12) ;
if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000)
{ psf_log_printf (psf, "Trying offset of 0x52 bytes.\n") ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ;
rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ;
rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ;
} ;
psf_log_printf (psf, " data offset : 0x%04X\n map offset : 0x%04X\n"
" data length : 0x%04X\n map length : 0x%04X\n",
rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ;
if (rsrc.data_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_offset (%d, 0x%x) > len\n", rsrc.data_offset, rsrc.data_offset) ;
error = SFE_SD2_BAD_DATA_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_offset > len\n") ;
error = SFE_SD2_BAD_MAP_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_length > len\n") ;
error = SFE_SD2_BAD_DATA_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_length > len\n") ;
error = SFE_SD2_BAD_MAP_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : This does not look like a MacOSX resource fork.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset + 28 >= rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad map offset (%d + 28 > %d).\n", rsrc.map_offset, rsrc.rsrc_len) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ;
if (rsrc.string_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad string offset (%d).\n", rsrc.string_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.type_offset = rsrc.map_offset + 30 ;
rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ;
if (rsrc.type_count < 1)
{ psf_log_printf (psf, "Bad type count.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ;
if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad item offset (%d).\n", rsrc.item_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.str_index = -1 ;
for (k = 0 ; k < rsrc.type_count ; k ++)
{ marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ;
if (marker == STR_MARKER)
{ rsrc.str_index = k ;
rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ;
error = parse_str_rsrc (psf, &rsrc) ;
goto parse_rsrc_fork_cleanup ;
} ;
} ;
psf_log_printf (psf, "No 'STR ' resource.\n") ;
error = SFE_SD2_BAD_RSRC ;
parse_rsrc_fork_cleanup :
psf_use_rsrc (psf, SF_FALSE) ;
if (rsrc.need_to_free_rsrc_data)
free (rsrc.rsrc_data) ;
return error ;
} /* sd2_parse_rsrc_fork */
Commit Message: src/sd2.c : Fix two potential buffer read overflows.
Closes: https://github.com/erikd/libsndfile/issues/93
CWE ID: CWE-119
Target: 1
Example 2:
Code: void InspectorNetworkAgent::DidFinishXHRInternal(ExecutionContext* context,
XMLHttpRequest* xhr,
ThreadableLoaderClient* client,
const AtomicString& method,
const String& url,
bool success) {
ClearPendingRequestData();
DelayedRemoveReplayXHR(xhr);
ThreadableLoaderClientRequestIdMap::iterator it =
known_request_id_map_.find(client);
if (it == known_request_id_map_.end())
return;
known_request_id_map_.erase(client);
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
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: pdf14_custom_put_image(gx_device * dev, gs_gstate * pgs, gx_device * target)
{
pdf14_device * pdev = (pdf14_device *)dev;
pdf14_buf *buf = pdev->ctx->stack;
gs_int_rect rect = buf->rect;
int x0 = rect.p.x, y0 = rect.p.y;
int planestride = buf->planestride;
int rowstride = buf->rowstride;
int num_comp = buf->n_chan - 1;
const byte bg = pdev->ctx->additive ? 0xff : 0;
int x1, y1, width, height;
byte *buf_ptr;
if_debug0m('v', dev->memory, "[v]pdf14_custom_put_image\n");
rect_intersect(rect, buf->dirty);
x1 = min(pdev->width, rect.q.x);
y1 = min(pdev->height, rect.q.y);
width = x1 - rect.p.x;
height = y1 - rect.p.y;
if (width <= 0 || height <= 0 || buf->data == NULL)
return 0;
buf_ptr = buf->data + rect.p.y * buf->rowstride + rect.p.x;
return gx_put_blended_image_custom(target, buf_ptr,
planestride, rowstride,
x0, y0, width, height, num_comp, bg);
}
Commit Message:
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 void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
unsigned long debugctlmsr;
/* Record the guest's net vcpu time for enforced NMI injections. */
if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
vmx->entry_time = ktime_get();
/* Don't enter VMX if guest state is invalid, let the exit handler
start emulation until we arrive back to a valid state */
if (vmx->emulation_required)
return;
if (vmx->ple_window_dirty) {
vmx->ple_window_dirty = false;
vmcs_write32(PLE_WINDOW, vmx->ple_window);
}
if (vmx->nested.sync_shadow_vmcs) {
copy_vmcs12_to_shadow(vmx);
vmx->nested.sync_shadow_vmcs = false;
}
if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
/* When single-stepping over STI and MOV SS, we must clear the
* corresponding interruptibility bits in the guest state. Otherwise
* vmentry fails as it then expects bit 14 (BS) in pending debug
* exceptions being set, but that's not correct for the guest debugging
* case. */
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
vmx_set_interrupt_shadow(vcpu, 0);
atomic_switch_perf_msrs(vmx);
debugctlmsr = get_debugctlmsr();
vmx->__launched = vmx->loaded_vmcs->launched;
asm(
/* Store host registers */
"push %%" _ASM_DX "; push %%" _ASM_BP ";"
"push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
"push %%" _ASM_CX " \n\t"
"cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
"je 1f \n\t"
"mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
__ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
"1: \n\t"
/* Reload cr2 if changed */
"mov %c[cr2](%0), %%" _ASM_AX " \n\t"
"mov %%cr2, %%" _ASM_DX " \n\t"
"cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
"je 2f \n\t"
"mov %%" _ASM_AX", %%cr2 \n\t"
"2: \n\t"
/* Check if vmlaunch of vmresume is needed */
"cmpl $0, %c[launched](%0) \n\t"
/* Load guest registers. Don't clobber flags. */
"mov %c[rax](%0), %%" _ASM_AX " \n\t"
"mov %c[rbx](%0), %%" _ASM_BX " \n\t"
"mov %c[rdx](%0), %%" _ASM_DX " \n\t"
"mov %c[rsi](%0), %%" _ASM_SI " \n\t"
"mov %c[rdi](%0), %%" _ASM_DI " \n\t"
"mov %c[rbp](%0), %%" _ASM_BP " \n\t"
#ifdef CONFIG_X86_64
"mov %c[r8](%0), %%r8 \n\t"
"mov %c[r9](%0), %%r9 \n\t"
"mov %c[r10](%0), %%r10 \n\t"
"mov %c[r11](%0), %%r11 \n\t"
"mov %c[r12](%0), %%r12 \n\t"
"mov %c[r13](%0), %%r13 \n\t"
"mov %c[r14](%0), %%r14 \n\t"
"mov %c[r15](%0), %%r15 \n\t"
#endif
"mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
/* Enter guest mode */
"jne 1f \n\t"
__ex(ASM_VMX_VMLAUNCH) "\n\t"
"jmp 2f \n\t"
"1: " __ex(ASM_VMX_VMRESUME) "\n\t"
"2: "
/* Save guest registers, load host registers, keep flags */
"mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
"pop %0 \n\t"
"mov %%" _ASM_AX ", %c[rax](%0) \n\t"
"mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
__ASM_SIZE(pop) " %c[rcx](%0) \n\t"
"mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
"mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
"mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
"mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
#ifdef CONFIG_X86_64
"mov %%r8, %c[r8](%0) \n\t"
"mov %%r9, %c[r9](%0) \n\t"
"mov %%r10, %c[r10](%0) \n\t"
"mov %%r11, %c[r11](%0) \n\t"
"mov %%r12, %c[r12](%0) \n\t"
"mov %%r13, %c[r13](%0) \n\t"
"mov %%r14, %c[r14](%0) \n\t"
"mov %%r15, %c[r15](%0) \n\t"
#endif
"mov %%cr2, %%" _ASM_AX " \n\t"
"mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
"pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
"setbe %c[fail](%0) \n\t"
".pushsection .rodata \n\t"
".global vmx_return \n\t"
"vmx_return: " _ASM_PTR " 2b \n\t"
".popsection"
: : "c"(vmx), "d"((unsigned long)HOST_RSP),
[launched]"i"(offsetof(struct vcpu_vmx, __launched)),
[fail]"i"(offsetof(struct vcpu_vmx, fail)),
[host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
[rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
[rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
[rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
[rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
[rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
[rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
[rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
#ifdef CONFIG_X86_64
[r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
[r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
[r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
[r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
[r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
[r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
[r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
[r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
#endif
[cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
[wordsize]"i"(sizeof(ulong))
: "cc", "memory"
#ifdef CONFIG_X86_64
, "rax", "rbx", "rdi", "rsi"
, "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
#else
, "eax", "ebx", "edi", "esi"
#endif
);
/* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
if (debugctlmsr)
update_debugctlmsr(debugctlmsr);
#ifndef CONFIG_X86_64
/*
* The sysexit path does not restore ds/es, so we must set them to
* a reasonable value ourselves.
*
* We can't defer this to vmx_load_host_state() since that function
* may be executed in interrupt context, which saves and restore segments
* around it, nullifying its effect.
*/
loadsegment(ds, __USER_DS);
loadsegment(es, __USER_DS);
#endif
vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
| (1 << VCPU_EXREG_RFLAGS)
| (1 << VCPU_EXREG_PDPTR)
| (1 << VCPU_EXREG_SEGMENTS)
| (1 << VCPU_EXREG_CR3));
vcpu->arch.regs_dirty = 0;
vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
vmx->loaded_vmcs->launched = 1;
vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX);
/*
* the KVM_REQ_EVENT optimization bit is only on for one entry, and if
* we did not inject a still-pending event to L1 now because of
* nested_run_pending, we need to re-enable this bit.
*/
if (vmx->nested.nested_run_pending)
kvm_make_request(KVM_REQ_EVENT, vcpu);
vmx->nested.nested_run_pending = 0;
vmx_complete_atomic_exit(vmx);
vmx_recover_nmi_blocking(vmx);
vmx_complete_interrupts(vmx);
}
Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry
CR4 isn't constant; at least the TSD and PCE bits can vary.
TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks
like it's correct.
This adds a branch and a read from cr4 to each vm entry. Because it is
extremely likely that consecutive entries into the same vcpu will have
the same host cr4 value, this fixes up the vmcs instead of restoring cr4
after the fact. A subsequent patch will add a kernel-wide cr4 shadow,
reducing the overhead in the common case to just two memory reads and a
branch.
Signed-off-by: Andy Lutomirski <[email protected]>
Acked-by: Paolo Bonzini <[email protected]>
Cc: [email protected]
Cc: Petr Matousek <[email protected]>
Cc: Gleb Natapov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: void __jbd2_journal_temp_unlink_buffer(struct journal_head *jh)
{
struct journal_head **list = NULL;
transaction_t *transaction;
struct buffer_head *bh = jh2bh(jh);
J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
transaction = jh->b_transaction;
if (transaction)
assert_spin_locked(&transaction->t_journal->j_list_lock);
J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
if (jh->b_jlist != BJ_None)
J_ASSERT_JH(jh, transaction != NULL);
switch (jh->b_jlist) {
case BJ_None:
return;
case BJ_Metadata:
transaction->t_nr_buffers--;
J_ASSERT_JH(jh, transaction->t_nr_buffers >= 0);
list = &transaction->t_buffers;
break;
case BJ_Forget:
list = &transaction->t_forget;
break;
case BJ_IO:
list = &transaction->t_iobuf_list;
break;
case BJ_Shadow:
list = &transaction->t_shadow_list;
break;
case BJ_LogCtl:
list = &transaction->t_log_list;
break;
case BJ_Reserved:
list = &transaction->t_reserved_list;
break;
}
__blist_del_buffer(list, jh);
jh->b_jlist = BJ_None;
if (test_clear_buffer_jbddirty(bh))
mark_buffer_dirty(bh); /* Expose it to the VM */
}
Commit Message: jbd2: clear BH_Delay & BH_Unwritten in journal_unmap_buffer
journal_unmap_buffer()'s zap_buffer: code clears a lot of buffer head
state ala discard_buffer(), but does not touch _Delay or _Unwritten as
discard_buffer() does.
This can be problematic in some areas of the ext4 code which assume
that if they have found a buffer marked unwritten or delay, then it's
a live one. Perhaps those spots should check whether it is mapped
as well, but if jbd2 is going to tear down a buffer, let's really
tear it down completely.
Without this I get some fsx failures on sub-page-block filesystems
up until v3.2, at which point 4e96b2dbbf1d7e81f22047a50f862555a6cb87cb
and 189e868fa8fdca702eb9db9d8afc46b5cb9144c9 make the failures go
away, because buried within that large change is some more flag
clearing. I still think it's worth doing in jbd2, since
->invalidatepage leads here directly, and it's the right place
to clear away these flags.
Signed-off-by: Eric Sandeen <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [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 __touch_watchdog(void)
{
int this_cpu = smp_processor_id();
__this_cpu_write(watchdog_touch_ts, get_timestamp(this_cpu));
}
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
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: parse_group_prop_ntr_selection_method(struct ofpbuf *payload,
enum ofp11_group_type group_type,
enum ofp15_group_mod_command group_cmd,
struct ofputil_group_props *gp)
{
struct ntr_group_prop_selection_method *prop = payload->data;
size_t fields_len, method_len;
enum ofperr error;
switch (group_type) {
case OFPGT11_SELECT:
break;
case OFPGT11_ALL:
case OFPGT11_INDIRECT:
case OFPGT11_FF:
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property is "
"only allowed for select groups");
return OFPERR_OFPBPC_BAD_VALUE;
default:
OVS_NOT_REACHED();
}
switch (group_cmd) {
case OFPGC15_ADD:
case OFPGC15_MODIFY:
case OFPGC15_ADD_OR_MOD:
break;
case OFPGC15_DELETE:
case OFPGC15_INSERT_BUCKET:
case OFPGC15_REMOVE_BUCKET:
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property is "
"only allowed for add and delete group modifications");
return OFPERR_OFPBPC_BAD_VALUE;
default:
OVS_NOT_REACHED();
}
if (payload->size < sizeof *prop) {
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property "
"length %u is not valid", payload->size);
return OFPERR_OFPBPC_BAD_LEN;
}
method_len = strnlen(prop->selection_method, NTR_MAX_SELECTION_METHOD_LEN);
if (method_len == NTR_MAX_SELECTION_METHOD_LEN) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method is not null terminated");
return OFPERR_OFPBPC_BAD_VALUE;
}
if (strcmp("hash", prop->selection_method)
&& strcmp("dp_hash", prop->selection_method)) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method '%s' is not supported",
prop->selection_method);
return OFPERR_OFPBPC_BAD_VALUE;
}
/* 'method_len' is now non-zero. */
strcpy(gp->selection_method, prop->selection_method);
gp->selection_method_param = ntohll(prop->selection_method_param);
ofpbuf_pull(payload, sizeof *prop);
fields_len = ntohs(prop->length) - sizeof *prop;
if (fields_len && strcmp("hash", gp->selection_method)) {
OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method %s "
"does not support fields", gp->selection_method);
return OFPERR_OFPBPC_BAD_VALUE;
}
error = oxm_pull_field_array(payload->data, fields_len,
&gp->fields);
if (error) {
OFPPROP_LOG(&bad_ofmsg_rl, false,
"ntr selection method fields are invalid");
return error;
}
return 0;
}
Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command.
When decoding a group mod, the current code validates the group type and
command after the whole group mod has been decoded. The OF1.5 decoder,
however, tries to use the type and command earlier, when it might still be
invalid. This caused an assertion failure (via OVS_NOT_REACHED). This
commit fixes the problem.
ovs-vswitchd does not enable support for OpenFlow 1.5 by default.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249
Signed-off-by: Ben Pfaff <[email protected]>
Reviewed-by: Yifeng Sun <[email protected]>
CWE ID: CWE-617
Target: 1
Example 2:
Code: default_inq_cb (engine_uiserver_t uiserver, const char *line)
{
if (!strncmp (line, "PINENTRY_LAUNCHED", 17) && (line[17]==' '||!line[17]))
{
_gpgme_allow_set_foreground_window ((pid_t)strtoul (line+17, NULL, 10));
}
return 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: void RenderMessageFilter::OnGetCookies(const GURL& url,
const GURL& first_party_for_cookies,
IPC::Message* reply_msg) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
if (!policy->CanAccessCookiesForOrigin(render_process_id_, url)) {
SendGetCookiesResponse(reply_msg, std::string());
return;
}
char url_buf[128];
base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
base::debug::Alias(url_buf);
net::URLRequestContext* context = GetRequestContextForURL(url);
net::CookieMonster* cookie_monster =
context->cookie_store()->GetCookieMonster();
cookie_monster->GetAllCookiesForURLAsync(
url, base::Bind(&RenderMessageFilter::CheckPolicyForCookies, this, url,
first_party_for_cookies, reply_msg));
}
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
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 const unsigned char *ReadResourceShort(const unsigned char *p,
unsigned short *quantum)
{
*quantum=(unsigned short) (*p++ << 8);
*quantum|=(unsigned short) (*p++ << 0);
return(p);
}static inline void WriteResourceLong(unsigned char *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: FrameNavigationDisabler::~FrameNavigationDisabler() {
frame_->EnableNavigation();
}
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567663}
CWE ID: CWE-285
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: AccessibilityExpanded AXNodeObject::isExpanded() const {
if (getNode() && isHTMLSummaryElement(*getNode())) {
if (getNode()->parentNode() &&
isHTMLDetailsElement(getNode()->parentNode()))
return toElement(getNode()->parentNode())->hasAttribute(openAttr)
? ExpandedExpanded
: ExpandedCollapsed;
}
const AtomicString& expanded = getAttribute(aria_expandedAttr);
if (equalIgnoringCase(expanded, "true"))
return ExpandedExpanded;
if (equalIgnoringCase(expanded, "false"))
return ExpandedCollapsed;
return ExpandedUndefined;
}
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
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 hashtable_init(hashtable_t *hashtable)
{
size_t i;
hashtable->size = 0;
hashtable->num_buckets = 0; /* index to primes[] */
hashtable->buckets = jsonp_malloc(num_buckets(hashtable) * sizeof(bucket_t));
if(!hashtable->buckets)
return -1;
list_init(&hashtable->list);
for(i = 0; i < num_buckets(hashtable); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
}
return 0;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310
Target: 1
Example 2:
Code: static void CALLBACK FormatPromptHook(HWINEVENTHOOK hWinEventHook, DWORD Event, HWND hWnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
char str[128];
BOOL found;
if (Event == EVENT_SYSTEM_FOREGROUND) {
if (GetWindowLong(hWnd, GWL_STYLE) & WS_POPUPWINDOW) {
str[0] = 0;
GetWindowTextU(hWnd, str, sizeof(str));
if (safe_strcmp(str, fp_title_str) == 0) {
found = FALSE;
EnumChildWindows(hWnd, FormatPromptCallback, (LPARAM)&found);
if (found) {
SendMessage(hWnd, WM_COMMAND, (WPARAM)IDCANCEL, (LPARAM)0);
uprintf("Closed Windows format prompt");
}
}
}
}
}
Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768
* This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as
it is described per its revision 11, which is the latest revision at the time of this commit,
by disabling Windows prompts, enacted during signature validation, that allow the user to
bypass the intended signature verification checks.
* It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed
certificate"), which relies on the end-user actively ignoring a Windows prompt that tells
them that the update failed the signature validation whilst also advising against running it,
is being fully addressed, even as the update protocol remains HTTP.
* It also need to be pointed out that the extended delay (48 hours) between the time the
vulnerability was reported and the moment it is fixed in our codebase has to do with
the fact that the reporter chose to deviate from standard security practices by not
disclosing the details of the vulnerability with us, be it publicly or privately,
before creating the cert.org report. The only advance notification we received was a
generic note about the use of HTTP vs HTTPS, which, as have established, is not
immediately relevant to addressing the reported vulnerability.
* Closes #1009
* Note: The other vulnerability scenario described towards the end of #1009, which
doesn't have to do with the "lack of CA checking", will be addressed separately.
CWE ID: CWE-494
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: PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval **rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && cursor[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 495 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 860 "ext/standard/var_unserializer.re"
{ return 0; }
#line 557 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
goto yy3;
yy5:
yych = *++YYCURSOR;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
#line 854 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 606 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
yy17:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych == '+') goto yy19;
yy18:
YYCURSOR = YYMARKER;
goto yy3;
yy19:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
goto yy18;
yy20:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych <= '/') goto yy18;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 707 "ext/standard/var_unserializer.re"
{
size_t len, len2, len3, maxlen;
long elements;
char *class_name;
zend_class_entry *ce;
zend_class_entry **pce;
int incomplete_class = 0;
int custom_object = 0;
zval *user_func;
zval *retval_ptr;
zval **args[1];
zval *arg_func_name;
if (!var_hash) return 0;
if (*start == 'C') {
custom_object = 1;
}
INIT_PZVAL(*rval);
len2 = len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len || len == 0) {
*p = start + 2;
return 0;
}
class_name = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR+1) != ':') {
*p = YYCURSOR+1;
return 0;
}
len3 = strspn(class_name, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\");
if (len3 != len)
{
*p = YYCURSOR + len3 - len;
return 0;
}
class_name = estrndup(class_name, len);
do {
/* Try to find class directly */
BG(serialize_lock)++;
if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
return 0;
}
ce = *pce;
break;
}
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
return 0;
}
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Call unserialize callback */
MAKE_STD_ZVAL(user_func);
ZVAL_STRING(user_func, PG(unserialize_callback_func), 1);
args[0] = &arg_func_name;
MAKE_STD_ZVAL(arg_func_name);
ZVAL_STRING(arg_func_name, class_name, 1);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), NULL, user_func, &retval_ptr, 1, args, 0, NULL TSRMLS_CC) != SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
efree(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
return 0;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "defined (%s) but not found", user_func->value.str.val);
incomplete_class = 1;
ce = PHP_IC_ENTRY;
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
break;
}
BG(serialize_lock)--;
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
efree(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
return 0;
}
/* The callback function may have defined the class */
if (zend_lookup_class(class_name, len2, &pce TSRMLS_CC) == SUCCESS) {
ce = *pce;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Function %s() hasn't defined the class it was called for", user_func->value.str.val);
incomplete_class = 1;
ce = PHP_IC_ENTRY;
}
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&arg_func_name);
break;
} while (1);
*p = YYCURSOR;
if (custom_object) {
int ret;
ret = object_custom(UNSERIALIZE_PASSTHRU, ce);
if (ret && incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return ret;
}
elements = object_common1(UNSERIALIZE_PASSTHRU, ce);
if (incomplete_class) {
php_store_class_name(*rval, class_name, len2);
}
efree(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 784 "ext/standard/var_unserializer.c"
yy25:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy26;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
goto yy18;
}
yy26:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy27:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 698 "ext/standard/var_unserializer.re"
{
if (!var_hash) return 0;
INIT_PZVAL(*rval);
return object_common2(UNSERIALIZE_PASSTHRU,
object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));
}
#line 818 "ext/standard/var_unserializer.c"
yy32:
yych = *++YYCURSOR;
if (yych == '+') goto yy33;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
goto yy18;
yy33:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy34:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '{') goto yy18;
++YYCURSOR;
#line 677 "ext/standard/var_unserializer.re"
{
long elements = parse_iv(start + 2);
/* use iv() not uiv() in order to check data range */
*p = YYCURSOR;
if (!var_hash) return 0;
if (elements < 0) {
return 0;
}
INIT_PZVAL(*rval);
array_init_size(*rval, elements);
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_PP(rval), elements, 0)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#line 860 "ext/standard/var_unserializer.c"
yy39:
yych = *++YYCURSOR;
if (yych == '+') goto yy40;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
goto yy18;
yy40:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy41:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 642 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
if ((str = unserialize_str(&YYCURSOR, &len, maxlen)) == NULL) {
return 0;
}
if (*(YYCURSOR) != '"') {
efree(str);
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
efree(str);
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_STRINGL(*rval, str, len, 0);
return 1;
}
#line 916 "ext/standard/var_unserializer.c"
yy46:
yych = *++YYCURSOR;
if (yych == '+') goto yy47;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
goto yy18;
yy47:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy48:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 609 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_STRINGL(*rval, str, len, 1);
return 1;
}
#line 970 "ext/standard/var_unserializer.c"
yy53:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych <= ',') {
if (yych == '+') goto yy57;
goto yy18;
} else {
if (yych <= '-') goto yy55;
if (yych <= '.') goto yy60;
goto yy18;
}
} else {
if (yych <= 'I') {
if (yych <= '9') goto yy58;
if (yych <= 'H') goto yy18;
goto yy56;
} else {
if (yych != 'N') goto yy18;
}
}
yych = *++YYCURSOR;
if (yych == 'A') goto yy76;
goto yy18;
yy55:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '.') goto yy60;
goto yy18;
} else {
if (yych <= '9') goto yy58;
if (yych != 'I') goto yy18;
}
yy56:
yych = *++YYCURSOR;
if (yych == 'N') goto yy72;
goto yy18;
yy57:
yych = *++YYCURSOR;
if (yych == '.') goto yy60;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy58:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ':') {
if (yych <= '.') {
if (yych <= '-') goto yy18;
goto yy70;
} else {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy58;
goto yy18;
}
} else {
if (yych <= 'E') {
if (yych <= ';') goto yy63;
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy60:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy61:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy61;
if (yych <= ':') goto yy18;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy63:
++YYCURSOR;
#line 599 "ext/standard/var_unserializer.re"
{
#if SIZEOF_LONG == 4
use_double:
#endif
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_DOUBLE(*rval, zend_strtod((const char *)start + 2, NULL));
return 1;
}
#line 1068 "ext/standard/var_unserializer.c"
yy65:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy66;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
}
yy66:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy69;
goto yy18;
} else {
if (yych <= '-') goto yy69;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
}
yy67:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
if (yych == ';') goto yy63;
goto yy18;
yy69:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
yy70:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy70;
if (yych <= ':') goto yy18;
goto yy63;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy72:
yych = *++YYCURSOR;
if (yych != 'F') goto yy18;
yy73:
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 584 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
if (!strncmp(start + 2, "NAN", 3)) {
ZVAL_DOUBLE(*rval, php_get_nan());
} else if (!strncmp(start + 2, "INF", 3)) {
ZVAL_DOUBLE(*rval, php_get_inf());
} else if (!strncmp(start + 2, "-INF", 4)) {
ZVAL_DOUBLE(*rval, -php_get_inf());
}
return 1;
}
#line 1142 "ext/standard/var_unserializer.c"
yy76:
yych = *++YYCURSOR;
if (yych == 'N') goto yy73;
goto yy18;
yy77:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy78;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
goto yy18;
}
yy78:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy79:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 557 "ext/standard/var_unserializer.re"
{
#if SIZEOF_LONG == 4
int digits = YYCURSOR - start - 3;
if (start[2] == '-' || start[2] == '+') {
digits--;
}
/* Use double for large long values that were serialized on a 64-bit system */
if (digits >= MAX_LENGTH_OF_LONG - 1) {
if (digits == MAX_LENGTH_OF_LONG - 1) {
int cmp = strncmp(YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);
if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {
goto use_double;
}
} else {
goto use_double;
}
}
#endif
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_LONG(*rval, parse_iv(start + 2));
return 1;
}
#line 1196 "ext/standard/var_unserializer.c"
yy83:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= '2') goto yy18;
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 550 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_BOOL(*rval, parse_iv(start + 2));
return 1;
}
#line 1211 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 543 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
INIT_PZVAL(*rval);
ZVAL_NULL(*rval);
return 1;
}
#line 1221 "ext/standard/var_unserializer.c"
yy89:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy90;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
goto yy18;
}
yy90:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy91:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 520 "ext/standard/var_unserializer.re"
{
long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {
return 0;
}
if (*rval == *rval_ref) return 0;
if (*rval != NULL) {
var_push_dtor_no_addref(var_hash, rval);
}
*rval = *rval_ref;
Z_ADDREF_PP(rval);
Z_UNSET_ISREF_PP(rval);
return 1;
}
#line 1267 "ext/standard/var_unserializer.c"
yy95:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy96;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
goto yy18;
}
yy96:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy97:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 499 "ext/standard/var_unserializer.re"
{
long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || var_access(var_hash, id, &rval_ref) != SUCCESS) {
return 0;
}
if (*rval != NULL) {
var_push_dtor_no_addref(var_hash, rval);
}
*rval = *rval_ref;
Z_ADDREF_PP(rval);
Z_SET_ISREF_PP(rval);
return 1;
}
#line 1311 "ext/standard/var_unserializer.c"
}
#line 862 "ext/standard/var_unserializer.re"
return 0;
}
Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction
CWE ID: CWE-119
Output: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.