prompt
stringlengths 799
20.4k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment)
{
int i, length;
segment->nb_index_entries = avio_rb32(pb);
length = avio_rb32(pb);
if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) ||
!(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) ||
!(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) {
av_freep(&segment->temporal_offset_entries);
av_freep(&segment->flag_entries);
return AVERROR(ENOMEM);
}
for (i = 0; i < segment->nb_index_entries; i++) {
segment->temporal_offset_entries[i] = avio_r8(pb);
avio_r8(pb); /* KeyFrameOffset */
segment->flag_entries[i] = avio_r8(pb);
segment->stream_offset_entries[i] = avio_rb64(pb);
avio_skip(pb, length - 11);
}
return 0;
}
CWE ID: CWE-834
Target: 1
Example 2:
Code: error::Error GLES2DecoderImpl::HandleTexImage2D(
uint32 immediate_data_size, const gles2::TexImage2D& c) {
TRACE_EVENT0("gpu", "GLES2DecoderImpl::HandleTexImage2D");
tex_image_2d_failed_ = true;
GLenum target = static_cast<GLenum>(c.target);
GLint level = static_cast<GLint>(c.level);
GLint internal_format = static_cast<GLint>(c.internalformat);
GLsizei width = static_cast<GLsizei>(c.width);
GLsizei height = static_cast<GLsizei>(c.height);
GLint border = static_cast<GLint>(c.border);
GLenum format = static_cast<GLenum>(c.format);
GLenum type = static_cast<GLenum>(c.type);
uint32 pixels_shm_id = static_cast<uint32>(c.pixels_shm_id);
uint32 pixels_shm_offset = static_cast<uint32>(c.pixels_shm_offset);
uint32 pixels_size;
if (!GLES2Util::ComputeImageDataSizes(
width, height, format, type, unpack_alignment_, &pixels_size, NULL,
NULL)) {
return error::kOutOfBounds;
}
const void* pixels = NULL;
if (pixels_shm_id != 0 || pixels_shm_offset != 0) {
pixels = GetSharedMemoryAs<const void*>(
pixels_shm_id, pixels_shm_offset, pixels_size);
if (!pixels) {
return error::kOutOfBounds;
}
}
return DoTexImage2D(
target, level, internal_format, width, height, border, format, type,
pixels, pixels_size);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code 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: SPL_METHOD(DirectoryIterator, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_STRING(intern->u.dir.entry.d_name, 1);
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: read_png(struct control *control)
/* Read a PNG, return 0 on success else an error (status) code; a bit mask as
* defined for file::status_code as above.
*/
{
png_structp png_ptr;
png_infop info_ptr = NULL;
volatile png_bytep row = NULL, display = NULL;
volatile int rc;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control,
error_handler, warning_handler);
if (png_ptr == NULL)
{
/* This is not really expected. */
log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct");
control->file.status_code |= INTERNAL_ERROR;
return LIBPNG_ERROR_CODE;
}
rc = setjmp(control->file.jmpbuf);
if (rc == 0)
{
png_set_read_fn(png_ptr, control, read_callback);
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
png_error(png_ptr, "OOM allocating info structure");
if (control->file.global->verbose)
fprintf(stderr, " INFO\n");
png_read_info(png_ptr, info_ptr);
{
png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
row = png_voidcast(png_byte*, malloc(rowbytes));
display = png_voidcast(png_byte*, malloc(rowbytes));
if (row == NULL || display == NULL)
png_error(png_ptr, "OOM allocating row buffers");
{
png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
int passes = png_set_interlace_handling(png_ptr);
int pass;
png_start_read_image(png_ptr);
for (pass = 0; pass < passes; ++pass)
{
png_uint_32 y = height;
/* NOTE: this trashes the row each time; interlace handling won't
* work, but this avoids memory thrashing for speed testing.
*/
while (y-- > 0)
png_read_row(png_ptr, row, display);
}
}
}
if (control->file.global->verbose)
fprintf(stderr, " END\n");
/* Make sure to read to the end of the file: */
png_read_end(png_ptr, info_ptr);
}
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
if (row != NULL) free(row);
if (display != NULL) free(display);
return rc;
}
CWE ID:
Target: 1
Example 2:
Code: void OmniboxViewWin::OnTemporaryTextMaybeChanged(const string16& display_text,
bool save_original_selection) {
if (save_original_selection)
GetSelection(original_selection_);
ScopedFreeze freeze(this, GetTextObjectModel());
SetWindowTextAndCaretPos(display_text, display_text.length());
TextChanged();
}
CWE ID:
Target: 0
Now analyze the following code 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 ContentEncoding::ParseContentEncodingEntry(long long start,
long long size,
IMkvReader* pReader) {
assert(pReader);
long long pos = start;
const long long stop = start + size;
int compression_count = 0;
int encryption_count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x1034) // ContentCompression ID
++compression_count;
if (id == 0x1035) // ContentEncryption ID
++encryption_count;
pos += size; //consume payload
assert(pos <= stop);
}
if (compression_count <= 0 && encryption_count <= 0)
return -1;
if (compression_count > 0) {
compression_entries_ =
new (std::nothrow) ContentCompression*[compression_count];
if (!compression_entries_)
return -1;
compression_entries_end_ = compression_entries_;
}
if (encryption_count > 0) {
encryption_entries_ =
new (std::nothrow) ContentEncryption*[encryption_count];
if (!encryption_entries_) {
delete [] compression_entries_;
return -1;
}
encryption_entries_end_ = encryption_entries_;
}
pos = start;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x1031) {
encoding_order_ = UnserializeUInt(pReader, pos, size);
} else if (id == 0x1032) {
encoding_scope_ = UnserializeUInt(pReader, pos, size);
if (encoding_scope_ < 1)
return -1;
} else if (id == 0x1033) {
encoding_type_ = UnserializeUInt(pReader, pos, size);
} else if (id == 0x1034) {
ContentCompression* const compression =
new (std::nothrow) ContentCompression();
if (!compression)
return -1;
status = ParseCompressionEntry(pos, size, pReader, compression);
if (status) {
delete compression;
return status;
}
*compression_entries_end_++ = compression;
} else if (id == 0x1035) {
ContentEncryption* const encryption =
new (std::nothrow) ContentEncryption();
if (!encryption)
return -1;
status = ParseEncryptionEntry(pos, size, pReader, encryption);
if (status) {
delete encryption;
return status;
}
*encryption_entries_end_++ = encryption;
}
pos += size; //consume payload
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Horizontal_Sweep_Drop( RAS_ARGS Short y,
FT_F26Dot6 x1,
FT_F26Dot6 x2,
PProfile left,
PProfile right )
{
Long e1, e2, pxl;
PByte bits;
Byte f1;
/* During the horizontal sweep, we only take care of drop-outs */
/* e1 + <-- pixel center */
/* | */
/* x1 ---+--> <-- contour */
/* | */
/* | */
/* x2 <--+--- <-- contour */
/* | */
/* | */
/* e2 + <-- pixel center */
e1 = CEILING( x1 );
e2 = FLOOR ( x2 );
pxl = e1;
if ( e1 > e2 )
{
Int dropOutControl = left->flags & 7;
if ( e1 == e2 + ras.precision )
{
switch ( dropOutControl )
{
case 0: /* simple drop-outs including stubs */
pxl = e2;
break;
case 4: /* smart drop-outs including stubs */
pxl = FLOOR( ( x1 + x2 - 1 ) / 2 + ras.precision_half );
break;
case 1: /* simple drop-outs excluding stubs */
case 5: /* smart drop-outs excluding stubs */
/* see Vertical_Sweep_Drop for details */
/* rightmost stub test */
if ( left->next == right &&
left->height <= 0 &&
!( left->flags & Overshoot_Top &&
x2 - x1 >= ras.precision_half ) )
return;
/* leftmost stub test */
if ( right->next == left &&
left->start == y &&
!( left->flags & Overshoot_Bottom &&
x2 - x1 >= ras.precision_half ) )
return;
if ( dropOutControl == 1 )
pxl = e2;
else
pxl = FLOOR( ( x1 + x2 - 1 ) / 2 + ras.precision_half );
break;
default: /* modes 2, 3, 6, 7 */
return; /* no drop-out control */
}
/* undocumented but confirmed: If the drop-out would result in a */
/* pixel outside of the bounding box, use the pixel inside of the */
/* bounding box instead */
if ( pxl < 0 )
pxl = e1;
else if ( TRUNC( pxl ) >= ras.target.rows )
pxl = e2;
/* check that the other pixel isn't set */
e1 = pxl == e1 ? e2 : e1;
e1 = TRUNC( e1 );
bits = ras.bTarget + ( y >> 3 );
f1 = (Byte)( 0x80 >> ( y & 7 ) );
bits -= e1 * ras.target.pitch;
if ( ras.target.pitch > 0 )
bits += ( ras.target.rows - 1 ) * ras.target.pitch;
if ( e1 >= 0 &&
e1 < ras.target.rows &&
*bits & f1 )
return;
}
else
return;
}
bits = ras.bTarget + ( y >> 3 );
f1 = (Byte)( 0x80 >> ( y & 7 ) );
e1 = TRUNC( pxl );
if ( e1 >= 0 && e1 < ras.target.rows )
{
bits -= e1 * ras.target.pitch;
if ( ras.target.pitch > 0 )
bits += ( ras.target.rows - 1 ) * ras.target.pitch;
bits[0] |= f1;
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void BrowserGpuChannelHostFactory::CommandBufferCreatedOnIO(
CreateRequest* request, int32 route_id) {
request->route_id = route_id;
request->event.Signal();
}
CWE ID:
Target: 0
Now analyze the following code 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 nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
{
return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int touch(const char *path) {
return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void GLES2DecoderImpl::DoWillUseTexImageIfNeeded(
Texture* texture, GLenum textarget) {
if (texture && !texture->IsAttachedToFramebuffer()) {
gfx::GLImage* image = texture->GetLevelImage(textarget, 0);
if (image) {
ScopedGLErrorSuppressor suppressor(
"GLES2DecoderImpl::DoWillUseTexImageIfNeeded",
GetErrorState());
glBindTexture(textarget, texture->service_id());
image->WillUseTexImage();
RestoreCurrentTextureBindings(&state_, textarget);
}
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 struct svc_serv *nfs_callback_create_svc(int minorversion)
{
struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion];
struct svc_serv *serv;
struct svc_serv_ops *sv_ops;
/*
* Check whether we're already up and running.
*/
if (cb_info->serv) {
/*
* Note: increase service usage, because later in case of error
* svc_destroy() will be called.
*/
svc_get(cb_info->serv);
return cb_info->serv;
}
switch (minorversion) {
case 0:
sv_ops = nfs4_cb_sv_ops[0];
break;
default:
sv_ops = nfs4_cb_sv_ops[1];
}
if (sv_ops == NULL)
return ERR_PTR(-ENOTSUPP);
/*
* Sanity check: if there's no task,
* we should be the first user ...
*/
if (cb_info->users)
printk(KERN_WARNING "nfs_callback_create_svc: no kthread, %d users??\n",
cb_info->users);
serv = svc_create(&nfs4_callback_program, NFS4_CALLBACK_BUFSIZE, sv_ops);
if (!serv) {
printk(KERN_ERR "nfs_callback_create_svc: create service failed\n");
return ERR_PTR(-ENOMEM);
}
cb_info->serv = serv;
/* As there is only one thread we need to over-ride the
* default maximum of 80 connections
*/
serv->sv_maxconn = 1024;
dprintk("nfs_callback_create_svc: service created\n");
return serv;
}
CWE ID: CWE-404
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int snd_hrtimer_stop(struct snd_timer *t)
{
struct snd_hrtimer *stime = t->private_data;
atomic_set(&stime->running, 0);
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool ImeObserver::HasListener(const std::string& event_name) const {
return extensions::EventRouter::Get(profile_)->HasEventListener(event_name);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code 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: v8::Handle<v8::Value> V8SVGLength::convertToSpecifiedUnitsCallback(const v8::Arguments& args)
{
INC_STATS("DOM.SVGLength.convertToSpecifiedUnits");
SVGPropertyTearOff<SVGLength>* wrapper = V8SVGLength::toNative(args.Holder());
if (wrapper->role() == AnimValRole) {
V8Proxy::setDOMException(NO_MODIFICATION_ALLOWED_ERR, args.GetIsolate());
return v8::Handle<v8::Value>();
}
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
SVGLength& imp = wrapper->propertyReference();
ExceptionCode ec = 0;
EXCEPTION_BLOCK(int, unitType, toUInt32(args[0]));
SVGLengthContext lengthContext(wrapper->contextElement());
imp.convertToSpecifiedUnits(unitType, lengthContext, ec);
if (UNLIKELY(ec))
V8Proxy::setDOMException(ec, args.GetIsolate());
else
wrapper->commitChange();
return v8::Handle<v8::Value>();
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and 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 generic_perform_write(struct file *file,
struct iov_iter *i, loff_t pos)
{
struct address_space *mapping = file->f_mapping;
const struct address_space_operations *a_ops = mapping->a_ops;
long status = 0;
ssize_t written = 0;
unsigned int flags = 0;
/*
* Copies from kernel address space cannot fail (NFSD is a big user).
*/
if (segment_eq(get_fs(), KERNEL_DS))
flags |= AOP_FLAG_UNINTERRUPTIBLE;
do {
struct page *page;
pgoff_t index; /* Pagecache index for current page */
unsigned long offset; /* Offset into pagecache page */
unsigned long bytes; /* Bytes to write to page */
size_t copied; /* Bytes copied from user */
void *fsdata;
offset = (pos & (PAGE_CACHE_SIZE - 1));
index = pos >> PAGE_CACHE_SHIFT;
bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
iov_iter_count(i));
again:
/*
* Bring in the user page that we will copy from _first_.
* Otherwise there's a nasty deadlock on copying from the
* same page as we're writing to, without it being marked
* up-to-date.
*
* Not only is this an optimisation, but it is also required
* to check that the address is actually valid, when atomic
* usercopies are used, below.
*/
if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
status = -EFAULT;
break;
}
status = a_ops->write_begin(file, mapping, pos, bytes, flags,
&page, &fsdata);
if (unlikely(status))
break;
pagefault_disable();
copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
pagefault_enable();
flush_dcache_page(page);
status = a_ops->write_end(file, mapping, pos, bytes, copied,
page, fsdata);
if (unlikely(status < 0))
break;
copied = status;
cond_resched();
if (unlikely(copied == 0)) {
/*
* If we were unable to copy any data at all, we must
* fall back to a single segment length write.
*
* If we didn't fallback here, we could livelock
* because not all segments in the iov can be copied at
* once without a pagefault.
*/
bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
iov_iter_single_seg_count(i));
goto again;
}
iov_iter_advance(i, copied);
pos += copied;
written += copied;
balance_dirty_pages_ratelimited(mapping);
} while (iov_iter_count(i));
return written ? written : status;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
{
ENTER();
if (likely(req->context)) {
struct ffs_ep *ep = _ep->driver_data;
ep->status = req->status ? req->status : req->actual;
complete(req->context);
}
}
CWE ID: CWE-416
Target: 0
Now analyze the following code 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: CanvasRenderingContext2DState& BaseRenderingContext2D::ModifiableState() {
RealizeSaves();
return *state_stack_.back();
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xmlParseInternalSubset(xmlParserCtxtPtr ctxt) {
/*
* Is there any DTD definition ?
*/
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
NEXT;
/*
* Parse the succession of Markup declarations and
* PEReferences.
* Subsequence (markupdecl | PEReference | S)*
*/
while (RAW != ']') {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
SKIP_BLANKS;
xmlParseMarkupDecl(ctxt);
xmlParsePEReference(ctxt);
/*
* Pop-up of finished entities.
*/
while ((RAW == 0) && (ctxt->inputNr > 1))
xmlPopInput(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseInternalSubset: error detected in Markup declaration\n");
break;
}
}
if (RAW == ']') {
NEXT;
SKIP_BLANKS;
}
}
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
{
struct xfrm_user_expire *ue;
struct nlmsghdr *nlh;
int err;
nlh = nlmsg_put(skb, c->portid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0);
if (nlh == NULL)
return -EMSGSIZE;
ue = nlmsg_data(nlh);
copy_to_user_state(x, &ue->state);
ue->hard = (c->data.hard != 0) ? 1 : 0;
err = xfrm_mark_put(skb, &x->mark);
if (err)
return err;
nlmsg_end(skb, nlh);
return 0;
}
CWE ID:
Target: 0
Now analyze the following code 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 bool cpuline_in_cpuset(const char *line, const char *cpuset)
{
int cpu;
if (sscanf(line, "processor : %d", &cpu) != 1)
return false;
return cpu_in_cpuset(cpu, cpuset);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintWebViewHelper::OnPrintPages() {
blink::WebLocalFrame* frame;
if (!GetPrintFrame(&frame))
return;
auto plugin = delegate_->GetPdfElement(frame);
Print(frame, plugin, false);
}
CWE ID:
Target: 1
Example 2:
Code: void Splash::vertFlipImage(SplashBitmap *img, int width, int height,
int nComps) {
Guchar *lineBuf;
Guchar *p0, *p1;
int w;
w = width * nComps;
lineBuf = (Guchar *)gmalloc(w);
for (p0 = img->data, p1 = img->data + (height - 1) * w;
p0 < p1;
p0 += w, p1 -= w) {
memcpy(lineBuf, p0, w);
memcpy(p0, p1, w);
memcpy(p1, lineBuf, w);
}
if (img->alpha) {
for (p0 = img->alpha, p1 = img->alpha + (height - 1) * width;
p0 < p1;
p0 += width, p1 -= width) {
memcpy(lineBuf, p0, width);
memcpy(p0, p1, width);
memcpy(p1, lineBuf, width);
}
}
gfree(lineBuf);
}
CWE ID:
Target: 0
Now analyze the following code 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: lldp_mgmt_addr_tlv_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
uint8_t mgmt_addr_len, intf_num_subtype, oid_len;
const u_char *tptr;
u_int tlen;
char *mgmt_addr;
tlen = len;
tptr = pptr;
if (tlen < 1) {
return 0;
}
mgmt_addr_len = *tptr++;
tlen--;
if (tlen < mgmt_addr_len) {
return 0;
}
mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len);
if (mgmt_addr == NULL) {
return 0;
}
ND_PRINT((ndo, "\n\t Management Address length %u, %s",
mgmt_addr_len, mgmt_addr));
tptr += mgmt_addr_len;
tlen -= mgmt_addr_len;
if (tlen < LLDP_INTF_NUM_LEN) {
return 0;
}
intf_num_subtype = *tptr;
ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u",
tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype),
intf_num_subtype,
EXTRACT_32BITS(tptr + 1)));
tptr += LLDP_INTF_NUM_LEN;
tlen -= LLDP_INTF_NUM_LEN;
/*
* The OID is optional.
*/
if (tlen) {
oid_len = *tptr;
if (tlen < oid_len) {
return 0;
}
if (oid_len) {
ND_PRINT((ndo, "\n\t OID length %u", oid_len));
safeputs(ndo, tptr + 1, oid_len);
}
}
return 1;
}
CWE ID: CWE-835
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GF_Err tenc_dump(GF_Box *a, FILE * trace)
{
GF_TrackEncryptionBox *ptr = (GF_TrackEncryptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "TrackEncryptionBox", trace);
fprintf(trace, "isEncrypted=\"%d\"", ptr->isProtected);
if (ptr->Per_Sample_IV_Size)
fprintf(trace, " IV_size=\"%d\" KID=\"", ptr->Per_Sample_IV_Size);
else {
fprintf(trace, " constant_IV_size=\"%d\" constant_IV=\"", ptr->constant_IV_size);
dump_data_hex(trace, (char *) ptr->constant_IV, ptr->constant_IV_size);
fprintf(trace, "\" KID=\"");
}
dump_data_hex(trace, (char *) ptr->KID, 16);
if (ptr->version)
fprintf(trace, "\" crypt_byte_block=\"%d\" skip_byte_block=\"%d", ptr->crypt_byte_block, ptr->skip_byte_block);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("TrackEncryptionBox", a, trace);
return GF_OK;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: find_hosts_entry(struct evdns_base *base, const char *hostname,
struct hosts_entry *find_after)
{
struct hosts_entry *e;
if (find_after)
e = TAILQ_NEXT(find_after, next);
else
e = TAILQ_FIRST(&base->hostsdb);
for (; e; e = TAILQ_NEXT(e, next)) {
if (!evutil_ascii_strcasecmp(e->hostname, hostname))
return e;
}
return NULL;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code 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 jas_iccpadtomult(long x, long y)
{
return ((x + y - 1) / y) * y;
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int SocketStream::DoBeforeConnect() {
next_state_ = STATE_BEFORE_CONNECT_COMPLETE;
if (!context_.get() || !context_->network_delegate()) {
return OK;
}
int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect(
this, io_callback_);
if (result != OK && result != ERR_IO_PENDING)
next_state_ = STATE_CLOSE;
return result;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void ScreenOrientationDispatcherHost::NotifyLockSuccess(int request_id) {
RenderFrameHost* render_frame_host =
GetRenderFrameHostForRequestID(request_id);
if (!render_frame_host)
return;
render_frame_host->Send(new ScreenOrientationMsg_LockSuccess(
render_frame_host->GetRoutingID(), request_id));
ResetCurrentLock();
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
int *peeked, int *off, int *err)
{
struct sk_buff *skb;
long timeo;
/*
* Caller is allowed not to check sk->sk_err before skb_recv_datagram()
*/
int error = sock_error(sk);
if (error)
goto no_packet;
timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
do {
/* Again only user level code calls this function, so nothing
* interrupt level will suddenly eat the receive_queue.
*
* Look at current nfs client by the way...
* However, this function was correct in any case. 8)
*/
unsigned long cpu_flags;
struct sk_buff_head *queue = &sk->sk_receive_queue;
spin_lock_irqsave(&queue->lock, cpu_flags);
skb_queue_walk(queue, skb) {
*peeked = skb->peeked;
if (flags & MSG_PEEK) {
if (*off >= skb->len) {
*off -= skb->len;
continue;
}
skb->peeked = 1;
atomic_inc(&skb->users);
} else
__skb_unlink(skb, queue);
spin_unlock_irqrestore(&queue->lock, cpu_flags);
return skb;
}
spin_unlock_irqrestore(&queue->lock, cpu_flags);
/* User doesn't want to wait */
error = -EAGAIN;
if (!timeo)
goto no_packet;
} while (!wait_for_packet(sk, err, &timeo));
return NULL;
no_packet:
*err = error;
return NULL;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void hostap_setup_dev(struct net_device *dev, local_info_t *local,
int type)
{
struct hostap_interface *iface;
iface = netdev_priv(dev);
ether_setup(dev);
/* kernel callbacks */
if (iface) {
/* Currently, we point to the proper spy_data only on
* the main_dev. This could be fixed. Jean II */
iface->wireless_data.spy_data = &iface->spy_data;
dev->wireless_data = &iface->wireless_data;
}
dev->wireless_handlers = &hostap_iw_handler_def;
dev->watchdog_timeo = TX_TIMEOUT;
switch(type) {
case HOSTAP_INTERFACE_AP:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_mgmt_netdev_ops;
dev->type = ARPHRD_IEEE80211;
dev->header_ops = &hostap_80211_ops;
break;
case HOSTAP_INTERFACE_MASTER:
dev->netdev_ops = &hostap_master_ops;
break;
default:
dev->tx_queue_len = 0; /* use main radio device queue */
dev->netdev_ops = &hostap_netdev_ops;
}
dev->mtu = local->mtu;
SET_ETHTOOL_OPS(dev, &prism2_ethtool_ops);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: skip_sfx(struct archive_read *a)
{
const void *h;
const char *p, *q;
size_t skip, total;
ssize_t bytes, window;
total = 0;
window = 4096;
while (total + window <= (1024 * 128)) {
h = __archive_read_ahead(a, window, &bytes);
if (h == NULL) {
/* Remaining bytes are less than window. */
window >>= 1;
if (window < 0x40)
goto fatal;
continue;
}
if (bytes < 0x40)
goto fatal;
p = h;
q = p + bytes;
/*
* Scan ahead until we find something that looks
* like the RAR header.
*/
while (p + 7 < q) {
if (memcmp(p, RAR_SIGNATURE, 7) == 0) {
skip = p - (const char *)h;
__archive_read_consume(a, skip);
return (ARCHIVE_OK);
}
p += 0x10;
}
skip = p - (const char *)h;
__archive_read_consume(a, skip);
total += skip;
}
fatal:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Couldn't find out RAR header");
return (ARCHIVE_FATAL);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 WaitForWriteCommit() {
DCHECK(run_loop_);
run_loop_->Run();
run_loop_.reset();
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BookmarksIOFunction::ShowSelectFileDialog(
ui::SelectFileDialog::Type type,
const base::FilePath& default_path) {
AddRef();
WebContents* web_contents = dispatcher()->delegate()->
GetAssociatedWebContents();
select_file_dialog_ = ui::SelectFileDialog::Create(
this, new ChromeSelectFilePolicy(web_contents));
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.resize(1);
file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html"));
if (type == ui::SelectFileDialog::SELECT_OPEN_FILE)
file_type_info.support_drive = true;
select_file_dialog_->SelectFile(type,
string16(),
default_path,
&file_type_info,
0,
FILE_PATH_LITERAL(""),
NULL,
NULL);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: ClearToEOS()
{
register int y = curr->w_y, x = curr->w_x;
if (x == 0 && y == 0)
{
ClearScreen();
RestorePosRendition();
return;
}
LClearArea(&curr->w_layer, x, y, cols - 1, rows - 1, CURR_BCE, 1);
MClearArea(curr, x, y, cols - 1, rows - 1, CURR_BCE);
RestorePosRendition();
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 PrelinOpt16free(cmsContext ContextID, void* ptr)
{
Prelin16Data* p16 = (Prelin16Data*) ptr;
_cmsFree(ContextID, p16 ->EvalCurveOut16);
_cmsFree(ContextID, p16 ->ParamsCurveOut16);
_cmsFree(ContextID, p16);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: v8::Local<v8::Value> ModuleSystem::RequireForJsInner(
v8::Local<v8::String> module_name) {
v8::EscapableHandleScope handle_scope(GetIsolate());
v8::Local<v8::Context> v8_context = context()->v8_context();
v8::Context::Scope context_scope(v8_context);
v8::Local<v8::Object> global(context()->v8_context()->Global());
v8::Local<v8::Value> modules_value;
if (!GetPrivate(global, kModulesField, &modules_value) ||
modules_value->IsUndefined()) {
Warn(GetIsolate(), "Extension view no longer exists");
return v8::Undefined(GetIsolate());
}
v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value));
v8::Local<v8::Value> exports;
if (!GetProperty(v8_context, modules, module_name, &exports) ||
!exports->IsUndefined())
return handle_scope.Escape(exports);
exports = LoadModule(*v8::String::Utf8Value(module_name));
SetProperty(v8_context, modules, module_name, exports);
return handle_scope.Escape(exports);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: TestNavigationThrottle(
NavigationHandle* handle,
NavigationThrottle::ThrottleCheckResult will_start_result,
NavigationThrottle::ThrottleCheckResult will_redirect_result,
NavigationThrottle::ThrottleCheckResult will_fail_result,
NavigationThrottle::ThrottleCheckResult will_process_result,
base::Closure did_call_will_start,
base::Closure did_call_will_redirect,
base::Closure did_call_will_fail,
base::Closure did_call_will_process)
: NavigationThrottle(handle),
will_start_result_(will_start_result),
will_redirect_result_(will_redirect_result),
will_fail_result_(will_fail_result),
will_process_result_(will_process_result),
did_call_will_start_(did_call_will_start),
did_call_will_redirect_(did_call_will_redirect),
did_call_will_fail_(did_call_will_fail),
did_call_will_process_(did_call_will_process) {}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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: SPL_METHOD(SplObjectStorage, offsetGet)
{
zval *obj;
spl_SplObjectStorageElement *element;
spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC);
char *hash;
int hash_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &obj) == FAILURE) {
return;
}
hash = spl_object_storage_get_hash(intern, getThis(), obj, &hash_len TSRMLS_CC);
if (!hash) {
return;
}
element = spl_object_storage_get(intern, hash, hash_len TSRMLS_CC);
spl_object_storage_free_hash(intern, hash);
if (!element) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Object not found");
} else {
RETURN_ZVAL(element->inf,1, 0);
}
} /* }}} */
/* {{{ proto bool SplObjectStorage::addAll(SplObjectStorage $os)
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,
char *data, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *p,*buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
inl=i2d(data,NULL);
buf_in=OPENSSL_malloc((unsigned int)inl);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
p=buf_in;
i2d(data,&p);
ret=
EVP_VerifyInit_ex(&ctx,type, NULL)
&& EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (!ret)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
goto err;
}
ret = -1;
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: static gboolean read_all_known_des(GDataInputStream* f, MenuCache* cache)
{
char *line;
gsize len;
line = g_data_input_stream_read_line(f, &len, cache->cancellable, NULL);
if(G_UNLIKELY(line == NULL))
return FALSE;
cache->known_des = g_strsplit_set( line, ";\n", 0 );
g_free(line);
return TRUE;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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 Microtask::performCheckpoint()
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
V8PerIsolateData* isolateData = V8PerIsolateData::from(isolate);
ASSERT(isolateData);
if (isolateData->recursionLevel() || isolateData->performingMicrotaskCheckpoint() || isolateData->destructionPending() || ScriptForbiddenScope::isScriptForbidden())
return;
isolateData->setPerformingMicrotaskCheckpoint(true);
{
V8RecursionScope recursionScope(isolate);
isolate->RunMicrotasks();
}
isolateData->setPerformingMicrotaskCheckpoint(false);
}
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: create_watching_parent (void)
{
pid_t child;
sigset_t ourset;
struct sigaction oldact[3];
int status = 0;
int retval;
retval = pam_open_session (pamh, 0);
if (is_pam_failure(retval))
{
cleanup_pam (retval);
errx (EXIT_FAILURE, _("cannot open session: %s"),
pam_strerror (pamh, retval));
}
else
_pam_session_opened = 1;
memset(oldact, 0, sizeof(oldact));
child = fork ();
if (child == (pid_t) -1)
{
cleanup_pam (PAM_ABORT);
err (EXIT_FAILURE, _("cannot create child process"));
}
/* the child proceeds to run the shell */
if (child == 0)
return;
/* In the parent watch the child. */
/* su without pam support does not have a helper that keeps
sitting on any directory so let's go to /. */
if (chdir ("/") != 0)
warn (_("cannot change directory to %s"), "/");
sigfillset (&ourset);
if (sigprocmask (SIG_BLOCK, &ourset, NULL))
{
warn (_("cannot block signals"));
caught_signal = true;
}
if (!caught_signal)
{
struct sigaction action;
action.sa_handler = su_catch_sig;
sigemptyset (&action.sa_mask);
action.sa_flags = 0;
sigemptyset (&ourset);
if (!same_session)
{
if (sigaddset(&ourset, SIGINT) || sigaddset(&ourset, SIGQUIT))
{
warn (_("cannot set signal handler"));
caught_signal = true;
}
}
if (!caught_signal && (sigaddset(&ourset, SIGTERM)
|| sigaddset(&ourset, SIGALRM)
|| sigaction(SIGTERM, &action, &oldact[0])
|| sigprocmask(SIG_UNBLOCK, &ourset, NULL))) {
warn (_("cannot set signal handler"));
caught_signal = true;
}
if (!caught_signal && !same_session && (sigaction(SIGINT, &action, &oldact[1])
|| sigaction(SIGQUIT, &action, &oldact[2])))
{
warn (_("cannot set signal handler"));
caught_signal = true;
}
}
if (!caught_signal)
{
pid_t pid;
for (;;)
{
pid = waitpid (child, &status, WUNTRACED);
if (pid != (pid_t)-1 && WIFSTOPPED (status))
{
kill (getpid (), SIGSTOP);
/* once we get here, we must have resumed */
kill (pid, SIGCONT);
}
else
break;
}
if (pid != (pid_t)-1)
{
if (WIFSIGNALED (status))
{
fprintf (stderr, "%s%s\n", strsignal (WTERMSIG (status)),
WCOREDUMP (status) ? _(" (core dumped)") : "");
status = WTERMSIG (status) + 128;
}
else
status = WEXITSTATUS (status);
}
else if (caught_signal)
status = caught_signal + 128;
else
status = 1;
}
else
status = 1;
if (caught_signal)
{
fprintf (stderr, _("\nSession terminated, killing shell..."));
kill (child, SIGTERM);
}
cleanup_pam (PAM_SUCCESS);
if (caught_signal)
{
sleep (2);
kill (child, SIGKILL);
fprintf (stderr, _(" ...killed.\n"));
/* Let's terminate itself with the received signal.
*
* It seems that shells use WIFSIGNALED() rather than our exit status
* value to detect situations when is necessary to cleanup (reset)
* terminal settings (kzak -- Jun 2013).
*/
switch (caught_signal) {
case SIGTERM:
sigaction(SIGTERM, &oldact[0], NULL);
break;
case SIGINT:
sigaction(SIGINT, &oldact[1], NULL);
break;
case SIGQUIT:
sigaction(SIGQUIT, &oldact[2], NULL);
break;
default:
/* just in case that signal stuff initialization failed and
* caught_signal = true */
caught_signal = SIGKILL;
break;
}
kill(getpid(), caught_signal);
}
exit (status);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: void GetSanitizedEnabledFlags(
FlagsStorage* flags_storage, std::set<std::string>* result) {
SanitizeList(flags_storage);
*result = flags_storage->GetFlags();
}
CWE ID: CWE-399
Target: 0
Now analyze the following code 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: cifs_find_smb_ses(struct TCP_Server_Info *server, char *username)
{
struct list_head *tmp;
struct cifsSesInfo *ses;
write_lock(&cifs_tcp_ses_lock);
list_for_each(tmp, &server->smb_ses_list) {
ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list);
if (strncmp(ses->userName, username, MAX_USERNAME_SIZE))
continue;
++ses->ses_count;
write_unlock(&cifs_tcp_ses_lock);
return ses;
}
write_unlock(&cifs_tcp_ses_lock);
return NULL;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format,
int width, int height,
bool init_to_zero) {
if (!IsImageDataFormatSupported(format))
return false; // Only support this one format for now.
if (width <= 0 || height <= 0)
return false;
if (static_cast<int64>(width) * static_cast<int64>(height) * 4 >=
std::numeric_limits<int32>::max())
return false; // Prevent overflow of signed 32-bit ints.
format_ = format;
width_ = width;
height_ = height;
return backend_->Init(this, format, width, height, init_to_zero);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: int ssl3_check_cert_and_algorithm(SSL *s)
{
int i,idx;
long alg_k,alg_a;
EVP_PKEY *pkey=NULL;
SESS_CERT *sc;
#ifndef OPENSSL_NO_RSA
RSA *rsa;
#endif
#ifndef OPENSSL_NO_DH
DH *dh;
#endif
alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
alg_a=s->s3->tmp.new_cipher->algorithm_auth;
/* we don't have a certificate */
if ((alg_a & (SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK))
return(1);
sc=s->session->sess_cert;
if (sc == NULL)
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
goto err;
}
#ifndef OPENSSL_NO_RSA
rsa=s->session->sess_cert->peer_rsa_tmp;
#endif
#ifndef OPENSSL_NO_DH
dh=s->session->sess_cert->peer_dh_tmp;
#endif
/* This is the passed certificate */
idx=sc->peer_cert_type;
#ifndef OPENSSL_NO_ECDH
if (idx == SSL_PKEY_ECC)
{
if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
s) == 0)
{ /* check failed */
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
goto f_err;
}
else
{
return 1;
}
}
else if (alg_a & SSL_aECDSA)
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDSA_SIGNING_CERT);
goto f_err;
}
else if (alg_k & (SSL_kECDHr|SSL_kECDHe))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDH_CERT);
goto f_err;
}
#endif
pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
EVP_PKEY_free(pkey);
/* Check that we have a certificate if we require one */
if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
goto f_err;
}
#ifndef OPENSSL_NO_DSA
else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
goto f_err;
}
#endif
#ifndef OPENSSL_NO_RSA
if ((alg_k & SSL_kRSA) &&
!(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
goto f_err;
}
#endif
#ifndef OPENSSL_NO_DH
if ((alg_k & SSL_kDHE) &&
!(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
goto f_err;
}
else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) &&
!has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
goto f_err;
}
#ifndef OPENSSL_NO_DSA
else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) &&
!has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
goto f_err;
}
#endif
#endif
if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
{
#ifndef OPENSSL_NO_RSA
if (alg_k & SSL_kRSA)
{
if (rsa == NULL
|| RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
goto f_err;
}
}
else
#endif
#ifndef OPENSSL_NO_DH
if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd))
{
if (dh == NULL
|| DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
goto f_err;
}
}
else
#endif
{
SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
goto f_err;
}
}
return(1);
f_err:
ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
err:
return(0);
}
CWE ID: CWE-310
Target: 0
Now analyze the following code 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 LowBatteryObserver::Hide() {
notification_.Hide();
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int Downmix_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
downmix_module_t *pDwmModule = (downmix_module_t *) self;
downmix_object_t *pDownmixer;
if (pDwmModule == NULL || pDwmModule->context.state == DOWNMIX_STATE_UNINITIALIZED) {
return -EINVAL;
}
pDownmixer = (downmix_object_t*) &pDwmModule->context;
ALOGV("Downmix_Command command %" PRIu32 " cmdSize %" PRIu32, cmdCode, cmdSize);
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Init(pDwmModule);
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 = Downmix_Configure(pDwmModule,
(effect_config_t *)pCmdData, false);
break;
case EFFECT_CMD_RESET:
Downmix_Reset(pDownmixer, false);
break;
case EFFECT_CMD_GET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM pCmdData %p, *replySize %" PRIu32 ", pReplyData: %p",
pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (int) sizeof(effect_param_t) + 2 * sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *rep = (effect_param_t *) pReplyData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(int32_t));
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM param %" PRId32 ", replySize %" PRIu32,
*(int32_t *)rep->data, rep->vsize);
rep->status = Downmix_getParameter(pDownmixer, *(int32_t *)rep->data, &rep->vsize,
rep->data + sizeof(int32_t));
*replySize = sizeof(effect_param_t) + sizeof(int32_t) + rep->vsize;
break;
case EFFECT_CMD_SET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_SET_PARAM cmdSize %d pCmdData %p, *replySize %" PRIu32
", pReplyData %p", cmdSize, pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || (cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || replySize == NULL || *replySize != (int)sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *cmd = (effect_param_t *) pCmdData;
*(int *)pReplyData = Downmix_setParameter(pDownmixer, *(int32_t *)cmd->data,
cmd->vsize, cmd->data + sizeof(int32_t));
break;
case EFFECT_CMD_SET_PARAM_DEFERRED:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_DEFERRED not supported, FIXME");
break;
case EFFECT_CMD_SET_PARAM_COMMIT:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_COMMIT not supported, FIXME");
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_INITIALIZED) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_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 (pDownmixer->state != DOWNMIX_STATE_ACTIVE) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_SET_DEVICE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_DEVICE: 0x%08" PRIx32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_VOLUME: {
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t) * 2) {
return -EINVAL;
}
ALOGW("Downmix_Command command EFFECT_CMD_SET_VOLUME not supported, FIXME");
float left = (float)(*(uint32_t *)pCmdData) / (1 << 24);
float right = (float)(*((uint32_t *)pCmdData + 1)) / (1 << 24);
ALOGV("Downmix_Command EFFECT_CMD_SET_VOLUME: left %f, right %f ", left, right);
break;
}
case EFFECT_CMD_SET_AUDIO_MODE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_AUDIO_MODE: %" PRIu32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_CONFIG_REVERSE:
case EFFECT_CMD_SET_INPUT_DEVICE:
break;
default:
ALOGW("Downmix_Command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
return 0;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void wake_up_idle_cpu(int cpu)
{
struct rq *rq = cpu_rq(cpu);
if (cpu == smp_processor_id())
return;
/*
* This is safe, as this function is called with the timer
* wheel base lock of (cpu) held. When the CPU is on the way
* to idle and has not yet set rq->curr to idle then it will
* be serialized on the timer wheel base lock and take the new
* timer into account automatically.
*/
if (rq->curr != rq->idle)
return;
/*
* We can set TIF_RESCHED on the idle task of the other CPU
* lockless. The worst case is that the other CPU runs the
* idle task through an additional NOOP schedule()
*/
set_tsk_need_resched(rq->idle);
/* NEED_RESCHED must be visible before we test polling */
smp_mb();
if (!tsk_is_polling(rq->idle))
smp_send_reschedule(cpu);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code 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: ZEND_API zval* ZEND_FASTCALL _zend_hash_str_update(HashTable *ht, const char *str, size_t len, zval *pData ZEND_FILE_LINE_DC)
{
zend_string *key = zend_string_init(str, len, ht->u.flags & HASH_FLAG_PERSISTENT);
zval *ret = _zend_hash_add_or_update_i(ht, key, pData, HASH_UPDATE ZEND_FILE_LINE_RELAY_CC);
zend_string_release(key);
return ret;
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void MockRenderThread::AddRoute(int32 routing_id,
IPC::Channel::Listener* listener) {
EXPECT_EQ(routing_id_, routing_id);
widget_ = listener;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (hooks == NULL)
{
/* Reset hooks */
global_hooks.allocate = malloc;
global_hooks.deallocate = free;
global_hooks.reallocate = realloc;
return;
}
global_hooks.allocate = malloc;
if (hooks->malloc_fn != NULL)
{
global_hooks.allocate = hooks->malloc_fn;
}
global_hooks.deallocate = free;
if (hooks->free_fn != NULL)
{
global_hooks.deallocate = hooks->free_fn;
}
/* use realloc only if both free and malloc are used */
global_hooks.reallocate = NULL;
if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free))
{
global_hooks.reallocate = realloc;
}
}
CWE ID: CWE-754
Target: 0
Now analyze the following code 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: sc_parse_ef_gdo_content(const unsigned char *gdo, size_t gdo_len,
unsigned char *iccsn, size_t *iccsn_len,
unsigned char *chn, size_t *chn_len)
{
int r = SC_SUCCESS, iccsn_found = 0, chn_found = 0;
const unsigned char *p = gdo;
size_t left = gdo_len;
while (left >= 2) {
unsigned int cla, tag;
size_t tag_len;
r = sc_asn1_read_tag(&p, left, &cla, &tag, &tag_len);
if (r != SC_SUCCESS) {
if (r == SC_ERROR_ASN1_END_OF_CONTENTS) {
/* not enough data */
r = SC_SUCCESS;
}
break;
}
if (p == NULL) {
/* done parsing */
break;
}
if (cla == SC_ASN1_TAG_APPLICATION) {
switch (tag) {
case 0x1A:
iccsn_found = 1;
if (iccsn && iccsn_len) {
memcpy(iccsn, p, MIN(tag_len, *iccsn_len));
*iccsn_len = MIN(tag_len, *iccsn_len);
}
break;
case 0x1F20:
chn_found = 1;
if (chn && chn_len) {
memcpy(chn, p, MIN(tag_len, *chn_len));
*chn_len = MIN(tag_len, *chn_len);
}
break;
}
}
p += tag_len;
left -= (p - gdo);
}
if (!iccsn_found && iccsn_len)
*iccsn_len = 0;
if (!chn_found && chn_len)
*chn_len = 0;
return r;
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CoordinatorImpl::GetVmRegionsForHeapProfiler(
const GetVmRegionsForHeapProfilerCallback& callback) {
RequestGlobalMemoryDump(
MemoryDumpType::EXPLICITLY_TRIGGERED,
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {}, callback);
}
CWE ID: CWE-269
Target: 1
Example 2:
Code: void filter_level_for_mb(VP8Context *s, VP8Macroblock *mb,
VP8FilterStrength *f, int is_vp7)
{
int interior_limit, filter_level;
if (s->segmentation.enabled) {
filter_level = s->segmentation.filter_level[mb->segment];
if (!s->segmentation.absolute_vals)
filter_level += s->filter.level;
} else
filter_level = s->filter.level;
if (s->lf_delta.enabled) {
filter_level += s->lf_delta.ref[mb->ref_frame];
filter_level += s->lf_delta.mode[mb->mode];
}
filter_level = av_clip_uintp2(filter_level, 6);
interior_limit = filter_level;
if (s->filter.sharpness) {
interior_limit >>= (s->filter.sharpness + 3) >> 2;
interior_limit = FFMIN(interior_limit, 9 - s->filter.sharpness);
}
interior_limit = FFMAX(interior_limit, 1);
f->filter_level = filter_level;
f->inner_limit = interior_limit;
f->inner_filter = is_vp7 || !mb->skip || mb->mode == MODE_I4x4 ||
mb->mode == VP8_MVMODE_SPLIT;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
{
ssize_t ret;
uint8_t *buffer = g_malloc(MIN(65536, size));
while (size > 0) {
size_t count = MIN(65536, size);
ret = nbd_negotiate_read(ioc, buffer, count);
if (ret < 0) {
g_free(buffer);
return ret;
}
size -= count;
}
g_free(buffer);
return 0;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and 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];
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: void __audit_log_capset(const struct cred *new, const struct cred *old)
{
struct audit_context *context = current->audit_context;
context->capset.pid = task_pid_nr(current);
context->capset.cap.effective = new->cap_effective;
context->capset.cap.inheritable = new->cap_effective;
context->capset.cap.permitted = new->cap_permitted;
context->type = AUDIT_CAPSET;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code 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: juniper_atm1_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM1;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[0] == 0x80) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: validate_event(struct pmu_hw_events *hw_events,
struct perf_event *event)
{
struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
struct pmu *leader_pmu = event->group_leader->pmu;
if (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF)
return 1;
if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)
return 1;
return armpmu->get_event_idx(hw_events, event) >= 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: std::string mid() { return mid_; }
CWE ID:
Target: 0
Now analyze the following code 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 SetUp() {
UUT_ = GET_PARAM(2);
/* Set up guard blocks for an inner block centered in the outer block */
for (int i = 0; i < kOutputBufferSize; ++i) {
if (IsIndexInBorder(i))
output_[i] = 255;
else
output_[i] = 0;
}
::libvpx_test::ACMRandom prng;
for (int i = 0; i < kInputBufferSize; ++i)
input_[i] = prng.Rand8Extremes();
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int VRDisplay::requestAnimationFrame(FrameRequestCallback* callback) {
Document* doc = this->GetDocument();
if (!doc)
return 0;
pending_raf_ = true;
if (!vr_v_sync_provider_.is_bound()) {
ConnectVSyncProvider();
} else if (!display_blurred_ && !pending_vsync_) {
pending_vsync_ = true;
vr_v_sync_provider_->GetVSync(ConvertToBaseCallback(
WTF::Bind(&VRDisplay::OnVSync, WrapWeakPersistent(this))));
}
callback->use_legacy_time_base_ = false;
return EnsureScriptedAnimationController(doc).RegisterCallback(callback);
}
CWE ID:
Target: 1
Example 2:
Code: hfs_close(TSK_FS_INFO * fs)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
tsk_take_lock(&(hfs->metadata_dir_cache_lock));
fs->tag = 0;
free(hfs->fs);
if (hfs->catalog_file) {
tsk_fs_file_close(hfs->catalog_file);
hfs->catalog_attr = NULL;
}
if (hfs->blockmap_file) {
tsk_fs_file_close(hfs->blockmap_file);
hfs->blockmap_attr = NULL;
}
if (hfs->meta_dir) {
tsk_fs_dir_close(hfs->meta_dir);
hfs->meta_dir = NULL;
}
if (hfs->dir_meta_dir) {
tsk_fs_dir_close(hfs->dir_meta_dir);
hfs->dir_meta_dir = NULL;
}
if (hfs->extents_file) {
tsk_fs_file_close(hfs->extents_file);
hfs->extents_file = NULL;
}
tsk_release_lock(&(hfs->metadata_dir_cache_lock));
tsk_deinit_lock(&(hfs->metadata_dir_cache_lock));
tsk_fs_free((TSK_FS_INFO *)hfs);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code 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 send_write(struct svcxprt_rdma *xprt, struct svc_rqst *rqstp,
u32 rmr, u64 to,
u32 xdr_off, int write_len,
struct svc_rdma_req_map *vec)
{
struct ib_rdma_wr write_wr;
struct ib_sge *sge;
int xdr_sge_no;
int sge_no;
int sge_bytes;
int sge_off;
int bc;
struct svc_rdma_op_ctxt *ctxt;
if (vec->count > RPCSVC_MAXPAGES) {
pr_err("svcrdma: Too many pages (%lu)\n", vec->count);
return -EIO;
}
dprintk("svcrdma: RDMA_WRITE rmr=%x, to=%llx, xdr_off=%d, "
"write_len=%d, vec->sge=%p, vec->count=%lu\n",
rmr, (unsigned long long)to, xdr_off,
write_len, vec->sge, vec->count);
ctxt = svc_rdma_get_context(xprt);
ctxt->direction = DMA_TO_DEVICE;
sge = ctxt->sge;
/* Find the SGE associated with xdr_off */
for (bc = xdr_off, xdr_sge_no = 1; bc && xdr_sge_no < vec->count;
xdr_sge_no++) {
if (vec->sge[xdr_sge_no].iov_len > bc)
break;
bc -= vec->sge[xdr_sge_no].iov_len;
}
sge_off = bc;
bc = write_len;
sge_no = 0;
/* Copy the remaining SGE */
while (bc != 0) {
sge_bytes = min_t(size_t,
bc, vec->sge[xdr_sge_no].iov_len-sge_off);
sge[sge_no].length = sge_bytes;
sge[sge_no].addr =
dma_map_xdr(xprt, &rqstp->rq_res, xdr_off,
sge_bytes, DMA_TO_DEVICE);
xdr_off += sge_bytes;
if (ib_dma_mapping_error(xprt->sc_cm_id->device,
sge[sge_no].addr))
goto err;
svc_rdma_count_mappings(xprt, ctxt);
sge[sge_no].lkey = xprt->sc_pd->local_dma_lkey;
ctxt->count++;
sge_off = 0;
sge_no++;
xdr_sge_no++;
if (xdr_sge_no > vec->count) {
pr_err("svcrdma: Too many sges (%d)\n", xdr_sge_no);
goto err;
}
bc -= sge_bytes;
if (sge_no == xprt->sc_max_sge)
break;
}
/* Prepare WRITE WR */
memset(&write_wr, 0, sizeof write_wr);
ctxt->cqe.done = svc_rdma_wc_write;
write_wr.wr.wr_cqe = &ctxt->cqe;
write_wr.wr.sg_list = &sge[0];
write_wr.wr.num_sge = sge_no;
write_wr.wr.opcode = IB_WR_RDMA_WRITE;
write_wr.wr.send_flags = IB_SEND_SIGNALED;
write_wr.rkey = rmr;
write_wr.remote_addr = to;
/* Post It */
atomic_inc(&rdma_stat_write);
if (svc_rdma_send(xprt, &write_wr.wr))
goto err;
return write_len - bc;
err:
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 0);
return -EIO;
}
CWE ID: CWE-404
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) {
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, UNINITIALIZED);
DCHECK(source);
DCHECK(!sink_);
DCHECK(!source_);
sink_ = AudioDeviceFactory::NewOutputDevice();
DCHECK(sink_);
int sample_rate = GetAudioOutputSampleRate();
DVLOG(1) << "Audio output hardware sample rate: " << sample_rate;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate",
sample_rate, media::kUnexpectedAudioSampleRate);
if (std::find(&kValidOutputRates[0],
&kValidOutputRates[0] + arraysize(kValidOutputRates),
sample_rate) ==
&kValidOutputRates[arraysize(kValidOutputRates)]) {
DLOG(ERROR) << sample_rate << " is not a supported output rate.";
return false;
}
media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO;
int buffer_size = 0;
#if defined(OS_WIN)
channel_layout = media::CHANNEL_LAYOUT_STEREO;
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
buffer_size = 2 * 440;
}
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
buffer_size = 3 * buffer_size;
DLOG(WARNING) << "Extending the output buffer size by a factor of three "
<< "since Windows XP has been detected.";
}
#elif defined(OS_MACOSX)
channel_layout = media::CHANNEL_LAYOUT_MONO;
if (sample_rate == 48000) {
buffer_size = 480;
} else {
buffer_size = 440;
}
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
channel_layout = media::CHANNEL_LAYOUT_MONO;
buffer_size = 480;
#else
DLOG(ERROR) << "Unsupported platform";
return false;
#endif
params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout,
sample_rate, 16, buffer_size);
buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]);
source_ = source;
source->SetRenderFormat(params_);
sink_->Initialize(params_, this);
sink_->SetSourceRenderView(source_render_view_id_);
sink_->Start();
state_ = PAUSED;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout",
channel_layout, media::CHANNEL_LAYOUT_MAX);
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer",
buffer_size, kUnexpectedAudioBufferSize);
AddHistogramFramesPerBuffer(buffer_size);
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: size_t utf8_to_utf32_length(const char *src, size_t src_len)
{
if (src == NULL || src_len == 0) {
return 0;
}
size_t ret = 0;
const char* cur;
const char* end;
size_t num_to_skip;
for (cur = src, end = src + src_len, num_to_skip = 1;
cur < end;
cur += num_to_skip, ret++) {
const char first_char = *cur;
num_to_skip = 1;
if ((first_char & 0x80) == 0) { // ASCII
continue;
}
int32_t mask;
for (mask = 0x40; (first_char & mask); num_to_skip++, mask >>= 1) {
}
}
return ret;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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: v8::Handle<v8::Value> V8WebKitMutationObserver::observeCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebKitMutationObserver.observe");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
WebKitMutationObserver* imp = V8WebKitMutationObserver::toNative(args.Holder());
EXCEPTION_BLOCK(Node*, target, V8Node::HasInstance(args[0]) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0);
if (!args[1]->IsObject())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
Dictionary optionsObject(args[1]);
unsigned options = 0;
HashSet<AtomicString> attributeFilter;
bool option;
if (optionsObject.get("childList", option) && option)
options |= WebKitMutationObserver::ChildList;
if (optionsObject.get("attributes", option) && option)
options |= WebKitMutationObserver::Attributes;
if (optionsObject.get("attributeFilter", attributeFilter))
options |= WebKitMutationObserver::AttributeFilter;
if (optionsObject.get("characterData", option) && option)
options |= WebKitMutationObserver::CharacterData;
if (optionsObject.get("subtree", option) && option)
options |= WebKitMutationObserver::Subtree;
if (optionsObject.get("attributeOldValue", option) && option)
options |= WebKitMutationObserver::AttributeOldValue;
if (optionsObject.get("characterDataOldValue", option) && option)
options |= WebKitMutationObserver::CharacterDataOldValue;
ExceptionCode ec = 0;
imp->observe(target, options, attributeFilter, ec);
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline int object_common2(UNSERIALIZE_PARAMETER, long elements)
{
zval *retval_ptr = NULL;
zval fname;
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_OBJPROP_PP(rval), elements, 1)) {
/* We've got partially constructed object on our hands here. Wipe it. */
if(Z_TYPE_PP(rval) == IS_OBJECT) {
zend_hash_clean(Z_OBJPROP_PP(rval));
}
ZVAL_NULL(*rval);
return 0;
}
if (Z_TYPE_PP(rval) != IS_OBJECT) {
return 0;
}
if (Z_OBJCE_PP(rval) != PHP_IC_ENTRY &&
zend_hash_exists(&Z_OBJCE_PP(rval)->function_table, "__wakeup", sizeof("__wakeup"))) {
INIT_PZVAL(&fname);
ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1, 0);
BG(serialize_lock)++;
call_user_function_ex(CG(function_table), rval, &fname, &retval_ptr, 0, 0, 1, NULL TSRMLS_CC);
BG(serialize_lock)--;
}
if (retval_ptr) {
zval_ptr_dtor(&retval_ptr);
}
if (EG(exception)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void freerdp_peer_disconnect(freerdp_peer* client)
{
transport_disconnect(client->context->rdp->transport);
}
CWE ID: CWE-476
Target: 0
Now analyze the following code 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 f2fs_quota_off(struct super_block *sb, int type)
{
struct inode *inode = sb_dqopt(sb)->files[type];
int err;
if (!inode || !igrab(inode))
return dquot_quota_off(sb, type);
f2fs_quota_sync(sb, type);
err = dquot_quota_off(sb, type);
if (err)
goto out_put;
inode_lock(inode);
F2FS_I(inode)->i_flags &= ~(FS_NOATIME_FL | FS_IMMUTABLE_FL);
inode_set_flags(inode, 0, S_NOATIME | S_IMMUTABLE);
inode_unlock(inode);
f2fs_mark_inode_dirty_sync(inode, false);
out_put:
iput(inode);
return err;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: native_handle_t* native_handle_create(int numFds, int numInts)
{
native_handle_t* h = malloc(
sizeof(native_handle_t) + sizeof(int)*(numFds+numInts));
if (h) {
h->version = sizeof(native_handle_t);
h->numFds = numFds;
h->numInts = numInts;
}
return h;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void HTMLInputElement::DefaultEventHandler(Event* evt) {
if (evt->IsMouseEvent() && evt->type() == EventTypeNames::click &&
ToMouseEvent(evt)->button() ==
static_cast<short>(WebPointerProperties::Button::kLeft)) {
input_type_view_->HandleClickEvent(ToMouseEvent(evt));
if (evt->DefaultHandled())
return;
}
if (evt->IsKeyboardEvent() && evt->type() == EventTypeNames::keydown) {
input_type_view_->HandleKeydownEvent(ToKeyboardEvent(evt));
if (evt->DefaultHandled())
return;
}
bool call_base_class_early =
IsTextField() && (evt->type() == EventTypeNames::keydown ||
evt->type() == EventTypeNames::keypress);
if (call_base_class_early) {
TextControlElement::DefaultEventHandler(evt);
if (evt->DefaultHandled())
return;
}
if (evt->type() == EventTypeNames::DOMActivate) {
input_type_view_->HandleDOMActivateEvent(evt);
if (evt->DefaultHandled())
return;
}
if (evt->IsKeyboardEvent() && evt->type() == EventTypeNames::keypress) {
input_type_view_->HandleKeypressEvent(ToKeyboardEvent(evt));
if (evt->DefaultHandled())
return;
}
if (evt->IsKeyboardEvent() && evt->type() == EventTypeNames::keyup) {
input_type_view_->HandleKeyupEvent(ToKeyboardEvent(evt));
if (evt->DefaultHandled())
return;
}
if (input_type_view_->ShouldSubmitImplicitly(evt)) {
if (type() == InputTypeNames::search) {
GetDocument()
.GetTaskRunner(TaskType::kUserInteraction)
->PostTask(FROM_HERE, WTF::Bind(&HTMLInputElement::OnSearch,
WrapPersistent(this)));
}
DispatchFormControlChangeEvent();
HTMLFormElement* form_for_submission =
input_type_view_->FormForSubmission();
if (form_for_submission) {
form_for_submission->SubmitImplicitly(evt,
CanTriggerImplicitSubmission());
}
evt->SetDefaultHandled();
return;
}
if (evt->IsBeforeTextInsertedEvent()) {
input_type_view_->HandleBeforeTextInsertedEvent(
static_cast<BeforeTextInsertedEvent*>(evt));
}
if (evt->IsMouseEvent() && evt->type() == EventTypeNames::mousedown) {
input_type_view_->HandleMouseDownEvent(ToMouseEvent(evt));
if (evt->DefaultHandled())
return;
}
input_type_view_->ForwardEvent(evt);
if (!call_base_class_early && !evt->DefaultHandled())
TextControlElement::DefaultEventHandler(evt);
}
CWE ID:
Target: 0
Now analyze the following code 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: notify_script_init(int extra_params, const char *type)
{
notify_script_t *script = MALLOC(sizeof(notify_script_t));
vector_t *strvec_qe;
/* We need to reparse the command line, allowing for quoted and escaped strings */
strvec_qe = alloc_strvec_quoted_escaped(NULL);
if (!strvec_qe) {
log_message(LOG_INFO, "Unable to parse notify script");
FREE(script);
return NULL;
}
set_script_params_array(strvec_qe, script, extra_params);
if (!script->args) {
log_message(LOG_INFO, "Unable to parse script '%s' - ignoring", FMT_STR_VSLOT(strvec_qe, 1));
FREE(script);
free_strvec(strvec_qe);
return NULL;
}
script->flags = 0;
if (vector_size(strvec_qe) > 2) {
if (set_script_uid_gid(strvec_qe, 2, &script->uid, &script->gid)) {
log_message(LOG_INFO, "Invalid user/group for %s script %s - ignoring", type, script->args[0]);
FREE(script->args);
FREE(script);
free_strvec(strvec_qe);
return NULL;
}
}
else {
if (set_default_script_user(NULL, NULL)) {
log_message(LOG_INFO, "Failed to set default user for %s script %s - ignoring", type, script->args[0]);
FREE(script->args);
FREE(script);
free_strvec(strvec_qe);
return NULL;
}
script->uid = default_script_uid;
script->gid = default_script_gid;
}
free_strvec(strvec_qe);
return script;
}
CWE ID: CWE-59
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
{
if (size == 0 || ncount == 0 || ncount > SIZE_MAX / size)
fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
return mm_malloc(mm, size * ncount);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AwContents::CancelProtectedMediaIdentifierPermissionRequests(
const GURL& origin) {
permission_request_handler_->CancelRequest(
origin, AwPermissionRequest::ProtectedMediaId);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code 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 crash_vmclear_local_loaded_vmcss(void)
{
int cpu = raw_smp_processor_id();
struct loaded_vmcs *v;
if (!crash_local_vmclear_enabled(cpu))
return;
list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
loaded_vmcss_on_cpu_link)
vmcs_clear(v->vmcs);
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebGLRenderingContextBase::TexImageImpl(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLenum format,
GLenum type,
Image* image,
WebGLImageConversion::ImageHtmlDomSource dom_source,
bool flip_y,
bool premultiply_alpha,
const IntRect& source_image_rect,
GLsizei depth,
GLint unpack_image_height) {
const char* func_name = GetTexImageFunctionName(function_id);
if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) {
type = GL_FLOAT;
}
Vector<uint8_t> data;
IntRect sub_rect = source_image_rect;
if (sub_rect == SentinelEmptyRect()) {
sub_rect = SafeGetImageSize(image);
}
bool selecting_sub_rectangle = false;
if (!ValidateTexImageSubRectangle(func_name, function_id, image, sub_rect,
depth, unpack_image_height,
&selecting_sub_rectangle)) {
return;
}
IntRect adjusted_source_image_rect = sub_rect;
if (flip_y) {
adjusted_source_image_rect.SetY(image->height() -
adjusted_source_image_rect.MaxY());
}
WebGLImageConversion::ImageExtractor image_extractor(
image, dom_source, premultiply_alpha,
unpack_colorspace_conversion_ == GL_NONE);
if (!image_extractor.ImagePixelData()) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data");
return;
}
WebGLImageConversion::DataFormat source_data_format =
image_extractor.ImageSourceFormat();
WebGLImageConversion::AlphaOp alpha_op = image_extractor.ImageAlphaOp();
const void* image_pixel_data = image_extractor.ImagePixelData();
bool need_conversion = true;
if (type == GL_UNSIGNED_BYTE &&
source_data_format == WebGLImageConversion::kDataFormatRGBA8 &&
format == GL_RGBA && alpha_op == WebGLImageConversion::kAlphaDoNothing &&
!flip_y && !selecting_sub_rectangle && depth == 1) {
need_conversion = false;
} else {
if (!WebGLImageConversion::PackImageData(
image, image_pixel_data, format, type, flip_y, alpha_op,
source_data_format, image_extractor.ImageWidth(),
image_extractor.ImageHeight(), adjusted_source_image_rect, depth,
image_extractor.ImageSourceUnpackAlignment(), unpack_image_height,
data)) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "packImage error");
return;
}
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(this);
if (function_id == kTexImage2D) {
TexImage2DBase(target, level, internalformat,
adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), 0, format, type,
need_conversion ? data.data() : image_pixel_data);
} else if (function_id == kTexSubImage2D) {
ContextGL()->TexSubImage2D(
target, level, xoffset, yoffset, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), format, type,
need_conversion ? data.data() : image_pixel_data);
} else {
if (function_id == kTexImage3D) {
ContextGL()->TexImage3D(
target, level, internalformat, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), depth, 0, format, type,
need_conversion ? data.data() : image_pixel_data);
} else {
DCHECK_EQ(function_id, kTexSubImage3D);
ContextGL()->TexSubImage3D(
target, level, xoffset, yoffset, zoffset,
adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), depth, format, type,
need_conversion ? data.data() : image_pixel_data);
}
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void saved_tgids_stop(struct seq_file *m, void *v)
{
}
CWE ID: CWE-787
Target: 0
Now analyze the following code 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 CrosLibrary::TestApi::SetSystemLibrary(
SystemLibrary* library, bool own) {
library_->system_lib_.SetImpl(library, own);
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf)
{
const HashSet<Page*>& pages = page->group().pages();
HashSet<Page*>::const_iterator end = pages.end();
for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) {
Page* otherPage = *it;
if ((deferSelf || otherPage != page)) {
if (!otherPage->defersLoading()) {
m_deferredFrames.append(otherPage->mainFrame());
for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext())
frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading);
}
}
}
size_t count = m_deferredFrames.size();
for (size_t i = 0; i < count; ++i)
if (Page* page = m_deferredFrames[i]->page())
page->setDefersLoading(true);
}
CWE ID:
Target: 1
Example 2:
Code: void WebPagePrivate::loadString(const BlackBerry::Platform::String& string, const BlackBerry::Platform::String& baseURL, const BlackBerry::Platform::String& contentType, const BlackBerry::Platform::String& failingURL)
{
KURL kurl = parseUrl(baseURL);
ResourceRequest request(kurl);
WTF::RefPtr<SharedBuffer> buffer
= SharedBuffer::create(string.c_str(), string.length());
SubstituteData substituteData(buffer,
extractMIMETypeFromMediaType(contentType),
extractCharsetFromMediaType(contentType),
!failingURL.empty() ? parseUrl(failingURL) : KURL());
m_mainFrame->loader()->load(FrameLoadRequest(m_mainFrame, request, substituteData));
}
CWE ID:
Target: 0
Now analyze the following code 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: SSLErrorHandler::SSLErrorHandler(base::WeakPtr<Delegate> delegate,
const content::GlobalRequestID& id,
ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id)
: manager_(NULL),
request_id_(id),
delegate_(delegate),
render_process_id_(render_process_id),
render_view_id_(render_view_id),
request_url_(url),
resource_type_(resource_type),
request_has_been_notified_(false) {
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(delegate);
AddRef();
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DownloadManagerImpl::DownloadUrl(
std::unique_ptr<download::DownloadUrlParameters> params,
std::unique_ptr<storage::BlobDataHandle> blob_data_handle,
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
if (params->post_id() >= 0) {
DCHECK(params->prefer_cache());
DCHECK_EQ("POST", params->method());
}
download::RecordDownloadCountWithSource(
download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT,
params->download_source());
auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(),
params->render_frame_host_routing_id());
BeginDownloadInternal(std::move(params), std::move(blob_data_handle),
std::move(blob_url_loader_factory), true,
rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL());
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static struct resource *register_memory_resource(u64 start, u64 size)
{
struct resource *res;
res = kzalloc(sizeof(struct resource), GFP_KERNEL);
BUG_ON(!res);
res->name = "System RAM";
res->start = start;
res->end = start + size - 1;
res->flags = IORESOURCE_MEM | IORESOURCE_BUSY;
if (request_resource(&iomem_resource, res) < 0) {
printk("System RAM resource %pR cannot be added\n", res);
kfree(res);
res = NULL;
}
return res;
}
CWE ID:
Target: 0
Now analyze the following code 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 drm_framebuffer_init(struct drm_device *dev, struct drm_framebuffer *fb,
const struct drm_framebuffer_funcs *funcs)
{
int ret;
ret = drm_mode_object_get(dev, &fb->base, DRM_MODE_OBJECT_FB);
if (ret) {
return ret;
}
fb->dev = dev;
fb->funcs = funcs;
dev->mode_config.num_fb++;
list_add(&fb->head, &dev->mode_config.fb_list);
return 0;
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int cipso_v4_delopt(struct ip_options **opt_ptr)
{
int hdr_delta = 0;
struct ip_options *opt = *opt_ptr;
if (opt->srr || opt->rr || opt->ts || opt->router_alert) {
u8 cipso_len;
u8 cipso_off;
unsigned char *cipso_ptr;
int iter;
int optlen_new;
cipso_off = opt->cipso - sizeof(struct iphdr);
cipso_ptr = &opt->__data[cipso_off];
cipso_len = cipso_ptr[1];
if (opt->srr > opt->cipso)
opt->srr -= cipso_len;
if (opt->rr > opt->cipso)
opt->rr -= cipso_len;
if (opt->ts > opt->cipso)
opt->ts -= cipso_len;
if (opt->router_alert > opt->cipso)
opt->router_alert -= cipso_len;
opt->cipso = 0;
memmove(cipso_ptr, cipso_ptr + cipso_len,
opt->optlen - cipso_off - cipso_len);
/* determining the new total option length is tricky because of
* the padding necessary, the only thing i can think to do at
* this point is walk the options one-by-one, skipping the
* padding at the end to determine the actual option size and
* from there we can determine the new total option length */
iter = 0;
optlen_new = 0;
while (iter < opt->optlen)
if (opt->__data[iter] != IPOPT_NOP) {
iter += opt->__data[iter + 1];
optlen_new = iter;
} else
iter++;
hdr_delta = opt->optlen;
opt->optlen = (optlen_new + 3) & ~3;
hdr_delta -= opt->optlen;
} else {
/* only the cipso option was present on the socket so we can
* remove the entire option struct */
*opt_ptr = NULL;
hdr_delta = opt->optlen;
kfree(opt);
}
return hdr_delta;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static void k_getrusage(struct task_struct *p, int who, struct rusage *r)
{
struct task_struct *t;
unsigned long flags;
cputime_t tgutime, tgstime, utime, stime;
unsigned long maxrss = 0;
memset((char *) r, 0, sizeof *r);
utime = stime = 0;
if (who == RUSAGE_THREAD) {
task_times(current, &utime, &stime);
accumulate_thread_rusage(p, r);
maxrss = p->signal->maxrss;
goto out;
}
if (!lock_task_sighand(p, &flags))
return;
switch (who) {
case RUSAGE_BOTH:
case RUSAGE_CHILDREN:
utime = p->signal->cutime;
stime = p->signal->cstime;
r->ru_nvcsw = p->signal->cnvcsw;
r->ru_nivcsw = p->signal->cnivcsw;
r->ru_minflt = p->signal->cmin_flt;
r->ru_majflt = p->signal->cmaj_flt;
r->ru_inblock = p->signal->cinblock;
r->ru_oublock = p->signal->coublock;
maxrss = p->signal->cmaxrss;
if (who == RUSAGE_CHILDREN)
break;
case RUSAGE_SELF:
thread_group_times(p, &tgutime, &tgstime);
utime += tgutime;
stime += tgstime;
r->ru_nvcsw += p->signal->nvcsw;
r->ru_nivcsw += p->signal->nivcsw;
r->ru_minflt += p->signal->min_flt;
r->ru_majflt += p->signal->maj_flt;
r->ru_inblock += p->signal->inblock;
r->ru_oublock += p->signal->oublock;
if (maxrss < p->signal->maxrss)
maxrss = p->signal->maxrss;
t = p;
do {
accumulate_thread_rusage(t, r);
t = next_thread(t);
} while (t != p);
break;
default:
BUG();
}
unlock_task_sighand(p, &flags);
out:
cputime_to_timeval(utime, &r->ru_utime);
cputime_to_timeval(stime, &r->ru_stime);
if (who != RUSAGE_CHILDREN) {
struct mm_struct *mm = get_task_mm(p);
if (mm) {
setmax_mm_hiwater_rss(&maxrss, mm);
mmput(mm);
}
}
r->ru_maxrss = maxrss * (PAGE_SIZE / 1024); /* convert pages to KBs */
}
CWE ID: CWE-16
Target: 0
Now analyze the following code 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: krb5_encode_krbsecretkey(krb5_key_data *key_data, int n_key_data,
krb5_kvno mkvno)
{
struct berval **ret = NULL;
int currkvno;
int num_versions = 0;
int i, j, last;
krb5_error_code err = 0;
if (n_key_data < 0)
return NULL;
/* Find the number of key versions */
if (n_key_data > 0) {
for (i = 0, num_versions = 1; i < n_key_data - 1; i++) {
if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno)
num_versions++;
}
}
ret = calloc(num_versions + 1, sizeof(struct berval *));
if (ret == NULL) {
err = ENOMEM;
goto cleanup;
}
ret[num_versions] = NULL;
/* n_key_data may be 0 if a principal is created without a key. */
if (n_key_data == 0)
goto cleanup;
currkvno = key_data[0].key_data_kvno;
for (i = 0, last = 0, j = 0; i < n_key_data; i++) {
if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) {
err = encode_keys(key_data + last, (krb5_int16)i - last + 1, mkvno,
&ret[j]);
if (err)
goto cleanup;
j++;
last = i + 1;
if (i < n_key_data - 1)
currkvno = key_data[i + 1].key_data_kvno;
}
}
cleanup:
if (err != 0) {
free_berdata(ret);
ret = NULL;
}
return ret;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return((image->columns+7)/8);
else
return(image->columns*GetPSDPacketSize(image));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: StringPiece16::const_iterator findNonAlphaNumericAndNotInSet(const StringPiece16& str,
const StringPiece16& allowedChars) {
const auto endIter = str.end();
for (auto iter = str.begin(); iter != endIter; ++iter) {
char16_t c = *iter;
if ((c >= u'a' && c <= u'z') ||
(c >= u'A' && c <= u'Z') ||
(c >= u'0' && c <= u'9')) {
continue;
}
bool match = false;
for (char16_t i : allowedChars) {
if (c == i) {
match = true;
break;
}
}
if (!match) {
return iter;
}
}
return endIter;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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: ZEND_API void ZEND_FASTCALL _zend_hash_init(HashTable *ht, uint32_t nSize, dtor_func_t pDestructor, zend_bool persistent ZEND_FILE_LINE_DC)
{
GC_REFCOUNT(ht) = 1;
GC_TYPE_INFO(ht) = IS_ARRAY;
ht->u.flags = (persistent ? HASH_FLAG_PERSISTENT : 0) | HASH_FLAG_APPLY_PROTECTION | HASH_FLAG_STATIC_KEYS;
ht->nTableSize = zend_hash_check_size(nSize);
ht->nTableMask = HT_MIN_MASK;
HT_SET_DATA_ADDR(ht, &uninitialized_bucket);
ht->nNumUsed = 0;
ht->nNumOfElements = 0;
ht->nInternalPointer = HT_INVALID_IDX;
ht->nNextFreeElement = 0;
ht->pDestructor = pDestructor;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebContentsImpl::CreateNewWindow(
RenderFrameHost* opener,
int32_t render_view_route_id,
int32_t main_frame_route_id,
int32_t main_frame_widget_route_id,
const mojom::CreateNewWindowParams& params,
SessionStorageNamespace* session_storage_namespace) {
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_route_id == MSG_ROUTING_NONE));
DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE),
(main_frame_widget_route_id == MSG_ROUTING_NONE));
DCHECK(opener);
int render_process_id = opener->GetProcess()->GetID();
SiteInstance* source_site_instance = opener->GetSiteInstance();
DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id));
bool is_guest = BrowserPluginGuest::IsGuest(this);
DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE);
scoped_refptr<SiteInstance> site_instance =
params.opener_suppressed && !is_guest
? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url)
: source_site_instance;
const std::string& partition_id =
GetContentClient()->browser()->
GetStoragePartitionIdForSite(GetBrowserContext(),
site_instance->GetSiteURL());
StoragePartition* partition = BrowserContext::GetStoragePartition(
GetBrowserContext(), site_instance.get());
DOMStorageContextWrapper* dom_storage_context =
static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
SessionStorageNamespaceImpl* session_storage_namespace_impl =
static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
if (delegate_ &&
!delegate_->ShouldCreateWebContents(
this, opener, source_site_instance, render_view_route_id,
main_frame_route_id, main_frame_widget_route_id,
params.window_container_type, opener->GetLastCommittedURL(),
params.frame_name, params.target_url, partition_id,
session_storage_namespace)) {
RenderFrameHostImpl* rfh =
RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id);
if (rfh) {
DCHECK(rfh->IsRenderFrameLive());
rfh->Init();
}
return;
}
CreateParams create_params(GetBrowserContext(), site_instance.get());
create_params.routing_id = render_view_route_id;
create_params.main_frame_routing_id = main_frame_route_id;
create_params.main_frame_widget_routing_id = main_frame_widget_route_id;
create_params.main_frame_name = params.frame_name;
create_params.opener_render_process_id = render_process_id;
create_params.opener_render_frame_id = opener->GetRoutingID();
create_params.opener_suppressed = params.opener_suppressed;
if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB)
create_params.initially_hidden = true;
create_params.renderer_initiated_creation =
main_frame_route_id != MSG_ROUTING_NONE;
std::unique_ptr<WebContents> new_contents;
if (!is_guest) {
create_params.context = view_->GetNativeView();
create_params.initial_size = GetContainerBounds().size();
new_contents = WebContents::Create(create_params);
} else {
new_contents = base::WrapUnique(
GetBrowserPluginGuest()->CreateNewGuestWindow(create_params));
}
WebContentsImpl* raw_new_contents =
static_cast<WebContentsImpl*>(new_contents.get());
raw_new_contents->GetController().SetSessionStorageNamespace(
partition_id, session_storage_namespace);
if (!params.frame_name.empty())
raw_new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame();
if (!params.opener_suppressed) {
if (!is_guest) {
WebContentsView* new_view = raw_new_contents->view_.get();
new_view->CreateViewForWidget(
new_contents->GetRenderViewHost()->GetWidget(), false);
}
DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id);
pending_contents_[std::make_pair(render_process_id,
main_frame_widget_route_id)] =
std::move(new_contents);
AddDestructionObserver(raw_new_contents);
}
if (delegate_) {
delegate_->WebContentsCreated(this, render_process_id,
opener->GetRoutingID(), params.frame_name,
params.target_url, raw_new_contents);
}
if (opener) {
for (auto& observer : observers_) {
observer.DidOpenRequestedURL(raw_new_contents, opener, params.target_url,
params.referrer, params.disposition,
ui::PAGE_TRANSITION_LINK,
false, // started_from_context_menu
true); // renderer_initiated
}
}
if (IsFullscreenForCurrentTab())
ExitFullscreen(true);
if (params.opener_suppressed) {
bool was_blocked = false;
base::WeakPtr<WebContentsImpl> weak_new_contents =
raw_new_contents->weak_factory_.GetWeakPtr();
if (delegate_) {
gfx::Rect initial_rect;
delegate_->AddNewContents(this, std::move(new_contents),
params.disposition, initial_rect,
params.mimic_user_gesture, &was_blocked);
if (!weak_new_contents)
return; // The delegate deleted |new_contents| during AddNewContents().
}
if (!was_blocked) {
OpenURLParams open_params(params.target_url, params.referrer,
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_LINK,
true /* is_renderer_initiated */);
open_params.user_gesture = params.mimic_user_gesture;
if (delegate_ && !is_guest &&
!delegate_->ShouldResumeRequestsForCreatedWindow()) {
DCHECK(weak_new_contents);
weak_new_contents->delayed_open_url_params_.reset(
new OpenURLParams(open_params));
} else {
weak_new_contents->OpenURL(open_params);
}
}
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool DevToolsDataSource::ShouldAddContentSecurityPolicy() const {
return false;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code 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 double abserr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
{
/* Absolute error permitted in linear values - affected by the bit depth of
* the calculations.
*/
if (pm->assume_16_bit_calculations ||
(pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
return pm->maxabs16;
else
return pm->maxabs8;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int perf_trace_event_perm(struct ftrace_event_call *tp_event,
struct perf_event *p_event)
{
/* The ftrace function trace is allowed only for root. */
if (ftrace_event_is_function(tp_event) &&
perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
return -EPERM;
/* No tracing, just counting, so no obvious leak */
if (!(p_event->attr.sample_type & PERF_SAMPLE_RAW))
return 0;
/* Some events are ok to be traced by non-root users... */
if (p_event->attach_state == PERF_ATTACH_TASK) {
if (tp_event->flags & TRACE_EVENT_FL_CAP_ANY)
return 0;
}
/*
* ...otherwise raw tracepoint data can be a severe data leak,
* only allow root to have these.
*/
if (perf_paranoid_tracepoint_raw() && !capable(CAP_SYS_ADMIN))
return -EPERM;
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: xsltWithParamComp(xsltStylesheetPtr style, xmlNodePtr inst) {
#ifdef XSLT_REFACTORED
xsltStyleItemWithParamPtr comp;
#else
xsltStylePreCompPtr comp;
#endif
if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE))
return;
#ifdef XSLT_REFACTORED
comp = (xsltStyleItemWithParamPtr) xsltNewStylePreComp(style, XSLT_FUNC_WITHPARAM);
#else
comp = xsltNewStylePreComp(style, XSLT_FUNC_WITHPARAM);
#endif
if (comp == NULL)
return;
inst->psvi = comp;
comp->inst = inst;
/*
* Attribute "name".
*/
xsltGetQNameProperty(style, inst, BAD_CAST "name",
1, &(comp->has_name), &(comp->ns), &(comp->name));
if (comp->ns)
comp->has_ns = 1;
/*
* Attribute "select".
*/
comp->select = xsltGetCNsProp(style, inst, (const xmlChar *)"select",
XSLT_NAMESPACE);
if (comp->select != NULL) {
comp->comp = xsltXPathCompile(style, comp->select);
if (comp->comp == NULL) {
xsltTransformError(NULL, style, inst,
"XSLT-with-param: Failed to compile select "
"expression '%s'\n", comp->select);
style->errors++;
}
if (inst->children != NULL) {
xsltTransformError(NULL, style, inst,
"XSLT-with-param: The content should be empty since "
"the attribute select is present.\n");
style->warnings++;
}
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 power_pmu_setup(int cpu)
{
struct cpu_hw_events *cpuhw = &per_cpu(cpu_hw_events, cpu);
if (!ppmu)
return;
memset(cpuhw, 0, sizeof(*cpuhw));
cpuhw->mmcr[0] = MMCR0_FC;
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: my_object_objpath (MyObject *obj, const char *incoming, const char **outgoing, GError **error)
{
if (strcmp (incoming, "/org/freedesktop/DBus/GLib/Tests/MyTestObject"))
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"invalid incoming object");
return FALSE;
}
*outgoing = "/org/freedesktop/DBus/GLib/Tests/MyTestObject2";
return TRUE;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: SavePackage::SavePackage(WebContents* web_contents,
SavePageType save_type,
const FilePath& file_full_path,
const FilePath& directory_full_path)
: WebContentsObserver(web_contents),
file_manager_(NULL),
download_manager_(NULL),
download_(NULL),
page_url_(GetUrlToBeSaved()),
saved_main_file_path_(file_full_path),
saved_main_directory_path_(directory_full_path),
title_(web_contents->GetTitle()),
start_tick_(base::TimeTicks::Now()),
finished_(false),
mhtml_finishing_(false),
user_canceled_(false),
disk_error_occurred_(false),
save_type_(save_type),
all_save_items_count_(0),
file_name_set_(&FilePath::CompareLessIgnoreCase),
wait_state_(INITIALIZE),
contents_id_(web_contents->GetRenderProcessHost()->GetID()),
unique_id_(g_save_package_id++),
wrote_to_completed_file_(false),
wrote_to_failed_file_(false) {
DCHECK(page_url_.is_valid());
DCHECK((save_type_ == SAVE_PAGE_TYPE_AS_ONLY_HTML) ||
(save_type_ == SAVE_PAGE_TYPE_AS_MHTML) ||
(save_type_ == SAVE_PAGE_TYPE_AS_COMPLETE_HTML));
DCHECK(!saved_main_file_path_.empty() &&
saved_main_file_path_.value().length() <= kMaxFilePathLength);
DCHECK(!saved_main_directory_path_.empty() &&
saved_main_directory_path_.value().length() < kMaxFilePathLength);
InternalInit();
}
CWE ID:
Target: 0
Now analyze the following code 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 check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_insn *insn, int *insn_idx)
{
struct bpf_verifier_state *this_branch = env->cur_state;
struct bpf_verifier_state *other_branch;
struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
struct bpf_reg_state *dst_reg, *other_branch_regs;
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode > BPF_JSLE) {
verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
return -EINVAL;
}
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->src_reg);
return -EACCES;
}
} else {
if (insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg = ®s[insn->dst_reg];
if (BPF_SRC(insn->code) == BPF_K) {
int pred = is_branch_taken(dst_reg, insn->imm, opcode);
if (pred == 1) {
/* only follow the goto, ignore fall-through */
*insn_idx += insn->off;
return 0;
} else if (pred == 0) {
/* only follow fall-through branch, since
* that's where the program will go
*/
return 0;
}
}
other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
if (!other_branch)
return -EFAULT;
other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
/* detect if we are comparing against a constant value so we can adjust
* our min/max values for our dst register.
* this is only legit if both are scalars (or pointers to the same
* object, I suppose, but we don't support that right now), because
* otherwise the different base pointers mean the offsets aren't
* comparable.
*/
if (BPF_SRC(insn->code) == BPF_X) {
if (dst_reg->type == SCALAR_VALUE &&
regs[insn->src_reg].type == SCALAR_VALUE) {
if (tnum_is_const(regs[insn->src_reg].var_off))
reg_set_min_max(&other_branch_regs[insn->dst_reg],
dst_reg, regs[insn->src_reg].var_off.value,
opcode);
else if (tnum_is_const(dst_reg->var_off))
reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
®s[insn->src_reg],
dst_reg->var_off.value, opcode);
else if (opcode == BPF_JEQ || opcode == BPF_JNE)
/* Comparing for equality, we can combine knowledge */
reg_combine_min_max(&other_branch_regs[insn->src_reg],
&other_branch_regs[insn->dst_reg],
®s[insn->src_reg],
®s[insn->dst_reg], opcode);
}
} else if (dst_reg->type == SCALAR_VALUE) {
reg_set_min_max(&other_branch_regs[insn->dst_reg],
dst_reg, insn->imm, opcode);
}
/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
if (BPF_SRC(insn->code) == BPF_K &&
insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
reg_type_may_be_null(dst_reg->type)) {
/* Mark all identical registers in each branch as either
* safe or unknown depending R == 0 or R != 0 conditional.
*/
mark_ptr_or_null_regs(this_branch, insn->dst_reg,
opcode == BPF_JNE);
mark_ptr_or_null_regs(other_branch, insn->dst_reg,
opcode == BPF_JEQ);
} else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
this_branch, other_branch) &&
is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->dst_reg);
return -EACCES;
}
if (env->log.level)
print_verifier_state(env, this_branch->frame[this_branch->curframe]);
return 0;
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void watchdog_overflow_callback(struct perf_event *event, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
/* Ensure the watchdog never gets throttled */
event->hw.interrupts = 0;
if (__this_cpu_read(watchdog_nmi_touch) == true) {
__this_cpu_write(watchdog_nmi_touch, false);
return;
}
/* check for a hardlockup
* This is done by making sure our timer interrupt
* is incrementing. The timer interrupt should have
* fired multiple times before we overflow'd. If it hasn't
* then this is a good indication the cpu is stuck
*/
if (is_hardlockup()) {
int this_cpu = smp_processor_id();
/* only print hardlockups once */
if (__this_cpu_read(hard_watchdog_warn) == true)
return;
if (hardlockup_panic)
panic("Watchdog detected hard LOCKUP on cpu %d", this_cpu);
else
WARN(1, "Watchdog detected hard LOCKUP on cpu %d", this_cpu);
__this_cpu_write(hard_watchdog_warn, true);
return;
}
__this_cpu_write(hard_watchdog_warn, false);
return;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void k90_cleanup_backlight(struct hid_device *dev)
{
struct corsair_drvdata *drvdata = hid_get_drvdata(dev);
if (drvdata->backlight) {
drvdata->backlight->removed = true;
led_classdev_unregister(&drvdata->backlight->cdev);
cancel_work_sync(&drvdata->backlight->work);
kfree(drvdata->backlight->cdev.name);
kfree(drvdata->backlight);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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: PHP_FUNCTION( locale_get_keywords )
{
UEnumeration* e = NULL;
UErrorCode status = U_ZERO_ERROR;
const char* kw_key = NULL;
int32_t kw_key_len = 0;
const char* loc_name = NULL;
int loc_name_len = 0;
/*
ICU expects the buffer to be allocated before calling the function
and so the buffer size has been explicitly specified
ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100
hence the kw_value buffer size is 100
*/
char* kw_value = NULL;
int32_t kw_value_len = 100;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&loc_name, &loc_name_len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_get_keywords: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
/* Get the keywords */
e = uloc_openKeywords( loc_name, &status );
if( e != NULL )
{
/* Traverse it, filling the return array. */
array_init( return_value );
while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){
kw_value = ecalloc( 1 , kw_value_len );
/* Get the keyword value for each keyword */
kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status );
if (status == U_BUFFER_OVERFLOW_ERROR) {
status = U_ZERO_ERROR;
kw_value = erealloc( kw_value , kw_value_len+1);
kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status );
} else if(!U_FAILURE(status)) {
kw_value = erealloc( kw_value , kw_value_len+1);
}
if (U_FAILURE(status)) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC );
if( kw_value){
efree( kw_value );
}
zval_dtor(return_value);
RETURN_FALSE;
}
add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0);
} /* end of while */
} /* end of if e!=NULL */
uenum_close( e );
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PresentationConnectionProxy::OnClose() {
DCHECK(target_connection_ptr_);
source_connection_->didChangeState(
blink::WebPresentationConnectionState::Closed);
target_connection_ptr_->DidChangeState(
content::PRESENTATION_CONNECTION_STATE_CLOSED);
}
CWE ID:
Target: 1
Example 2:
Code: SYSCALL_DEFINE4(semctl, int, semid, int, semnum, int, cmd, unsigned long, arg)
{
int version;
struct ipc_namespace *ns;
void __user *p = (void __user *)arg;
if (semid < 0)
return -EINVAL;
version = ipc_parse_version(&cmd);
ns = current->nsproxy->ipc_ns;
switch(cmd) {
case IPC_INFO:
case SEM_INFO:
case IPC_STAT:
case SEM_STAT:
return semctl_nolock(ns, semid, cmd, version, p);
case GETALL:
case GETVAL:
case GETPID:
case GETNCNT:
case GETZCNT:
case SETALL:
return semctl_main(ns, semid, semnum, cmd, p);
case SETVAL:
return semctl_setval(ns, semid, semnum, arg);
case IPC_RMID:
case IPC_SET:
return semctl_down(ns, semid, cmd, version, p);
default:
return -EINVAL;
}
}
CWE ID: CWE-189
Target: 0
Now analyze the following code 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 tls1_process_ticket(SSL *s, unsigned char *session_id, int len,
const unsigned char *limit, SSL_SESSION **ret)
{
/* Point after session ID in client hello */
const unsigned char *p = session_id + len;
unsigned short i;
*ret = NULL;
s->tlsext_ticket_expected = 0;
/*
* If tickets disabled behave as if no ticket present to permit stateful
* resumption.
*/
if (SSL_get_options(s) & SSL_OP_NO_TICKET)
return 0;
if ((s->version <= SSL3_VERSION) || !limit)
return 0;
if (p >= limit)
return -1;
/* Skip past DTLS cookie */
if (SSL_IS_DTLS(s)) {
i = *(p++);
p += i;
if (p >= limit)
return -1;
}
/* Skip past cipher list */
n2s(p, i);
p += i;
if (p >= limit)
return -1;
/* Skip past compression algorithm list */
i = *(p++);
p += i;
if (p > limit)
return -1;
/* Now at start of extensions */
if ((p + 2) >= limit)
return 0;
n2s(p, i);
while ((p + 4) <= limit) {
unsigned short type, size;
n2s(p, type);
n2s(p, size);
if (p + size > limit)
return 0;
if (type == TLSEXT_TYPE_session_ticket) {
int r;
*/
s->tlsext_ticket_expected = 1;
return 1;
}
if (s->tls_session_secret_cb) {
/*
* Indicate that the ticket couldn't be decrypted rather than
* generating the session from ticket now, trigger
* abbreviated handshake based on external mechanism to
* calculate the master secret later.
*/
return 2;
}
r = tls_decrypt_ticket(s, p, size, session_id, len, ret);
switch (r) {
case 2: /* ticket couldn't be decrypted */
s->tlsext_ticket_expected = 1;
return 2;
case 3: /* ticket was decrypted */
return r;
case 4: /* ticket decrypted but need to renew */
s->tlsext_ticket_expected = 1;
return 3;
default: /* fatal error */
return -1;
}
}
p += size;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FrameSelection::SelectAll(SetSelectionBy set_selection_by) {
if (isHTMLSelectElement(GetDocument().FocusedElement())) {
HTMLSelectElement* select_element =
toHTMLSelectElement(GetDocument().FocusedElement());
if (select_element->CanSelectAll()) {
select_element->SelectAll();
return;
}
}
Node* root = nullptr;
Node* select_start_target = nullptr;
if (set_selection_by == SetSelectionBy::kUser && IsHidden()) {
root = GetDocument().documentElement();
select_start_target = GetDocument().body();
} else if (ComputeVisibleSelectionInDOMTree().IsContentEditable()) {
root = HighestEditableRoot(ComputeVisibleSelectionInDOMTree().Start());
if (Node* shadow_root = NonBoundaryShadowTreeRootNode(
ComputeVisibleSelectionInDOMTree().Start()))
select_start_target = shadow_root->OwnerShadowHost();
else
select_start_target = root;
} else {
root = NonBoundaryShadowTreeRootNode(
ComputeVisibleSelectionInDOMTree().Start());
if (root) {
select_start_target = root->OwnerShadowHost();
} else {
root = GetDocument().documentElement();
select_start_target = GetDocument().body();
}
}
if (!root || EditingIgnoresContent(*root))
return;
if (select_start_target) {
const Document& expected_document = GetDocument();
if (select_start_target->DispatchEvent(Event::CreateCancelableBubble(
EventTypeNames::selectstart)) != DispatchEventResult::kNotCanceled)
return;
if (!IsAvailable()) {
return;
}
if (!root->isConnected() || expected_document != root->GetDocument())
return;
}
SetSelection(SelectionInDOMTree::Builder()
.SelectAllChildren(*root)
.SetIsHandleVisible(IsHandleVisible())
.Build());
SelectFrameElementInParentIfFullySelected();
NotifyTextControlOfSelectionChange(SetSelectionBy::kUser);
if (IsHandleVisible()) {
ContextMenuAllowedScope scope;
frame_->GetEventHandler().ShowNonLocatedContextMenu(nullptr,
kMenuSourceTouch);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int pcrlock(const int pcrnum)
{
unsigned char hash[SHA1_DIGEST_SIZE];
int ret;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
ret = tpm_get_random(TPM_ANY_NUM, hash, SHA1_DIGEST_SIZE);
if (ret != SHA1_DIGEST_SIZE)
return ret;
return tpm_pcr_extend(TPM_ANY_NUM, pcrnum, hash) ? -EINVAL : 0;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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: SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
unsigned int, flags, struct sockaddr __user *, addr,
int, addr_len)
{
struct socket *sock;
struct sockaddr_storage address;
int err;
struct msghdr msg;
struct iovec iov;
int fput_needed;
if (len > INT_MAX)
len = INT_MAX;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
iov.iov_base = buff;
iov.iov_len = len;
msg.msg_name = NULL;
iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len);
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_namelen = 0;
if (addr) {
err = move_addr_to_kernel(addr, addr_len, &address);
if (err < 0)
goto out_put;
msg.msg_name = (struct sockaddr *)&address;
msg.msg_namelen = addr_len;
}
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
msg.msg_flags = flags;
err = sock_sendmsg(sock, &msg, len);
out_put:
fput_light(sock->file, fput_needed);
out:
return err;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: spnego_gss_init_sec_context(
OM_uint32 *minor_status,
gss_cred_id_t claimant_cred_handle,
gss_ctx_id_t *context_handle,
gss_name_t target_name,
gss_OID mech_type,
OM_uint32 req_flags,
OM_uint32 time_req,
gss_channel_bindings_t input_chan_bindings,
gss_buffer_t input_token,
gss_OID *actual_mech,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec)
{
send_token_flag send_token = NO_TOKEN_SEND;
OM_uint32 tmpmin, ret, negState;
gss_buffer_t mechtok_in, mechListMIC_in, mechListMIC_out;
gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER;
spnego_gss_cred_id_t spcred = NULL;
spnego_gss_ctx_id_t spnego_ctx = NULL;
dsyslog("Entering init_sec_context\n");
mechtok_in = mechListMIC_out = mechListMIC_in = GSS_C_NO_BUFFER;
negState = REJECT;
/*
* This function works in three steps:
*
* 1. Perform mechanism negotiation.
* 2. Invoke the negotiated or optimistic mech's gss_init_sec_context
* function and examine the results.
* 3. Process or generate MICs if necessary.
*
* The three steps share responsibility for determining when the
* exchange is complete. If the selected mech completed in a previous
* call and no MIC exchange is expected, then step 1 will decide. If
* the selected mech completes in this call and no MIC exchange is
* expected, then step 2 will decide. If a MIC exchange is expected,
* then step 3 will decide. If an error occurs in any step, the
* exchange will be aborted, possibly with an error token.
*
* negState determines the state of the negotiation, and is
* communicated to the acceptor if a continuing token is sent.
* send_token is used to indicate what type of token, if any, should be
* generated.
*/
/* Validate arguments. */
if (minor_status != NULL)
*minor_status = 0;
if (output_token != GSS_C_NO_BUFFER) {
output_token->length = 0;
output_token->value = NULL;
}
if (minor_status == NULL ||
output_token == GSS_C_NO_BUFFER ||
context_handle == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
if (actual_mech != NULL)
*actual_mech = GSS_C_NO_OID;
/* Step 1: perform mechanism negotiation. */
spcred = (spnego_gss_cred_id_t)claimant_cred_handle;
if (*context_handle == GSS_C_NO_CONTEXT) {
ret = init_ctx_new(minor_status, spcred,
context_handle, &send_token);
if (ret != GSS_S_CONTINUE_NEEDED) {
goto cleanup;
}
} else {
ret = init_ctx_cont(minor_status, context_handle,
input_token, &mechtok_in,
&mechListMIC_in, &negState, &send_token);
if (HARD_ERROR(ret)) {
goto cleanup;
}
}
/* Step 2: invoke the selected or optimistic mechanism's
* gss_init_sec_context function, if it didn't complete previously. */
spnego_ctx = (spnego_gss_ctx_id_t)*context_handle;
if (!spnego_ctx->mech_complete) {
ret = init_ctx_call_init(
minor_status, spnego_ctx, spcred,
target_name, req_flags,
time_req, mechtok_in,
actual_mech, &mechtok_out,
ret_flags, time_rec,
&negState, &send_token);
/* Give the mechanism a chance to force a mechlistMIC. */
if (!HARD_ERROR(ret) && mech_requires_mechlistMIC(spnego_ctx))
spnego_ctx->mic_reqd = 1;
}
/* Step 3: process or generate the MIC, if the negotiated mech is
* complete and supports MICs. */
if (!HARD_ERROR(ret) && spnego_ctx->mech_complete &&
(spnego_ctx->ctx_flags & GSS_C_INTEG_FLAG)) {
ret = handle_mic(minor_status,
mechListMIC_in,
(mechtok_out.length != 0),
spnego_ctx, &mechListMIC_out,
&negState, &send_token);
}
cleanup:
if (send_token == INIT_TOKEN_SEND) {
if (make_spnego_tokenInit_msg(spnego_ctx,
0,
mechListMIC_out,
req_flags,
&mechtok_out, send_token,
output_token) < 0) {
ret = GSS_S_FAILURE;
}
} else if (send_token != NO_TOKEN_SEND) {
if (make_spnego_tokenTarg_msg(negState, GSS_C_NO_OID,
&mechtok_out, mechListMIC_out,
send_token,
output_token) < 0) {
ret = GSS_S_FAILURE;
}
}
gss_release_buffer(&tmpmin, &mechtok_out);
if (ret == GSS_S_COMPLETE) {
/*
* Now, switch the output context to refer to the
* negotiated mechanism's context.
*/
*context_handle = (gss_ctx_id_t)spnego_ctx->ctx_handle;
if (actual_mech != NULL)
*actual_mech = spnego_ctx->actual_mech;
if (ret_flags != NULL)
*ret_flags = spnego_ctx->ctx_flags;
release_spnego_ctx(&spnego_ctx);
} else if (ret != GSS_S_CONTINUE_NEEDED) {
if (spnego_ctx != NULL) {
gss_delete_sec_context(&tmpmin,
&spnego_ctx->ctx_handle,
GSS_C_NO_BUFFER);
release_spnego_ctx(&spnego_ctx);
}
*context_handle = GSS_C_NO_CONTEXT;
}
if (mechtok_in != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mechtok_in);
free(mechtok_in);
}
if (mechListMIC_in != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mechListMIC_in);
free(mechListMIC_in);
}
if (mechListMIC_out != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mechListMIC_out);
free(mechListMIC_out);
}
return ret;
} /* init_sec_context */
CWE ID: CWE-18
Target: 1
Example 2:
Code: void RenderWidgetHostViewAura::OnWindowSurfaceChanged(
const cc::SurfaceInfo& surface_info) {
if (!is_guest_view_hack_)
return;
host_->GetView()->OnSurfaceChanged(surface_info);
}
CWE ID: CWE-254
Target: 0
Now analyze the following code 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 agraph_print_edge_dot(RANode *from, RANode *to, void *user) {
r_cons_printf ("\"%s\" -> \"%s\"\n", from->title, to->title);
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: feed_table_block_tag(struct table *tbl,
char *line, struct table_mode *mode, int indent, int cmd)
{
int offset;
if (mode->indent_level <= 0 && indent == -1)
return;
if (mode->indent_level >= CHAR_MAX && indent == 1)
return;
setwidth(tbl, mode);
feed_table_inline_tag(tbl, line, mode, -1);
clearcontentssize(tbl, mode);
if (indent == 1) {
mode->indent_level++;
if (mode->indent_level <= MAX_INDENT_LEVEL)
tbl->indent += INDENT_INCR;
}
else if (indent == -1) {
mode->indent_level--;
if (mode->indent_level < MAX_INDENT_LEVEL)
tbl->indent -= INDENT_INCR;
}
offset = tbl->indent;
if (cmd == HTML_DT) {
if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL)
offset -= INDENT_INCR;
}
if (tbl->indent > 0) {
check_minimum0(tbl, 0);
addcontentssize(tbl, offset);
}
}
CWE ID: CWE-835
Target: 1
Example 2:
Code: PHP_FUNCTION(sleep)
{
long num;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &num) == FAILURE) {
RETURN_FALSE;
}
if (num < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Number of seconds must be greater than or equal to 0");
RETURN_FALSE;
}
#ifdef PHP_SLEEP_NON_VOID
RETURN_LONG(php_sleep(num));
#else
php_sleep(num);
#endif
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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 might_fault(void)
{
/*
* Some code (nfs/sunrpc) uses socket ops on kernel memory while
* holding the mmap_sem, this is safe because kernel memory doesn't
* get paged out, therefore we'll never actually fault, and the
* below annotations will generate false positives.
*/
if (segment_eq(get_fs(), KERNEL_DS))
return;
might_sleep();
/*
* it would be nicer only to annotate paths which are not under
* pagefault_disable, however that requires a larger audit and
* providing helpers like get_user_atomic.
*/
if (!in_atomic() && current->mm)
might_lock_read(¤t->mm->mmap_sem);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and 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 ucma_process_join(struct ucma_file *file,
struct rdma_ucm_join_mcast *cmd, int out_len)
{
struct rdma_ucm_create_id_resp resp;
struct ucma_context *ctx;
struct ucma_multicast *mc;
struct sockaddr *addr;
int ret;
u8 join_state;
if (out_len < sizeof(resp))
return -ENOSPC;
addr = (struct sockaddr *) &cmd->addr;
if (cmd->addr_size != rdma_addr_size(addr))
return -EINVAL;
if (cmd->join_flags == RDMA_MC_JOIN_FLAG_FULLMEMBER)
join_state = BIT(FULLMEMBER_JOIN);
else if (cmd->join_flags == RDMA_MC_JOIN_FLAG_SENDONLY_FULLMEMBER)
join_state = BIT(SENDONLY_FULLMEMBER_JOIN);
else
return -EINVAL;
ctx = ucma_get_ctx_dev(file, cmd->id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
mutex_lock(&file->mut);
mc = ucma_alloc_multicast(ctx);
if (!mc) {
ret = -ENOMEM;
goto err1;
}
mc->join_state = join_state;
mc->uid = cmd->uid;
memcpy(&mc->addr, addr, cmd->addr_size);
ret = rdma_join_multicast(ctx->cm_id, (struct sockaddr *)&mc->addr,
join_state, mc);
if (ret)
goto err2;
resp.id = mc->id;
if (copy_to_user(u64_to_user_ptr(cmd->response),
&resp, sizeof(resp))) {
ret = -EFAULT;
goto err3;
}
mutex_unlock(&file->mut);
ucma_put_ctx(ctx);
return 0;
err3:
rdma_leave_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr);
ucma_cleanup_mc_events(mc);
err2:
mutex_lock(&mut);
idr_remove(&multicast_idr, mc->id);
mutex_unlock(&mut);
list_del(&mc->list);
kfree(mc);
err1:
mutex_unlock(&file->mut);
ucma_put_ctx(ctx);
return ret;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static JSON_INLINE void list_init(list_t *list)
{
list->next = list;
list->prev = list;
}
CWE ID: CWE-310
Target: 0
Now analyze the following code 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 FileBrowserPrivateGetDownloadUrlFunction::OnTokenFetched(
google_apis::GDataErrorCode code,
const std::string& access_token) {
if (code != google_apis::HTTP_SUCCESS) {
SetError("Not able to fetch the token.");
SetResult(new base::StringValue("")); // Intentionally returns a blank.
SendResponse(false);
return;
}
const std::string url = download_url_ + "?access_token=" + access_token;
SetResult(new base::StringValue(url));
SendResponse(true);
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DevToolsUI::DevToolsUI(content::WebUI* web_ui)
: WebUIController(web_ui),
bindings_(web_ui->GetWebContents()) {
web_ui->SetBindings(0);
Profile* profile = Profile::FromWebUI(web_ui);
content::URLDataSource::Add(
profile,
new DevToolsDataSource(profile->GetRequestContext()));
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: person_obstructed_at(const person_t* person, double x, double y, person_t** out_obstructing_person, int* out_tile_index)
{
rect_t area;
rect_t base, my_base;
double cur_x, cur_y;
bool is_obstructed = false;
int layer;
const obsmap_t* obsmap;
int tile_w, tile_h;
const tileset_t* tileset;
int i, i_x, i_y;
map_normalize_xy(&x, &y, person->layer);
person_get_xyz(person, &cur_x, &cur_y, &layer, true);
my_base = rect_translate(person_base(person), x - cur_x, y - cur_y);
if (out_obstructing_person != NULL)
*out_obstructing_person = NULL;
if (out_tile_index != NULL)
*out_tile_index = -1;
if (!person->ignore_all_persons) {
for (i = 0; i < s_num_persons; ++i) {
if (s_persons[i] == person) // these persons aren't going to obstruct themselves!
continue;
if (s_persons[i]->layer != layer)
continue; // ignore persons not on the same layer
if (person_following(s_persons[i], person))
continue; // ignore own followers
base = person_base(s_persons[i]);
if (do_rects_overlap(my_base, base) && !person_ignored_by(person, s_persons[i])) {
is_obstructed = true;
if (out_obstructing_person)
*out_obstructing_person = s_persons[i];
break;
}
}
}
obsmap = layer_obsmap(layer);
if (obsmap_test_rect(obsmap, my_base))
is_obstructed = true;
if (!person->ignore_all_tiles) {
tileset = map_tileset();
tileset_get_size(tileset, &tile_w, &tile_h);
area.x1 = my_base.x1 / tile_w;
area.y1 = my_base.y1 / tile_h;
area.x2 = area.x1 + (my_base.x2 - my_base.x1) / tile_w + 2;
area.y2 = area.y1 + (my_base.y2 - my_base.y1) / tile_h + 2;
for (i_x = area.x1; i_x < area.x2; ++i_x) for (i_y = area.y1; i_y < area.y2; ++i_y) {
base = rect_translate(my_base, -(i_x * tile_w), -(i_y * tile_h));
obsmap = tileset_obsmap(tileset, map_tile_at(i_x, i_y, layer));
if (obsmap != NULL && obsmap_test_rect(obsmap, base)) {
is_obstructed = true;
if (out_tile_index)
*out_tile_index = map_tile_at(i_x, i_y, layer);
break;
}
}
}
return is_obstructed;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code 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: mojo::PendingRemote<mojom::InputChannel> CreatePendingRemote() {
return receiver_.BindNewPipeAndPassRemote();
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void StartSync(const StartSyncArgs& args,
OneClickSigninSyncStarter::StartSyncMode start_mode) {
if (start_mode == OneClickSigninSyncStarter::UNDO_SYNC) {
LogOneClickHistogramValue(one_click_signin::HISTOGRAM_UNDO);
return;
}
OneClickSigninSyncStarter::ConfirmationRequired confirmation =
args.confirmation_required;
if (start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST &&
confirmation == OneClickSigninSyncStarter::CONFIRM_UNTRUSTED_SIGNIN) {
confirmation = OneClickSigninSyncStarter::CONFIRM_AFTER_SIGNIN;
}
new OneClickSigninSyncStarter(args.profile, args.browser, args.session_index,
args.email, args.password, start_mode,
args.force_same_tab_navigation,
confirmation);
int action = one_click_signin::HISTOGRAM_MAX;
switch (args.auto_accept) {
case OneClickSigninHelper::AUTO_ACCEPT_EXPLICIT:
break;
case OneClickSigninHelper::AUTO_ACCEPT_ACCEPTED:
action =
start_mode == OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS ?
one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS :
one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
action = one_click_signin::HISTOGRAM_AUTO_WITH_DEFAULTS;
break;
case OneClickSigninHelper::AUTO_ACCEPT_CONFIGURE:
DCHECK(start_mode == OneClickSigninSyncStarter::CONFIGURE_SYNC_FIRST);
action = one_click_signin::HISTOGRAM_AUTO_WITH_ADVANCED;
break;
default:
NOTREACHED() << "Invalid auto_accept: " << args.auto_accept;
break;
}
if (action != one_click_signin::HISTOGRAM_MAX)
LogOneClickHistogramValue(action);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static ssize_t proc_pid_attr_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
char *page;
ssize_t length;
struct task_struct *task = get_proc_task(inode);
length = -ESRCH;
if (!task)
goto out_no_task;
if (count > PAGE_SIZE)
count = PAGE_SIZE;
/* No partial writes. */
length = -EINVAL;
if (*ppos != 0)
goto out;
length = -ENOMEM;
page = (char*)__get_free_page(GFP_TEMPORARY);
if (!page)
goto out;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out_free;
/* Guard against adverse ptrace interaction */
length = mutex_lock_interruptible(&task->cred_guard_mutex);
if (length < 0)
goto out_free;
length = security_setprocattr(task,
(char*)file->f_path.dentry->d_name.name,
(void*)page, count);
mutex_unlock(&task->cred_guard_mutex);
out_free:
free_page((unsigned long) page);
out:
put_task_struct(task);
out_no_task:
return length;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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: ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
struct ofpbuf *msg,
bool flow_age_extension,
struct ofpbuf *ofpacts)
{
const struct ofp_header *oh;
size_t instructions_len;
enum ofperr error;
enum ofpraw raw;
error = (msg->header ? ofpraw_decode(&raw, msg->header)
: ofpraw_pull(&raw, msg));
if (error) {
return error;
}
oh = msg->header;
if (!msg->size) {
return EOF;
} else if (raw == OFPRAW_OFPST11_FLOW_REPLY
|| raw == OFPRAW_OFPST13_FLOW_REPLY) {
const struct ofp11_flow_stats *ofs;
size_t length;
uint16_t padded_match_len;
ofs = ofpbuf_try_pull(msg, sizeof *ofs);
if (!ofs) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %"PRIu32" leftover "
"bytes at end", msg->size);
return EINVAL;
}
length = ntohs(ofs->length);
if (length < sizeof *ofs) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
"length %"PRIuSIZE, length);
return EINVAL;
}
if (ofputil_pull_ofp11_match(msg, NULL, NULL, &fs->match,
&padded_match_len)) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad match");
return EINVAL;
}
instructions_len = length - sizeof *ofs - padded_match_len;
fs->priority = ntohs(ofs->priority);
fs->table_id = ofs->table_id;
fs->duration_sec = ntohl(ofs->duration_sec);
fs->duration_nsec = ntohl(ofs->duration_nsec);
fs->idle_timeout = ntohs(ofs->idle_timeout);
fs->hard_timeout = ntohs(ofs->hard_timeout);
if (oh->version >= OFP14_VERSION) {
fs->importance = ntohs(ofs->importance);
} else {
fs->importance = 0;
}
if (raw == OFPRAW_OFPST13_FLOW_REPLY) {
error = ofputil_decode_flow_mod_flags(ofs->flags, -1, oh->version,
&fs->flags);
if (error) {
return error;
}
} else {
fs->flags = 0;
}
fs->idle_age = -1;
fs->hard_age = -1;
fs->cookie = ofs->cookie;
fs->packet_count = ntohll(ofs->packet_count);
fs->byte_count = ntohll(ofs->byte_count);
} else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
const struct ofp10_flow_stats *ofs;
size_t length;
ofs = ofpbuf_try_pull(msg, sizeof *ofs);
if (!ofs) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %"PRIu32" leftover "
"bytes at end", msg->size);
return EINVAL;
}
length = ntohs(ofs->length);
if (length < sizeof *ofs) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
"length %"PRIuSIZE, length);
return EINVAL;
}
instructions_len = length - sizeof *ofs;
fs->cookie = get_32aligned_be64(&ofs->cookie);
ofputil_match_from_ofp10_match(&ofs->match, &fs->match);
fs->priority = ntohs(ofs->priority);
fs->table_id = ofs->table_id;
fs->duration_sec = ntohl(ofs->duration_sec);
fs->duration_nsec = ntohl(ofs->duration_nsec);
fs->idle_timeout = ntohs(ofs->idle_timeout);
fs->hard_timeout = ntohs(ofs->hard_timeout);
fs->importance = 0;
fs->idle_age = -1;
fs->hard_age = -1;
fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
fs->flags = 0;
} else if (raw == OFPRAW_NXST_FLOW_REPLY) {
const struct nx_flow_stats *nfs;
size_t match_len, length;
nfs = ofpbuf_try_pull(msg, sizeof *nfs);
if (!nfs) {
VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %"PRIu32" leftover "
"bytes at end", msg->size);
return EINVAL;
}
length = ntohs(nfs->length);
match_len = ntohs(nfs->match_len);
if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%"PRIuSIZE" "
"claims invalid length %"PRIuSIZE, match_len, length);
return EINVAL;
}
if (nx_pull_match(msg, match_len, &fs->match, NULL, NULL, NULL,
NULL)) {
return EINVAL;
}
instructions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
fs->cookie = nfs->cookie;
fs->table_id = nfs->table_id;
fs->duration_sec = ntohl(nfs->duration_sec);
fs->duration_nsec = ntohl(nfs->duration_nsec);
fs->priority = ntohs(nfs->priority);
fs->idle_timeout = ntohs(nfs->idle_timeout);
fs->hard_timeout = ntohs(nfs->hard_timeout);
fs->importance = 0;
fs->idle_age = -1;
fs->hard_age = -1;
if (flow_age_extension) {
if (nfs->idle_age) {
fs->idle_age = ntohs(nfs->idle_age) - 1;
}
if (nfs->hard_age) {
fs->hard_age = ntohs(nfs->hard_age) - 1;
}
}
fs->packet_count = ntohll(nfs->packet_count);
fs->byte_count = ntohll(nfs->byte_count);
fs->flags = 0;
} else {
OVS_NOT_REACHED();
}
if (ofpacts_pull_openflow_instructions(msg, instructions_len, oh->version,
NULL, NULL, ofpacts)) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad instructions");
return EINVAL;
}
fs->ofpacts = ofpacts->data;
fs->ofpacts_len = ofpacts->size;
return 0;
}
CWE ID: CWE-617
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Status XvMCGetDRInfo(Display *dpy, XvPortID port,
char **name, char **busID,
int *major, int *minor,
int *patchLevel,
int *isLocal)
{
XExtDisplayInfo *info = xvmc_find_display(dpy);
xvmcGetDRInfoReply rep;
xvmcGetDRInfoReq *req;
CARD32 magic;
#ifdef HAVE_SHMAT
volatile CARD32 *shMem;
struct timezone here;
struct timeval now;
here.tz_minuteswest = 0;
here.tz_dsttime = 0;
#endif
*name = NULL;
*busID = NULL;
XvMCCheckExtension (dpy, info, BadImplementation);
LockDisplay (dpy);
XvMCGetReq (GetDRInfo, req);
req->port = port;
magic = 0;
req->magic = 0;
#ifdef HAVE_SHMAT
req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600);
/*
* We fill a shared memory page with a repetitive pattern. If the
* X server can read this pattern, we probably have a local connection.
* Note that we can trigger the remote X server to read any shared
* page on the remote machine, so we shouldn't be able to guess and verify
* any complicated data on those pages. Thats the explanation of this
* otherwise stupid-looking pattern algorithm.
*/
if (req->shmKey >= 0) {
shMem = (CARD32 *) shmat(req->shmKey, NULL, 0);
shmctl( req->shmKey, IPC_RMID, NULL);
if ( shMem ) {
register volatile CARD32 *shMemC = shMem;
register int i;
gettimeofday( &now, &here);
magic = now.tv_usec & 0x000FFFFF;
req->magic = magic;
i = 1024 / sizeof(CARD32);
while(i--) {
*shMemC++ = magic;
magic = ~magic;
}
} else {
req->shmKey = -1;
}
}
#else
req->shmKey = 0;
#endif
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) {
UnlockDisplay (dpy);
SyncHandle ();
#ifdef HAVE_SHMAT
if ( req->shmKey >= 0) {
shmdt( (const void *) shMem );
}
#endif
return -1;
}
#ifdef HAVE_SHMAT
shmdt( (const void *) shMem );
#endif
if (rep.length > 0) {
unsigned long realSize = 0;
char *tmpBuf = NULL;
if ((rep.length < (INT_MAX >> 2)) &&
/* protect against overflow in strncpy below */
(rep.nameLen + rep.busIDLen > rep.nameLen)) {
realSize = rep.length << 2;
if (realSize >= (rep.nameLen + rep.busIDLen)) {
tmpBuf = Xmalloc(realSize);
*name = Xmalloc(rep.nameLen);
*busID = Xmalloc(rep.busIDLen);
}
}
if (*name && *busID && tmpBuf) {
_XRead(dpy, tmpBuf, realSize);
strncpy(*name,tmpBuf,rep.nameLen);
(*name)[rep.nameLen - 1] = '\0';
strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen);
(*busID)[rep.busIDLen - 1] = '\0';
XFree(tmpBuf);
} else {
XFree(*name);
*name = NULL;
XFree(*busID);
*busID = NULL;
XFree(tmpBuf);
_XEatDataWords(dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return -1;
}
}
UnlockDisplay (dpy);
SyncHandle ();
*major = rep.major;
*minor = rep.minor;
*patchLevel = rep.patchLevel;
*isLocal = (req->shmKey > 0) ? rep.isLocal : 1;
return (rep.length > 0) ? Success : BadImplementation;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void DevToolsWindow::OnLoadCompleted() {
WebContents* inspected_web_contents = GetInspectedWebContents();
if (inspected_web_contents) {
SessionTabHelper* session_tab_helper =
SessionTabHelper::FromWebContents(inspected_web_contents);
if (session_tab_helper) {
base::Value tabId(session_tab_helper->session_id().id());
bindings_->CallClientFunction("DevToolsAPI.setInspectedTabId",
&tabId, NULL, NULL);
}
}
if (life_stage_ == kClosing)
return;
if (life_stage_ != kLoadCompleted) {
life_stage_ = life_stage_ == kIsDockedSet ? kLoadCompleted : kOnLoadFired;
}
if (life_stage_ == kLoadCompleted)
LoadCompleted();
}
CWE ID: CWE-668
Target: 0
Now analyze the following code 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 mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index)
{
struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table;
int i, err = 0;
int free = -1;
mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac);
mutex_lock(&table->mutex);
for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) {
if (free < 0 && !table->refs[i]) {
free = i;
continue;
}
if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) {
/* MAC already registered, increase refernce count */
*index = i;
++table->refs[i];
goto out;
}
}
mlx4_dbg(dev, "Free MAC index is %d\n", free);
if (table->total == table->max) {
/* No free mac entries */
err = -ENOSPC;
goto out;
}
/* Register new MAC */
table->refs[free] = 1;
table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID);
err = mlx4_set_port_mac_table(dev, port, table->entries);
if (unlikely(err)) {
mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac);
table->refs[free] = 0;
table->entries[free] = 0;
goto out;
}
*index = free;
++table->total;
out:
mutex_unlock(&table->mutex);
return err;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintWebViewHelper::OnPrintPreview(const base::DictionaryValue& settings) {
print_preview_context_.OnPrintPreview();
UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent",
PREVIEW_EVENT_REQUESTED, PREVIEW_EVENT_MAX);
if (!print_preview_context_.source_frame()) {
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (!UpdatePrintSettings(print_preview_context_.source_frame(),
print_preview_context_.source_node(), settings)) {
if (print_preview_context_.last_error() != PREVIEW_ERROR_BAD_SETTING) {
Send(new PrintHostMsg_PrintPreviewInvalidPrinterSettings(
routing_id(), print_pages_params_
? print_pages_params_->params.document_cookie
: 0));
notify_browser_of_print_failure_ = false; // Already sent.
}
DidFinishPrinting(FAIL_PREVIEW);
return;
}
if (print_pages_params_->params.is_first_request &&
!print_preview_context_.IsModifiable()) {
PrintHostMsg_SetOptionsFromDocument_Params options;
if (SetOptionsFromPdfDocument(&options))
Send(new PrintHostMsg_SetOptionsFromDocument(routing_id(), options));
}
is_print_ready_metafile_sent_ = false;
print_pages_params_->params.supports_alpha_blend = true;
bool generate_draft_pages = false;
if (!settings.GetBoolean(kSettingGenerateDraftData, &generate_draft_pages)) {
NOTREACHED();
}
print_preview_context_.set_generate_draft_pages(generate_draft_pages);
PrepareFrameForPreviewDocument();
}
CWE ID:
Target: 1
Example 2:
Code: void infoCommand(client *c) {
char *section = c->argc == 2 ? c->argv[1]->ptr : "default";
if (c->argc > 2) {
addReply(c,shared.syntaxerr);
return;
}
addReplyBulkSds(c, genRedisInfoString(section));
}
CWE ID: CWE-254
Target: 0
Now analyze the following code 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 ~StubbornSpellCheckClient() { }
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: size_t jsvGetString(const JsVar *v, char *str, size_t len) {
assert(len>0);
const char *s = jsvGetConstString(v);
if (s) {
/* don't use strncpy here because we don't
* want to pad the entire buffer with zeros */
len--;
int l = 0;
while (*s && l<len) {
str[l] = s[l];
l++;
}
str[l] = 0;
return l;
} else if (jsvIsInt(v)) {
itostr(v->varData.integer, str, 10);
return strlen(str);
} else if (jsvIsFloat(v)) {
ftoa_bounded(v->varData.floating, str, len);
return strlen(str);
} else if (jsvHasCharacterData(v)) {
assert(!jsvIsStringExt(v));
size_t l = len;
JsvStringIterator it;
jsvStringIteratorNewConst(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (l--<=1) {
*str = 0;
jsvStringIteratorFree(&it);
return len;
}
*(str++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
*str = 0;
return len-l;
} else {
JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here
if (stringVar) {
size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var
jsvUnLock(stringVar);
return l;
} else {
str[0] = 0;
jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
return 0;
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void nested_svm_unmap(struct page *page)
{
kunmap(page);
kvm_release_page_dirty(page);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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_echo_variant (MyObject *obj, GValue *variant, GValue *ret, GError **error)
{
GType t;
t = G_VALUE_TYPE(variant);
g_value_init (ret, t);
g_value_copy (variant, ret);
return TRUE;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void perf_event_interrupt(struct pt_regs *regs)
{
int i;
struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
struct perf_event *event;
unsigned long val;
int found = 0;
int nmi;
if (cpuhw->n_limited)
freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5),
mfspr(SPRN_PMC6));
perf_read_regs(regs);
nmi = perf_intr_is_nmi(regs);
if (nmi)
nmi_enter();
else
irq_enter();
for (i = 0; i < cpuhw->n_events; ++i) {
event = cpuhw->event[i];
if (!event->hw.idx || is_limited_pmc(event->hw.idx))
continue;
val = read_pmc(event->hw.idx);
if ((int)val < 0) {
/* event has overflowed */
found = 1;
record_and_restart(event, val, regs, nmi);
}
}
/*
* In case we didn't find and reset the event that caused
* the interrupt, scan all events and reset any that are
* negative, to avoid getting continual interrupts.
* Any that we processed in the previous loop will not be negative.
*/
if (!found) {
for (i = 0; i < ppmu->n_counter; ++i) {
if (is_limited_pmc(i + 1))
continue;
val = read_pmc(i + 1);
if (pmc_overflow(val))
write_pmc(i + 1, 0);
}
}
/*
* Reset MMCR0 to its normal value. This will set PMXE and
* clear FC (freeze counters) and PMAO (perf mon alert occurred)
* and thus allow interrupts to occur again.
* XXX might want to use MSR.PM to keep the events frozen until
* we get back out of this interrupt.
*/
write_mmcr0(cpuhw, cpuhw->mmcr[0]);
if (nmi)
nmi_exit();
else
irq_exit();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void TranslateInfoBarDelegate::GetAfterTranslateStrings(
std::vector<base::string16>* strings,
bool* swap_languages,
bool autodetermined_source_language) {
DCHECK(strings);
if (autodetermined_source_language) {
size_t offset;
base::string16 text = l10n_util::GetStringFUTF16(
IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE_AUTODETERMINED_SOURCE_LANGUAGE,
base::string16(),
&offset);
strings->push_back(text.substr(0, offset));
strings->push_back(text.substr(offset));
return;
}
DCHECK(swap_languages);
std::vector<size_t> offsets;
base::string16 text = l10n_util::GetStringFUTF16(
IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE, base::string16(), base::string16(),
&offsets);
DCHECK_EQ(2U, offsets.size());
*swap_languages = (offsets[0] > offsets[1]);
if (*swap_languages)
std::swap(offsets[0], offsets[1]);
strings->push_back(text.substr(0, offsets[0]));
strings->push_back(text.substr(offsets[0], offsets[1] - offsets[0]));
strings->push_back(text.substr(offsets[1]));
}
CWE ID: CWE-362
Target: 0
Now analyze the following code 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: HRESULT CGaiaCredentialBase::UnAdvise(void) {
LOGFN(INFO);
events_.Release();
return S_OK;
}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: DefragTimeoutTest(void)
{
int i;
int ret = 0;
/* Setup a small numberr of trackers. */
if (ConfSet("defrag.trackers", "16") != 1) {
printf("ConfSet failed: ");
goto end;
}
DefragInit();
/* Load in 16 packets. */
for (i = 0; i < 16; i++) {
Packet *p = BuildTestPacket(i, 0, 1, 'A' + i, 16);
if (p == NULL)
goto end;
Packet *tp = Defrag(NULL, NULL, p, NULL);
SCFree(p);
if (tp != NULL) {
SCFree(tp);
goto end;
}
}
/* Build a new packet but push the timestamp out by our timeout.
* This should force our previous fragments to be timed out. */
Packet *p = BuildTestPacket(99, 0, 1, 'A' + i, 16);
if (p == NULL)
goto end;
p->ts.tv_sec += (defrag_context->timeout + 1);
Packet *tp = Defrag(NULL, NULL, p, NULL);
if (tp != NULL) {
SCFree(tp);
goto end;
}
DefragTracker *tracker = DefragLookupTrackerFromHash(p);
if (tracker == NULL)
goto end;
if (tracker->id != 99)
goto end;
SCFree(p);
ret = 1;
end:
DefragDestroy();
return ret;
}
CWE ID: CWE-358
Target: 1
Example 2:
Code: DEFINE_TRACE(Document)
{
#if ENABLE(OILPAN)
visitor->trace(m_importsController);
visitor->trace(m_docType);
visitor->trace(m_implementation);
visitor->trace(m_autofocusElement);
visitor->trace(m_focusedElement);
visitor->trace(m_hoverNode);
visitor->trace(m_activeHoverElement);
visitor->trace(m_documentElement);
visitor->trace(m_titleElement);
visitor->trace(m_axObjectCache);
visitor->trace(m_markers);
visitor->trace(m_cssTarget);
visitor->trace(m_currentScriptStack);
visitor->trace(m_scriptRunner);
visitor->trace(m_listsInvalidatedAtDocument);
for (int i = 0; i < numNodeListInvalidationTypes; ++i)
visitor->trace(m_nodeLists[i]);
visitor->trace(m_cssCanvasElements);
visitor->trace(m_topLayerElements);
visitor->trace(m_elemSheet);
visitor->trace(m_nodeIterators);
visitor->trace(m_ranges);
visitor->trace(m_styleEngine);
visitor->trace(m_formController);
visitor->trace(m_visitedLinkState);
visitor->trace(m_frame);
visitor->trace(m_domWindow);
visitor->trace(m_fetcher);
visitor->trace(m_parser);
visitor->trace(m_contextFeatures);
visitor->trace(m_styleSheetList);
visitor->trace(m_documentTiming);
visitor->trace(m_mediaQueryMatcher);
visitor->trace(m_scriptedAnimationController);
visitor->trace(m_scriptedIdleTaskController);
visitor->trace(m_taskRunner);
visitor->trace(m_textAutosizer);
visitor->trace(m_registrationContext);
visitor->trace(m_customElementMicrotaskRunQueue);
visitor->trace(m_elementDataCache);
visitor->trace(m_associatedFormControls);
visitor->trace(m_useElementsNeedingUpdate);
visitor->trace(m_layerUpdateSVGFilterElements);
visitor->trace(m_timers);
visitor->trace(m_templateDocument);
visitor->trace(m_templateDocumentHost);
visitor->trace(m_visibilityObservers);
visitor->trace(m_userActionElements);
visitor->trace(m_svgExtensions);
visitor->trace(m_timeline);
visitor->trace(m_compositorPendingAnimations);
visitor->trace(m_contextDocument);
visitor->trace(m_canvasFontCache);
WillBeHeapSupplementable<Document>::trace(visitor);
#endif
TreeScope::trace(visitor);
ContainerNode::trace(visitor);
ExecutionContext::trace(visitor);
DocumentLifecycleNotifier::trace(visitor);
SecurityContext::trace(visitor);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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 WebContentsImpl::NotifyManifestUrlChanged(
const base::Optional<GURL>& manifest_url) {
for (auto& observer : observers_)
observer.DidUpdateWebManifestURL(manifest_url);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool snd_ctl_remove_numid_conflict(struct snd_card *card,
unsigned int count)
{
struct snd_kcontrol *kctl;
list_for_each_entry(kctl, &card->controls, list) {
if (kctl->id.numid < card->last_numid + 1 + count &&
kctl->id.numid + kctl->count > card->last_numid + 1) {
card->last_numid = kctl->id.numid + kctl->count - 1;
return true;
}
}
return false;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void ip_cmsg_recv_fragsize(struct msghdr *msg, struct sk_buff *skb)
{
int val;
if (IPCB(skb)->frag_max_size == 0)
return;
val = IPCB(skb)->frag_max_size;
put_cmsg(msg, SOL_IP, IP_RECVFRAGSIZE, sizeof(val), &val);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code 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 init_once(void *foo)
{
struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
inode_init_once(&ei->vfs_inode);
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ExtensionWebContentsObserver::RenderViewCreated(
content::RenderViewHost* render_view_host) {
const Extension* extension = GetExtension(render_view_host);
if (!extension)
return;
content::RenderProcessHost* process = render_view_host->GetProcess();
if (type == Manifest::TYPE_EXTENSION ||
type == Manifest::TYPE_LEGACY_PACKAGED_APP ||
(type == Manifest::TYPE_PLATFORM_APP &&
extension->location() == Manifest::COMPONENT)) {
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
process->GetID(), content::kChromeUIScheme);
}
if (type == Manifest::TYPE_EXTENSION ||
type == Manifest::TYPE_LEGACY_PACKAGED_APP) {
ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context_);
if (prefs->AllowFileAccess(extension->id())) {
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
process->GetID(), url::kFileScheme);
}
}
render_view_host->Send(new ExtensionMsg_ActivateExtension(extension->id()));
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep,
bool modify, bool restore)
{
const struct usb_endpoint_descriptor *desc = dep->endpoint.desc;
struct dwc3 *dwc = dep->dwc;
u32 reg;
int ret;
if (!(dep->flags & DWC3_EP_ENABLED)) {
ret = dwc3_gadget_start_config(dwc, dep);
if (ret)
return ret;
}
ret = dwc3_gadget_set_ep_config(dwc, dep, modify, restore);
if (ret)
return ret;
if (!(dep->flags & DWC3_EP_ENABLED)) {
struct dwc3_trb *trb_st_hw;
struct dwc3_trb *trb_link;
dep->type = usb_endpoint_type(desc);
dep->flags |= DWC3_EP_ENABLED;
dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
reg |= DWC3_DALEPENA_EP(dep->number);
dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
init_waitqueue_head(&dep->wait_end_transfer);
if (usb_endpoint_xfer_control(desc))
goto out;
/* Initialize the TRB ring */
dep->trb_dequeue = 0;
dep->trb_enqueue = 0;
memset(dep->trb_pool, 0,
sizeof(struct dwc3_trb) * DWC3_TRB_NUM);
/* Link TRB. The HWO bit is never reset */
trb_st_hw = &dep->trb_pool[0];
trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
}
/*
* Issue StartTransfer here with no-op TRB so we can always rely on No
* Response Update Transfer command.
*/
if (usb_endpoint_xfer_bulk(desc)) {
struct dwc3_gadget_ep_cmd_params params;
struct dwc3_trb *trb;
dma_addr_t trb_dma;
u32 cmd;
memset(¶ms, 0, sizeof(params));
trb = &dep->trb_pool[0];
trb_dma = dwc3_trb_dma_offset(dep, trb);
params.param0 = upper_32_bits(trb_dma);
params.param1 = lower_32_bits(trb_dma);
cmd = DWC3_DEPCMD_STARTTRANSFER;
ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
if (ret < 0)
return ret;
dep->flags |= DWC3_EP_BUSY;
dep->resource_index = dwc3_gadget_ep_get_transfer_index(dep);
WARN_ON_ONCE(!dep->resource_index);
}
out:
trace_dwc3_gadget_ep_enable(dep);
return 0;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code 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 netdev_features_t dflt_features_check(const struct sk_buff *skb,
struct net_device *dev,
netdev_features_t features)
{
return vlan_features_check(skb, features);
}
CWE ID: CWE-400
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
AVFilterContext *ctx = inlink->dst;
LutContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
AVFrame *out;
uint8_t *inrow, *outrow, *inrow0, *outrow0;
int i, j, plane, direct = 0;
if (av_frame_is_writable(in)) {
direct = 1;
out = in;
} else {
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
}
if (s->is_rgb) {
/* packed */
inrow0 = in ->data[0];
outrow0 = out->data[0];
for (i = 0; i < in->height; i ++) {
int w = inlink->w;
const uint8_t (*tab)[256] = (const uint8_t (*)[256])s->lut;
inrow = inrow0;
outrow = outrow0;
for (j = 0; j < w; j++) {
switch (s->step) {
case 4: outrow[3] = tab[3][inrow[3]]; // Fall-through
case 3: outrow[2] = tab[2][inrow[2]]; // Fall-through
case 2: outrow[1] = tab[1][inrow[1]]; // Fall-through
default: outrow[0] = tab[0][inrow[0]];
}
outrow += s->step;
inrow += s->step;
}
inrow0 += in ->linesize[0];
outrow0 += out->linesize[0];
}
} else {
/* planar */
for (plane = 0; plane < 4 && in->data[plane]; plane++) {
int vsub = plane == 1 || plane == 2 ? s->vsub : 0;
int hsub = plane == 1 || plane == 2 ? s->hsub : 0;
int h = FF_CEIL_RSHIFT(inlink->h, vsub);
int w = FF_CEIL_RSHIFT(inlink->w, hsub);
inrow = in ->data[plane];
outrow = out->data[plane];
for (i = 0; i < h; i++) {
const uint8_t *tab = s->lut[plane];
for (j = 0; j < w; j++)
outrow[j] = tab[inrow[j]];
inrow += in ->linesize[plane];
outrow += out->linesize[plane];
}
}
}
if (!direct)
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
RenderWidgetHostViewBase* view = GetViewForAccessibility();
if (view &&
!browser_accessibility_manager_ &&
!no_create_browser_accessibility_manager_for_testing_) {
bool is_root_frame = !frame_tree_node()->parent();
browser_accessibility_manager_.reset(
view->CreateBrowserAccessibilityManager(this, is_root_frame));
}
return browser_accessibility_manager_.get();
}
CWE ID: CWE-254
Target: 0
Now analyze the following code 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: size_t ZSTD_compress_generic (ZSTD_CCtx* cctx,
ZSTD_outBuffer* output,
ZSTD_inBuffer* input,
ZSTD_EndDirective endOp)
{
DEBUGLOG(5, "ZSTD_compress_generic, endOp=%u ", (U32)endOp);
/* check conditions */
if (output->pos > output->size) return ERROR(GENERIC);
if (input->pos > input->size) return ERROR(GENERIC);
assert(cctx!=NULL);
/* transparent initialization stage */
if (cctx->streamStage == zcss_init) {
ZSTD_CCtx_params params = cctx->requestedParams;
ZSTD_prefixDict const prefixDict = cctx->prefixDict;
memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */
assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */
DEBUGLOG(4, "ZSTD_compress_generic : transparent init stage");
if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = input->size + 1; /* auto-fix pledgedSrcSize */
params.cParams = ZSTD_getCParamsFromCCtxParams(
&cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1, 0 /*dictSize*/);
#ifdef ZSTD_MULTITHREAD
if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
}
if (params.nbWorkers > 0) {
/* mt context creation */
if (cctx->mtctx == NULL) {
DEBUGLOG(4, "ZSTD_compress_generic: creating new mtctx for nbWorkers=%u",
params.nbWorkers);
cctx->mtctx = ZSTDMT_createCCtx_advanced(params.nbWorkers, cctx->customMem);
if (cctx->mtctx == NULL) return ERROR(memory_allocation);
}
/* mt compression */
DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
CHECK_F( ZSTDMT_initCStream_internal(
cctx->mtctx,
prefixDict.dict, prefixDict.dictSize, ZSTD_dct_rawContent,
cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) );
cctx->streamStage = zcss_load;
cctx->appliedParams.nbWorkers = params.nbWorkers;
} else
#endif
{ CHECK_F( ZSTD_resetCStream_internal(cctx,
prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
cctx->cdict,
params, cctx->pledgedSrcSizePlusOne-1) );
assert(cctx->streamStage == zcss_load);
assert(cctx->appliedParams.nbWorkers == 0);
} }
/* compression stage */
#ifdef ZSTD_MULTITHREAD
if (cctx->appliedParams.nbWorkers > 0) {
if (cctx->cParamsChanged) {
ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
cctx->cParamsChanged = 0;
}
{ size_t const flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
if ( ZSTD_isError(flushMin)
|| (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
ZSTD_CCtx_reset(cctx);
}
DEBUGLOG(5, "completed ZSTD_compress_generic delegating to ZSTDMT_compressStream_generic");
return flushMin;
} }
#endif
CHECK_F( ZSTD_compressStream_generic(cctx, output, input, endOp) );
DEBUGLOG(5, "completed ZSTD_compress_generic");
return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int get_bitmap_file(struct mddev *mddev, void __user * arg)
{
mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
char *ptr;
int err;
file = kmalloc(sizeof(*file), GFP_NOIO);
if (!file)
return -ENOMEM;
err = 0;
spin_lock(&mddev->lock);
/* bitmap disabled, zero the first byte and copy out */
if (!mddev->bitmap_info.file)
file->pathname[0] = '\0';
else if ((ptr = file_path(mddev->bitmap_info.file,
file->pathname, sizeof(file->pathname))),
IS_ERR(ptr))
err = PTR_ERR(ptr);
else
memmove(file->pathname, ptr,
sizeof(file->pathname)-(ptr-file->pathname));
spin_unlock(&mddev->lock);
if (err == 0 &&
copy_to_user(arg, file, sizeof(*file)))
err = -EFAULT;
kfree(file);
return err;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, unsigned int optlen)
{
struct sctp_rtoinfo rtoinfo;
struct sctp_association *asoc;
if (optlen != sizeof (struct sctp_rtoinfo))
return -EINVAL;
if (copy_from_user(&rtoinfo, optval, optlen))
return -EFAULT;
asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
/* Set the values to the specific association */
if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
if (asoc) {
if (rtoinfo.srto_initial != 0)
asoc->rto_initial =
msecs_to_jiffies(rtoinfo.srto_initial);
if (rtoinfo.srto_max != 0)
asoc->rto_max = msecs_to_jiffies(rtoinfo.srto_max);
if (rtoinfo.srto_min != 0)
asoc->rto_min = msecs_to_jiffies(rtoinfo.srto_min);
} else {
/* If there is no association or the association-id = 0
* set the values to the endpoint.
*/
struct sctp_sock *sp = sctp_sk(sk);
if (rtoinfo.srto_initial != 0)
sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
if (rtoinfo.srto_max != 0)
sp->rtoinfo.srto_max = rtoinfo.srto_max;
if (rtoinfo.srto_min != 0)
sp->rtoinfo.srto_min = rtoinfo.srto_min;
}
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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 lba512_t lba512_muldiv(lba512_t block_count, lba512_t mul_by, int div_by)
{
lba512_t bc_quot, bc_rem;
/* x * m / d == x / d * m + (x % d) * m / d */
bc_quot = block_count >> div_by;
bc_rem = block_count - (bc_quot << div_by);
return bc_quot * mul_by + ((bc_rem * mul_by) >> div_by);
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GDataCache::Pin(const std::string& resource_id,
const std::string& md5,
FileOperationType file_operation_type,
base::PlatformFileError* error) {
AssertOnSequencedWorkerPool();
DCHECK(error);
FilePath source_path;
FilePath dest_path;
FilePath symlink_path;
bool create_symlink = true;
int cache_state = CACHE_STATE_PINNED;
CacheSubDirectoryType sub_dir_type = CACHE_TYPE_PERSISTENT;
scoped_ptr<CacheEntry> cache_entry = GetCacheEntry(resource_id, md5);
if (!cache_entry.get()) { // Entry does not exist in cache.
dest_path = FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull);
source_path = dest_path;
sub_dir_type = CACHE_TYPE_PINNED;
} else { // File exists in cache, determines destination path.
cache_state |= cache_entry->cache_state;
if (cache_entry->IsDirty() || cache_entry->IsMounted()) {
DCHECK_EQ(CACHE_TYPE_PERSISTENT, cache_entry->sub_dir_type);
dest_path = GetCacheFilePath(resource_id,
md5,
cache_entry->sub_dir_type,
CACHED_FILE_LOCALLY_MODIFIED);
source_path = dest_path;
} else {
source_path = GetCacheFilePath(resource_id,
md5,
cache_entry->sub_dir_type,
CACHED_FILE_FROM_SERVER);
if (cache_entry->sub_dir_type == CACHE_TYPE_PINNED) {
dest_path = source_path;
create_symlink = false;
} else { // File exists, move it to persistent dir.
dest_path = GetCacheFilePath(resource_id,
md5,
CACHE_TYPE_PERSISTENT,
CACHED_FILE_FROM_SERVER);
}
}
}
if (create_symlink) {
symlink_path = GetCacheFilePath(resource_id,
std::string(),
CACHE_TYPE_PINNED,
CACHED_FILE_FROM_SERVER);
}
*error = ModifyCacheState(source_path,
dest_path,
file_operation_type,
symlink_path,
create_symlink);
if (*error == base::PLATFORM_FILE_OK) {
metadata_->UpdateCache(resource_id, md5, sub_dir_type, cache_state);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: dissect_spoolss_printer_enum_values(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree,
dcerpc_info *di, guint8 *drep)
{
guint32 start_offset = offset;
guint32 name_offset, name_len, val_offset, val_len, val_type;
char *name;
proto_item *item;
proto_tree *subtree;
/* Get offset of value name */
offset = dissect_ndr_uint32(
tvb, offset, pinfo, NULL, di, drep,
hf_enumprinterdataex_name_offset, &name_offset);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, NULL, di, drep,
hf_enumprinterdataex_name_len, &name_len);
dissect_spoolss_uint16uni(
tvb, start_offset + name_offset, pinfo, NULL, drep,
&name, hf_enumprinterdataex_name);
subtree = proto_tree_add_subtree_format(tree, tvb, offset, 0, ett_printer_enumdataex_value, &item, "Name: %s", name);
proto_tree_add_uint(subtree, hf_enumprinterdataex_name_offset, tvb, offset - 8, 4, name_offset);
proto_tree_add_uint(subtree, hf_enumprinterdataex_name_len, tvb, offset - 4, 4, name_len);
proto_tree_add_string( subtree, hf_enumprinterdataex_name, tvb, start_offset + name_offset, ((int)strlen(name) + 1) * 2, name);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep, hf_printerdata_type,
&val_type);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_enumprinterdataex_val_offset, &val_offset);
offset = dissect_ndr_uint32(
tvb, offset, pinfo, subtree, di, drep,
hf_enumprinterdataex_val_len, &val_len);
if (val_len == 0) {
proto_tree_add_uint_format_value(subtree, hf_enumprinterdataex_value_null, tvb, start_offset + val_offset, 4, 0, "(null)");
goto done;
}
switch(val_type) {
case DCERPC_REG_DWORD: {
guint32 value;
guint16 low, high;
int offset2 = start_offset + val_offset;
/* Needs to be broken into two 16-byte ints because it may
not be aligned. */
offset2 = dissect_ndr_uint16(
tvb, offset2, pinfo, subtree, di, drep,
hf_enumprinterdataex_val_dword_low, &low);
/*offset2 = */dissect_ndr_uint16(
tvb, offset2, pinfo, subtree, di, drep,
hf_enumprinterdataex_val_dword_high, &high);
value = (high << 16) | low;
proto_tree_add_uint(subtree, hf_enumprinterdataex_value_uint, tvb, start_offset + val_offset, 4, value);
proto_item_append_text(item, ", Value: %d", value);
break;
}
case DCERPC_REG_SZ: {
char *value;
dissect_spoolss_uint16uni(
tvb, start_offset + val_offset, pinfo, subtree, drep,
&value, hf_value_string);
proto_item_append_text(item, ", Value: %s", value);
g_free(value);
break;
}
case DCERPC_REG_BINARY:
/* FIXME: nicer way to display this */
proto_tree_add_bytes_format_value( subtree, hf_enumprinterdataex_value_binary, tvb, start_offset + val_offset, val_len, NULL, "<binary data>");
break;
case DCERPC_REG_MULTI_SZ:
/* FIXME: implement REG_MULTI_SZ support */
proto_tree_add_bytes_format_value(subtree, hf_enumprinterdataex_value_multi_sz, tvb, start_offset + val_offset, val_len, NULL, "<REG_MULTI_SZ not implemented>");
break;
default:
proto_tree_add_expert_format( subtree, pinfo, &ei_enumprinterdataex_value, tvb, start_offset + val_offset, val_len, "%s: unknown type %d", name, val_type);
}
done:
g_free(name);
return offset;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code 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: ScriptPromise VRDisplay::exitPresent(ScriptState* script_state) {
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (!is_presenting_) {
DOMException* exception = DOMException::Create(
kInvalidStateError, "VRDisplay is not presenting.");
resolver->Reject(exception);
return promise;
}
if (!display_) {
DOMException* exception =
DOMException::Create(kInvalidStateError, "VRService is not available.");
resolver->Reject(exception);
return promise;
}
display_->ExitPresent();
resolver->Resolve();
StopPresenting();
return promise;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t Camera3Device::createDefaultRequest(int templateId,
CameraMetadata *request) {
ATRACE_CALL();
ALOGV("%s: for template %d", __FUNCTION__, templateId);
Mutex::Autolock il(mInterfaceLock);
Mutex::Autolock l(mLock);
switch (mStatus) {
case STATUS_ERROR:
CLOGE("Device has encountered a serious error");
return INVALID_OPERATION;
case STATUS_UNINITIALIZED:
CLOGE("Device is not initialized!");
return INVALID_OPERATION;
case STATUS_UNCONFIGURED:
case STATUS_CONFIGURED:
case STATUS_ACTIVE:
break;
default:
SET_ERR_L("Unexpected status: %d", mStatus);
return INVALID_OPERATION;
}
if (!mRequestTemplateCache[templateId].isEmpty()) {
*request = mRequestTemplateCache[templateId];
return OK;
}
const camera_metadata_t *rawRequest;
ATRACE_BEGIN("camera3->construct_default_request_settings");
rawRequest = mHal3Device->ops->construct_default_request_settings(
mHal3Device, templateId);
ATRACE_END();
if (rawRequest == NULL) {
ALOGI("%s: template %d is not supported on this camera device",
__FUNCTION__, templateId);
return BAD_VALUE;
}
*request = rawRequest;
mRequestTemplateCache[templateId] = rawRequest;
return OK;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool LayerTreeHostImpl::EvictedUIResourcesExist() const {
return !evicted_ui_resources_.empty();
}
CWE ID: CWE-362
Target: 0
Now analyze the following code 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: server_input_global_request(int type, u_int32_t seq, void *ctxt)
{
char *rtype;
int want_reply;
int r, success = 0, allocated_listen_port = 0;
struct sshbuf *resp = NULL;
rtype = packet_get_string(NULL);
want_reply = packet_get_char();
debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
/* -R style forwarding */
if (strcmp(rtype, "tcpip-forward") == 0) {
struct passwd *pw;
struct Forward fwd;
pw = the_authctxt->pw;
if (pw == NULL || !the_authctxt->valid)
fatal("server_input_global_request: no/invalid user");
memset(&fwd, 0, sizeof(fwd));
fwd.listen_host = packet_get_string(NULL);
fwd.listen_port = (u_short)packet_get_int();
debug("server_input_global_request: tcpip-forward listen %s port %d",
fwd.listen_host, fwd.listen_port);
/* check permissions */
if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
no_port_forwarding_flag || options.disable_forwarding ||
(!want_reply && fwd.listen_port == 0) ||
(fwd.listen_port != 0 &&
!bind_permitted(fwd.listen_port, pw->pw_uid))) {
success = 0;
packet_send_debug("Server has disabled port forwarding.");
} else {
/* Start listening on the port */
success = channel_setup_remote_fwd_listener(&fwd,
&allocated_listen_port, &options.fwd_opts);
}
free(fwd.listen_host);
if ((resp = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new", __func__);
if (allocated_listen_port != 0 &&
(r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
} else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_host = packet_get_string(NULL);
fwd.listen_port = (u_short)packet_get_int();
debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
fwd.listen_host, fwd.listen_port);
success = channel_cancel_rport_listener(&fwd);
free(fwd.listen_host);
} else if (strcmp(rtype, "[email protected]") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_path = packet_get_string(NULL);
debug("server_input_global_request: streamlocal-forward listen path %s",
fwd.listen_path);
/* check permissions */
if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
|| no_port_forwarding_flag || options.disable_forwarding) {
success = 0;
packet_send_debug("Server has disabled port forwarding.");
} else {
/* Start listening on the socket */
success = channel_setup_remote_fwd_listener(
&fwd, NULL, &options.fwd_opts);
}
free(fwd.listen_path);
} else if (strcmp(rtype, "[email protected]") == 0) {
struct Forward fwd;
memset(&fwd, 0, sizeof(fwd));
fwd.listen_path = packet_get_string(NULL);
debug("%s: cancel-streamlocal-forward path %s", __func__,
fwd.listen_path);
success = channel_cancel_rport_listener(&fwd);
free(fwd.listen_path);
} else if (strcmp(rtype, "[email protected]") == 0) {
no_more_sessions = 1;
success = 1;
} else if (strcmp(rtype, "[email protected]") == 0) {
success = server_input_hostkeys_prove(&resp);
}
if (want_reply) {
packet_start(success ?
SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
if (success && resp != NULL)
ssh_packet_put_raw(active_state, sshbuf_ptr(resp),
sshbuf_len(resp));
packet_send();
packet_write_wait();
}
free(rtype);
sshbuf_free(resp);
return 0;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t CameraService::dump(int fd, const Vector<String16>& args) {
String8 result;
if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
result.appendFormat("Permission Denial: "
"can't dump CameraService from pid=%d, uid=%d\n",
getCallingPid(),
getCallingUid());
write(fd, result.string(), result.size());
} else {
bool locked = tryLock(mServiceLock);
if (!locked) {
result.append("CameraService may be deadlocked\n");
write(fd, result.string(), result.size());
}
bool hasClient = false;
if (!mModule) {
result = String8::format("No camera module available!\n");
write(fd, result.string(), result.size());
return NO_ERROR;
}
result = String8::format("Camera module HAL API version: 0x%x\n",
mModule->common.hal_api_version);
result.appendFormat("Camera module API version: 0x%x\n",
mModule->common.module_api_version);
result.appendFormat("Camera module name: %s\n",
mModule->common.name);
result.appendFormat("Camera module author: %s\n",
mModule->common.author);
result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
write(fd, result.string(), result.size());
for (int i = 0; i < mNumberOfCameras; i++) {
result = String8::format("Camera %d static information:\n", i);
camera_info info;
status_t rc = mModule->get_camera_info(i, &info);
if (rc != OK) {
result.appendFormat(" Error reading static information!\n");
write(fd, result.string(), result.size());
} else {
result.appendFormat(" Facing: %s\n",
info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
result.appendFormat(" Orientation: %d\n", info.orientation);
int deviceVersion;
if (mModule->common.module_api_version <
CAMERA_MODULE_API_VERSION_2_0) {
deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
} else {
deviceVersion = info.device_version;
}
result.appendFormat(" Device version: 0x%x\n", deviceVersion);
if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
result.appendFormat(" Device static metadata:\n");
write(fd, result.string(), result.size());
dump_indented_camera_metadata(info.static_camera_characteristics,
fd, 2, 4);
} else {
write(fd, result.string(), result.size());
}
}
sp<BasicClient> client = mClient[i].promote();
if (client == 0) {
result = String8::format(" Device is closed, no client instance\n");
write(fd, result.string(), result.size());
continue;
}
hasClient = true;
result = String8::format(" Device is open. Client instance dump:\n");
write(fd, result.string(), result.size());
client->dump(fd, args);
}
if (!hasClient) {
result = String8::format("\nNo active camera clients yet.\n");
write(fd, result.string(), result.size());
}
if (locked) mServiceLock.unlock();
write(fd, "\n", 1);
camera3::CameraTraces::dump(fd, args);
int n = args.size();
for (int i = 0; i + 1 < n; i++) {
String16 verboseOption("-v");
if (args[i] == verboseOption) {
String8 levelStr(args[i+1]);
int level = atoi(levelStr.string());
result = String8::format("\nSetting log level to %d.\n", level);
setLogLevel(level);
write(fd, result.string(), result.size());
}
}
}
return NO_ERROR;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void AppCacheUpdateJob::NotifySingleHost(AppCacheHost* host,
AppCacheEventID event_id) {
std::vector<int> ids(1, host->host_id());
host->frontend()->OnEventRaised(ids, event_id);
}
CWE ID:
Target: 0
Now analyze the following code 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 Initialized(mojo::ScopedSharedBufferHandle shared_buffer,
mojo::ScopedHandle socket_handle,
bool initially_muted) {
ASSERT_TRUE(shared_buffer.is_valid());
ASSERT_TRUE(socket_handle.is_valid());
base::PlatformFile fd;
mojo::UnwrapPlatformFile(std::move(socket_handle), &fd);
socket_ = std::make_unique<base::CancelableSyncSocket>(fd);
EXPECT_NE(socket_->handle(), base::CancelableSyncSocket::kInvalidHandle);
size_t memory_length;
base::SharedMemoryHandle shmem_handle;
bool read_only;
EXPECT_EQ(
mojo::UnwrapSharedMemoryHandle(std::move(shared_buffer), &shmem_handle,
&memory_length, &read_only),
MOJO_RESULT_OK);
EXPECT_TRUE(read_only);
buffer_ = std::make_unique<base::SharedMemory>(shmem_handle, read_only);
GotNotification(initially_muted);
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: call_bind_status(struct rpc_task *task)
{
int status = -EIO;
if (task->tk_status >= 0) {
dprint_status(task);
task->tk_status = 0;
task->tk_action = call_connect;
return;
}
switch (task->tk_status) {
case -ENOMEM:
dprintk("RPC: %5u rpcbind out of memory\n", task->tk_pid);
rpc_delay(task, HZ >> 2);
goto retry_timeout;
case -EACCES:
dprintk("RPC: %5u remote rpcbind: RPC program/version "
"unavailable\n", task->tk_pid);
/* fail immediately if this is an RPC ping */
if (task->tk_msg.rpc_proc->p_proc == 0) {
status = -EOPNOTSUPP;
break;
}
rpc_delay(task, 3*HZ);
goto retry_timeout;
case -ETIMEDOUT:
dprintk("RPC: %5u rpcbind request timed out\n",
task->tk_pid);
goto retry_timeout;
case -EPFNOSUPPORT:
/* server doesn't support any rpcbind version we know of */
dprintk("RPC: %5u unrecognized remote rpcbind service\n",
task->tk_pid);
break;
case -EPROTONOSUPPORT:
dprintk("RPC: %5u remote rpcbind version unavailable, retrying\n",
task->tk_pid);
task->tk_status = 0;
task->tk_action = call_bind;
return;
case -ECONNREFUSED: /* connection problems */
case -ECONNRESET:
case -ENOTCONN:
case -EHOSTDOWN:
case -EHOSTUNREACH:
case -ENETUNREACH:
case -EPIPE:
dprintk("RPC: %5u remote rpcbind unreachable: %d\n",
task->tk_pid, task->tk_status);
if (!RPC_IS_SOFTCONN(task)) {
rpc_delay(task, 5*HZ);
goto retry_timeout;
}
status = task->tk_status;
break;
default:
dprintk("RPC: %5u unrecognized rpcbind error (%d)\n",
task->tk_pid, -task->tk_status);
}
rpc_exit(task, status);
return;
retry_timeout:
task->tk_action = call_timeout;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void V8TestObject::OverloadedMethodIMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_overloadedMethodI");
test_object_v8_internal::OverloadedMethodIMethod(info);
}
CWE ID:
Target: 0
Now analyze the following code 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 ipv4_redirect(struct sk_buff *skb, struct net *net,
int oif, u32 mark, u8 protocol, int flow_flags)
{
const struct iphdr *iph = (const struct iphdr *) skb->data;
struct flowi4 fl4;
struct rtable *rt;
__build_flow_key(&fl4, NULL, iph, oif,
RT_TOS(iph->tos), protocol, mark, flow_flags);
rt = __ip_route_output_key(net, &fl4);
if (!IS_ERR(rt)) {
__ip_do_redirect(rt, skb, &fl4, false);
ip_rt_put(rt);
}
}
CWE ID: CWE-17
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadRAWImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*canvas_image,
*image;
MagickBooleanType
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
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);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
/*
Create virtual canvas to support cropping (i.e. image.gray[100x100+10+20]).
*/
canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse,
exception);
(void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod);
quantum_type=GrayQuantum;
quantum_info=AcquireQuantumInfo(image_info,canvas_image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
if (image_info->number_scenes != 0)
while (image->scene < image_info->scene)
{
/*
Skip to next image.
*/
image->scene++;
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
break;
}
}
scene=0;
count=0;
length=0;
do
{
/*
Read pixels to virtual canvas image then push to image.
*/
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene == 0)
{
length=GetQuantumExtent(canvas_image,quantum_info,quantum_type);
count=ReadBlob(image,length,pixels);
}
for (y=0; y < (ssize_t) image->extract_info.height; y++)
{
register const PixelPacket
*restrict p;
register PixelPacket
*restrict q;
register ssize_t
x;
if (count != (ssize_t) length)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
length=ImportQuantumPixels(canvas_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse)
break;
if (((y-image->extract_info.y) >= 0) &&
((y-image->extract_info.y) < (ssize_t) image->rows))
{
p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0,
image->columns,1,exception);
q=QueueAuthenticPixels(image,0,y-image->extract_info.y,image->columns,
1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelRed(p));
SetPixelGreen(q,GetPixelGreen(p));
SetPixelBlue(q,GetPixelBlue(p));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
count=ReadBlob(image,length,pixels);
}
SetQuantumImageType(image,quantum_type);
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (count == (ssize_t) length)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
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;
}
scene++;
} while (count == (ssize_t) length);
quantum_info=DestroyQuantumInfo(quantum_info);
InheritException(&image->exception,&canvas_image->exception);
canvas_image=DestroyImage(canvas_image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int InputHandler::selectionStart() const
{
return selectionPosition(true);
}
CWE ID:
Target: 0
Now analyze the following code 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: DomainReliabilityClearMode last_clear_mode() const {
return mock_service_->last_clear_mode();
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: uint64 Clipboard::GetSequenceNumber(Buffer buffer) {
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: static inline struct crypto_ccm_req_priv_ctx *crypto_ccm_reqctx(
struct aead_request *req)
{
unsigned long align = crypto_aead_alignmask(crypto_aead_reqtfm(req));
return (void *)PTR_ALIGN((u8 *)aead_request_ctx(req), align + 1);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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 SharedMemory::Create(const SharedMemoryCreateOptions& options) {
DCHECK(!options.executable);
DCHECK(!mapped_file_);
if (options.size == 0)
return false;
uint32 rounded_size = (options.size + 0xffff) & ~0xffff;
name_ = ASCIIToWide(options.name == NULL ? "" : *options.name);
mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size),
name_.empty() ? NULL : name_.c_str());
if (!mapped_file_)
return false;
created_size_ = options.size;
if (GetLastError() == ERROR_ALREADY_EXISTS) {
created_size_ = 0;
if (!options.open_existing) {
Close();
return false;
}
}
return true;
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and 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_nal_unit(iv_obj_t *dec_hdl,
ivd_video_decode_op_t *ps_dec_op,
UWORD8 *pu1_buf,
UWORD32 u4_length)
{
dec_bit_stream_t *ps_bitstrm;
dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle;
ivd_video_decode_ip_t *ps_dec_in =
(ivd_video_decode_ip_t *)ps_dec->pv_dec_in;
dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice;
UWORD8 u1_first_byte, u1_nal_ref_idc;
UWORD8 u1_nal_unit_type;
WORD32 i_status = OK;
ps_bitstrm = ps_dec->ps_bitstrm;
if(pu1_buf)
{
if(u4_length)
{
ps_dec_op->u4_frame_decoded_flag = 0;
ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf,
u4_length);
SWITCHOFFTRACE;
u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8);
if(NAL_FORBIDDEN_BIT(u1_first_byte))
{
H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n");
}
u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte);
ps_dec->u1_nal_unit_type = u1_nal_unit_type;
u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte));
switch(u1_nal_unit_type)
{
case SLICE_DATA_PARTITION_A_NAL:
case SLICE_DATA_PARTITION_B_NAL:
case SLICE_DATA_PARTITION_C_NAL:
if(!ps_dec->i4_decode_header)
ih264d_parse_slice_partition(ps_dec, ps_bitstrm);
break;
case IDR_SLICE_NAL:
case SLICE_NAL:
/* ! */
DEBUG_THREADS_PRINTF("Decoding a slice NAL\n");
if(!ps_dec->i4_decode_header)
{
if(ps_dec->i4_header_decoded == 3)
{
/* ! */
ps_dec->u4_slice_start_code_found = 1;
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_decode_slice(
(UWORD8)(u1_nal_unit_type
== IDR_SLICE_NAL),
u1_nal_ref_idc, ps_dec);
if((ps_dec->u4_first_slice_in_pic != 0)&&
((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0))
{
/* if the first slice header was not valid set to 1 */
ps_dec->u4_first_slice_in_pic = 1;
}
if(i_status != OK)
{
return i_status;
}
}
else
{
H264_DEC_DEBUG_PRINT(
"\nSlice NAL Supplied but no header has been supplied\n");
}
}
break;
case SEI_NAL:
if(!ps_dec->i4_decode_header)
{
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm);
if(i_status != OK)
return i_status;
ih264d_parse_sei(ps_dec, ps_bitstrm);
}
break;
case SEQ_PARAM_NAL:
/* ! */
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_sps(ps_dec, ps_bitstrm);
if(i_status == ERROR_INV_SPS_PPS_T)
return i_status;
if(!i_status)
ps_dec->i4_header_decoded |= 0x1;
break;
case PIC_PARAM_NAL:
/* ! */
ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm);
i_status = ih264d_parse_pps(ps_dec, ps_bitstrm);
if(i_status == ERROR_INV_SPS_PPS_T)
return i_status;
if(!i_status)
ps_dec->i4_header_decoded |= 0x2;
break;
case ACCESS_UNIT_DELIMITER_RBSP:
if(!ps_dec->i4_decode_header)
{
ih264d_access_unit_delimiter_rbsp(ps_dec);
}
break;
case END_OF_STREAM_RBSP:
if(!ps_dec->i4_decode_header)
{
ih264d_parse_end_of_stream(ps_dec);
}
break;
case FILLER_DATA_NAL:
if(!ps_dec->i4_decode_header)
{
ih264d_parse_filler_data(ps_dec, ps_bitstrm);
}
break;
default:
H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type);
break;
}
}
}
return i_status;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void hub_event(struct work_struct *work)
{
struct usb_device *hdev;
struct usb_interface *intf;
struct usb_hub *hub;
struct device *hub_dev;
u16 hubstatus;
u16 hubchange;
int i, ret;
hub = container_of(work, struct usb_hub, events);
hdev = hub->hdev;
hub_dev = hub->intfdev;
intf = to_usb_interface(hub_dev);
dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
hdev->state, hdev->maxchild,
/* NOTE: expects max 15 ports... */
(u16) hub->change_bits[0],
(u16) hub->event_bits[0]);
/* Lock the device, then check to see if we were
* disconnected while waiting for the lock to succeed. */
usb_lock_device(hdev);
if (unlikely(hub->disconnected))
goto out_hdev_lock;
/* If the hub has died, clean up after it */
if (hdev->state == USB_STATE_NOTATTACHED) {
hub->error = -ENODEV;
hub_quiesce(hub, HUB_DISCONNECT);
goto out_hdev_lock;
}
/* Autoresume */
ret = usb_autopm_get_interface(intf);
if (ret) {
dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
goto out_hdev_lock;
}
/* If this is an inactive hub, do nothing */
if (hub->quiescing)
goto out_autopm;
if (hub->error) {
dev_dbg(hub_dev, "resetting for error %d\n", hub->error);
ret = usb_reset_device(hdev);
if (ret) {
dev_dbg(hub_dev, "error resetting hub: %d\n", ret);
goto out_autopm;
}
hub->nerrors = 0;
hub->error = 0;
}
/* deal with port status changes */
for (i = 1; i <= hdev->maxchild; i++) {
struct usb_port *port_dev = hub->ports[i - 1];
if (test_bit(i, hub->event_bits)
|| test_bit(i, hub->change_bits)
|| test_bit(i, hub->wakeup_bits)) {
/*
* The get_noresume and barrier ensure that if
* the port was in the process of resuming, we
* flush that work and keep the port active for
* the duration of the port_event(). However,
* if the port is runtime pm suspended
* (powered-off), we leave it in that state, run
* an abbreviated port_event(), and move on.
*/
pm_runtime_get_noresume(&port_dev->dev);
pm_runtime_barrier(&port_dev->dev);
usb_lock_port(port_dev);
port_event(hub, i);
usb_unlock_port(port_dev);
pm_runtime_put_sync(&port_dev->dev);
}
}
/* deal with hub status changes */
if (test_and_clear_bit(0, hub->event_bits) == 0)
; /* do nothing */
else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
dev_err(hub_dev, "get_hub_status failed\n");
else {
if (hubchange & HUB_CHANGE_LOCAL_POWER) {
dev_dbg(hub_dev, "power change\n");
clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
if (hubstatus & HUB_STATUS_LOCAL_POWER)
/* FIXME: Is this always true? */
hub->limited_power = 1;
else
hub->limited_power = 0;
}
if (hubchange & HUB_CHANGE_OVERCURRENT) {
u16 status = 0;
u16 unused;
dev_dbg(hub_dev, "over-current change\n");
clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
msleep(500); /* Cool down */
hub_power_on(hub, true);
hub_hub_status(hub, &status, &unused);
if (status & HUB_STATUS_OVERCURRENT)
dev_err(hub_dev, "over-current condition\n");
}
}
out_autopm:
/* Balance the usb_autopm_get_interface() above */
usb_autopm_put_interface_no_suspend(intf);
out_hdev_lock:
usb_unlock_device(hdev);
/* Balance the stuff in kick_hub_wq() and allow autosuspend */
usb_autopm_put_interface(intf);
kref_put(&hub->kref, hub_release);
}
CWE ID:
Target: 0
Now analyze the following code 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: get_policy_2_svc(gpol_arg *arg, struct svc_req *rqstp)
{
static gpol_ret ret;
kadm5_ret_t ret2;
char *prime_arg, *funcname;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_principal_ent_rec caller_ent;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gpol_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_get_policy";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
prime_arg = arg->name;
ret.code = KADM5_AUTH_GET;
if (!CHANGEPW_SERVICE(rqstp) && kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE, NULL, NULL))
ret.code = KADM5_OK;
else {
ret.code = kadm5_get_principal(handle->lhandle,
handle->current_caller,
&caller_ent,
KADM5_PRINCIPAL_NORMAL_MASK);
if (ret.code == KADM5_OK) {
if (caller_ent.aux_attributes & KADM5_POLICY &&
strcmp(caller_ent.policy, arg->name) == 0) {
ret.code = KADM5_OK;
} else ret.code = KADM5_AUTH_GET;
ret2 = kadm5_free_principal_ent(handle->lhandle,
&caller_ent);
ret.code = ret.code ? ret.code : ret2;
}
}
if (ret.code == KADM5_OK) {
ret.code = kadm5_get_policy(handle, arg->name, &ret.rec);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname,
((prime_arg == NULL) ? "(null)" : prime_arg), errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
} else {
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
}
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DevToolsDataSource::StartDataRequest(
const std::string& path,
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
const content::URLDataSource::GotDataCallback& callback) {
std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath);
bundled_path_prefix += "/";
if (base::StartsWith(path, bundled_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
StartBundledDataRequest(path.substr(bundled_path_prefix.length()),
callback);
return;
}
std::string empty_path_prefix(chrome::kChromeUIDevToolsBlankPath);
if (base::StartsWith(path, empty_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
callback.Run(new base::RefCountedStaticMemory());
return;
}
std::string remote_path_prefix(chrome::kChromeUIDevToolsRemotePath);
remote_path_prefix += "/";
if (base::StartsWith(path, remote_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url(kRemoteFrontendBase + path.substr(remote_path_prefix.length()));
CHECK_EQ(url.host(), kRemoteFrontendDomain);
if (url.is_valid() && DevToolsUIBindings::IsValidRemoteFrontendURL(url)) {
StartRemoteDataRequest(url, callback);
} else {
DLOG(ERROR) << "Refusing to load invalid remote front-end URL";
callback.Run(new base::RefCountedStaticMemory(kHttpNotFound,
strlen(kHttpNotFound)));
}
return;
}
std::string custom_frontend_url =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kCustomDevtoolsFrontend);
if (custom_frontend_url.empty()) {
callback.Run(NULL);
return;
}
std::string custom_path_prefix(chrome::kChromeUIDevToolsCustomPath);
custom_path_prefix += "/";
if (base::StartsWith(path, custom_path_prefix,
base::CompareCase::INSENSITIVE_ASCII)) {
GURL url = GURL(custom_frontend_url +
path.substr(custom_path_prefix.length()));
StartCustomDataRequest(url, callback);
return;
}
callback.Run(NULL);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: std::unique_ptr<DocumentState> BuildDocumentStateFromParams(
const CommonNavigationParams& common_params,
const CommitNavigationParams& commit_params,
base::TimeTicks time_commit_requested,
mojom::FrameNavigationControl::CommitNavigationCallback commit_callback,
mojom::NavigationClient::CommitNavigationCallback
per_navigation_mojo_interface_commit_callback,
const network::ResourceResponseHead* head,
std::unique_ptr<NavigationClient> navigation_client,
int request_id,
bool was_initiated_in_this_frame) {
std::unique_ptr<DocumentState> document_state(new DocumentState());
InternalDocumentStateData* internal_data =
InternalDocumentStateData::FromDocumentState(document_state.get());
DCHECK(!common_params.navigation_start.is_null());
DCHECK(!common_params.url.SchemeIs(url::kJavaScriptScheme));
if (common_params.navigation_type == FrameMsg_Navigate_Type::RESTORE) {
internal_data->set_cache_policy_override(
blink::mojom::FetchCacheMode::kDefault);
}
internal_data->set_is_overriding_user_agent(
commit_params.is_overriding_user_agent);
internal_data->set_must_reset_scroll_and_scale_state(
common_params.navigation_type ==
FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
internal_data->set_previews_state(common_params.previews_state);
internal_data->set_request_id(request_id);
document_state->set_can_load_local_resources(
commit_params.can_load_local_resources);
if (head) {
if (head->headers)
internal_data->set_http_status_code(head->headers->response_code());
else if (common_params.url.SchemeIs(url::kDataScheme))
internal_data->set_http_status_code(200);
document_state->set_was_fetched_via_spdy(head->was_fetched_via_spdy);
document_state->set_was_alpn_negotiated(head->was_alpn_negotiated);
document_state->set_alpn_negotiated_protocol(
head->alpn_negotiated_protocol);
document_state->set_was_alternate_protocol_available(
head->was_alternate_protocol_available);
document_state->set_connection_info(head->connection_info);
internal_data->set_effective_connection_type(
head->effective_connection_type);
}
bool load_data = !common_params.base_url_for_data_url.is_empty() &&
!common_params.history_url_for_data_url.is_empty() &&
common_params.url.SchemeIs(url::kDataScheme);
document_state->set_was_load_data_with_base_url_request(load_data);
if (load_data)
document_state->set_data_url(common_params.url);
InternalDocumentStateData::FromDocumentState(document_state.get())
->set_navigation_state(NavigationState::CreateBrowserInitiated(
common_params, commit_params, time_commit_requested,
std::move(commit_callback),
std::move(per_navigation_mojo_interface_commit_callback),
std::move(navigation_client), was_initiated_in_this_frame));
return document_state;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code 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 DefaultTabHandler::CanCloseContentsAt(int index) {
return delegate_->AsBrowser()->CanCloseContentsAt(index);
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int list_locations(struct kmem_cache *s, char *buf,
enum track_item alloc)
{
int len = 0;
unsigned long i;
struct loc_track t = { 0, 0, NULL };
int node;
if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
GFP_TEMPORARY))
return sprintf(buf, "Out of memory\n");
/* Push back cpu slabs */
flush_all(s);
for_each_node_state(node, N_NORMAL_MEMORY) {
struct kmem_cache_node *n = get_node(s, node);
unsigned long flags;
struct page *page;
if (!atomic_long_read(&n->nr_slabs))
continue;
spin_lock_irqsave(&n->list_lock, flags);
list_for_each_entry(page, &n->partial, lru)
process_slab(&t, s, page, alloc);
list_for_each_entry(page, &n->full, lru)
process_slab(&t, s, page, alloc);
spin_unlock_irqrestore(&n->list_lock, flags);
}
for (i = 0; i < t.count; i++) {
struct location *l = &t.loc[i];
if (len > PAGE_SIZE - 100)
break;
len += sprintf(buf + len, "%7ld ", l->count);
if (l->addr)
len += sprint_symbol(buf + len, (unsigned long)l->addr);
else
len += sprintf(buf + len, "<not-available>");
if (l->sum_time != l->min_time) {
unsigned long remainder;
len += sprintf(buf + len, " age=%ld/%ld/%ld",
l->min_time,
div_long_long_rem(l->sum_time, l->count, &remainder),
l->max_time);
} else
len += sprintf(buf + len, " age=%ld",
l->min_time);
if (l->min_pid != l->max_pid)
len += sprintf(buf + len, " pid=%ld-%ld",
l->min_pid, l->max_pid);
else
len += sprintf(buf + len, " pid=%ld",
l->min_pid);
if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
len < PAGE_SIZE - 60) {
len += sprintf(buf + len, " cpus=");
len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
l->cpus);
}
if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
len < PAGE_SIZE - 60) {
len += sprintf(buf + len, " nodes=");
len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
l->nodes);
}
len += sprintf(buf + len, "\n");
}
free_loc_track(&t);
if (!t.count)
len += sprintf(buf, "No data\n");
return len;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void DocumentTypeAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.Holder();
TestObject* impl = V8TestObject::ToImpl(holder);
V8SetReturnValueFast(info, WTF::GetPtr(impl->documentTypeAttribute()), impl);
}
CWE ID:
Target: 0
Now analyze the following code 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 RenderFrameHostImpl::AXContentNodeDataToAXNodeData(
const AXContentNodeData& src,
ui::AXNodeData* dst) {
*dst = src;
for (auto iter : src.content_int_attributes) {
AXContentIntAttribute attr = iter.first;
int32_t value = iter.second;
switch (attr) {
case AX_CONTENT_ATTR_CHILD_ROUTING_ID:
dst->int_attributes.push_back(std::make_pair(
ui::AX_ATTR_CHILD_TREE_ID, RoutingIDToAXTreeID(value)));
break;
case AX_CONTENT_ATTR_CHILD_BROWSER_PLUGIN_INSTANCE_ID:
dst->int_attributes.push_back(std::make_pair(
ui::AX_ATTR_CHILD_TREE_ID,
BrowserPluginInstanceIDToAXTreeID(value)));
break;
case AX_CONTENT_INT_ATTRIBUTE_LAST:
NOTREACHED();
break;
}
}
}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int sock_send_all(int sock_fd, const uint8_t* buf, int len)
{
int s = len;
int ret;
while(s)
{
do ret = send(sock_fd, buf, s, 0);
while(ret < 0 && errno == EINTR);
if(ret <= 0)
{
BTIF_TRACE_ERROR("sock fd:%d send errno:%d, ret:%d", sock_fd, errno, ret);
return -1;
}
buf += ret;
s -= ret;
}
return len;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: Ins_FLIPON( INS_ARG )
{
DO_FLIPON
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 DebuggerGetTargetsFunction::SendTargetList(
const content::DevToolsAgentHost::List& target_list) {
std::unique_ptr<base::ListValue> result(new base::ListValue());
for (size_t i = 0; i < target_list.size(); ++i)
result->Append(SerializeTarget(target_list[i]));
SetResult(std::move(result));
SendResponse(true);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct rtable *icmp_route_lookup(struct net *net, struct sk_buff *skb_in,
const struct iphdr *iph,
__be32 saddr, u8 tos,
int type, int code,
struct icmp_bxm *param)
{
struct flowi4 fl4 = {
.daddr = (param->replyopts.srr ?
param->replyopts.faddr : iph->saddr),
.saddr = saddr,
.flowi4_tos = RT_TOS(tos),
.flowi4_proto = IPPROTO_ICMP,
.fl4_icmp_type = type,
.fl4_icmp_code = code,
};
struct rtable *rt, *rt2;
int err;
security_skb_classify_flow(skb_in, flowi4_to_flowi(&fl4));
rt = __ip_route_output_key(net, &fl4);
if (IS_ERR(rt))
return rt;
/* No need to clone since we're just using its address. */
rt2 = rt;
if (!fl4.saddr)
fl4.saddr = rt->rt_src;
rt = (struct rtable *) xfrm_lookup(net, &rt->dst,
flowi4_to_flowi(&fl4), NULL, 0);
if (!IS_ERR(rt)) {
if (rt != rt2)
return rt;
} else if (PTR_ERR(rt) == -EPERM) {
rt = NULL;
} else
return rt;
err = xfrm_decode_session_reverse(skb_in, flowi4_to_flowi(&fl4), AF_INET);
if (err)
goto relookup_failed;
if (inet_addr_type(net, fl4.saddr) == RTN_LOCAL) {
rt2 = __ip_route_output_key(net, &fl4);
if (IS_ERR(rt2))
err = PTR_ERR(rt2);
} else {
struct flowi4 fl4_2 = {};
unsigned long orefdst;
fl4_2.daddr = fl4.saddr;
rt2 = ip_route_output_key(net, &fl4_2);
if (IS_ERR(rt2)) {
err = PTR_ERR(rt2);
goto relookup_failed;
}
/* Ugh! */
orefdst = skb_in->_skb_refdst; /* save old refdst */
err = ip_route_input(skb_in, fl4.daddr, fl4.saddr,
RT_TOS(tos), rt2->dst.dev);
dst_release(&rt2->dst);
rt2 = skb_rtable(skb_in);
skb_in->_skb_refdst = orefdst; /* restore old refdst */
}
if (err)
goto relookup_failed;
rt2 = (struct rtable *) xfrm_lookup(net, &rt2->dst,
flowi4_to_flowi(&fl4), NULL,
XFRM_LOOKUP_ICMP);
if (!IS_ERR(rt2)) {
dst_release(&rt->dst);
rt = rt2;
} else if (PTR_ERR(rt2) == -EPERM) {
if (rt)
dst_release(&rt->dst);
return rt2;
} else {
err = PTR_ERR(rt2);
goto relookup_failed;
}
return rt;
relookup_failed:
if (rt)
return rt;
return ERR_PTR(err);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: R_API const RList* /*<RFlagItem*>*/ r_flag_get_list(RFlag *f, ut64 off) {
const RFlagsAtOffset *item = r_flag_get_nearest_list (f, off, 0);
return item ? item->flags : NULL;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code 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 mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)
{
major = 1;
minor = 0;
build = 0;
revision = 27;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
{
spl_filesystem_iterator *iterator;
spl_filesystem_object *dir_object;
if (by_ref) {
zend_error(E_ERROR, "An iterator cannot be used with foreach by reference");
}
dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC);
iterator = spl_filesystem_object_to_iterator(dir_object);
/* initialize iterator if it wasn't gotten before */
if (iterator->intern.data == NULL) {
iterator->intern.data = object;
iterator->intern.funcs = &spl_filesystem_dir_it_funcs;
/* ->current must be initialized; rewind doesn't set it and valid
* doesn't check whether it's set */
iterator->current = object;
}
zval_add_ref(&object);
return (zend_object_iterator*)iterator;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static void bond_ab_arp_commit(struct bonding *bond, int delta_in_ticks)
{
struct slave *slave;
int i;
unsigned long trans_start;
bond_for_each_slave(bond, slave, i) {
switch (slave->new_link) {
case BOND_LINK_NOCHANGE:
continue;
case BOND_LINK_UP:
trans_start = dev_trans_start(slave->dev);
if ((!bond->curr_active_slave &&
time_in_range(jiffies,
trans_start - delta_in_ticks,
trans_start + delta_in_ticks)) ||
bond->curr_active_slave != slave) {
slave->link = BOND_LINK_UP;
bond->current_arp_slave = NULL;
pr_info("%s: link status definitely up for interface %s.\n",
bond->dev->name, slave->dev->name);
if (!bond->curr_active_slave ||
(slave == bond->primary_slave))
goto do_failover;
}
continue;
case BOND_LINK_DOWN:
if (slave->link_failure_count < UINT_MAX)
slave->link_failure_count++;
slave->link = BOND_LINK_DOWN;
bond_set_slave_inactive_flags(slave);
pr_info("%s: link status definitely down for interface %s, disabling it\n",
bond->dev->name, slave->dev->name);
if (slave == bond->curr_active_slave) {
bond->current_arp_slave = NULL;
goto do_failover;
}
continue;
default:
pr_err("%s: impossible: new_link %d on slave %s\n",
bond->dev->name, slave->new_link,
slave->dev->name);
continue;
}
do_failover:
ASSERT_RTNL();
block_netpoll_tx();
write_lock_bh(&bond->curr_slave_lock);
bond_select_active_slave(bond);
write_unlock_bh(&bond->curr_slave_lock);
unblock_netpoll_tx();
}
bond_set_carrier(bond);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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: bmexec (kwset_t kws, char const *text, size_t size)
{
struct kwset const *kwset;
unsigned char const *d1;
char const *ep, *sp, *tp;
int d, gc, i, len, md2;
kwset = (struct kwset const *) kws;
len = kwset->mind;
if (len == 0)
return 0;
if (len > size)
return -1;
if (len == 1)
{
tp = memchr (text, kwset->target[0], size);
return tp ? tp - text : -1;
}
d1 = kwset->delta;
sp = kwset->target + len;
gc = U(sp[-2]);
md2 = kwset->mind2;
tp = text + len;
/* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
if (size > 12 * len)
/* 11 is not a bug, the initial offset happens only once. */
for (ep = text + size - 11 * len;;)
{
while (tp <= ep)
{
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d == 0)
goto found;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d == 0)
goto found;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d == 0)
goto found;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
}
break;
found:
if (U(tp[-2]) == gc)
{
for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
;
if (i > len)
return tp - len - text;
}
tp += md2;
}
/* Now we have only a few characters left to search. We
carefully avoid ever producing an out-of-bounds pointer. */
ep = text + size;
d = d1[U(tp[-1])];
while (d <= ep - tp)
{
d = d1[U((tp += d)[-1])];
if (d != 0)
continue;
if (U(tp[-2]) == gc)
{
for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
;
if (i > len)
return tp - len - text;
}
d = md2;
}
return -1;
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC)
{
size_t retlen;
char *ret;
enum entity_charset charset;
const entity_ht *inverse_map = NULL;
size_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen);
if (all) {
charset = determine_charset(hint_charset TSRMLS_CC);
} else {
charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */
}
/* don't use LIMIT_ALL! */
if (oldlen > new_size) {
/* overflow, refuse to do anything */
ret = estrndup((char*)old, oldlen);
retlen = oldlen;
goto empty_source;
}
ret = emalloc(new_size);
*ret = '\0';
retlen = oldlen;
if (retlen == 0) {
goto empty_source;
}
inverse_map = unescape_inverse_map(all, flags);
/* replace numeric entities */
traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset);
empty_source:
*newlen = retlen;
return ret;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: prefix_cmd(int midi_dev, unsigned char status)
{
if ((char *) midi_devs[midi_dev]->prefix_cmd == NULL)
return 1;
return midi_devs[midi_dev]->prefix_cmd(midi_dev, status);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code 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 clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc)
{
struct list_head *head = &(SM_I(sbi)->dcc_info->entry_list);
struct discard_entry *entry, *this;
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
unsigned int start = 0, end = -1;
unsigned int secno, start_segno;
bool force = (cpc->reason & CP_DISCARD);
mutex_lock(&dirty_i->seglist_lock);
while (1) {
int i;
start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
if (start >= MAIN_SEGS(sbi))
break;
end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
start + 1);
for (i = start; i < end; i++)
clear_bit(i, prefree_map);
dirty_i->nr_dirty[PRE] -= end - start;
if (!test_opt(sbi, DISCARD))
continue;
if (force && start >= cpc->trim_start &&
(end - 1) <= cpc->trim_end)
continue;
if (!test_opt(sbi, LFS) || sbi->segs_per_sec == 1) {
f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
(end - start) << sbi->log_blocks_per_seg);
continue;
}
next:
secno = GET_SEC_FROM_SEG(sbi, start);
start_segno = GET_SEG_FROM_SEC(sbi, secno);
if (!IS_CURSEC(sbi, secno) &&
!get_valid_blocks(sbi, start, true))
f2fs_issue_discard(sbi, START_BLOCK(sbi, start_segno),
sbi->segs_per_sec << sbi->log_blocks_per_seg);
start = start_segno + sbi->segs_per_sec;
if (start < end)
goto next;
else
end = start - 1;
}
mutex_unlock(&dirty_i->seglist_lock);
/* send small discards */
list_for_each_entry_safe(entry, this, head, list) {
unsigned int cur_pos = 0, next_pos, len, total_len = 0;
bool is_valid = test_bit_le(0, entry->discard_map);
find_next:
if (is_valid) {
next_pos = find_next_zero_bit_le(entry->discard_map,
sbi->blocks_per_seg, cur_pos);
len = next_pos - cur_pos;
if (f2fs_sb_mounted_blkzoned(sbi->sb) ||
(force && len < cpc->trim_minlen))
goto skip;
f2fs_issue_discard(sbi, entry->start_blkaddr + cur_pos,
len);
cpc->trimmed += len;
total_len += len;
} else {
next_pos = find_next_bit_le(entry->discard_map,
sbi->blocks_per_seg, cur_pos);
}
skip:
cur_pos = next_pos;
is_valid = !is_valid;
if (cur_pos < sbi->blocks_per_seg)
goto find_next;
list_del(&entry->list);
SM_I(sbi)->dcc_info->nr_discards -= total_len;
kmem_cache_free(discard_entry_slab, entry);
}
wake_up(&SM_I(sbi)->dcc_info->discard_wait_queue);
}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int key_notify_policy_flush(const struct km_event *c)
{
struct sk_buff *skb_out;
struct sadb_msg *hdr;
skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb_out)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
hdr->sadb_msg_type = SADB_X_SPDFLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: DebuggerFunction::DebuggerFunction()
: client_host_(NULL) {
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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 WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
EAS_PCM *pInputBuffer;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I32 numSamples;
#if (NUM_OUTPUT_CHANNELS == 2)
EAS_I32 gainLeft, gainRight;
#endif
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
if (numSamples <= 0) {
ALOGE("b/26366256");
return;
}
pMixBuffer = pWTIntFrame->pMixBuffer;
pInputBuffer = pWTIntFrame->pAudioBuffer;
/*lint -e{703} <avoid multiply for performance>*/
gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
/*lint -e{703} <avoid multiply for performance>*/
gain = pWTIntFrame->prevGain << 16;
#if (NUM_OUTPUT_CHANNELS == 2)
gainLeft = pWTVoice->gainLeft;
gainRight = pWTVoice->gainRight;
#endif
while (numSamples--) {
/* incremental gain step to prevent zipper noise */
tmp0 = *pInputBuffer++;
gain += gainIncrement;
/*lint -e{704} <avoid divide>*/
tmp2 = gain >> 16;
/* scale sample by gain */
tmp2 *= tmp0;
/* stereo output */
#if (NUM_OUTPUT_CHANNELS == 2)
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> 14;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* left channel */
tmp0 = tmp2 * gainLeft;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/* right channel */
tmp0 = tmp2 * gainRight;
/*lint -e{704} <avoid divide>*/
tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS;
tmp1 += tmp0;
*pMixBuffer++ = tmp1;
/* mono output */
#else
/* get the current sample in the final mix buffer */
tmp1 = *pMixBuffer;
/*lint -e{704} <avoid divide>*/
tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1);
tmp1 += tmp2;
*pMixBuffer++ = tmp1;
#endif
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->MaxLen < 1)
fields->MaxLen = fields->Len;
Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void AutofillManager::FillOrPreviewDataModelForm(
AutofillDriver::RendererFormDataAction action,
int query_id,
const FormData& form,
const FormFieldData& field,
const AutofillDataModel& data_model,
bool is_credit_card,
const base::string16& cvc,
FormStructure* form_structure,
AutofillField* autofill_field,
bool is_refill) {
DCHECK(form_structure);
DCHECK(autofill_field);
FormData result = form;
if (base::FeatureList::IsEnabled(kAutofillRationalizeFieldTypePredictions)) {
form_structure->RationalizePhoneNumbersInSection(autofill_field->section);
}
DCHECK_EQ(form_structure->field_count(), form.fields.size());
FillingContext* filling_context = nullptr;
auto itr =
filling_contexts_map_.find(form_structure->GetIdentifierForRefill());
if (itr != filling_contexts_map_.end())
filling_context = itr->second.get();
bool could_attempt_refill =
base::FeatureList::IsEnabled(features::kAutofillDynamicForms) &&
filling_context != nullptr && !filling_context->attempted_refill &&
!is_refill && !is_credit_card;
for (size_t i = 0; i < form_structure->field_count(); ++i) {
if (form_structure->field(i)->section != autofill_field->section)
continue;
if (form_structure->field(i)->only_fill_when_focused() &&
!form_structure->field(i)->SameFieldAs(field)) {
continue;
}
DCHECK(form_structure->field(i)->SameFieldAs(result.fields[i]));
AutofillField* cached_field = form_structure->field(i);
FieldTypeGroup field_group_type = cached_field->Type().group();
if (!cached_field->IsVisible()) {
bool skip = result.fields[i].form_control_type != "select-one";
form_interactions_ukm_logger_->LogHiddenRepresentationalFieldSkipDecision(
*form_structure, *cached_field, skip);
if (skip)
continue;
}
if (result.fields[i].is_autofilled && !cached_field->SameFieldAs(field) &&
!is_refill) {
continue;
}
if (field_group_type == NO_GROUP)
continue;
if (is_refill &&
!base::ContainsKey(filling_context->type_groups_originally_filled,
field_group_type)) {
continue;
}
if (IsCreditCardExpirationType(cached_field->Type().GetStorableType()) &&
static_cast<const CreditCard*>(&data_model)
->IsExpired(AutofillClock::Now())) {
continue;
}
if (could_attempt_refill)
filling_context->type_groups_originally_filled.insert(field_group_type);
bool should_notify = !is_credit_card &&
(result.fields[i].SameFieldAs(field) ||
result.fields[i].form_control_type == "select-one" ||
result.fields[i].value.empty());
FillFieldWithValue(cached_field, data_model, &result.fields[i],
should_notify, cvc);
if (result.fields[i].is_autofilled)
result.fields[i].section = form_structure->field(i)->section;
if (!cached_field->IsVisible() && result.fields[i].is_autofilled) {
AutofillMetrics::LogHiddenOrPresentationalSelectFieldsFilled();
}
}
autofilled_form_signatures_.push_front(form_structure->FormSignatureAsStr());
if (autofilled_form_signatures_.size() > kMaxRecentFormSignaturesToRemember)
autofilled_form_signatures_.pop_back();
if (action == AutofillDriver::FORM_DATA_ACTION_FILL && !is_refill)
personal_data_->RecordUseOf(data_model);
driver()->SendFormDataToRenderer(query_id, action, result);
}
CWE ID:
Target: 0
Now analyze the following code 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 exit_ext2_fs(void)
{
unregister_filesystem(&ext2_fs_type);
destroy_inodecache();
exit_ext2_xattr();
}
CWE ID: CWE-19
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: nfs4_open_revalidate(struct inode *dir, struct dentry *dentry, int openflags, struct nameidata *nd)
{
struct path path = {
.mnt = nd->path.mnt,
.dentry = dentry,
};
struct rpc_cred *cred;
struct nfs4_state *state;
cred = rpc_lookup_cred();
if (IS_ERR(cred))
return PTR_ERR(cred);
state = nfs4_do_open(dir, &path, openflags, NULL, cred);
put_rpccred(cred);
if (IS_ERR(state)) {
switch (PTR_ERR(state)) {
case -EPERM:
case -EACCES:
case -EDQUOT:
case -ENOSPC:
case -EROFS:
lookup_instantiate_filp(nd, (struct dentry *)state, NULL);
return 1;
default:
goto out_drop;
}
}
if (state->inode == dentry->d_inode) {
nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
nfs4_intent_set_file(nd, &path, state);
return 1;
}
nfs4_close_sync(&path, state, openflags);
out_drop:
d_drop(dentry);
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: static int tls12_find_nid(int id, tls12_lookup *table, size_t tlen)
{
size_t i;
for (i = 0; i < tlen; i++)
{
if (table[i].id == id)
return table[i].nid;
}
return -1;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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 SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) {
ALOGE("input buffer too small: got %u, expected %u",
outHeader->nAllocLen, mConfig->outputFrameSize);
android_errorWriteLog(0x534e4554, "27793371");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return;
}
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
memset(outHeader->pBuffer,
0,
mConfig->outputFrameSize * sizeof(int16_t));
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: plan_a (char const *filename)
{
char const *s;
char const *lim;
char const **ptr;
char *buffer;
lin iline;
size_t size = instat.st_size;
/* Fail if the file size doesn't fit in a size_t,
or if storage isn't available. */
if (! (size == instat.st_size
&& (buffer = malloc (size ? size : (size_t) 1))))
return false;
/* Read the input file, but don't bother reading it if it's empty.
When creating files, the files do not actually exist. */
if (size)
{
if (S_ISREG (instat.st_mode))
{
int ifd = safe_open (filename, O_RDONLY|binary_transput, 0);
size_t buffered = 0, n;
if (ifd < 0)
pfatal ("can't open file %s", quotearg (filename));
/* Some non-POSIX hosts exaggerate st_size in text mode;
or the file may have shrunk! */
size = buffered;
break;
}
if (n == (size_t) -1)
{
/* Perhaps size is too large for this host. */
close (ifd);
free (buffer);
return false;
}
buffered += n;
}
if (close (ifd) != 0)
read_fatal ();
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: static void tun_poll_controller(struct net_device *dev)
{
/*
* Tun only receives frames when:
* 1) the char device endpoint gets data from user space
* 2) the tun socket gets a sendmsg call from user space
* Since both of those are syncronous operations, we are guaranteed
* never to have pending data when we poll for it
* so theres nothing to do here but return.
* We need this though so netpoll recognizes us as an interface that
* supports polling, which enables bridge devices in virt setups to
* still use netconsole
*/
return;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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 acpi_check_region(resource_size_t start, resource_size_t n,
const char *name)
{
struct resource res = {
.start = start,
.end = start + n - 1,
.name = name,
.flags = IORESOURCE_IO,
};
return acpi_check_resource_conflict(&res);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
AVFilterContext *ctx = inlink->dst;
BoxBlurContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
int plane;
int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub);
int w[4] = { inlink->w, cw, cw, inlink->w };
int h[4] = { in->height, ch, ch, in->height };
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
for (plane = 0; in->data[plane] && plane < 4; plane++)
hblur(out->data[plane], out->linesize[plane],
in ->data[plane], in ->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
for (plane = 0; in->data[plane] && plane < 4; plane++)
vblur(out->data[plane], out->linesize[plane],
out->data[plane], out->linesize[plane],
w[plane], h[plane], s->radius[plane], s->power[plane],
s->temp);
av_frame_free(&in);
return ff_filter_frame(outlink, out);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: DevToolsWindowBeforeUnloadObserver::DevToolsWindowBeforeUnloadObserver(
DevToolsWindow* devtools_window)
: WebContentsObserver(devtools_window->web_contents()),
m_fired(false) {
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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: ProcessingChangeGuard(InputHandler* inputHandler)
: m_inputHandler(inputHandler)
, m_savedProcessingChange(false)
{
ASSERT(m_inputHandler);
m_savedProcessingChange = m_inputHandler->processingChange();
m_inputHandler->setProcessingChange(true);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock,
struct buffer_head *bh_map, struct metapath *mp,
const unsigned int sheight,
const unsigned int height,
const unsigned int maxlen)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct buffer_head *dibh = mp->mp_bh[0];
u64 bn, dblock = 0;
unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0;
unsigned dblks = 0;
unsigned ptrs_per_blk;
const unsigned end_of_metadata = height - 1;
int eob = 0;
enum alloc_state state;
__be64 *ptr;
__be64 zero_bn = 0;
BUG_ON(sheight < 1);
BUG_ON(dibh == NULL);
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (height == sheight) {
struct buffer_head *bh;
/* Bottom indirect block exists, find unalloced extent size */
ptr = metapointer(end_of_metadata, mp);
bh = mp->mp_bh[end_of_metadata];
dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen,
&eob);
BUG_ON(dblks < 1);
state = ALLOC_DATA;
} else {
/* Need to allocate indirect blocks */
ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs;
dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]);
if (height == ip->i_height) {
/* Writing into existing tree, extend tree down */
iblks = height - sheight;
state = ALLOC_GROW_DEPTH;
} else {
/* Building up tree height */
state = ALLOC_GROW_HEIGHT;
iblks = height - ip->i_height;
branch_start = metapath_branch_start(mp);
iblks += (height - branch_start);
}
}
/* start of the second part of the function (state machine) */
blks = dblks + iblks;
i = sheight;
do {
int error;
n = blks - alloced;
error = gfs2_alloc_block(ip, &bn, &n);
if (error)
return error;
alloced += n;
if (state != ALLOC_DATA || gfs2_is_jdata(ip))
gfs2_trans_add_unrevoke(sdp, bn, n);
switch (state) {
/* Growing height of tree */
case ALLOC_GROW_HEIGHT:
if (i == 1) {
ptr = (__be64 *)(dibh->b_data +
sizeof(struct gfs2_dinode));
zero_bn = *ptr;
}
for (; i - 1 < height - ip->i_height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++);
if (i - 1 == height - ip->i_height) {
i--;
gfs2_buffer_copy_tail(mp->mp_bh[i],
sizeof(struct gfs2_meta_header),
dibh, sizeof(struct gfs2_dinode));
gfs2_buffer_clear_tail(dibh,
sizeof(struct gfs2_dinode) +
sizeof(__be64));
ptr = (__be64 *)(mp->mp_bh[i]->b_data +
sizeof(struct gfs2_meta_header));
*ptr = zero_bn;
state = ALLOC_GROW_DEPTH;
for(i = branch_start; i < height; i++) {
if (mp->mp_bh[i] == NULL)
break;
brelse(mp->mp_bh[i]);
mp->mp_bh[i] = NULL;
}
i = branch_start;
}
if (n == 0)
break;
/* Branching from existing tree */
case ALLOC_GROW_DEPTH:
if (i > 1 && i < height)
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1);
for (; i < height && n > 0; i++, n--)
gfs2_indirect_init(mp, ip->i_gl, i,
mp->mp_list[i-1], bn++);
if (i == height)
state = ALLOC_DATA;
if (n == 0)
break;
/* Tree complete, adding data blocks */
case ALLOC_DATA:
BUG_ON(n > dblks);
BUG_ON(mp->mp_bh[end_of_metadata] == NULL);
gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1);
dblks = n;
ptr = metapointer(end_of_metadata, mp);
dblock = bn;
while (n-- > 0)
*ptr++ = cpu_to_be64(bn++);
break;
}
} while ((state != ALLOC_DATA) || !dblock);
ip->i_height = height;
gfs2_add_inode_blocks(&ip->i_inode, alloced);
gfs2_dinode_out(ip, mp->mp_bh[0]->b_data);
map_bh(bh_map, inode->i_sb, dblock);
bh_map->b_size = dblks << inode->i_blkbits;
set_buffer_new(bh_map);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void free_vfsmnt(struct mount *mnt)
{
kfree(mnt->mnt_devname);
mnt_free_id(mnt);
#ifdef CONFIG_SMP
free_percpu(mnt->mnt_pcp);
#endif
kmem_cache_free(mnt_cache, mnt);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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: grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector,
grub_off_t offset, grub_size_t size, void *buf)
{
char *tmp_buf;
unsigned real_offset;
/* First of all, check if the region is within the disk. */
if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE)
{
grub_error_push ();
grub_dprintf ("disk", "Read out of range: sector 0x%llx (%s).\n",
(unsigned long long) sector, grub_errmsg);
grub_error_pop ();
return grub_errno;
}
real_offset = offset;
/* Allocate a temporary buffer. */
tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS);
if (! tmp_buf)
return grub_errno;
/* Until SIZE is zero... */
while (size)
{
char *data;
grub_disk_addr_t start_sector;
grub_size_t len;
grub_size_t pos;
/* For reading bulk data. */
start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1);
pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS;
len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS)
- pos - real_offset);
if (len > size)
len = size;
/* Fetch the cache. */
data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector);
if (data)
{
/* Just copy it! */
if (buf)
grub_memcpy (buf, data + pos + real_offset, len);
grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector);
}
else
{
/* Otherwise read data from the disk actually. */
if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors
|| (disk->dev->read) (disk, start_sector,
GRUB_DISK_CACHE_SIZE, tmp_buf)
!= GRUB_ERR_NONE)
{
/* Uggh... Failed. Instead, just read necessary data. */
unsigned num;
char *p;
grub_errno = GRUB_ERR_NONE;
num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1)
>> GRUB_DISK_SECTOR_BITS);
p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS);
if (!p)
goto finish;
tmp_buf = p;
if ((disk->dev->read) (disk, sector, num, tmp_buf))
{
grub_error_push ();
grub_dprintf ("disk", "%s read failed\n", disk->name);
grub_error_pop ();
goto finish;
}
if (buf)
grub_memcpy (buf, tmp_buf + real_offset, size);
/* Call the read hook, if any. */
if (disk->read_hook)
while (size)
{
grub_size_t to_read;
to_read = size;
if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE)
to_read = GRUB_DISK_SECTOR_SIZE - real_offset;
(disk->read_hook) (sector, real_offset,
to_read, disk->closure);
if (grub_errno != GRUB_ERR_NONE)
goto finish;
sector++;
size -= to_read;
real_offset = 0;
}
/* This must be the end. */
goto finish;
}
/* Copy it and store it in the disk cache. */
if (buf)
grub_memcpy (buf, tmp_buf + pos + real_offset, len);
grub_disk_cache_store (disk->dev->id, disk->id,
start_sector, tmp_buf);
}
/* Call the read hook, if any. */
if (disk->read_hook)
{
grub_disk_addr_t s = sector;
grub_size_t l = len;
while (l)
{
(disk->read_hook) (s, real_offset,
((l > GRUB_DISK_SECTOR_SIZE)
? GRUB_DISK_SECTOR_SIZE
: l), disk->closure);
if (l < GRUB_DISK_SECTOR_SIZE - real_offset)
break;
s++;
l -= GRUB_DISK_SECTOR_SIZE - real_offset;
real_offset = 0;
}
}
sector = start_sector + GRUB_DISK_CACHE_SIZE;
if (buf)
buf = (char *) buf + len;
size -= len;
real_offset = 0;
}
finish:
grub_free (tmp_buf);
return grub_errno;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int sbusfb_ioctl_helper(unsigned long cmd, unsigned long arg,
struct fb_info *info,
int type, int fb_depth, unsigned long fb_size)
{
switch(cmd) {
case FBIOGTYPE: {
struct fbtype __user *f = (struct fbtype __user *) arg;
if (put_user(type, &f->fb_type) ||
__put_user(info->var.yres, &f->fb_height) ||
__put_user(info->var.xres, &f->fb_width) ||
__put_user(fb_depth, &f->fb_depth) ||
__put_user(0, &f->fb_cmsize) ||
__put_user(fb_size, &f->fb_cmsize))
return -EFAULT;
return 0;
}
case FBIOPUTCMAP_SPARC: {
struct fbcmap __user *c = (struct fbcmap __user *) arg;
struct fb_cmap cmap;
u16 red, green, blue;
u8 red8, green8, blue8;
unsigned char __user *ured;
unsigned char __user *ugreen;
unsigned char __user *ublue;
int index, count, i;
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
cmap.len = 1;
cmap.red = &red;
cmap.green = &green;
cmap.blue = &blue;
cmap.transp = NULL;
for (i = 0; i < count; i++) {
int err;
if (get_user(red8, &ured[i]) ||
get_user(green8, &ugreen[i]) ||
get_user(blue8, &ublue[i]))
return -EFAULT;
red = red8 << 8;
green = green8 << 8;
blue = blue8 << 8;
cmap.start = index + i;
err = fb_set_cmap(&cmap, info);
if (err)
return err;
}
return 0;
}
case FBIOGETCMAP_SPARC: {
struct fbcmap __user *c = (struct fbcmap __user *) arg;
unsigned char __user *ured;
unsigned char __user *ugreen;
unsigned char __user *ublue;
struct fb_cmap *cmap = &info->cmap;
int index, count, i;
u8 red, green, blue;
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
if (index + count > cmap->len)
return -EINVAL;
for (i = 0; i < count; i++) {
red = cmap->red[index + i] >> 8;
green = cmap->green[index + i] >> 8;
blue = cmap->blue[index + i] >> 8;
if (put_user(red, &ured[i]) ||
put_user(green, &ugreen[i]) ||
put_user(blue, &ublue[i]))
return -EFAULT;
}
return 0;
}
default:
return -EINVAL;
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void WebContentsImpl::ExitPictureInPicture() {
if (delegate_)
delegate_->ExitPictureInPicture();
}
CWE ID: CWE-254
Target: 0
Now analyze the following code 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: GF_Err tfhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->trackID);
if (ptr->flags & GF_ISOM_TRAF_BASE_OFFSET) {
gf_bs_write_u64(bs, ptr->base_data_offset);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DESC) {
gf_bs_write_u32(bs, ptr->sample_desc_index);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DUR) {
gf_bs_write_u32(bs, ptr->def_sample_duration);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_SIZE) {
gf_bs_write_u32(bs, ptr->def_sample_size);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) {
gf_bs_write_u32(bs, ptr->def_sample_flags);
}
return GF_OK;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void Register(const GURL& url,
const base::FilePath& root_http,
ReportResponseHeadersOnUI report_on_ui) {
EXPECT_TRUE(
content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
base::FilePath file_path(root_http);
file_path =
file_path.AppendASCII(url.scheme() + "." + url.host() + ".html");
net::URLRequestFilter::GetInstance()->AddUrlInterceptor(
url, base::WrapUnique(
new MirrorMockJobInterceptor(file_path, report_on_ui)));
}
CWE ID:
Target: 1
Example 2:
Code: bson_iter_oid (const bson_iter_t *iter) /* IN */
{
BSON_ASSERT (iter);
if (ITER_TYPE (iter) == BSON_TYPE_OID) {
return bson_iter_oid_unsafe (iter);
}
return NULL;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code 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: find_table_lock(struct net *net, const char *name, int *error,
struct mutex *mutex)
{
return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name,
"ebtable_", error, mutex);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void test_burl_normalize (void) {
buffer *psrc = buffer_init();
buffer *ptmp = buffer_init();
int flags;
flags = HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("no-slash"), CONST_STR_LEN("no-slash"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d="));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/%2B"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/%2B"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/%3A"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/%3A"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2);
flags = HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d="));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/+"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/+"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/:"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/:"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2);
flags |= HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\a"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\t"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\r"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\177"), "", (size_t)-2);
#if defined(__WIN32) || defined(__CYGWIN__)
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a\\b"), CONST_STR_LEN("/a/b"));
#endif
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=/"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=/"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), CONST_STR_LEN("/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), CONST_STR_LEN("/a/b/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), CONST_STR_LEN("/a/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b/.."), CONST_STR_LEN("/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), "", (size_t)-2);
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d+e"), CONST_STR_LEN("/a/b?c=d+e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d%20e"), CONST_STR_LEN("/a/b?c=d+e"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
buffer_free(psrc);
buffer_free(ptmp);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void lock_two_nondirectories(struct inode *inode1, struct inode *inode2)
{
if (inode1 > inode2)
swap(inode1, inode2);
if (inode1 && !S_ISDIR(inode1->i_mode))
inode_lock(inode1);
if (inode2 && !S_ISDIR(inode2->i_mode) && inode2 != inode1)
inode_lock_nested(inode2, I_MUTEX_NONDIR2);
}
CWE ID: CWE-269
Target: 0
Now analyze the following code 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 char *get_field(char *src, int nfields)
{
char *p = src;
int i;
for (i = 0; i < nfields; i++) {
while (*p && *p != ' ' && *p != '\t')
p++;
if (!*p)
break;
p++;
}
return p;
}
CWE ID: CWE-59
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ip6_frag_queue(struct frag_queue *fq, struct sk_buff *skb,
struct frag_hdr *fhdr, int nhoff)
{
struct sk_buff *prev, *next;
struct net_device *dev;
int offset, end;
struct net *net = dev_net(skb_dst(skb)->dev);
if (fq->q.last_in & INET_FRAG_COMPLETE)
goto err;
offset = ntohs(fhdr->frag_off) & ~0x7;
end = offset + (ntohs(ipv6_hdr(skb)->payload_len) -
((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1)));
if ((unsigned int)end > IPV6_MAXPLEN) {
IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
((u8 *)&fhdr->frag_off -
skb_network_header(skb)));
return -1;
}
if (skb->ip_summed == CHECKSUM_COMPLETE) {
const unsigned char *nh = skb_network_header(skb);
skb->csum = csum_sub(skb->csum,
csum_partial(nh, (u8 *)(fhdr + 1) - nh,
0));
}
/* Is this the final fragment? */
if (!(fhdr->frag_off & htons(IP6_MF))) {
/* If we already have some bits beyond end
* or have different end, the segment is corrupted.
*/
if (end < fq->q.len ||
((fq->q.last_in & INET_FRAG_LAST_IN) && end != fq->q.len))
goto err;
fq->q.last_in |= INET_FRAG_LAST_IN;
fq->q.len = end;
} else {
/* Check if the fragment is rounded to 8 bytes.
* Required by the RFC.
*/
if (end & 0x7) {
/* RFC2460 says always send parameter problem in
* this case. -DaveM
*/
IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
offsetof(struct ipv6hdr, payload_len));
return -1;
}
if (end > fq->q.len) {
/* Some bits beyond end -> corruption. */
if (fq->q.last_in & INET_FRAG_LAST_IN)
goto err;
fq->q.len = end;
}
}
if (end == offset)
goto err;
/* Point into the IP datagram 'data' part. */
if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data))
goto err;
if (pskb_trim_rcsum(skb, end - offset))
goto err;
/* Find out which fragments are in front and at the back of us
* in the chain of fragments so far. We must know where to put
* this fragment, right?
*/
prev = fq->q.fragments_tail;
if (!prev || FRAG6_CB(prev)->offset < offset) {
next = NULL;
goto found;
}
prev = NULL;
for(next = fq->q.fragments; next != NULL; next = next->next) {
if (FRAG6_CB(next)->offset >= offset)
break; /* bingo! */
prev = next;
}
found:
/* We found where to put this one. Check for overlap with
* preceding fragment, and, if needed, align things so that
* any overlaps are eliminated.
*/
if (prev) {
int i = (FRAG6_CB(prev)->offset + prev->len) - offset;
if (i > 0) {
offset += i;
if (end <= offset)
goto err;
if (!pskb_pull(skb, i))
goto err;
if (skb->ip_summed != CHECKSUM_UNNECESSARY)
skb->ip_summed = CHECKSUM_NONE;
}
}
/* Look for overlap with succeeding segments.
* If we can merge fragments, do it.
*/
while (next && FRAG6_CB(next)->offset < end) {
int i = end - FRAG6_CB(next)->offset; /* overlap is 'i' bytes */
if (i < next->len) {
/* Eat head of the next overlapped fragment
* and leave the loop. The next ones cannot overlap.
*/
if (!pskb_pull(next, i))
goto err;
FRAG6_CB(next)->offset += i; /* next fragment */
fq->q.meat -= i;
if (next->ip_summed != CHECKSUM_UNNECESSARY)
next->ip_summed = CHECKSUM_NONE;
break;
} else {
struct sk_buff *free_it = next;
/* Old fragment is completely overridden with
* new one drop it.
*/
next = next->next;
if (prev)
prev->next = next;
else
fq->q.fragments = next;
fq->q.meat -= free_it->len;
frag_kfree_skb(fq->q.net, free_it);
}
}
FRAG6_CB(skb)->offset = offset;
/* Insert this fragment in the chain of fragments. */
skb->next = next;
if (!next)
fq->q.fragments_tail = skb;
if (prev)
prev->next = skb;
else
fq->q.fragments = skb;
dev = skb->dev;
if (dev) {
fq->iif = dev->ifindex;
skb->dev = NULL;
}
fq->q.stamp = skb->tstamp;
fq->q.meat += skb->len;
atomic_add(skb->truesize, &fq->q.net->mem);
/* The first fragment.
* nhoffset is obtained from the first fragment, of course.
*/
if (offset == 0) {
fq->nhoffset = nhoff;
fq->q.last_in |= INET_FRAG_FIRST_IN;
}
if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&
fq->q.meat == fq->q.len)
return ip6_frag_reasm(fq, prev, dev);
write_lock(&ip6_frags.lock);
list_move_tail(&fq->q.lru_list, &fq->q.net->lru_list);
write_unlock(&ip6_frags.lock);
return -1;
err:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_REASMFAILS);
kfree_skb(skb);
return -1;
}
CWE ID:
Target: 1
Example 2:
Code: nm_setting_vpn_new (void)
{
return (NMSetting *) g_object_new (NM_TYPE_SETTING_VPN, NULL);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code 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 AXNodeObject::computeAccessibilityIsIgnored(
IgnoredReasons* ignoredReasons) const {
#if DCHECK_IS_ON()
ASSERT(m_initialized);
#endif
if (isDescendantOfLeafNode()) {
if (ignoredReasons)
ignoredReasons->push_back(
IgnoredReason(AXAncestorIsLeafNode, leafNodeAncestor()));
return true;
}
AXObject* controlObject = correspondingControlForLabelElement();
if (controlObject && controlObject->isCheckboxOrRadio() &&
controlObject->nameFromLabelElement()) {
if (ignoredReasons) {
HTMLLabelElement* label = labelElementContainer();
if (label && label != getNode()) {
AXObject* labelAXObject = axObjectCache().getOrCreate(label);
ignoredReasons->push_back(
IgnoredReason(AXLabelContainer, labelAXObject));
}
ignoredReasons->push_back(IgnoredReason(AXLabelFor, controlObject));
}
return true;
}
Element* element = getNode()->isElementNode() ? toElement(getNode())
: getNode()->parentElement();
if (!getLayoutObject() && (!element || !element->isInCanvasSubtree()) &&
!equalIgnoringCase(getAttribute(aria_hiddenAttr), "false")) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXNotRendered));
return true;
}
if (m_role == UnknownRole) {
if (ignoredReasons)
ignoredReasons->push_back(IgnoredReason(AXUninteresting));
return true;
}
return false;
}
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev,
struct ib_udata *udata)
{
int ret = 0;
struct hns_roce_ucontext *context;
struct hns_roce_ib_alloc_ucontext_resp resp;
struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev);
resp.qp_tab_size = hr_dev->caps.num_qps;
context = kmalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return ERR_PTR(-ENOMEM);
ret = hns_roce_uar_alloc(hr_dev, &context->uar);
if (ret)
goto error_fail_uar_alloc;
if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) {
INIT_LIST_HEAD(&context->page_list);
mutex_init(&context->page_mutex);
}
ret = ib_copy_to_udata(udata, &resp, sizeof(resp));
if (ret)
goto error_fail_copy_to_udata;
return &context->ibucontext;
error_fail_copy_to_udata:
hns_roce_uar_free(hr_dev, &context->uar);
error_fail_uar_alloc:
kfree(context);
return ERR_PTR(ret);
}
CWE ID: CWE-665
Target: 1
Example 2:
Code: static void led_work(struct work_struct *work)
{
struct usb_hub *hub =
container_of(work, struct usb_hub, leds.work);
struct usb_device *hdev = hub->hdev;
unsigned i;
unsigned changed = 0;
int cursor = -1;
if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
return;
for (i = 0; i < hdev->maxchild; i++) {
unsigned selector, mode;
/* 30%-50% duty cycle */
switch (hub->indicator[i]) {
/* cycle marker */
case INDICATOR_CYCLE:
cursor = i;
selector = HUB_LED_AUTO;
mode = INDICATOR_AUTO;
break;
/* blinking green = sw attention */
case INDICATOR_GREEN_BLINK:
selector = HUB_LED_GREEN;
mode = INDICATOR_GREEN_BLINK_OFF;
break;
case INDICATOR_GREEN_BLINK_OFF:
selector = HUB_LED_OFF;
mode = INDICATOR_GREEN_BLINK;
break;
/* blinking amber = hw attention */
case INDICATOR_AMBER_BLINK:
selector = HUB_LED_AMBER;
mode = INDICATOR_AMBER_BLINK_OFF;
break;
case INDICATOR_AMBER_BLINK_OFF:
selector = HUB_LED_OFF;
mode = INDICATOR_AMBER_BLINK;
break;
/* blink green/amber = reserved */
case INDICATOR_ALT_BLINK:
selector = HUB_LED_GREEN;
mode = INDICATOR_ALT_BLINK_OFF;
break;
case INDICATOR_ALT_BLINK_OFF:
selector = HUB_LED_AMBER;
mode = INDICATOR_ALT_BLINK;
break;
default:
continue;
}
if (selector != HUB_LED_AUTO)
changed = 1;
set_port_led(hub, i + 1, selector);
hub->indicator[i] = mode;
}
if (!changed && blinkenlights) {
cursor++;
cursor %= hdev->maxchild;
set_port_led(hub, cursor + 1, HUB_LED_GREEN);
hub->indicator[cursor] = INDICATOR_CYCLE;
changed++;
}
if (changed)
queue_delayed_work(system_power_efficient_wq,
&hub->leds, LED_CYCLE_PERIOD);
}
CWE ID:
Target: 0
Now analyze the following code 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, const char **argv)
{
const char * prog = *argv;
const char * outfile = NULL;
const char * suffix = NULL;
const char * prefix = NULL;
int done = 0; /* if at least one file is processed */
struct global global;
global_init(&global);
while (--argc > 0)
{
++argv;
if (strcmp(*argv, "--debug") == 0)
{
/* To help debugging problems: */
global.errors = global.warnings = 1;
global.quiet = 0;
global.verbose = 7;
}
else if (strncmp(*argv, "--max=", 6) == 0)
{
global.idat_max = (png_uint_32)atol(6+*argv);
if (global.skip < SKIP_UNSAFE)
global.skip = SKIP_UNSAFE;
}
else if (strcmp(*argv, "--max") == 0)
{
global.idat_max = 0x7fffffff;
if (global.skip < SKIP_UNSAFE)
global.skip = SKIP_UNSAFE;
}
else if (strcmp(*argv, "--optimize") == 0 || strcmp(*argv, "-o") == 0)
global.optimize_zlib = 1;
else if (strncmp(*argv, "--out=", 6) == 0)
outfile = 6+*argv;
else if (strncmp(*argv, "--suffix=", 9) == 0)
suffix = 9+*argv;
else if (strncmp(*argv, "--prefix=", 9) == 0)
prefix = 9+*argv;
else if (strcmp(*argv, "--strip=none") == 0)
global.skip = SKIP_NONE;
else if (strcmp(*argv, "--strip=crc") == 0)
global.skip = SKIP_BAD_CRC;
else if (strcmp(*argv, "--strip=unsafe") == 0)
global.skip = SKIP_UNSAFE;
else if (strcmp(*argv, "--strip=unused") == 0)
global.skip = SKIP_UNUSED;
else if (strcmp(*argv, "--strip=transform") == 0)
global.skip = SKIP_TRANSFORM;
else if (strcmp(*argv, "--strip=color") == 0)
global.skip = SKIP_COLOR;
else if (strcmp(*argv, "--strip=all") == 0)
global.skip = SKIP_ALL;
else if (strcmp(*argv, "--errors") == 0 || strcmp(*argv, "-e") == 0)
global.errors = 1;
else if (strcmp(*argv, "--warnings") == 0 || strcmp(*argv, "-w") == 0)
global.warnings = 1;
else if (strcmp(*argv, "--quiet") == 0 || strcmp(*argv, "-q") == 0)
{
if (global.quiet)
global.quiet = 2;
else
global.quiet = 1;
}
else if (strcmp(*argv, "--verbose") == 0 || strcmp(*argv, "-v") == 0)
++global.verbose;
#if 0
/* NYI */
# ifdef PNG_MAXIMUM_INFLATE_WINDOW
else if (strcmp(*argv, "--test") == 0)
++set_option;
# endif
#endif
else if ((*argv)[0] == '-')
usage(prog);
else
{
size_t outlen = strlen(*argv);
char temp_name[FILENAME_MAX+1];
if (outfile == NULL) /* else this takes precedence */
{
/* Consider the prefix/suffix options */
if (prefix != NULL)
{
size_t prefixlen = strlen(prefix);
if (prefixlen+outlen > FILENAME_MAX)
{
fprintf(stderr, "%s: output file name too long: %s%s%s\n",
prog, prefix, *argv, suffix ? suffix : "");
global.status_code |= WRITE_ERROR;
continue;
}
memcpy(temp_name, prefix, prefixlen);
memcpy(temp_name+prefixlen, *argv, outlen);
outlen += prefixlen;
outfile = temp_name;
}
else if (suffix != NULL)
memcpy(temp_name, *argv, outlen);
temp_name[outlen] = 0;
if (suffix != NULL)
{
size_t suffixlen = strlen(suffix);
if (outlen+suffixlen > FILENAME_MAX)
{
fprintf(stderr, "%s: output file name too long: %s%s\n",
prog, *argv, suffix);
global.status_code |= WRITE_ERROR;
continue;
}
memcpy(temp_name+outlen, suffix, suffixlen);
outlen += suffixlen;
temp_name[outlen] = 0;
outfile = temp_name;
}
}
(void)one_file(&global, *argv, outfile);
++done;
outfile = NULL;
}
}
if (!done)
usage(prog);
return global_end(&global);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_write_ctxt *wc;
struct ocfs2_write_cluster_desc *desc = NULL;
struct ocfs2_dio_write_ctxt *dwc = NULL;
struct buffer_head *di_bh = NULL;
u64 p_blkno;
loff_t pos = iblock << inode->i_sb->s_blocksize_bits;
unsigned len, total_len = bh_result->b_size;
int ret = 0, first_get_block = 0;
len = osb->s_clustersize - (pos & (osb->s_clustersize - 1));
len = min(total_len, len);
mlog(0, "get block of %lu at %llu:%u req %u\n",
inode->i_ino, pos, len, total_len);
/*
* Because we need to change file size in ocfs2_dio_end_io_write(), or
* we may need to add it to orphan dir. So can not fall to fast path
* while file size will be changed.
*/
if (pos + total_len <= i_size_read(inode)) {
down_read(&oi->ip_alloc_sem);
/* This is the fast path for re-write. */
ret = ocfs2_get_block(inode, iblock, bh_result, create);
up_read(&oi->ip_alloc_sem);
if (buffer_mapped(bh_result) &&
!buffer_new(bh_result) &&
ret == 0)
goto out;
/* Clear state set by ocfs2_get_block. */
bh_result->b_state = 0;
}
dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block);
if (unlikely(dwc == NULL)) {
ret = -ENOMEM;
mlog_errno(ret);
goto out;
}
if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) >
ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) &&
!dwc->dw_orphaned) {
/*
* when we are going to alloc extents beyond file size, add the
* inode to orphan dir, so we can recall those spaces when
* system crashed during write.
*/
ret = ocfs2_add_inode_to_orphan(osb, inode);
if (ret < 0) {
mlog_errno(ret);
goto out;
}
dwc->dw_orphaned = 1;
}
ret = ocfs2_inode_lock(inode, &di_bh, 1);
if (ret) {
mlog_errno(ret);
goto out;
}
down_write(&oi->ip_alloc_sem);
if (first_get_block) {
if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)))
ret = ocfs2_zero_tail(inode, di_bh, pos);
else
ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos,
total_len, NULL);
if (ret < 0) {
mlog_errno(ret);
goto unlock;
}
}
ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len,
OCFS2_WRITE_DIRECT, NULL,
(void **)&wc, di_bh, NULL);
if (ret) {
mlog_errno(ret);
goto unlock;
}
desc = &wc->w_desc[0];
p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys);
BUG_ON(p_blkno == 0);
p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1);
map_bh(bh_result, inode->i_sb, p_blkno);
bh_result->b_size = len;
if (desc->c_needs_zero)
set_buffer_new(bh_result);
/* May sleep in end_io. It should not happen in a irq context. So defer
* it to dio work queue. */
set_buffer_defer_completion(bh_result);
if (!list_empty(&wc->w_unwritten_list)) {
struct ocfs2_unwritten_extent *ue = NULL;
ue = list_first_entry(&wc->w_unwritten_list,
struct ocfs2_unwritten_extent,
ue_node);
BUG_ON(ue->ue_cpos != desc->c_cpos);
/* The physical address may be 0, fill it. */
ue->ue_phys = desc->c_phys;
list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list);
dwc->dw_zero_count++;
}
ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc);
BUG_ON(ret != len);
ret = 0;
unlock:
up_write(&oi->ip_alloc_sem);
ocfs2_inode_unlock(inode, 1);
brelse(di_bh);
out:
if (ret < 0)
ret = -EIO;
return ret;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int ftrace_profile_init_cpu(int cpu)
{
struct ftrace_profile_stat *stat;
int size;
stat = &per_cpu(ftrace_profile_stats, cpu);
if (stat->hash) {
/* If the profile is already created, simply reset it */
ftrace_profile_reset(stat);
return 0;
}
/*
* We are profiling all functions, but usually only a few thousand
* functions are hit. We'll make a hash of 1024 items.
*/
size = FTRACE_PROFILE_HASH_SIZE;
stat->hash = kzalloc(sizeof(struct hlist_head) * size, GFP_KERNEL);
if (!stat->hash)
return -ENOMEM;
if (!ftrace_profile_bits) {
size--;
for (; size; size >>= 1)
ftrace_profile_bits++;
}
/* Preallocate the function profiling pages */
if (ftrace_profile_pages_init(stat) < 0) {
kfree(stat->hash);
stat->hash = NULL;
return -ENOMEM;
}
return 0;
}
CWE ID:
Target: 0
Now analyze the following code 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: nl80211_send_cqm_rssi_notify(struct cfg80211_registered_device *rdev,
struct net_device *netdev,
enum nl80211_cqm_rssi_threshold_event rssi_event,
gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *pinfoattr;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_NOTIFY_CQM);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex);
pinfoattr = nla_nest_start(msg, NL80211_ATTR_CQM);
if (!pinfoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT,
rssi_event);
nla_nest_end(msg, pinfoattr);
if (genlmsg_end(msg, hdr) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) {
if (!document_)
return;
LocalFrame* frame = document_->GetFrame();
if (!frame)
return;
if (info.IsMainResource()) {
DCHECK(frame->Owner());
frame->Owner()->AddResourceTiming(info);
frame->DidSendResourceTimingInfoToParent();
return;
}
DOMWindowPerformance::performance(*document_->domWindow())
->GenerateAndAddResourceTiming(info);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: xps_parse_linear_gradient_brush(xps_document *doc, const fz_matrix *ctm, const fz_rect *area,
char *base_uri, xps_resource *dict, fz_xml *root)
{
xps_parse_gradient_brush(doc, ctm, area, base_uri, dict, root, xps_draw_linear_gradient);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 sk_decode_filter(struct sock_filter *filt, struct sock_filter *to)
{
static const u16 decodes[] = {
[BPF_S_ALU_ADD_K] = BPF_ALU|BPF_ADD|BPF_K,
[BPF_S_ALU_ADD_X] = BPF_ALU|BPF_ADD|BPF_X,
[BPF_S_ALU_SUB_K] = BPF_ALU|BPF_SUB|BPF_K,
[BPF_S_ALU_SUB_X] = BPF_ALU|BPF_SUB|BPF_X,
[BPF_S_ALU_MUL_K] = BPF_ALU|BPF_MUL|BPF_K,
[BPF_S_ALU_MUL_X] = BPF_ALU|BPF_MUL|BPF_X,
[BPF_S_ALU_DIV_X] = BPF_ALU|BPF_DIV|BPF_X,
[BPF_S_ALU_MOD_K] = BPF_ALU|BPF_MOD|BPF_K,
[BPF_S_ALU_MOD_X] = BPF_ALU|BPF_MOD|BPF_X,
[BPF_S_ALU_AND_K] = BPF_ALU|BPF_AND|BPF_K,
[BPF_S_ALU_AND_X] = BPF_ALU|BPF_AND|BPF_X,
[BPF_S_ALU_OR_K] = BPF_ALU|BPF_OR|BPF_K,
[BPF_S_ALU_OR_X] = BPF_ALU|BPF_OR|BPF_X,
[BPF_S_ALU_XOR_K] = BPF_ALU|BPF_XOR|BPF_K,
[BPF_S_ALU_XOR_X] = BPF_ALU|BPF_XOR|BPF_X,
[BPF_S_ALU_LSH_K] = BPF_ALU|BPF_LSH|BPF_K,
[BPF_S_ALU_LSH_X] = BPF_ALU|BPF_LSH|BPF_X,
[BPF_S_ALU_RSH_K] = BPF_ALU|BPF_RSH|BPF_K,
[BPF_S_ALU_RSH_X] = BPF_ALU|BPF_RSH|BPF_X,
[BPF_S_ALU_NEG] = BPF_ALU|BPF_NEG,
[BPF_S_LD_W_ABS] = BPF_LD|BPF_W|BPF_ABS,
[BPF_S_LD_H_ABS] = BPF_LD|BPF_H|BPF_ABS,
[BPF_S_LD_B_ABS] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_PROTOCOL] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_PKTTYPE] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_IFINDEX] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_NLATTR] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_NLATTR_NEST] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_MARK] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_QUEUE] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_HATYPE] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_RXHASH] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_CPU] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_ALU_XOR_X] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_SECCOMP_LD_W] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_VLAN_TAG] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_VLAN_TAG_PRESENT] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_ANC_PAY_OFFSET] = BPF_LD|BPF_B|BPF_ABS,
[BPF_S_LD_W_LEN] = BPF_LD|BPF_W|BPF_LEN,
[BPF_S_LD_W_IND] = BPF_LD|BPF_W|BPF_IND,
[BPF_S_LD_H_IND] = BPF_LD|BPF_H|BPF_IND,
[BPF_S_LD_B_IND] = BPF_LD|BPF_B|BPF_IND,
[BPF_S_LD_IMM] = BPF_LD|BPF_IMM,
[BPF_S_LDX_W_LEN] = BPF_LDX|BPF_W|BPF_LEN,
[BPF_S_LDX_B_MSH] = BPF_LDX|BPF_B|BPF_MSH,
[BPF_S_LDX_IMM] = BPF_LDX|BPF_IMM,
[BPF_S_MISC_TAX] = BPF_MISC|BPF_TAX,
[BPF_S_MISC_TXA] = BPF_MISC|BPF_TXA,
[BPF_S_RET_K] = BPF_RET|BPF_K,
[BPF_S_RET_A] = BPF_RET|BPF_A,
[BPF_S_ALU_DIV_K] = BPF_ALU|BPF_DIV|BPF_K,
[BPF_S_LD_MEM] = BPF_LD|BPF_MEM,
[BPF_S_LDX_MEM] = BPF_LDX|BPF_MEM,
[BPF_S_ST] = BPF_ST,
[BPF_S_STX] = BPF_STX,
[BPF_S_JMP_JA] = BPF_JMP|BPF_JA,
[BPF_S_JMP_JEQ_K] = BPF_JMP|BPF_JEQ|BPF_K,
[BPF_S_JMP_JEQ_X] = BPF_JMP|BPF_JEQ|BPF_X,
[BPF_S_JMP_JGE_K] = BPF_JMP|BPF_JGE|BPF_K,
[BPF_S_JMP_JGE_X] = BPF_JMP|BPF_JGE|BPF_X,
[BPF_S_JMP_JGT_K] = BPF_JMP|BPF_JGT|BPF_K,
[BPF_S_JMP_JGT_X] = BPF_JMP|BPF_JGT|BPF_X,
[BPF_S_JMP_JSET_K] = BPF_JMP|BPF_JSET|BPF_K,
[BPF_S_JMP_JSET_X] = BPF_JMP|BPF_JSET|BPF_X,
};
u16 code;
code = filt->code;
to->code = decodes[code];
to->jt = filt->jt;
to->jf = filt->jf;
to->k = filt->k;
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static size_t read_entry(
git_index_entry **out,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return 0;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return 0;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len;
size_t strip_len = git_decode_varint((const unsigned char *)path_ptr,
&varint_len);
size_t last_len = strlen(last);
size_t prefix_len = last_len - strip_len;
size_t suffix_len = strlen(path_ptr + varint_len);
size_t path_len;
if (varint_len == 0)
return index_error_invalid("incorrect prefix length");
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return 0;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return 0;
}
git__free(tmp_path);
return entry_size;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: void Splash::setLineCap(int lineCap) {
state->lineCap = lineCap;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code 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: ScriptValue WebGL2RenderingContextBase::getTexParameter(
ScriptState* script_state,
GLenum target,
GLenum pname) {
if (isContextLost() || !ValidateTextureBinding("getTexParameter", target))
return ScriptValue::CreateNull(script_state);
switch (pname) {
case GL_TEXTURE_WRAP_R:
case GL_TEXTURE_COMPARE_FUNC:
case GL_TEXTURE_COMPARE_MODE:
case GL_TEXTURE_IMMUTABLE_LEVELS: {
GLint value = 0;
ContextGL()->GetTexParameteriv(target, pname, &value);
return WebGLAny(script_state, static_cast<unsigned>(value));
}
case GL_TEXTURE_IMMUTABLE_FORMAT: {
GLint value = 0;
ContextGL()->GetTexParameteriv(target, pname, &value);
return WebGLAny(script_state, static_cast<bool>(value));
}
case GL_TEXTURE_BASE_LEVEL:
case GL_TEXTURE_MAX_LEVEL: {
GLint value = 0;
ContextGL()->GetTexParameteriv(target, pname, &value);
return WebGLAny(script_state, value);
}
case GL_TEXTURE_MAX_LOD:
case GL_TEXTURE_MIN_LOD: {
GLfloat value = 0.f;
ContextGL()->GetTexParameterfv(target, pname, &value);
return WebGLAny(script_state, value);
}
default:
return WebGLRenderingContextBase::getTexParameter(script_state, target,
pname);
}
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage,
png_uint_32 y)
{
png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
if (ps->image == NULL)
png_error(pp, "no allocated image");
if (coffset + ps->cb_row + 3 > ps->cb_image)
png_error(pp, "image too small");
return ps->image + coffset;
}
CWE ID:
Target: 1
Example 2:
Code: BOOL nsc_write_message(NSC_CONTEXT* context, wStream* s, NSC_MESSAGE* message)
{
UINT32 totalPlaneByteCount;
totalPlaneByteCount = message->LumaPlaneByteCount +
message->OrangeChromaPlaneByteCount +
message->GreenChromaPlaneByteCount + message->AlphaPlaneByteCount;
if (!Stream_EnsureRemainingCapacity(s, 20 + totalPlaneByteCount))
return -1;
Stream_Write_UINT32(s,
message->LumaPlaneByteCount); /* LumaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(s,
message->OrangeChromaPlaneByteCount); /* OrangeChromaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(s,
message->GreenChromaPlaneByteCount); /* GreenChromaPlaneByteCount (4 bytes) */
Stream_Write_UINT32(s,
message->AlphaPlaneByteCount); /* AlphaPlaneByteCount (4 bytes) */
Stream_Write_UINT8(s, message->ColorLossLevel); /* ColorLossLevel (1 byte) */
Stream_Write_UINT8(s,
message->ChromaSubsamplingLevel); /* ChromaSubsamplingLevel (1 byte) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
if (message->LumaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[0],
message->LumaPlaneByteCount); /* LumaPlane */
if (message->OrangeChromaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[1],
message->OrangeChromaPlaneByteCount); /* OrangeChromaPlane */
if (message->GreenChromaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[2],
message->GreenChromaPlaneByteCount); /* GreenChromaPlane */
if (message->AlphaPlaneByteCount)
Stream_Write(s, message->PlaneBuffers[3],
message->AlphaPlaneByteCount); /* AlphaPlane */
return TRUE;
}
CWE ID: CWE-787
Target: 0
Now analyze the following code 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 IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DocumentWriter::setDecoder(TextResourceDecoder* decoder)
{
m_decoder = decoder;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static char *sapi_fcgi_read_cookies(TSRMLS_D)
{
fcgi_request *request = (fcgi_request*) SG(server_context);
return FCGI_GETENV(request, "HTTP_COOKIE");
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 SoundTriggerHwService::Module::startRecognition(sound_model_handle_t handle,
const sp<IMemory>& dataMemory)
{
ALOGV("startRecognition() model handle %d", handle);
if (!captureHotwordAllowed()) {
return PERMISSION_DENIED;
}
if (dataMemory != 0 && dataMemory->pointer() == NULL) {
ALOGE("startRecognition() dataMemory is non-0 but has NULL pointer()");
return BAD_VALUE;
}
AutoMutex lock(mLock);
if (mServiceState == SOUND_TRIGGER_STATE_DISABLED) {
return INVALID_OPERATION;
}
sp<Model> model = getModel(handle);
if (model == 0) {
return BAD_VALUE;
}
if ((dataMemory == 0) ||
(dataMemory->size() < sizeof(struct sound_trigger_recognition_config))) {
return BAD_VALUE;
}
if (model->mState == Model::STATE_ACTIVE) {
return INVALID_OPERATION;
}
struct sound_trigger_recognition_config *config =
(struct sound_trigger_recognition_config *)dataMemory->pointer();
config->capture_handle = model->mCaptureIOHandle;
config->capture_device = model->mCaptureDevice;
status_t status = mHwDevice->start_recognition(mHwDevice, handle, config,
SoundTriggerHwService::recognitionCallback,
this);
if (status == NO_ERROR) {
model->mState = Model::STATE_ACTIVE;
model->mConfig = *config;
}
return status;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ScriptPromise BluetoothRemoteGATTService::getCharacteristicsImpl(
ScriptState* scriptState,
mojom::blink::WebBluetoothGATTQueryQuantity quantity,
const String& characteristicsUUID) {
if (!device()->gatt()->connected()) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(NetworkError, kGATTServerNotConnected));
}
if (!device()->isValidService(m_service->instance_id)) {
return ScriptPromise::rejectWithDOMException(
scriptState, DOMException::create(InvalidStateError, kInvalidService));
}
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
device()->gatt()->AddToActiveAlgorithms(resolver);
mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service();
WTF::Optional<String> uuid = WTF::nullopt;
if (!characteristicsUUID.isEmpty())
uuid = characteristicsUUID;
service->RemoteServiceGetCharacteristics(
m_service->instance_id, quantity, uuid,
convertToBaseCallback(
WTF::bind(&BluetoothRemoteGATTService::GetCharacteristicsCallback,
wrapPersistent(this), m_service->instance_id, quantity,
wrapPersistent(resolver))));
return promise;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: do_exec_no_pty(Session *s, const char *command)
{
pid_t pid;
#ifdef USE_PIPES
int pin[2], pout[2], perr[2];
if (s == NULL)
fatal("do_exec_no_pty: no session");
/* Allocate pipes for communicating with the program. */
if (pipe(pin) < 0) {
error("%s: pipe in: %.100s", __func__, strerror(errno));
return -1;
}
if (pipe(pout) < 0) {
error("%s: pipe out: %.100s", __func__, strerror(errno));
close(pin[0]);
close(pin[1]);
return -1;
}
if (pipe(perr) < 0) {
error("%s: pipe err: %.100s", __func__,
strerror(errno));
close(pin[0]);
close(pin[1]);
close(pout[0]);
close(pout[1]);
return -1;
}
#else
int inout[2], err[2];
if (s == NULL)
fatal("do_exec_no_pty: no session");
/* Uses socket pairs to communicate with the program. */
if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) {
error("%s: socketpair #1: %.100s", __func__, strerror(errno));
return -1;
}
if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) {
error("%s: socketpair #2: %.100s", __func__,
strerror(errno));
close(inout[0]);
close(inout[1]);
return -1;
}
#endif
session_proctitle(s);
/* Fork the child. */
switch ((pid = fork())) {
case -1:
error("%s: fork: %.100s", __func__, strerror(errno));
#ifdef USE_PIPES
close(pin[0]);
close(pin[1]);
close(pout[0]);
close(pout[1]);
close(perr[0]);
close(perr[1]);
#else
close(inout[0]);
close(inout[1]);
close(err[0]);
close(err[1]);
#endif
return -1;
case 0:
is_child = 1;
/* Child. Reinitialize the log since the pid has changed. */
log_init(__progname, options.log_level,
options.log_facility, log_stderr);
/*
* Create a new session and process group since the 4.4BSD
* setlogin() affects the entire process group.
*/
if (setsid() < 0)
error("setsid failed: %.100s", strerror(errno));
#ifdef USE_PIPES
/*
* Redirect stdin. We close the parent side of the socket
* pair, and make the child side the standard input.
*/
close(pin[1]);
if (dup2(pin[0], 0) < 0)
perror("dup2 stdin");
close(pin[0]);
/* Redirect stdout. */
close(pout[0]);
if (dup2(pout[1], 1) < 0)
perror("dup2 stdout");
close(pout[1]);
/* Redirect stderr. */
close(perr[0]);
if (dup2(perr[1], 2) < 0)
perror("dup2 stderr");
close(perr[1]);
#else
/*
* Redirect stdin, stdout, and stderr. Stdin and stdout will
* use the same socket, as some programs (particularly rdist)
* seem to depend on it.
*/
close(inout[1]);
close(err[1]);
if (dup2(inout[0], 0) < 0) /* stdin */
perror("dup2 stdin");
if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */
perror("dup2 stdout");
close(inout[0]);
if (dup2(err[0], 2) < 0) /* stderr */
perror("dup2 stderr");
close(err[0]);
#endif
#ifdef _UNICOS
cray_init_job(s->pw); /* set up cray jid and tmpdir */
#endif
/* Do processing for the child (exec command etc). */
do_child(s, command);
/* NOTREACHED */
default:
break;
}
#ifdef _UNICOS
signal(WJSIGNAL, cray_job_termination_handler);
#endif /* _UNICOS */
#ifdef HAVE_CYGWIN
cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
#endif
s->pid = pid;
/* Set interactive/non-interactive mode. */
packet_set_interactive(s->display != NULL,
options.ip_qos_interactive, options.ip_qos_bulk);
/*
* Clear loginmsg, since it's the child's responsibility to display
* it to the user, otherwise multiple sessions may accumulate
* multiple copies of the login messages.
*/
buffer_clear(&loginmsg);
#ifdef USE_PIPES
/* We are the parent. Close the child sides of the pipes. */
close(pin[0]);
close(pout[1]);
close(perr[1]);
if (compat20) {
session_set_fds(s, pin[1], pout[0], perr[0],
s->is_subsystem, 0);
} else {
/* Enter the interactive session. */
server_loop(pid, pin[1], pout[0], perr[0]);
/* server_loop has closed pin[1], pout[0], and perr[0]. */
}
#else
/* We are the parent. Close the child sides of the socket pairs. */
close(inout[0]);
close(err[0]);
/*
* Enter the interactive session. Note: server_loop must be able to
* handle the case that fdin and fdout are the same.
*/
if (compat20) {
session_set_fds(s, inout[1], inout[1], err[1],
s->is_subsystem, 0);
} else {
server_loop(pid, inout[1], inout[1], err[1]);
/* server_loop has closed inout[1] and err[1]. */
}
#endif
return 0;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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<RTCSessionDescriptionDescriptor> RTCPeerConnectionHandlerDummy::remoteDescription()
{
return 0;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *pktap_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint32 pkt_len, rectype, dlt;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP");
col_clear(pinfo->cinfo, COL_INFO);
pkt_len = tvb_get_letohl(tvb, offset);
col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len);
/* Dissect the packet */
ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA);
pktap_tree = proto_item_add_subtree(ti, ett_pktap);
proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
if (pkt_len < MIN_PKTAP_HDR_LEN) {
proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short,
tvb, offset, 4);
return;
}
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
rectype = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
dlt = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24,
ENC_ASCII|ENC_NA);
offset += 24;
proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
offset += 20;
proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
/*offset += 20;*/
if (rectype == PKT_REC_PACKET) {
next_tvb = tvb_new_subset_remaining(tvb, pkt_len);
dissector_try_uint(wtap_encap_dissector_table,
wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree);
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool RenderViewImpl::OnMessageReceived(const IPC::Message& message) {
WebFrame* main_frame = webview() ? webview()->MainFrame() : nullptr;
if (main_frame) {
GURL active_url;
if (main_frame->IsWebLocalFrame())
active_url = main_frame->ToWebLocalFrame()->GetDocument().Url();
GetContentClient()->SetActiveURL(
active_url, main_frame->Top()->GetSecurityOrigin().ToString().Utf8());
}
if (is_swapped_out_ &&
IPC_MESSAGE_ID_CLASS(message.type()) == InputMsgStart) {
IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
IPC_MESSAGE_HANDLER(InputMsg_HandleInputEvent, OnDiscardInputEvent)
IPC_END_MESSAGE_MAP()
return false;
}
for (auto& observer : observers_) {
if (observer.OnMessageReceived(message))
return true;
}
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderViewImpl, message)
IPC_MESSAGE_HANDLER(ViewMsg_SetPageScale, OnSetPageScale)
IPC_MESSAGE_HANDLER(ViewMsg_SetInitialFocus, OnSetInitialFocus)
IPC_MESSAGE_HANDLER(ViewMsg_UpdateTargetURL_ACK, OnUpdateTargetURLAck)
IPC_MESSAGE_HANDLER(ViewMsg_UpdateWebPreferences, OnUpdateWebPreferences)
IPC_MESSAGE_HANDLER(ViewMsg_EnumerateDirectoryResponse,
OnEnumerateDirectoryResponse)
IPC_MESSAGE_HANDLER(ViewMsg_ClosePage, OnClosePage)
IPC_MESSAGE_HANDLER(ViewMsg_MoveOrResizeStarted, OnMoveOrResizeStarted)
IPC_MESSAGE_HANDLER(ViewMsg_SetBackgroundOpaque, OnSetBackgroundOpaque)
IPC_MESSAGE_HANDLER(ViewMsg_EnablePreferredSizeChangedMode,
OnEnablePreferredSizeChangedMode)
IPC_MESSAGE_HANDLER(ViewMsg_EnableAutoResize, OnEnableAutoResize)
IPC_MESSAGE_HANDLER(ViewMsg_DisableAutoResize, OnDisableAutoResize)
IPC_MESSAGE_HANDLER(ViewMsg_SetLocalSurfaceIdForAutoResize,
OnSetLocalSurfaceIdForAutoResize)
IPC_MESSAGE_HANDLER(ViewMsg_DisableScrollbarsForSmallWindows,
OnDisableScrollbarsForSmallWindows)
IPC_MESSAGE_HANDLER(ViewMsg_SetRendererPrefs, OnSetRendererPrefs)
IPC_MESSAGE_HANDLER(ViewMsg_MediaPlayerActionAt, OnMediaPlayerActionAt)
IPC_MESSAGE_HANDLER(ViewMsg_PluginActionAt, OnPluginActionAt)
IPC_MESSAGE_HANDLER(ViewMsg_SetActive, OnSetActive)
IPC_MESSAGE_HANDLER(ViewMsg_ResolveTapDisambiguation,
OnResolveTapDisambiguation)
IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw)
IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret)
IPC_MESSAGE_HANDLER(PageMsg_UpdateWindowScreenRect,
OnUpdateWindowScreenRect)
IPC_MESSAGE_HANDLER(PageMsg_SetZoomLevel, OnSetZoomLevel)
IPC_MESSAGE_HANDLER(PageMsg_WasHidden, OnPageWasHidden)
IPC_MESSAGE_HANDLER(PageMsg_WasShown, OnPageWasShown)
IPC_MESSAGE_HANDLER(PageMsg_SetHistoryOffsetAndLength,
OnSetHistoryOffsetAndLength)
IPC_MESSAGE_HANDLER(PageMsg_AudioStateChanged, OnAudioStateChanged)
IPC_MESSAGE_HANDLER(PageMsg_UpdateScreenInfo, OnUpdateScreenInfo)
#if defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(ViewMsg_UpdateBrowserControlsState,
OnUpdateBrowserControlsState)
#elif defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(ViewMsg_GetRenderedText,
OnGetRenderedText)
IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose)
#endif
IPC_MESSAGE_UNHANDLED(handled = RenderWidget::OnMessageReceived(message))
IPC_END_MESSAGE_MAP()
return handled;
}
CWE ID:
Target: 0
Now analyze the following code 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 ParamTraits<SkBitmap>::Read(const base::Pickle* m,
base::PickleIterator* iter,
SkBitmap* r) {
const char* fixed_data;
int fixed_data_size = 0;
if (!iter->ReadData(&fixed_data, &fixed_data_size) ||
(fixed_data_size <= 0)) {
return false;
}
if (fixed_data_size != sizeof(SkBitmap_Data))
return false; // Message is malformed.
const char* variable_data;
int variable_data_size = 0;
if (!iter->ReadData(&variable_data, &variable_data_size) ||
(variable_data_size < 0)) {
return false;
}
const SkBitmap_Data* bmp_data =
reinterpret_cast<const SkBitmap_Data*>(fixed_data);
return bmp_data->InitSkBitmapFromData(r, variable_data, variable_data_size);
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: unsigned int get_random_int(void)
{
struct keydata *keyptr;
__u32 *hash = get_cpu_var(get_random_int_hash);
int ret;
keyptr = get_keyptr();
hash[0] += current->pid + jiffies + get_cycles();
ret = half_md4_transform(hash, keyptr->secret);
put_cpu_var(get_random_int_hash);
return ret;
}
CWE ID:
Target: 1
Example 2:
Code: bool HTMLFormElement::layoutObjectIsNeeded(const ComputedStyle& style) {
if (!m_wasDemoted)
return HTMLElement::layoutObjectIsNeeded(style);
ContainerNode* node = parentNode();
if (!node || !node->layoutObject())
return HTMLElement::layoutObjectIsNeeded(style);
LayoutObject* parentLayoutObject = node->layoutObject();
bool parentIsTableElementPart =
(parentLayoutObject->isTable() && isHTMLTableElement(*node)) ||
(parentLayoutObject->isTableRow() && isHTMLTableRowElement(*node)) ||
(parentLayoutObject->isTableSection() && node->hasTagName(tbodyTag)) ||
(parentLayoutObject->isLayoutTableCol() && node->hasTagName(colTag)) ||
(parentLayoutObject->isTableCell() && isHTMLTableRowElement(*node));
if (!parentIsTableElementPart)
return true;
EDisplay display = style.display();
bool formIsTablePart =
display == EDisplay::Table || display == EDisplay::InlineTable ||
display == EDisplay::TableRowGroup ||
display == EDisplay::TableHeaderGroup ||
display == EDisplay::TableFooterGroup || display == EDisplay::TableRow ||
display == EDisplay::TableColumnGroup ||
display == EDisplay::TableColumn || display == EDisplay::TableCell ||
display == EDisplay::TableCaption;
return formIsTablePart;
}
CWE ID: CWE-19
Target: 0
Now analyze the following code 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: ubik_print(netdissect_options *ndo,
register const u_char *bp)
{
int ubik_op;
int32_t temp;
/*
* Print out the afs call we're invoking. The table used here was
* gleaned from ubik/ubik_int.xg
*/
ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header));
ND_PRINT((ndo, " ubik call %s", tok2str(ubik_req, "op#%d", ubik_op)));
/*
* Decode some of the arguments to the Ubik calls
*/
bp += sizeof(struct rx_header) + 4;
switch (ubik_op) {
case 10000: /* Beacon */
ND_TCHECK2(bp[0], 4);
temp = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
ND_PRINT((ndo, " syncsite %s", temp ? "yes" : "no"));
ND_PRINT((ndo, " votestart"));
DATEOUT();
ND_PRINT((ndo, " dbversion"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
break;
case 10003: /* Get sync site */
ND_PRINT((ndo, " site"));
UINTOUT();
break;
case 20000: /* Begin */
case 20001: /* Commit */
case 20007: /* Abort */
case 20008: /* Release locks */
case 20010: /* Writev */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
break;
case 20002: /* Lock */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " pos"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
temp = EXTRACT_32BITS(bp);
bp += sizeof(int32_t);
tok2str(ubik_lock_types, "type %d", temp);
break;
case 20003: /* Write */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " pos"));
INTOUT();
break;
case 20005: /* Get file */
ND_PRINT((ndo, " file"));
INTOUT();
break;
case 20006: /* Send file */
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
ND_PRINT((ndo, " dbversion"));
UBIK_VERSIONOUT();
break;
case 20009: /* Truncate */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " file"));
INTOUT();
ND_PRINT((ndo, " length"));
INTOUT();
break;
case 20012: /* Set version */
ND_PRINT((ndo, " tid"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " oldversion"));
UBIK_VERSIONOUT();
ND_PRINT((ndo, " newversion"));
UBIK_VERSIONOUT();
break;
default:
;
}
return;
trunc:
ND_PRINT((ndo, " [|ubik]"));
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ChromeMockRenderThread::OnGetDefaultPrintSettings(
PrintMsg_Print_Params* params) {
if (printer_.get())
printer_->GetDefaultPrintSettings(params);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: keepalived_running(unsigned long mode)
{
if (process_running(main_pidfile))
return true;
#ifdef _WITH_VRRP_
if (__test_bit(DAEMON_VRRP, &mode) && process_running(vrrp_pidfile))
return true;
#endif
#ifdef _WITH_LVS_
if (__test_bit(DAEMON_CHECKERS, &mode) && process_running(checkers_pidfile))
return true;
#endif
#ifdef _WITH_BFD_
if (__test_bit(DAEMON_BFD, &mode) && process_running(bfd_pidfile))
return true;
#endif
return false;
}
CWE ID: CWE-59
Target: 0
Now analyze the following code 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 pop_fetch_headers(struct Context *ctx)
{
struct PopData *pop_data = (struct PopData *) ctx->data;
struct Progress progress;
#ifdef USE_HCACHE
header_cache_t *hc = pop_hcache_open(pop_data, ctx->path);
#endif
time(&pop_data->check_time);
pop_data->clear_cache = false;
for (int i = 0; i < ctx->msgcount; i++)
ctx->hdrs[i]->refno = -1;
const int old_count = ctx->msgcount;
int ret = pop_fetch_data(pop_data, "UIDL\r\n", NULL, fetch_uidl, ctx);
const int new_count = ctx->msgcount;
ctx->msgcount = old_count;
if (pop_data->cmd_uidl == 2)
{
if (ret == 0)
{
pop_data->cmd_uidl = 1;
mutt_debug(1, "set UIDL capability\n");
}
if (ret == -2 && pop_data->cmd_uidl == 2)
{
pop_data->cmd_uidl = 0;
mutt_debug(1, "unset UIDL capability\n");
snprintf(pop_data->err_msg, sizeof(pop_data->err_msg), "%s",
_("Command UIDL is not supported by server."));
}
}
if (!ctx->quiet)
{
mutt_progress_init(&progress, _("Fetching message headers..."),
MUTT_PROGRESS_MSG, ReadInc, new_count - old_count);
}
if (ret == 0)
{
int i, deleted;
for (i = 0, deleted = 0; i < old_count; i++)
{
if (ctx->hdrs[i]->refno == -1)
{
ctx->hdrs[i]->deleted = true;
deleted++;
}
}
if (deleted > 0)
{
mutt_error(
ngettext("%d message has been lost. Try reopening the mailbox.",
"%d messages have been lost. Try reopening the mailbox.", deleted),
deleted);
}
bool hcached = false;
for (i = old_count; i < new_count; i++)
{
if (!ctx->quiet)
mutt_progress_update(&progress, i + 1 - old_count, -1);
#ifdef USE_HCACHE
void *data = mutt_hcache_fetch(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data));
if (data)
{
char *uidl = mutt_str_strdup(ctx->hdrs[i]->data);
int refno = ctx->hdrs[i]->refno;
int index = ctx->hdrs[i]->index;
/*
* - POP dynamically numbers headers and relies on h->refno
* to map messages; so restore header and overwrite restored
* refno with current refno, same for index
* - h->data needs to a separate pointer as it's driver-specific
* data freed separately elsewhere
* (the old h->data should point inside a malloc'd block from
* hcache so there shouldn't be a memleak here)
*/
struct Header *h = mutt_hcache_restore((unsigned char *) data);
mutt_hcache_free(hc, &data);
mutt_header_free(&ctx->hdrs[i]);
ctx->hdrs[i] = h;
ctx->hdrs[i]->refno = refno;
ctx->hdrs[i]->index = index;
ctx->hdrs[i]->data = uidl;
ret = 0;
hcached = true;
}
else
#endif
if ((ret = pop_read_header(pop_data, ctx->hdrs[i])) < 0)
break;
#ifdef USE_HCACHE
else
{
mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data),
ctx->hdrs[i], 0);
}
#endif
/*
* faked support for flags works like this:
* - if 'hcached' is true, we have the message in our hcache:
* - if we also have a body: read
* - if we don't have a body: old
* (if $mark_old is set which is maybe wrong as
* $mark_old should be considered for syncing the
* folder and not when opening it XXX)
* - if 'hcached' is false, we don't have the message in our hcache:
* - if we also have a body: read
* - if we don't have a body: new
*/
const bool bcached =
(mutt_bcache_exists(pop_data->bcache, ctx->hdrs[i]->data) == 0);
ctx->hdrs[i]->old = false;
ctx->hdrs[i]->read = false;
if (hcached)
{
if (bcached)
ctx->hdrs[i]->read = true;
else if (MarkOld)
ctx->hdrs[i]->old = true;
}
else
{
if (bcached)
ctx->hdrs[i]->read = true;
}
ctx->msgcount++;
}
if (i > old_count)
mx_update_context(ctx, i - old_count);
}
#ifdef USE_HCACHE
mutt_hcache_close(hc);
#endif
if (ret < 0)
{
for (int i = ctx->msgcount; i < new_count; i++)
mutt_header_free(&ctx->hdrs[i]);
return ret;
}
/* after putting the result into our structures,
* clean up cache, i.e. wipe messages deleted outside
* the availability of our cache
*/
if (MessageCacheClean)
mutt_bcache_list(pop_data->bcache, msg_cache_check, (void *) ctx);
mutt_clear_error();
return (new_count - old_count);
}
CWE ID: CWE-22
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE SoftAVCEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcParams =
(OMX_VIDEO_PARAM_AVCTYPE *)params;
if (avcParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
OMX_U32 omxLevel = AVC_LEVEL2;
if (OMX_ErrorNone !=
ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
return OMX_ErrorUndefined;
}
avcParams->eLevel = (OMX_VIDEO_AVCLEVELTYPE) omxLevel;
avcParams->nRefFrames = 1;
avcParams->nBFrames = 0;
avcParams->bUseHadamard = OMX_TRUE;
avcParams->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
avcParams->nRefIdx10ActiveMinus1 = 0;
avcParams->nRefIdx11ActiveMinus1 = 0;
avcParams->bWeightedPPrediction = OMX_FALSE;
avcParams->bEntropyCodingCABAC = OMX_FALSE;
avcParams->bconstIpred = OMX_FALSE;
avcParams->bDirect8x8Inference = OMX_FALSE;
avcParams->bDirectSpatialTemporal = OMX_FALSE;
avcParams->nCabacInitIdc = 0;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool Element::hasAttribute(const QualifiedName& name) const
{
return hasAttributeNS(name.namespaceURI(), name.localName());
}
CWE ID: CWE-399
Target: 0
Now analyze the following code 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 TabLifecycleUnitSource::TabLifecycleUnit::Freeze() {
if (!IsValidStateChange(GetState(), LifecycleUnitState::PENDING_FREEZE,
StateChangeReason::BROWSER_INITIATED)) {
return false;
}
if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE)
return false;
SetState(LifecycleUnitState::PENDING_FREEZE,
StateChangeReason::BROWSER_INITIATED);
GetWebContents()->SetPageFrozen(true);
return true;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: IPC::PlatformFileForTransit ProxyChannelDelegate::ShareHandleWithRemote(
base::PlatformFile handle,
const IPC::SyncChannel& channel,
bool should_close_source) {
return content::BrokerGetFileHandleForProcess(handle, channel.peer_pid(),
should_close_source);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void WebContentsImpl::AttachToOuterWebContentsFrame(
WebContents* outer_web_contents,
RenderFrameHost* outer_contents_frame) {
DCHECK(!node_.outer_web_contents());
RenderFrameHostManager* render_manager = GetRenderManager();
view_.reset(new WebContentsViewChildFrame(
this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
&render_view_host_delegate_view_));
render_manager->InitRenderView(GetRenderViewHost(), nullptr);
GetMainFrame()->Init();
if (!render_manager->GetRenderWidgetHostView())
CreateRenderWidgetHostViewForRenderManager(GetRenderViewHost());
auto* outer_web_contents_impl =
static_cast<WebContentsImpl*>(outer_web_contents);
auto* outer_contents_frame_impl =
static_cast<RenderFrameHostImpl*>(outer_contents_frame);
node_.ConnectToOuterWebContents(outer_web_contents_impl,
outer_contents_frame_impl);
DCHECK(outer_contents_frame);
render_manager->CreateOuterDelegateProxy(
outer_contents_frame->GetSiteInstance(), outer_contents_frame_impl);
ReattachToOuterWebContentsFrame();
if (outer_web_contents_impl->frame_tree_.GetFocusedFrame() ==
outer_contents_frame_impl->frame_tree_node()) {
SetFocusedFrame(frame_tree_.root(),
outer_contents_frame->GetSiteInstance());
}
text_input_manager_.reset(nullptr);
}
CWE ID: CWE-254
Target: 0
Now analyze the following code 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 async_read_clear_handlers(AsyncRead *obj)
{
ssize_t ret;
if (!s->sasl.encoded) {
int err;
err = sasl_encode(s->sasl.conn, (char *)buf, nbyte,
(const char **)&s->sasl.encoded,
&s->sasl.encodedLength);
if (err != SASL_OK) {
spice_warning("sasl_encode error: %d", err);
return -1;
}
if (s->sasl.encodedLength == 0) {
return 0;
}
if (!s->sasl.encoded) {
spice_warning("sasl_encode didn't return a buffer!");
return 0;
}
s->sasl.encodedOffset = 0;
}
ret = s->write(s, s->sasl.encoded + s->sasl.encodedOffset,
s->sasl.encodedLength - s->sasl.encodedOffset);
if (ret <= 0) {
return ret;
}
s->sasl.encodedOffset += ret;
if (s->sasl.encodedOffset == s->sasl.encodedLength) {
s->sasl.encoded = NULL;
s->sasl.encodedOffset = s->sasl.encodedLength = 0;
return nbyte;
}
/* we didn't flush the encoded buffer */
errno = EAGAIN;
return -1;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void xen_netbk_tx_submit(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops;
struct sk_buff *skb;
while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) {
struct xen_netif_tx_request *txp;
struct xenvif *vif;
u16 pending_idx;
unsigned data_len;
pending_idx = *((u16 *)skb->data);
vif = netbk->pending_tx_info[pending_idx].vif;
txp = &netbk->pending_tx_info[pending_idx].req;
/* Check the remap error code. */
if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) {
netdev_dbg(vif->dev, "netback grant failed.\n");
skb_shinfo(skb)->nr_frags = 0;
kfree_skb(skb);
continue;
}
data_len = skb->len;
memcpy(skb->data,
(void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset),
data_len);
if (data_len < txp->size) {
/* Append the packet payload as a fragment. */
txp->offset += data_len;
txp->size -= data_len;
} else {
/* Schedule a response immediately. */
xen_netbk_idx_release(netbk, pending_idx);
}
if (txp->flags & XEN_NETTXF_csum_blank)
skb->ip_summed = CHECKSUM_PARTIAL;
else if (txp->flags & XEN_NETTXF_data_validated)
skb->ip_summed = CHECKSUM_UNNECESSARY;
xen_netbk_fill_frags(netbk, skb);
/*
* If the initial fragment was < PKT_PROT_LEN then
* pull through some bytes from the other fragments to
* increase the linear region to PKT_PROT_LEN bytes.
*/
if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) {
int target = min_t(int, skb->len, PKT_PROT_LEN);
__pskb_pull_tail(skb, target - skb_headlen(skb));
}
skb->dev = vif->dev;
skb->protocol = eth_type_trans(skb, skb->dev);
if (checksum_setup(vif, skb)) {
netdev_dbg(vif->dev,
"Can't setup checksum in net_tx_action\n");
kfree_skb(skb);
continue;
}
vif->dev->stats.rx_bytes += skb->len;
vif->dev->stats.rx_packets++;
xenvif_receive_skb(vif, skb);
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: int GetPreCountAndReset() {
int r = pre_count_;
pre_count_ = 0;
return r;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 validate_camera_metadata_structure(const camera_metadata_t *metadata,
const size_t *expected_size) {
if (metadata == NULL) {
ALOGE("%s: metadata is null!", __FUNCTION__);
return ERROR;
}
{
static const struct {
const char *name;
size_t alignment;
} alignments[] = {
{
.name = "camera_metadata",
.alignment = METADATA_ALIGNMENT
},
{
.name = "camera_metadata_buffer_entry",
.alignment = ENTRY_ALIGNMENT
},
{
.name = "camera_metadata_data",
.alignment = DATA_ALIGNMENT
},
};
for (size_t i = 0; i < sizeof(alignments)/sizeof(alignments[0]); ++i) {
uintptr_t aligned_ptr = ALIGN_TO(metadata, alignments[i].alignment);
if ((uintptr_t)metadata != aligned_ptr) {
ALOGE("%s: Metadata pointer is not aligned (actual %p, "
"expected %p) to type %s",
__FUNCTION__, metadata,
(void*)aligned_ptr, alignments[i].name);
return ERROR;
}
}
}
/**
* Check that the metadata contents are correct
*/
if (expected_size != NULL && metadata->size > *expected_size) {
ALOGE("%s: Metadata size (%" PRIu32 ") should be <= expected size (%zu)",
__FUNCTION__, metadata->size, *expected_size);
return ERROR;
}
if (metadata->entry_count > metadata->entry_capacity) {
ALOGE("%s: Entry count (%" PRIu32 ") should be <= entry capacity "
"(%" PRIu32 ")",
__FUNCTION__, metadata->entry_count, metadata->entry_capacity);
return ERROR;
}
const metadata_uptrdiff_t entries_end =
metadata->entries_start + metadata->entry_capacity;
if (entries_end < metadata->entries_start || // overflow check
entries_end > metadata->data_start) {
ALOGE("%s: Entry start + capacity (%" PRIu32 ") should be <= data start "
"(%" PRIu32 ")",
__FUNCTION__,
(metadata->entries_start + metadata->entry_capacity),
metadata->data_start);
return ERROR;
}
const metadata_uptrdiff_t data_end =
metadata->data_start + metadata->data_capacity;
if (data_end < metadata->data_start || // overflow check
data_end > metadata->size) {
ALOGE("%s: Data start + capacity (%" PRIu32 ") should be <= total size "
"(%" PRIu32 ")",
__FUNCTION__,
(metadata->data_start + metadata->data_capacity),
metadata->size);
return ERROR;
}
const metadata_size_t entry_count = metadata->entry_count;
camera_metadata_buffer_entry_t *entries = get_entries(metadata);
for (size_t i = 0; i < entry_count; ++i) {
if ((uintptr_t)&entries[i] != ALIGN_TO(&entries[i], ENTRY_ALIGNMENT)) {
ALOGE("%s: Entry index %zu had bad alignment (address %p),"
" expected alignment %zu",
__FUNCTION__, i, &entries[i], ENTRY_ALIGNMENT);
return ERROR;
}
camera_metadata_buffer_entry_t entry = entries[i];
if (entry.type >= NUM_TYPES) {
ALOGE("%s: Entry index %zu had a bad type %d",
__FUNCTION__, i, entry.type);
return ERROR;
}
uint32_t tag_section = entry.tag >> 16;
int tag_type = get_camera_metadata_tag_type(entry.tag);
if (tag_type != (int)entry.type && tag_section < VENDOR_SECTION) {
ALOGE("%s: Entry index %zu had tag type %d, but the type was %d",
__FUNCTION__, i, tag_type, entry.type);
return ERROR;
}
size_t data_size;
if (validate_and_calculate_camera_metadata_entry_data_size(&data_size, entry.type,
entry.count) != OK) {
ALOGE("%s: Entry data size is invalid. type: %u count: %u", __FUNCTION__, entry.type,
entry.count);
return ERROR;
}
if (data_size != 0) {
camera_metadata_data_t *data =
(camera_metadata_data_t*) (get_data(metadata) +
entry.data.offset);
if ((uintptr_t)data != ALIGN_TO(data, DATA_ALIGNMENT)) {
ALOGE("%s: Entry index %zu had bad data alignment (address %p),"
" expected align %zu, (tag name %s, data size %zu)",
__FUNCTION__, i, data, DATA_ALIGNMENT,
get_camera_metadata_tag_name(entry.tag) ?: "unknown",
data_size);
return ERROR;
}
size_t data_entry_end = entry.data.offset + data_size;
if (data_entry_end < entry.data.offset || // overflow check
data_entry_end > metadata->data_capacity) {
ALOGE("%s: Entry index %zu data ends (%zu) beyond the capacity "
"%" PRIu32, __FUNCTION__, i, data_entry_end,
metadata->data_capacity);
return ERROR;
}
} else if (entry.count == 0) {
if (entry.data.offset != 0) {
ALOGE("%s: Entry index %zu had 0 items, but offset was non-0 "
"(%" PRIu32 "), tag name: %s", __FUNCTION__, i, entry.data.offset,
get_camera_metadata_tag_name(entry.tag) ?: "unknown");
return ERROR;
}
} // else data stored inline, so we look at value which can be anything.
}
return OK;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void InputMethodBase::OnInputMethodChanged() const {
TextInputClient* client = GetTextInputClient();
if (client && client->GetTextInputType() != TEXT_INPUT_TYPE_NONE)
client->OnInputMethodChanged();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void RenderFrameHostImpl::Init() {
ResumeBlockedRequestsForFrame();
if (!waiting_for_init_)
return;
waiting_for_init_ = false;
if (pending_navigate_) {
frame_tree_node()->navigator()->OnBeginNavigation(
frame_tree_node(), pending_navigate_->common_params,
std::move(pending_navigate_->begin_params),
std::move(pending_navigate_->blob_url_loader_factory));
pending_navigate_.reset();
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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: iakerb_gss_set_sec_context_option(OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
const gss_OID desired_object,
const gss_buffer_t value)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)*context_handle;
if (ctx == NULL || ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_UNAVAILABLE;
return krb5_gss_set_sec_context_option(minor_status, &ctx->gssc,
desired_object, value);
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BaseShadow::log_except(const char *msg)
{
ShadowExceptionEvent event;
bool exception_already_logged = false;
if(!msg) msg = "";
sprintf(event.message, msg);
if ( BaseShadow::myshadow_ptr ) {
BaseShadow *shadow = BaseShadow::myshadow_ptr;
event.recvd_bytes = shadow->bytesSent();
event.sent_bytes = shadow->bytesReceived();
exception_already_logged = shadow->exception_already_logged;
if (shadow->began_execution) {
event.began_execution = TRUE;
}
} else {
event.recvd_bytes = 0.0;
event.sent_bytes = 0.0;
}
if (!exception_already_logged && !uLog.writeEventNoFsync (&event,NULL))
{
::dprintf (D_ALWAYS, "Unable to log ULOG_SHADOW_EXCEPTION event\n");
}
}
CWE ID: CWE-134
Target: 1
Example 2:
Code: void NonWhitelistedCommandsAreDisabled(CommandUpdaterImpl* command_updater) {
constexpr int kWhitelistedIds[] = {
IDC_CUT, IDC_COPY, IDC_PASTE,
IDC_FIND, IDC_FIND_NEXT, IDC_FIND_PREVIOUS,
IDC_ZOOM_PLUS, IDC_ZOOM_NORMAL, IDC_ZOOM_MINUS,
};
for (int id : command_updater->GetAllIds()) {
if (base::ContainsValue(kWhitelistedIds, id)) {
continue;
}
DCHECK(!command_updater->IsCommandEnabled(id));
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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 GetResponseInfoSize(const net::HttpResponseInfo* info) {
base::Pickle pickle;
return PickleResponseInfo(&pickle, info);
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: spnego_gss_accept_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_cred_id_t verifier_cred_handle,
gss_buffer_t input_token,
gss_channel_bindings_t input_chan_bindings,
gss_name_t *src_name,
gss_OID *mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec,
gss_cred_id_t *delegated_cred_handle)
{
OM_uint32 ret, tmpmin, negState;
send_token_flag return_token;
gss_buffer_t mechtok_in, mic_in, mic_out;
gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER;
spnego_gss_ctx_id_t sc = NULL;
spnego_gss_cred_id_t spcred = NULL;
int sendTokenInit = 0, tmpret;
mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER;
/*
* This function works in three steps:
*
* 1. Perform mechanism negotiation.
* 2. Invoke the negotiated mech's gss_accept_sec_context function
* and examine the results.
* 3. Process or generate MICs if necessary.
*
* Step one determines whether the negotiation requires a MIC exchange,
* while steps two and three share responsibility for determining when
* the exchange is complete. If the selected mech completes in this
* call and no MIC exchange is expected, then step 2 will decide. If a
* MIC exchange is expected, then step 3 will decide. If an error
* occurs in any step, the exchange will be aborted, possibly with an
* error token.
*
* negState determines the state of the negotiation, and is
* communicated to the acceptor if a continuing token is sent.
* return_token is used to indicate what type of token, if any, should
* be generated.
*/
/* Validate arguments. */
if (minor_status != NULL)
*minor_status = 0;
if (output_token != GSS_C_NO_BUFFER) {
output_token->length = 0;
output_token->value = NULL;
}
if (minor_status == NULL ||
output_token == GSS_C_NO_BUFFER ||
context_handle == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
if (input_token == GSS_C_NO_BUFFER)
return GSS_S_CALL_INACCESSIBLE_READ;
/* Step 1: Perform mechanism negotiation. */
sc = (spnego_gss_ctx_id_t)*context_handle;
spcred = (spnego_gss_cred_id_t)verifier_cred_handle;
if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) {
/* Process an initial token or request for NegHints. */
if (src_name != NULL)
*src_name = GSS_C_NO_NAME;
if (mech_type != NULL)
*mech_type = GSS_C_NO_OID;
if (time_rec != NULL)
*time_rec = 0;
if (ret_flags != NULL)
*ret_flags = 0;
if (delegated_cred_handle != NULL)
*delegated_cred_handle = GSS_C_NO_CREDENTIAL;
if (input_token->length == 0) {
ret = acc_ctx_hints(minor_status,
context_handle, spcred,
&mic_out,
&negState,
&return_token);
if (ret != GSS_S_COMPLETE)
goto cleanup;
sendTokenInit = 1;
ret = GSS_S_CONTINUE_NEEDED;
} else {
/* Can set negState to REQUEST_MIC */
ret = acc_ctx_new(minor_status, input_token,
context_handle, spcred,
&mechtok_in, &mic_in,
&negState, &return_token);
if (ret != GSS_S_COMPLETE)
goto cleanup;
ret = GSS_S_CONTINUE_NEEDED;
}
} else {
/* Process a response token. Can set negState to
* ACCEPT_INCOMPLETE. */
ret = acc_ctx_cont(minor_status, input_token,
context_handle, &mechtok_in,
&mic_in, &negState, &return_token);
if (ret != GSS_S_COMPLETE)
goto cleanup;
ret = GSS_S_CONTINUE_NEEDED;
}
/* Step 2: invoke the negotiated mechanism's gss_accept_sec_context
* function. */
sc = (spnego_gss_ctx_id_t)*context_handle;
/*
* Handle mechtok_in and mic_in only if they are
* present in input_token. If neither is present, whether
* this is an error depends on whether this is the first
* round-trip. RET is set to a default value according to
* whether it is the first round-trip.
*/
if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) {
ret = acc_ctx_call_acc(minor_status, sc, spcred,
mechtok_in, mech_type, &mechtok_out,
ret_flags, time_rec,
delegated_cred_handle,
&negState, &return_token);
}
/* Step 3: process or generate the MIC, if the negotiated mech is
* complete and supports MICs. */
if (!HARD_ERROR(ret) && sc->mech_complete &&
(sc->ctx_flags & GSS_C_INTEG_FLAG)) {
ret = handle_mic(minor_status, mic_in,
(mechtok_out.length != 0),
sc, &mic_out,
&negState, &return_token);
}
cleanup:
if (return_token == INIT_TOKEN_SEND && sendTokenInit) {
assert(sc != NULL);
tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0,
GSS_C_NO_BUFFER,
return_token, output_token);
if (tmpret < 0)
ret = GSS_S_FAILURE;
} else if (return_token != NO_TOKEN_SEND &&
return_token != CHECK_MIC) {
tmpret = make_spnego_tokenTarg_msg(negState,
sc ? sc->internal_mech :
GSS_C_NO_OID,
&mechtok_out, mic_out,
return_token,
output_token);
if (tmpret < 0)
ret = GSS_S_FAILURE;
}
if (ret == GSS_S_COMPLETE) {
*context_handle = (gss_ctx_id_t)sc->ctx_handle;
if (sc->internal_name != GSS_C_NO_NAME &&
src_name != NULL) {
*src_name = sc->internal_name;
sc->internal_name = GSS_C_NO_NAME;
}
release_spnego_ctx(&sc);
} else if (ret != GSS_S_CONTINUE_NEEDED) {
if (sc != NULL) {
gss_delete_sec_context(&tmpmin, &sc->ctx_handle,
GSS_C_NO_BUFFER);
release_spnego_ctx(&sc);
}
*context_handle = GSS_C_NO_CONTEXT;
}
gss_release_buffer(&tmpmin, &mechtok_out);
if (mechtok_in != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mechtok_in);
free(mechtok_in);
}
if (mic_in != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mic_in);
free(mic_in);
}
if (mic_out != GSS_C_NO_BUFFER) {
gss_release_buffer(&tmpmin, mic_out);
free(mic_out);
}
return ret;
}
CWE ID: CWE-18
Target: 1
Example 2:
Code: resp_print_simple_string(netdissect_options *ndo, register const u_char *bp, int length) {
return resp_print_string_error_integer(ndo, bp, length);
}
CWE ID: CWE-835
Target: 0
Now analyze the following code 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 WebGLRenderingContextBase::ValidateWebGLProgramOrShader(
const char* function_name,
WebGLObject* object) {
if (isContextLost())
return false;
DCHECK(object);
if (!object->HasObject()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name,
"attempt to use a deleted object");
return false;
}
if (!object->Validate(ContextGroup(), this)) {
SynthesizeGLError(GL_INVALID_OPERATION, function_name,
"object does not belong to this context");
return false;
}
return true;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ActionReply Smb4KMountHelper::mount(const QVariantMap &args)
{
ActionReply reply;
QMapIterator<QString, QVariant> it(args);
proc.setOutputChannelMode(KProcess::SeparateChannels);
proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment());
#if defined(Q_OS_LINUX)
proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true);
#endif
QVariantMap entry = it.value().toMap();
KProcess proc(this);
command << entry["mh_mountpoint"].toString();
command << entry["mh_options"].toStringList();
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
command << entry["mh_command"].toString();
command << entry["mh_options"].toStringList();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
#else
#endif
proc.setProgram(command);
proc.start();
if (proc.waitForStarted(-1))
{
bool userKill = false;
QStringList command;
#if defined(Q_OS_LINUX)
command << entry["mh_command"].toString();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
command << entry["mh_options"].toStringList();
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
command << entry["mh_command"].toString();
command << entry["mh_options"].toStringList();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
else
{
}
if (HelperSupport::isStopped())
{
proc.kill();
userKill = true;
break;
}
else
{
}
}
if (proc.exitStatus() == KProcess::CrashExit)
{
if (!userKill)
{
reply.setType(ActionReply::HelperErrorType);
reply.setErrorDescription(i18n("The mount process crashed."));
break;
}
else
{
}
}
else
{
QString stdErr = QString::fromUtf8(proc.readAllStandardError());
reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed());
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void WebGLRenderingContextBase::texSubImage2D(
GLenum target,
GLint level,
GLint xoffset,
GLint yoffset,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels) {
TexImageHelperDOMArrayBufferView(kTexSubImage2D, target, level, 0, width,
height, 1, 0, format, type, xoffset, yoffset,
0, pixels.View(), kNullNotAllowed, 0);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code 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 i8042_controller_resume(bool s2r_wants_reset)
{
int error;
error = i8042_controller_check();
if (error)
return error;
if (i8042_reset == I8042_RESET_ALWAYS ||
(i8042_reset == I8042_RESET_ON_S2RAM && s2r_wants_reset)) {
error = i8042_controller_selftest();
if (error)
return error;
}
/*
* Restore original CTR value and disable all ports
*/
i8042_ctr = i8042_initial_ctr;
if (i8042_direct)
i8042_ctr &= ~I8042_CTR_XLATE;
i8042_ctr |= I8042_CTR_AUXDIS | I8042_CTR_KBDDIS;
i8042_ctr &= ~(I8042_CTR_AUXINT | I8042_CTR_KBDINT);
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
pr_warn("Can't write CTR to resume, retrying...\n");
msleep(50);
if (i8042_command(&i8042_ctr, I8042_CMD_CTL_WCTR)) {
pr_err("CTR write retry failed\n");
return -EIO;
}
}
#ifdef CONFIG_X86
if (i8042_dritek)
i8042_dritek_enable();
#endif
if (i8042_mux_present) {
if (i8042_set_mux_mode(true, NULL) || i8042_enable_mux_ports())
pr_warn("failed to resume active multiplexor, mouse won't work\n");
} else if (i8042_ports[I8042_AUX_PORT_NO].serio)
i8042_enable_aux_port();
if (i8042_ports[I8042_KBD_PORT_NO].serio)
i8042_enable_kbd_port();
i8042_interrupt(0, NULL);
return 0;
}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: png_have_neon(png_structp png_ptr)
{
FILE *f = fopen("/proc/cpuinfo", "rb");
if (f != NULL)
{
/* This is a simple state machine which reads the input byte-by-byte until
* it gets a match on the 'neon' feature or reaches the end of the stream.
*/
static const char ch_feature[] = { 70, 69, 65, 84, 85, 82, 69, 83 };
static const char ch_neon[] = { 78, 69, 79, 78 };
enum
{
StartLine, Feature, Colon, StartTag, Neon, HaveNeon, SkipTag, SkipLine
} state;
int counter;
for (state=StartLine, counter=0;;)
{
int ch = fgetc(f);
if (ch == EOF)
{
/* EOF means error or end-of-file, return false; neon at EOF is
* assumed to be a mistake.
*/
fclose(f);
return 0;
}
switch (state)
{
case StartLine:
/* Match spaces at the start of line */
if (ch <= 32) /* skip control characters and space */
break;
counter=0;
state = Feature;
/* FALL THROUGH */
case Feature:
/* Match 'FEATURE', ASCII case insensitive. */
if ((ch & ~0x20) == ch_feature[counter])
{
if (++counter == (sizeof ch_feature))
state = Colon;
break;
}
/* did not match 'feature' */
state = SkipLine;
/* FALL THROUGH */
case SkipLine:
skipLine:
/* Skip everything until we see linefeed or carriage return */
if (ch != 10 && ch != 13)
break;
state = StartLine;
break;
case Colon:
/* Match any number of space or tab followed by ':' */
if (ch == 32 || ch == 9)
break;
if (ch == 58) /* i.e. ':' */
{
state = StartTag;
break;
}
/* Either a bad line format or a 'feature' prefix followed by
* other characters.
*/
state = SkipLine;
goto skipLine;
case StartTag:
/* Skip space characters before a tag */
if (ch == 32 || ch == 9)
break;
state = Neon;
counter = 0;
/* FALL THROUGH */
case Neon:
/* Look for 'neon' tag */
if ((ch & ~0x20) == ch_neon[counter])
{
if (++counter == (sizeof ch_neon))
state = HaveNeon;
break;
}
state = SkipTag;
/* FALL THROUGH */
case SkipTag:
/* Skip non-space characters */
if (ch == 10 || ch == 13)
state = StartLine;
else if (ch == 32 || ch == 9)
state = StartTag;
break;
case HaveNeon:
/* Have seen a 'neon' prefix, but there must be a space or new
* line character to terminate it.
*/
if (ch == 10 || ch == 13 || ch == 32 || ch == 9)
{
fclose(f);
return 1;
}
state = SkipTag;
break;
default:
png_error(png_ptr, "png_have_neon: internal error (bug)");
}
}
}
else
png_warning(png_ptr, "/proc/cpuinfo open failed");
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: BOOL security_encrypt(BYTE* data, int length, rdpRdp* rdp)
{
if (rdp->encrypt_use_count >= 4096)
{
security_key_update(rdp->encrypt_key, rdp->encrypt_update_key, rdp->rc4_key_len);
crypto_rc4_free(rdp->rc4_encrypt_key);
rdp->rc4_encrypt_key = crypto_rc4_init(rdp->encrypt_key, rdp->rc4_key_len);
rdp->encrypt_use_count = 0;
}
crypto_rc4(rdp->rc4_encrypt_key, length, data, data);
rdp->encrypt_use_count++;
rdp->encrypt_checksum_use_count++;
return TRUE;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code 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 main(int argc, char *argv[])
{
int ret;
struct lxc_lock *lock;
lock = lxc_newlock(NULL, NULL);
if (!lock) {
fprintf(stderr, "%d: failed to get unnamed lock\n", __LINE__);
exit(1);
}
ret = lxclock(lock, 0);
if (ret) {
fprintf(stderr, "%d: failed to take unnamed lock (%d)\n", __LINE__, ret);
exit(1);
}
ret = lxcunlock(lock);
if (ret) {
fprintf(stderr, "%d: failed to put unnamed lock (%d)\n", __LINE__, ret);
exit(1);
}
lxc_putlock(lock);
lock = lxc_newlock("/var/lib/lxc", mycontainername);
if (!lock) {
fprintf(stderr, "%d: failed to get lock\n", __LINE__);
exit(1);
}
struct stat sb;
char *pathname = RUNTIME_PATH "/lock/lxc/var/lib/lxc/";
ret = stat(pathname, &sb);
if (ret != 0) {
fprintf(stderr, "%d: filename %s not created\n", __LINE__,
pathname);
exit(1);
}
lxc_putlock(lock);
test_two_locks();
fprintf(stderr, "all tests passed\n");
exit(ret);
}
CWE ID: CWE-59
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int intel_pmu_drain_bts_buffer(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct debug_store *ds = cpuc->ds;
struct bts_record {
u64 from;
u64 to;
u64 flags;
};
struct perf_event *event = cpuc->events[X86_PMC_IDX_FIXED_BTS];
struct bts_record *at, *top;
struct perf_output_handle handle;
struct perf_event_header header;
struct perf_sample_data data;
struct pt_regs regs;
if (!event)
return 0;
if (!x86_pmu.bts_active)
return 0;
at = (struct bts_record *)(unsigned long)ds->bts_buffer_base;
top = (struct bts_record *)(unsigned long)ds->bts_index;
if (top <= at)
return 0;
ds->bts_index = ds->bts_buffer_base;
perf_sample_data_init(&data, 0);
data.period = event->hw.last_period;
regs.ip = 0;
/*
* Prepare a generic sample, i.e. fill in the invariant fields.
* We will overwrite the from and to address before we output
* the sample.
*/
perf_prepare_sample(&header, &data, event, ®s);
if (perf_output_begin(&handle, event, header.size * (top - at), 1, 1))
return 1;
for (; at < top; at++) {
data.ip = at->from;
data.addr = at->to;
perf_output_sample(&handle, &header, &data, event);
}
perf_output_end(&handle);
/* There's new data available. */
event->hw.interrupts++;
event->pending_kill = POLL_IN;
return 1;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void dvcC_del(GF_Box *s)
{
GF_DOVIConfigurationBox *ptr = (GF_DOVIConfigurationBox*)s;
gf_free(ptr);
}
CWE ID: CWE-400
Target: 0
Now analyze the following code 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: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle,
TALLOC_CTX *ctx, const char *src, size_t n)
{
size_t size=0;
char *dest;
if (!src) {
return NULL;
}
/* this takes advantage of the fact that upper/lower can't
change the length of a character by more than 1 byte */
dest = talloc_array(ctx, char, 2*(n+1));
if (dest == NULL) {
return NULL;
}
while (n-- && *src) {
size_t c_size;
codepoint_t c = next_codepoint_handle_ext(iconv_handle, src, n,
CH_UNIX, &c_size);
src += c_size;
c = toupper_m(c);
if (c_size == -1) {
talloc_free(dest);
return NULL;
}
size += c_size;
}
dest[size] = 0;
/* trim it so talloc_append_string() works */
dest = talloc_realloc(ctx, dest, char, size+1);
talloc_set_name_const(dest, dest);
return dest;
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents)
: PrintManager(web_contents),
printing_rfh_(nullptr),
printing_succeeded_(false),
inside_inner_message_loop_(false),
#if !defined(OS_MACOSX)
expecting_first_page_(true),
#endif
queue_(g_browser_process->print_job_manager()->queue()) {
DCHECK(queue_.get());
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
printing_enabled_.Init(
prefs::kPrintingEnabled, profile->GetPrefs(),
base::Bind(&PrintViewManagerBase::UpdatePrintingEnabled,
base::Unretained(this)));
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static void shm_add_rss_swap(struct shmid_kernel *shp,
unsigned long *rss_add, unsigned long *swp_add)
{
struct inode *inode;
inode = file_inode(shp->shm_file);
if (is_file_hugepages(shp->shm_file)) {
struct address_space *mapping = inode->i_mapping;
struct hstate *h = hstate_file(shp->shm_file);
*rss_add += pages_per_huge_page(h) * mapping->nrpages;
} else {
#ifdef CONFIG_SHMEM
struct shmem_inode_info *info = SHMEM_I(inode);
spin_lock(&info->lock);
*rss_add += inode->i_mapping->nrpages;
*swp_add += info->swapped;
spin_unlock(&info->lock);
#else
*rss_add += inode->i_mapping->nrpages;
#endif
}
}
CWE ID: CWE-362
Target: 0
Now analyze the following code 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 TypedUrlModelAssociator::AssociateModels() {
VLOG(1) << "Associating TypedUrl Models";
DCHECK(expected_loop_ == MessageLoop::current());
std::vector<history::URLRow> typed_urls;
if (!history_backend_->GetAllTypedURLs(&typed_urls)) {
LOG(ERROR) << "Could not get the typed_url entries.";
return false;
}
std::map<history::URLID, history::VisitVector> visit_vectors;
for (std::vector<history::URLRow>::iterator ix = typed_urls.begin();
ix != typed_urls.end(); ++ix) {
if (!history_backend_->GetVisitsForURL(ix->id(),
&(visit_vectors[ix->id()]))) {
LOG(ERROR) << "Could not get the url's visits.";
return false;
}
if (visit_vectors[ix->id()].empty()) {
history::VisitRow visit(
ix->id(), ix->last_visit(), 0, PageTransition::TYPED, 0);
visit_vectors[ix->id()].push_back(visit);
}
}
TypedUrlTitleVector titles;
TypedUrlVector new_urls;
TypedUrlVisitVector new_visits;
TypedUrlUpdateVector updated_urls;
{
sync_api::WriteTransaction trans(sync_service_->GetUserShare());
sync_api::ReadNode typed_url_root(&trans);
if (!typed_url_root.InitByTagLookup(kTypedUrlTag)) {
LOG(ERROR) << "Server did not create the top-level typed_url node. We "
<< "might be running against an out-of-date server.";
return false;
}
std::set<std::string> current_urls;
for (std::vector<history::URLRow>::iterator ix = typed_urls.begin();
ix != typed_urls.end(); ++ix) {
std::string tag = ix->url().spec();
history::VisitVector& visits = visit_vectors[ix->id()];
sync_api::ReadNode node(&trans);
if (node.InitByClientTagLookup(syncable::TYPED_URLS, tag)) {
const sync_pb::TypedUrlSpecifics& typed_url(
node.GetTypedUrlSpecifics());
DCHECK_EQ(tag, typed_url.url());
history::URLRow new_url(*ix);
std::vector<history::VisitInfo> added_visits;
int difference = MergeUrls(typed_url, *ix, &visits, &new_url,
&added_visits);
if (difference & DIFF_UPDATE_NODE) {
sync_api::WriteNode write_node(&trans);
if (!write_node.InitByClientTagLookup(syncable::TYPED_URLS, tag)) {
LOG(ERROR) << "Failed to edit typed_url sync node.";
return false;
}
if (typed_url.visits_size() > 0) {
base::Time earliest_visit =
base::Time::FromInternalValue(typed_url.visits(0));
for (history::VisitVector::iterator it = visits.begin();
it != visits.end() && it->visit_time < earliest_visit; ) {
it = visits.erase(it);
}
DCHECK(visits.size() > 0);
} else {
NOTREACHED() << "Syncing typed URL with no visits: " <<
typed_url.url();
}
WriteToSyncNode(new_url, visits, &write_node);
}
if (difference & DIFF_LOCAL_TITLE_CHANGED) {
titles.push_back(std::pair<GURL, string16>(new_url.url(),
new_url.title()));
}
if (difference & DIFF_LOCAL_ROW_CHANGED) {
updated_urls.push_back(
std::pair<history::URLID, history::URLRow>(ix->id(), new_url));
}
if (difference & DIFF_LOCAL_VISITS_ADDED) {
new_visits.push_back(
std::pair<GURL, std::vector<history::VisitInfo> >(ix->url(),
added_visits));
}
Associate(&tag, node.GetId());
} else {
sync_api::WriteNode node(&trans);
if (!node.InitUniqueByCreation(syncable::TYPED_URLS,
typed_url_root, tag)) {
LOG(ERROR) << "Failed to create typed_url sync node.";
return false;
}
node.SetTitle(UTF8ToWide(tag));
WriteToSyncNode(*ix, visits, &node);
Associate(&tag, node.GetId());
}
current_urls.insert(tag);
}
int64 sync_child_id = typed_url_root.GetFirstChildId();
while (sync_child_id != sync_api::kInvalidId) {
sync_api::ReadNode sync_child_node(&trans);
if (!sync_child_node.InitByIdLookup(sync_child_id)) {
LOG(ERROR) << "Failed to fetch child node.";
return false;
}
const sync_pb::TypedUrlSpecifics& typed_url(
sync_child_node.GetTypedUrlSpecifics());
if (current_urls.find(typed_url.url()) == current_urls.end()) {
new_visits.push_back(
std::pair<GURL, std::vector<history::VisitInfo> >(
GURL(typed_url.url()),
std::vector<history::VisitInfo>()));
std::vector<history::VisitInfo>& visits = new_visits.back().second;
history::URLRow new_url(GURL(typed_url.url()));
TypedUrlModelAssociator::UpdateURLRowFromTypedUrlSpecifics(
typed_url, &new_url);
for (int c = 0; c < typed_url.visits_size(); ++c) {
DCHECK(c == 0 || typed_url.visits(c) > typed_url.visits(c - 1));
DCHECK_LE(typed_url.visit_transitions(c),
static_cast<int>(PageTransition::LAST_CORE));
visits.push_back(history::VisitInfo(
base::Time::FromInternalValue(typed_url.visits(c)),
static_cast<PageTransition::Type>(
typed_url.visit_transitions(c))));
}
Associate(&typed_url.url(), sync_child_node.GetId());
new_urls.push_back(new_url);
}
sync_child_id = sync_child_node.GetSuccessorId();
}
}
return WriteToHistoryBackend(&titles, &new_urls, &updated_urls,
&new_visits, NULL);
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void longMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestObject* imp = V8TestObject::toNative(info.Holder());
v8SetReturnValueInt(info, imp->longMethod());
}
CWE ID: CWE-399
Target: 0
Now analyze the following code 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: CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string)
{
cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string));
}
CWE ID: CWE-754
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BOOL SQLWriteFileDSN( LPCSTR pszFileName,
LPCSTR pszAppName,
LPCSTR pszKeyName,
LPCSTR pszString )
{
HINI hIni;
char szFileName[ODBC_FILENAME_MAX+1];
if ( pszFileName[0] == '/' )
{
strncpy( szFileName, sizeof(szFileName) - 5, pszFileName );
}
else
{
char szPath[ODBC_FILENAME_MAX+1];
*szPath = '\0';
_odbcinst_FileINI( szPath );
snprintf( szFileName, sizeof(szFileName) - 5, "%s/%s", szPath, pszFileName );
}
if ( strlen( szFileName ) < 4 || strcmp( szFileName + strlen( szFileName ) - 4, ".dsn" ))
{
strcat( szFileName, ".dsn" );
}
#ifdef __OS2__
if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE, 0L ) != INI_SUCCESS )
#else
if ( iniOpen( &hIni, szFileName, "#;", '[', ']', '=', TRUE ) != INI_SUCCESS )
#endif
{
inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_INVALID_PATH, "" );
return FALSE;
}
/* delete section */
if ( pszString == NULL && pszKeyName == NULL )
{
if ( iniObjectSeek( hIni, (char *)pszAppName ) == INI_SUCCESS )
{
iniObjectDelete( hIni );
}
}
/* delete entry */
else if ( pszString == NULL )
{
if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS )
{
iniPropertyDelete( hIni );
}
}
else
{
/* add section */
if ( iniObjectSeek( hIni, (char *)pszAppName ) != INI_SUCCESS )
{
iniObjectInsert( hIni, (char *)pszAppName );
}
/* update entry */
if ( iniPropertySeek( hIni, (char *)pszAppName, (char *)pszKeyName, "" ) == INI_SUCCESS )
{
iniObjectSeek( hIni, (char *)pszAppName );
iniPropertyUpdate( hIni, (char *)pszKeyName, (char *)pszString );
}
/* add entry */
else
{
iniObjectSeek( hIni, (char *)pszAppName );
iniPropertyInsert( hIni, (char *)pszKeyName, (char *)pszString );
}
}
if ( iniCommit( hIni ) != INI_SUCCESS )
{
iniClose( hIni );
inst_logPushMsg( __FILE__, __FILE__, __LINE__, LOG_CRITICAL, ODBC_ERROR_REQUEST_FAILED, "" );
return FALSE;
}
iniClose( hIni );
return TRUE;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: resolveEmphasisAllCapsSymbols(
EmphasisInfo *buffer, formtype *typebuf, const InString *input) {
/* Marks every caps letter with capsEmphClass symbol.
* Used in the special case where capsnocont has been defined and capsword has not
* been defined. */
int inEmphasis = 0, i;
for (i = 0; i < input->length; i++) {
if (buffer[i].end & capsEmphClass) {
inEmphasis = 0;
buffer[i].end &= ~capsEmphClass;
} else {
if (buffer[i].begin & capsEmphClass) {
buffer[i].begin &= ~capsEmphClass;
inEmphasis = 1;
}
if (inEmphasis) {
if (typebuf[i] & CAPSEMPH)
/* Only mark if actually a capital letter (don't mark spaces or
* punctuation). */
buffer[i].symbol |= capsEmphClass;
} /* In emphasis */
} /* Not caps end */
}
}
CWE ID: CWE-125
Target: 0
Now analyze the following code 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 usage(char *progname) {
printf("Usage:\n");
printf("%s <input_yuv> <width>x<height> <target_width>x<target_height> ",
progname);
printf("<output_yuv> [<frames>]\n");
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and 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;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
CWE ID: CWE-834
Target: 0
Now analyze the following code 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: XcursorFileLoadImage (FILE *file, int size)
{
XcursorFile f;
if (!file)
return NULL;
_XcursorStdioFileInitialize (file, &f);
return XcursorXcFileLoadImage (&f, size);
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
{
u32 low32, high32;
unsigned long tmpl;
struct desc_ptr dt;
vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */
vmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */
vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
#ifdef CONFIG_X86_64
/*
* Load null selectors, so we can avoid reloading them in
* __vmx_load_host_state(), in case userspace uses the null selectors
* too (the expected case).
*/
vmcs_write16(HOST_DS_SELECTOR, 0);
vmcs_write16(HOST_ES_SELECTOR, 0);
#else
vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
#endif
vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
native_store_idt(&dt);
vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
vmx->host_idt_base = dt.address;
vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
rdmsr(MSR_IA32_CR_PAT, low32, high32);
vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: wifi_error wifi_get_supported_feature_set(wifi_interface_handle handle, feature_set *set)
{
GetFeatureSetCommand command(handle, FEATURE_SET, set, NULL, NULL, 1);
return (wifi_error) command.requestResponse();
}
CWE ID: CWE-264
Target: 0
Now analyze the following code 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 testPervertedQueryString() {
helperTestQueryString("http://example.org/?&&=&&&=&&&&==&===&====", 5);
}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int jas_iccgetuint(jas_stream_t *in, int n, ulonglong *val)
{
int i;
int c;
ulonglong v;
v = 0;
for (i = n; i > 0; --i) {
if ((c = jas_stream_getc(in)) == EOF)
return -1;
v = (v << 8) | c;
}
*val = v;
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: WebContents* FindFirstDevToolsContents() {
std::unique_ptr<content::RenderWidgetHostIterator> widgets(
RenderWidgetHost::GetRenderWidgetHosts());
while (content::RenderWidgetHost* widget = widgets->GetNextHost()) {
if (!widget->GetProcess()->IsInitializedAndNotDead())
continue;
RenderViewHost* view_host = RenderViewHost::From(widget);
if (!view_host)
continue;
WebContents* contents = WebContents::FromRenderViewHost(view_host);
GURL url = contents->GetURL();
if (url.SchemeIs(content::kChromeDevToolsScheme))
return contents;
}
return NULL;
}
CWE ID: CWE-285
Target: 0
Now analyze the following code 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: GLvoid StubGLGenTextures(GLsizei n, GLuint* textures) {
glGenTextures(n, textures);
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool GDataCache::CreateCacheDirectories(
const std::vector<FilePath>& paths_to_create) {
bool success = true;
for (size_t i = 0; i < paths_to_create.size(); ++i) {
if (file_util::DirectoryExists(paths_to_create[i]))
continue;
if (!file_util::CreateDirectory(paths_to_create[i])) {
success = false;
PLOG(ERROR) << "Error creating directory " << paths_to_create[i].value();
} else {
DVLOG(1) << "Created directory " << paths_to_create[i].value();
}
}
return success;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool Extension::OverlapsWithOrigin(const GURL& origin) const {
if (url() == origin)
return true;
if (web_extent().is_empty())
return false;
URLPattern origin_only_pattern(kValidWebExtentSchemes);
if (!origin_only_pattern.SetScheme(origin.scheme()))
return false;
origin_only_pattern.set_host(origin.host());
origin_only_pattern.SetPath("/*");
URLPatternSet origin_only_pattern_list;
origin_only_pattern_list.AddPattern(origin_only_pattern);
return web_extent().OverlapsWith(origin_only_pattern_list);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code 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 js_Ast *callexp(js_State *J)
{
js_Ast *a = newexp(J);
loop:
if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; }
if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; }
if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; }
return a;
}
CWE ID: CWE-674
Output: | 1 |
Subsets and Splits