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 aac_compat_ioctl(struct scsi_device *sdev, int cmd, void __user *arg)
{
struct aac_dev *dev = (struct aac_dev *)sdev->host->hostdata;
return aac_compat_do_ioctl(dev, cmd, (unsigned long)arg);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void OnShowWidget(int routing_id, const gfx::Rect& initial_rect) {
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::BindOnce(&PendingWidgetMessageFilter::OnReceivedRoutingIDOnUI,
this, routing_id));
}
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: MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (width == 0)
return(threshold_image);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
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: MagickExport int LocaleUppercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: GfxDeviceCMYKColorSpace::~GfxDeviceCMYKColorSpace() {
}
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 MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const MagickBooleanType separate,ExceptionInfo *exception)
{
size_t
channels,
packet_size;
unsigned char
*compact_pixels;
/*
Write uncompressed pixels as separate planes.
*/
channels=1;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels*
next_image->columns,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if (IsImageGray(next_image) != MagickFalse)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GrayQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GrayQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
if (next_image->storage_class == PseudoClass)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,IndexQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
IndexQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,RedQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GreenQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlueQuantum,exception);
if (next_image->colorspace == CMYKColorspace)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlackQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
(void) SetImageProgress(image,SaveImagesTag,0,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
RedQuantum,MagickTrue,exception);
(void) SetImageProgress(image,SaveImagesTag,1,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GreenQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,2,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlueQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,3,6);
if (next_image->colorspace == CMYKColorspace)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlackQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,4,6);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,5,6);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
}
if (next_image->compression == RLECompression)
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
return(MagickTrue);
}
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: image_transform_png_set_strip_16_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth > 8;
}
CWE ID:
Target: 1
Example 2:
Code: int PostScript_MetaHandler::FindPostScriptHint()
{
bool found = false;
IOBuffer ioBuf;
XMP_Uns8 ch;
XMP_IO* fileRef = this->parent->ioRef;
XMP_AbortProc abortProc = this->parent->abortProc;
void * abortArg = this->parent->abortArg;
const bool checkAbort = (abortProc != 0);
fileRef->Rewind();
if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return false;
XMP_Uns32 fileheader = GetUns32BE ( ioBuf.ptr );
if ( fileheader == 0xC5D0D3C6 ) {
if ( ! CheckFileSpace ( fileRef, &ioBuf, 30 ) ) return false;
XMP_Uns32 psOffset = GetUns32LE ( ioBuf.ptr+4 ); // PostScript offset.
XMP_Uns32 psLength = GetUns32LE ( ioBuf.ptr+8 ); // PostScript length.
MoveToOffset ( fileRef, psOffset, &ioBuf );
}
while ( true ) {
if ( checkAbort && abortProc(abortArg) ) {
XMP_Throw ( "PostScript_MetaHandler::FindPostScriptHint - User abort", kXMPErr_UserAbort );
}
if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsXMPString.length() ) ) return kPSHint_NoMarker;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() ) ) {
return kPSHint_NoMarker;
} else if ( ! CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsXMPString.c_str()), kPSContainsXMPString.length() ) ) {
do {
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMarker;
ch = *ioBuf.ptr;
++ioBuf.ptr;
} while ( ! IsNewline ( ch ) );
} else {
ioBuf.ptr += kPSContainsXMPString.length();
int xmpHint = kPSHint_NoMain; // ! From here on, a failure means "no main", not "no marker".
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMain;
if ( ! IsSpaceOrTab ( *ioBuf.ptr ) ) return kPSHint_NoMain;
while ( true ) {
while ( true ) { // Skip leading spaces and tabs.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMain;
if ( ! IsSpaceOrTab ( *ioBuf.ptr ) ) break;
++ioBuf.ptr;
}
if ( IsNewline ( *ioBuf.ptr ) ) return kPSHint_NoMain; // Reached the end of the ContainsXMP comment.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 6 ) ) return kPSHint_NoMain;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("NoMain"), 6 ) ) {
ioBuf.ptr += 6;
xmpHint = kPSHint_NoMain;
break;
} else if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("MainFi"), 6 ) ) {
ioBuf.ptr += 6;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 3 ) ) return kPSHint_NoMain;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("rst"), 3 ) ) {
ioBuf.ptr += 3;
xmpHint = kPSHint_MainFirst;
}
break;
} else if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("MainLa"), 6 ) ) {
ioBuf.ptr += 6;
if ( ! CheckFileSpace ( fileRef, &ioBuf, 2 ) ) return kPSHint_NoMain;
if ( CheckBytes ( ioBuf.ptr, Uns8Ptr("st"), 2 ) ) {
ioBuf.ptr += 2;
xmpHint = kPSHint_MainLast;
}
break;
} else {
while ( true ) { // Skip until whitespace.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMain;
if ( IsWhitespace ( *ioBuf.ptr ) ) break;
++ioBuf.ptr;
}
}
} // Look for the main packet location option.
if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return kPSHint_NoMain;
if ( ! IsWhitespace ( *ioBuf.ptr ) ) return kPSHint_NoMain;
return xmpHint;
} // Found "%ADO_ContainsXMP:".
} // Outer marker loop.
return kPSHint_NoMarker; // Should never reach here.
} // PostScript_MetaHandler::FindPostScriptHint
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: IW_IMPL(void) iw_set_max_malloc(struct iw_context *ctx, size_t n)
{
ctx->max_malloc = n;
}
CWE ID: CWE-369
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: nf_ct_frag6_reasm(struct nf_ct_frag6_queue *fq, struct net_device *dev)
{
struct sk_buff *fp, *op, *head = fq->q.fragments;
int payload_len;
fq_kill(fq);
WARN_ON(head == NULL);
WARN_ON(NFCT_FRAG6_CB(head)->offset != 0);
/* Unfragmented part is taken from the first segment. */
payload_len = ((head->data - skb_network_header(head)) -
sizeof(struct ipv6hdr) + fq->q.len -
sizeof(struct frag_hdr));
if (payload_len > IPV6_MAXPLEN) {
pr_debug("payload len is too large.\n");
goto out_oversize;
}
/* Head of list must not be cloned. */
if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC)) {
pr_debug("skb is cloned but can't expand head");
goto out_oom;
}
/* If the first fragment is fragmented itself, we split
* it to two chunks: the first with data and paged part
* and the second, holding only fragments. */
if (skb_has_frags(head)) {
struct sk_buff *clone;
int i, plen = 0;
if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL) {
pr_debug("Can't alloc skb\n");
goto out_oom;
}
clone->next = head->next;
head->next = clone;
skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;
skb_frag_list_init(head);
for (i=0; i<skb_shinfo(head)->nr_frags; i++)
plen += skb_shinfo(head)->frags[i].size;
clone->len = clone->data_len = head->data_len - plen;
head->data_len -= clone->len;
head->len -= clone->len;
clone->csum = 0;
clone->ip_summed = head->ip_summed;
NFCT_FRAG6_CB(clone)->orig = NULL;
atomic_add(clone->truesize, &nf_init_frags.mem);
}
/* We have to remove fragment header from datagram and to relocate
* header in order to calculate ICV correctly. */
skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0];
memmove(head->head + sizeof(struct frag_hdr), head->head,
(head->data - head->head) - sizeof(struct frag_hdr));
head->mac_header += sizeof(struct frag_hdr);
head->network_header += sizeof(struct frag_hdr);
skb_shinfo(head)->frag_list = head->next;
skb_reset_transport_header(head);
skb_push(head, head->data - skb_network_header(head));
atomic_sub(head->truesize, &nf_init_frags.mem);
for (fp=head->next; fp; fp = fp->next) {
head->data_len += fp->len;
head->len += fp->len;
if (head->ip_summed != fp->ip_summed)
head->ip_summed = CHECKSUM_NONE;
else if (head->ip_summed == CHECKSUM_COMPLETE)
head->csum = csum_add(head->csum, fp->csum);
head->truesize += fp->truesize;
atomic_sub(fp->truesize, &nf_init_frags.mem);
}
head->next = NULL;
head->dev = dev;
head->tstamp = fq->q.stamp;
ipv6_hdr(head)->payload_len = htons(payload_len);
/* Yes, and fold redundant checksum back. 8) */
if (head->ip_summed == CHECKSUM_COMPLETE)
head->csum = csum_partial(skb_network_header(head),
skb_network_header_len(head),
head->csum);
fq->q.fragments = NULL;
/* all original skbs are linked into the NFCT_FRAG6_CB(head).orig */
fp = skb_shinfo(head)->frag_list;
if (NFCT_FRAG6_CB(fp)->orig == NULL)
/* at above code, head skb is divided into two skbs. */
fp = fp->next;
op = NFCT_FRAG6_CB(head)->orig;
for (; fp; fp = fp->next) {
struct sk_buff *orig = NFCT_FRAG6_CB(fp)->orig;
op->next = orig;
op = orig;
NFCT_FRAG6_CB(fp)->orig = NULL;
}
return head;
out_oversize:
if (net_ratelimit())
printk(KERN_DEBUG "nf_ct_frag6_reasm: payload len = %d\n", payload_len);
goto out_fail;
out_oom:
if (net_ratelimit())
printk(KERN_DEBUG "nf_ct_frag6_reasm: no memory for reassembly\n");
out_fail:
return NULL;
}
CWE ID:
Target: 1
Example 2:
Code: static int apic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
void *data)
{
unsigned char alignment = offset & 0xf;
u32 result;
/* this bitmask has a bit cleared for each reserved register */
static const u64 rmask = 0x43ff01ffffffe70cULL;
if ((alignment + len) > 4) {
apic_debug("KVM_APIC_READ: alignment error %x %d\n",
offset, len);
return 1;
}
if (offset > 0x3f0 || !(rmask & (1ULL << (offset >> 4)))) {
apic_debug("KVM_APIC_READ: read reserved register %x\n",
offset);
return 1;
}
result = __apic_read(apic, offset & ~0xf);
trace_kvm_apic_read(offset, result);
switch (len) {
case 1:
case 2:
case 4:
memcpy(data, (char *)&result + alignment, len);
break;
default:
printk(KERN_ERR "Local APIC read with len = %x, "
"should be 1,2, or 4 instead\n", len);
break;
}
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 struct rtnl_link_stats64 *macvlan_dev_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
struct macvlan_dev *vlan = netdev_priv(dev);
if (vlan->pcpu_stats) {
struct macvlan_pcpu_stats *p;
u64 rx_packets, rx_bytes, rx_multicast, tx_packets, tx_bytes;
u32 rx_errors = 0, tx_dropped = 0;
unsigned int start;
int i;
for_each_possible_cpu(i) {
p = per_cpu_ptr(vlan->pcpu_stats, i);
do {
start = u64_stats_fetch_begin_bh(&p->syncp);
rx_packets = p->rx_packets;
rx_bytes = p->rx_bytes;
rx_multicast = p->rx_multicast;
tx_packets = p->tx_packets;
tx_bytes = p->tx_bytes;
} while (u64_stats_fetch_retry_bh(&p->syncp, start));
stats->rx_packets += rx_packets;
stats->rx_bytes += rx_bytes;
stats->multicast += rx_multicast;
stats->tx_packets += tx_packets;
stats->tx_bytes += tx_bytes;
/* rx_errors & tx_dropped are u32, updated
* without syncp protection.
*/
rx_errors += p->rx_errors;
tx_dropped += p->tx_dropped;
}
stats->rx_errors = rx_errors;
stats->rx_dropped = rx_errors;
stats->tx_dropped = tx_dropped;
}
return stats;
}
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: MockRenderProcess::MockRenderProcess()
: transport_dib_next_sequence_number_(0) {
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void RenderWidgetHostViewAura::ProcessAckedTouchEvent(
const WebKit::WebTouchEvent& touch_event, InputEventAckState ack_result) {
ScopedVector<ui::TouchEvent> events;
if (!MakeUITouchEventsFromWebTouchEvents(touch_event, &events))
return;
aura::RootWindow* root = window_->GetRootWindow();
if (!root)
return;
ui::EventResult result = (ack_result ==
INPUT_EVENT_ACK_STATE_CONSUMED) ? ui::ER_HANDLED : ui::ER_UNHANDLED;
for (ScopedVector<ui::TouchEvent>::iterator iter = events.begin(),
end = events.end(); iter != end; ++iter) {
root->ProcessedTouchEvent((*iter), window_, 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: SPL_METHOD(FilesystemIterator, getFlags)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK));
} /* }}} */
/* {{{ proto void FilesystemIterator::setFlags(long $flags)
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: struct inet_peer *inet_getpeer(struct inetpeer_addr *daddr, int create)
{
struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr;
struct inet_peer_base *base = family_to_base(daddr->family);
struct inet_peer *p;
unsigned int sequence;
int invalidated, gccnt = 0;
/* Attempt a lockless lookup first.
* Because of a concurrent writer, we might not find an existing entry.
*/
rcu_read_lock();
sequence = read_seqbegin(&base->lock);
p = lookup_rcu(daddr, base);
invalidated = read_seqretry(&base->lock, sequence);
rcu_read_unlock();
if (p)
return p;
/* If no writer did a change during our lookup, we can return early. */
if (!create && !invalidated)
return NULL;
/* retry an exact lookup, taking the lock before.
* At least, nodes should be hot in our cache.
*/
write_seqlock_bh(&base->lock);
relookup:
p = lookup(daddr, stack, base);
if (p != peer_avl_empty) {
atomic_inc(&p->refcnt);
write_sequnlock_bh(&base->lock);
return p;
}
if (!gccnt) {
gccnt = inet_peer_gc(base, stack, stackptr);
if (gccnt && create)
goto relookup;
}
p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL;
if (p) {
p->daddr = *daddr;
atomic_set(&p->refcnt, 1);
atomic_set(&p->rid, 0);
atomic_set(&p->ip_id_count, secure_ip_id(daddr->addr.a4));
p->tcp_ts_stamp = 0;
p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
p->rate_tokens = 0;
p->rate_last = 0;
p->pmtu_expires = 0;
p->pmtu_orig = 0;
memset(&p->redirect_learned, 0, sizeof(p->redirect_learned));
/* Link the node. */
link_to_pool(p, base);
base->total++;
}
write_sequnlock_bh(&base->lock);
return p;
}
CWE ID:
Target: 1
Example 2:
Code: static int do_cmdtest_ioctl(struct comedi_device *dev,
struct comedi_cmd __user *arg, void *file)
{
struct comedi_cmd user_cmd;
struct comedi_subdevice *s;
int ret = 0;
unsigned int *chanlist = NULL;
unsigned int __user *chanlist_saver = NULL;
if (copy_from_user(&user_cmd, arg, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
return -EFAULT;
}
/* save user's chanlist pointer so it can be restored later */
chanlist_saver = user_cmd.chanlist;
if (user_cmd.subdev >= dev->n_subdevices) {
DPRINTK("%d no such subdevice\n", user_cmd.subdev);
return -ENODEV;
}
s = dev->subdevices + user_cmd.subdev;
if (s->type == COMEDI_SUBD_UNUSED) {
DPRINTK("%d not valid subdevice\n", user_cmd.subdev);
return -EIO;
}
if (!s->do_cmd || !s->do_cmdtest) {
DPRINTK("subdevice %i does not support commands\n",
user_cmd.subdev);
return -EIO;
}
/* make sure channel/gain list isn't too long */
if (user_cmd.chanlist_len > s->len_chanlist) {
DPRINTK("channel/gain list too long %d > %d\n",
user_cmd.chanlist_len, s->len_chanlist);
ret = -EINVAL;
goto cleanup;
}
/* load channel/gain list */
if (user_cmd.chanlist) {
chanlist =
kmalloc(user_cmd.chanlist_len * sizeof(int), GFP_KERNEL);
if (!chanlist) {
DPRINTK("allocation failed\n");
ret = -ENOMEM;
goto cleanup;
}
if (copy_from_user(chanlist, user_cmd.chanlist,
user_cmd.chanlist_len * sizeof(int))) {
DPRINTK("fault reading chanlist\n");
ret = -EFAULT;
goto cleanup;
}
/* make sure each element in channel/gain list is valid */
ret = comedi_check_chanlist(s, user_cmd.chanlist_len, chanlist);
if (ret < 0) {
DPRINTK("bad chanlist\n");
goto cleanup;
}
user_cmd.chanlist = chanlist;
}
ret = s->do_cmdtest(dev, s, &user_cmd);
/* restore chanlist pointer before copying back */
user_cmd.chanlist = chanlist_saver;
if (copy_to_user(arg, &user_cmd, sizeof(struct comedi_cmd))) {
DPRINTK("bad cmd address\n");
ret = -EFAULT;
goto cleanup;
}
cleanup:
kfree(chanlist);
return ret;
}
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: void Chapters::Edition::Clear()
{
while (m_atoms_count > 0)
{
Atom& a = m_atoms[--m_atoms_count];
a.Clear();
}
delete[] m_atoms;
m_atoms = NULL;
m_atoms_size = 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: ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext2_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb_cache_entry_release(ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: static void iw_set_error_internal(struct iw_context *ctx, const char *s)
{
if(ctx->error_flag) return; // Only record the first error.
ctx->error_flag = 1;
if(!ctx->error_msg) {
ctx->error_msg=iw_malloc_ex(ctx,IW_MALLOCFLAG_NOERRORS,IW_MSG_MAX*sizeof(char));
if(!ctx->error_msg) {
return;
}
}
iw_strlcpy(ctx->error_msg,s,IW_MSG_MAX);
}
CWE ID: CWE-369
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(openssl_pbkdf2)
{
zend_long key_length = 0, iterations = 0;
char *password;
size_t password_len;
char *salt;
size_t salt_len;
char *method;
size_t method_len = 0;
zend_string *out_buffer;
const EVP_MD *digest;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssll|s",
&password, &password_len,
&salt, &salt_len,
&key_length, &iterations,
&method, &method_len) == FAILURE) {
return;
}
if (key_length <= 0) {
RETURN_FALSE;
}
if (method_len) {
digest = EVP_get_digestbyname(method);
} else {
digest = EVP_sha1();
}
if (!digest) {
php_error_docref(NULL, E_WARNING, "Unknown signature algorithm");
RETURN_FALSE;
}
PHP_OPENSSL_CHECK_LONG_TO_INT(key_length, key);
PHP_OPENSSL_CHECK_LONG_TO_INT(iterations, iterations);
PHP_OPENSSL_CHECK_SIZE_T_TO_INT(password_len, password);
PHP_OPENSSL_CHECK_SIZE_T_TO_INT(salt_len, salt);
out_buffer = zend_string_alloc(key_length, 0);
if (PKCS5_PBKDF2_HMAC(password, (int)password_len, (unsigned char *)salt, (int)salt_len, (int)iterations, digest, (int)key_length, (unsigned char*)ZSTR_VAL(out_buffer)) == 1) {
ZSTR_VAL(out_buffer)[key_length] = 0;
RETURN_NEW_STR(out_buffer);
} else {
php_openssl_store_errors();
zend_string_release(out_buffer);
RETURN_FALSE;
}
}
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: static Image *ReadJBIGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickStatusType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
ssize_t
length,
y;
struct jbg_dec_state
jbig_info;
unsigned char
bit,
*buffer,
byte;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JBIG toolkit.
*/
jbg_dec_init(&jbig_info);
jbg_dec_maxsize(&jbig_info,(unsigned long) image->columns,(unsigned long)
image->rows);
image->columns=jbg_dec_getwidth(&jbig_info);
image->rows=jbg_dec_getheight(&jbig_info);
image->depth=8;
image->storage_class=PseudoClass;
image->colors=2;
/*
Read JBIG file.
*/
buffer=(unsigned char *) AcquireQuantumMemory(MagickMaxBufferExtent,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
status=JBG_EAGAIN;
do
{
length=(ssize_t) ReadBlob(image,MagickMaxBufferExtent,buffer);
if (length == 0)
break;
p=buffer;
while ((length > 0) && ((status == JBG_EAGAIN) || (status == JBG_EOK)))
{
size_t
count;
status=jbg_dec_in(&jbig_info,p,length,&count);
p+=count;
length-=(ssize_t) count;
}
} while ((status == JBG_EAGAIN) || (status == JBG_EOK));
/*
Create colormap.
*/
image->columns=jbg_dec_getwidth(&jbig_info);
image->rows=jbg_dec_getheight(&jbig_info);
image->compression=JBIG2Compression;
if (AcquireImageColormap(image,2) == MagickFalse)
{
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
image->colormap[0].red=0;
image->colormap[0].green=0;
image->colormap[0].blue=0;
image->colormap[1].red=QuantumRange;
image->colormap[1].green=QuantumRange;
image->colormap[1].blue=QuantumRange;
image->x_resolution=300;
image->y_resolution=300;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert X bitmap image to pixel packets.
*/
p=jbg_dec_getimage(&jbig_info,0);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(*p++);
index=(byte & 0x80) ? 0 : 1;
bit++;
byte<<=1;
if (bit == 8)
bit=0;
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free scale resource.
*/
jbg_dec_free(&jbig_info);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int AutofillDialogViews::SuggestionView::GetHeightForWidth(int width) const {
int height = 0;
CanUseVerticallyCompactText(width, &height);
return height;
}
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: const extensions::Extension* GetExtension(Profile* profile,
const std::string& extension_id) {
const ExtensionService* service =
extensions::ExtensionSystem::Get(profile)->extension_service();
const extensions::Extension* extension =
service->GetInstalledExtension(extension_id);
return extension;
}
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: struct edid *drm_load_edid_firmware(struct drm_connector *connector)
{
const char *connector_name = connector->name;
char *edidname, *last, *colon, *fwstr, *edidstr, *fallback = NULL;
struct edid *edid;
if (edid_firmware[0] == '\0')
return ERR_PTR(-ENOENT);
/*
* If there are multiple edid files specified and separated
* by commas, search through the list looking for one that
* matches the connector.
*
* If there's one or more that doesn't specify a connector, keep
* the last one found one as a fallback.
*/
fwstr = kstrdup(edid_firmware, GFP_KERNEL);
edidstr = fwstr;
while ((edidname = strsep(&edidstr, ","))) {
if (strncmp(connector_name, edidname, colon - edidname))
continue;
edidname = colon + 1;
break;
}
if (*edidname != '\0') /* corner case: multiple ',' */
fallback = edidname;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void skb_warn_bad_offload(const struct sk_buff *skb)
{
static const netdev_features_t null_features = 0;
struct net_device *dev = skb->dev;
const char *name = "";
if (!net_ratelimit())
return;
if (dev) {
if (dev->dev.parent)
name = dev_driver_string(dev->dev.parent);
else
name = netdev_name(dev);
}
WARN(1, "%s: caps=(%pNF, %pNF) len=%d data_len=%d gso_size=%d "
"gso_type=%d ip_summed=%d\n",
name, dev ? &dev->features : &null_features,
skb->sk ? &skb->sk->sk_route_caps : &null_features,
skb->len, skb->data_len, skb_shinfo(skb)->gso_size,
skb_shinfo(skb)->gso_type, skb->ip_summed);
}
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: PHP_FUNCTION(openssl_decrypt)
{
zend_bool raw_input = 0;
char *data, *method, *password, *iv = "";
int data_len, method_len, password_len, iv_len = 0;
const EVP_CIPHER *cipher_type;
EVP_CIPHER_CTX cipher_ctx;
int i, outlen, keylen;
unsigned char *outbuf, *key;
int base64_str_len;
char *base64_str = NULL;
zend_bool free_iv;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_input, &iv, &iv_len) == FAILURE) {
return;
}
if (!method_len) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
cipher_type = EVP_get_cipherbyname(method);
if (!cipher_type) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
RETURN_FALSE;
}
if (!raw_input) {
base64_str = (char*)php_base64_decode((unsigned char*)data, data_len, &base64_str_len);
if (!base64_str) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to base64 decode the input");
RETURN_FALSE;
}
data_len = base64_str_len;
data = base64_str;
}
keylen = EVP_CIPHER_key_length(cipher_type);
if (keylen > password_len) {
key = emalloc(keylen);
memset(key, 0, keylen);
memcpy(key, password, password_len);
} else {
key = (unsigned char*)password;
}
free_iv = php_openssl_validate_iv(&iv, &iv_len, EVP_CIPHER_iv_length(cipher_type) TSRMLS_CC);
outlen = data_len + EVP_CIPHER_block_size(cipher_type);
outbuf = emalloc(outlen + 1);
EVP_DecryptInit(&cipher_ctx, cipher_type, NULL, NULL);
if (password_len > keylen) {
EVP_CIPHER_CTX_set_key_length(&cipher_ctx, password_len);
}
EVP_DecryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);
EVP_DecryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
outlen = i;
if (EVP_DecryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
outlen += i;
outbuf[outlen] = '\0';
RETVAL_STRINGL((char *)outbuf, outlen, 0);
} else {
efree(outbuf);
RETVAL_FALSE;
}
if (key != (unsigned char*)password) {
efree(key);
}
if (free_iv) {
efree(iv);
}
if (base64_str) {
efree(base64_str);
}
EVP_CIPHER_CTX_cleanup(&cipher_ctx);
}
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: ftp_genlist(ftpbuf_t *ftp, const char *cmd, const char *path TSRMLS_DC)
{
php_stream *tmpstream = NULL;
databuf_t *data = NULL;
char *ptr;
int ch, lastch;
size_t size, rcvd;
size_t lines;
char **ret = NULL;
char **entry;
char *text;
if ((tmpstream = php_stream_fopen_tmpfile()) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create temporary file. Check permissions in temporary files directory.");
return NULL;
}
if (!ftp_type(ftp, FTPTYPE_ASCII)) {
goto bail;
}
if ((data = ftp_getdata(ftp TSRMLS_CC)) == NULL) {
goto bail;
}
ftp->data = data;
if (!ftp_putcmd(ftp, cmd, path)) {
goto bail;
}
if (!ftp_getresp(ftp) || (ftp->resp != 150 && ftp->resp != 125 && ftp->resp != 226)) {
goto bail;
}
/* some servers don't open a ftp-data connection if the directory is empty */
if (ftp->resp == 226) {
ftp->data = data_close(ftp, data);
php_stream_close(tmpstream);
return ecalloc(1, sizeof(char*));
}
/* pull data buffer into tmpfile */
if ((data = data_accept(data, ftp TSRMLS_CC)) == NULL) {
goto bail;
}
size = 0;
lines = 0;
lastch = 0;
while ((rcvd = my_recv(ftp, data->fd, data->buf, FTP_BUFSIZE))) {
if (rcvd == -1 || rcvd > ((size_t)(-1))-size) {
goto bail;
}
php_stream_write(tmpstream, data->buf, rcvd);
size += rcvd;
for (ptr = data->buf; rcvd; rcvd--, ptr++) {
if (*ptr == '\n' && lastch == '\r') {
lines++;
} else {
size++;
}
lastch = *ptr;
}
lastch = *ptr;
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: SafeSock::msgReady() {
return _msgReady;
}
CWE ID: CWE-134
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 page *alloc_fresh_gigantic_page_node(struct hstate *h, int nid)
{
struct page *page;
page = alloc_gigantic_page(nid, h);
if (page) {
prep_compound_gigantic_page(page, huge_page_order(h));
prep_new_huge_page(h, page, nid);
}
return page;
}
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 int __init xfrm6_tunnel_init(void)
{
int rv;
rv = xfrm_register_type(&xfrm6_tunnel_type, AF_INET6);
if (rv < 0)
goto err;
rv = xfrm6_tunnel_register(&xfrm6_tunnel_handler, AF_INET6);
if (rv < 0)
goto unreg;
rv = xfrm6_tunnel_register(&xfrm46_tunnel_handler, AF_INET);
if (rv < 0)
goto dereg6;
rv = xfrm6_tunnel_spi_init();
if (rv < 0)
goto dereg46;
rv = register_pernet_subsys(&xfrm6_tunnel_net_ops);
if (rv < 0)
goto deregspi;
return 0;
deregspi:
xfrm6_tunnel_spi_fini();
dereg46:
xfrm6_tunnel_deregister(&xfrm46_tunnel_handler, AF_INET);
dereg6:
xfrm6_tunnel_deregister(&xfrm6_tunnel_handler, AF_INET6);
unreg:
xfrm_unregister_type(&xfrm6_tunnel_type, AF_INET6);
err:
return rv;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static inline void evmcs_write32(unsigned long field, u32 value)
{
u16 clean_field;
int offset = get_evmcs_offset(field, &clean_field);
if (offset < 0)
return;
*(u32 *)((char *)current_evmcs + offset) = value;
current_evmcs->hv_clean_fields &= ~clean_field;
}
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: ZEND_API zend_bool zend_is_executing(void) /* {{{ */
{
return EG(current_execute_data) != 0;
}
/* }}} */
CWE ID: CWE-134
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 ExternalProtocolHandler::LaunchUrlWithDelegate(
const GURL& url,
int render_process_host_id,
int render_view_routing_id,
ui::PageTransition page_transition,
bool has_user_gesture,
Delegate* delegate) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::string escaped_url_string = net::EscapeExternalHandlerValue(url.spec());
GURL escaped_url(escaped_url_string);
content::WebContents* web_contents = tab_util::GetWebContentsByID(
render_process_host_id, render_view_routing_id);
Profile* profile = nullptr;
if (web_contents) // Maybe NULL during testing.
profile = Profile::FromBrowserContext(web_contents->GetBrowserContext());
BlockState block_state =
GetBlockStateWithDelegate(escaped_url.scheme(), delegate, profile);
if (block_state == BLOCK) {
if (delegate)
delegate->BlockRequest();
return;
}
g_accept_requests = false;
shell_integration::DefaultWebClientWorkerCallback callback = base::Bind(
&OnDefaultProtocolClientWorkerFinished, url, render_process_host_id,
render_view_routing_id, block_state == UNKNOWN, page_transition,
has_user_gesture, delegate);
CreateShellWorker(callback, escaped_url.scheme(), delegate)
->StartCheckIsDefault();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void float32ArrayMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
TestObjectPythonV8Internal::float32ArrayMethodMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
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 inline void dccp_v6_send_check(struct sock *sk, struct sk_buff *skb)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct dccp_hdr *dh = dccp_hdr(skb);
dccp_csum_outgoing(skb);
dh->dccph_checksum = dccp_v6_csum_finish(skb, &np->saddr, &np->daddr);
}
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: bool WebviewHandler::Parse(Extension* extension, base::string16* error) {
scoped_ptr<WebviewInfo> info(new WebviewInfo());
const base::DictionaryValue* dict_value = NULL;
if (!extension->manifest()->GetDictionary(keys::kWebview,
&dict_value)) {
*error = base::ASCIIToUTF16(errors::kInvalidWebview);
return false;
}
const base::ListValue* url_list = NULL;
if (!dict_value->GetList(keys::kWebviewAccessibleResources,
&url_list)) {
*error = base::ASCIIToUTF16(errors::kInvalidWebviewAccessibleResourcesList);
return false;
}
for (size_t i = 0; i < url_list->GetSize(); ++i) {
std::string relative_path;
if (!url_list->GetString(i, &relative_path)) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidWebviewAccessibleResource, base::IntToString(i));
return false;
}
URLPattern pattern(URLPattern::SCHEME_EXTENSION);
if (pattern.Parse(extension->url().spec()) != URLPattern::PARSE_SUCCESS) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidURLPatternError, extension->url().spec());
return false;
}
while (relative_path[0] == '/')
relative_path = relative_path.substr(1, relative_path.length() - 1);
pattern.SetPath(pattern.path() + relative_path);
info->webview_accessible_resources_.AddPattern(pattern);
}
const base::ListValue* partition_list = NULL;
if (!dict_value->GetList(keys::kWebviewPrivilegedPartitions,
&partition_list)) {
*error = base::ASCIIToUTF16(errors::kInvalidWebviewPrivilegedPartitionList);
return false;
}
for (size_t i = 0; i < partition_list->GetSize(); ++i) {
std::string partition_wildcard;
if (!partition_list->GetString(i, &partition_wildcard)) {
*error = ErrorUtils::FormatErrorMessageUTF16(
errors::kInvalidWebviewPrivilegedPartition, base::IntToString(i));
return false;
}
info->webview_privileged_partitions_.push_back(partition_wildcard);
}
extension->SetManifestData(keys::kWebviewAccessibleResources, info.release());
return true;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: Gif_SetErrorHandler(Gif_ReadErrorHandler handler) {
default_error_handler = handler;
}
CWE ID: CWE-415
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: pgp_strip_path(sc_card_t *card, const sc_path_t *path)
{
unsigned int start_point = 0;
/* start_point will move through the path string */
if (path->len == 0)
return 0;
/* ignore 3F00 (MF) at the beginning */
start_point = (memcmp(path->value, "\x3f\x00", 2) == 0) ? 2 : 0;
/* strip path of PKCS15-App DF (5015) */
start_point += (memcmp(path->value + start_point, "\x50\x15", 2) == 0) ? 2 : 0;
return start_point;
}
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: long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) {
assert(m_pos < 0);
assert(m_pUnknownSize);
#if 0
assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this
const long long element_start = m_pUnknownSize->m_element_start;
pos = -m_pos;
assert(pos > element_start);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long element_size = -1;
for (;;) { //determine cluster size
if ((total >= 0) && (pos >= total))
{
element_size = total - element_start;
assert(element_size > 0);
break;
}
if ((segment_stop >= 0) && (pos >= segment_stop))
{
element_size = segment_stop - element_start;
assert(element_size > 0);
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { //Cluster ID or Cues ID
element_size = pos - element_start;
assert(element_size > 0);
break;
}
#ifdef _DEBUG
switch (id)
{
case 0x20: //BlockGroup
case 0x23: //Simple Block
case 0x67: //TimeCode
case 0x2B: //PrevSize
break;
default:
assert(false);
break;
}
#endif
pos += len; //consume ID (of sub-element)
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field of element
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not allowed for sub-elements
if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload of sub-element
assert((segment_stop < 0) || (pos <= segment_stop));
} //determine cluster size
assert(element_size >= 0);
m_pos = element_start + element_size;
m_pUnknownSize = 0;
return 2; //continue parsing
#else
const long status = m_pUnknownSize->Parse(pos, len);
if (status < 0) // error or underflow
return status;
if (status == 0) // parsed a block
return 2; // continue parsing
assert(status > 0); // nothing left to parse of this cluster
const long long start = m_pUnknownSize->m_element_start;
const long long size = m_pUnknownSize->GetElementSize();
assert(size >= 0);
pos = start + size;
m_pos = pos;
m_pUnknownSize = 0;
return 2; // continue parsing
#endif
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool DownloadItemImpl::GetOpenWhenComplete() const {
return open_when_complete_;
}
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: ProcPseudoramiXGetScreenSize(ClientPtr client)
{
REQUEST(xPanoramiXGetScreenSizeReq);
WindowPtr pWin;
xPanoramiXGetScreenSizeReply rep;
register int rc;
TRACE;
if (stuff->screen >= pseudoramiXNumScreens)
return BadMatch;
REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq);
rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
if (rc != Success)
return rc;
rep.type = X_Reply;
rep.length = 0;
rep.sequenceNumber = client->sequence;
/* screen dimensions */
rep.width = pseudoramiXScreens[stuff->screen].w;
rep.height = pseudoramiXScreens[stuff->screen].h;
rep.window = stuff->window;
rep.screen = stuff->screen;
if (client->swapped) {
swaps(&rep.sequenceNumber);
swapl(&rep.length);
swapl(&rep.width);
swapl(&rep.height);
swapl(&rep.window);
swapl(&rep.screen);
}
WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply),&rep);
return Success;
}
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: char* _multi_string_alloc_and_copy( LPCWSTR in )
{
char *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc( len + 2 );
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = 0xFF & in[ len ];
len ++;
}
chr[ len ++ ] = '\0';
chr[ len ++ ] = '\0';
return chr;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void BluetoothAdapterChromeOS::SetDiscoverable(
bool discoverable,
const base::Closure& callback,
const ErrorCallback& error_callback) {
DBusThreadManager::Get()->GetBluetoothAdapterClient()->
GetProperties(object_path_)->discoverable.Set(
discoverable,
base::Bind(&BluetoothAdapterChromeOS::OnSetDiscoverable,
weak_ptr_factory_.GetWeakPtr(),
callback,
error_callback));
}
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 pppol2tp_next_tunnel(struct net *net, struct pppol2tp_seq_data *pd)
{
for (;;) {
pd->tunnel = l2tp_tunnel_find_nth(net, pd->tunnel_idx);
pd->tunnel_idx++;
if (pd->tunnel == NULL)
break;
/* Ignore L2TPv3 tunnels */
if (pd->tunnel->version < 3)
break;
}
}
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: tight_detect_smooth_image(VncState *vs, int w, int h)
{
unsigned int errors;
int compression = vs->tight.compression;
int quality = vs->tight.quality;
if (!vs->vd->lossy) {
return 0;
}
if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
vs->clientds.pf.bytes_per_pixel == 1 ||
w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) {
return 0;
}
if (vs->tight.quality != (uint8_t)-1) {
if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) {
return 0;
}
} else {
if (w * h < tight_conf[compression].gradient_min_rect_size) {
return 0;
}
}
if (vs->clientds.pf.bytes_per_pixel == 4) {
if (vs->tight.pixel24) {
errors = tight_detect_smooth_image24(vs, w, h);
if (vs->tight.quality != (uint8_t)-1) {
return (errors < tight_conf[quality].jpeg_threshold24);
}
return (errors < tight_conf[compression].gradient_threshold24);
} else {
errors = tight_detect_smooth_image32(vs, w, h);
}
} else {
errors = tight_detect_smooth_image16(vs, w, h);
}
if (quality != -1) {
return (errors < tight_conf[quality].jpeg_threshold);
}
return (errors < tight_conf[compression].gradient_threshold);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: RenderProcessHost* RenderWidgetHostImpl::GetProcess() const {
return process_;
}
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: struct r_bin_dyldcache_lib_t *r_bin_dyldcache_extract(struct r_bin_dyldcache_obj_t* bin, int idx, int *nlib) {
ut64 liboff, linkedit_offset;
ut64 dyld_vmbase;
ut32 addend = 0;
struct r_bin_dyldcache_lib_t *ret = NULL;
struct dyld_cache_image_info* image_infos = NULL;
struct mach_header *mh;
ut8 *data, *cmdptr;
int cmd, libsz = 0;
RBuffer* dbuf;
char *libname;
if (!bin) {
return NULL;
}
if (bin->size < 1) {
eprintf ("Empty file? (%s)\n", bin->file? bin->file: "(null)");
return NULL;
}
if (bin->nlibs < 0 || idx < 0 || idx >= bin->nlibs) {
return NULL;
}
*nlib = bin->nlibs;
ret = R_NEW0 (struct r_bin_dyldcache_lib_t);
if (!ret) {
perror ("malloc (ret)");
return NULL;
}
if (bin->hdr.startaddr > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
if (bin->hdr.startaddr > bin->size || bin->hdr.baseaddroff > bin->size) {
eprintf ("corrupted dyldcache");
free (ret);
return NULL;
}
image_infos = (struct dyld_cache_image_info*) (bin->b->buf + bin->hdr.startaddr);
dyld_vmbase = *(ut64 *)(bin->b->buf + bin->hdr.baseaddroff);
liboff = image_infos[idx].address - dyld_vmbase;
if (liboff > bin->size) {
eprintf ("Corrupted file\n");
free (ret);
return NULL;
}
ret->offset = liboff;
if (image_infos[idx].pathFileOffset > bin->size) {
eprintf ("corrupted file\n");
free (ret);
return NULL;
}
libname = (char *)(bin->b->buf + image_infos[idx].pathFileOffset);
/* Locate lib hdr in cache */
data = bin->b->buf + liboff;
mh = (struct mach_header *)data;
/* Check it is mach-o */
if (mh->magic != MH_MAGIC && mh->magic != MH_MAGIC_64) {
if (mh->magic == 0xbebafeca) { //FAT binary
eprintf ("FAT Binary\n");
}
eprintf ("Not mach-o\n");
free (ret);
return NULL;
}
/* Write mach-o hdr */
if (!(dbuf = r_buf_new ())) {
eprintf ("new (dbuf)\n");
free (ret);
return NULL;
}
addend = mh->magic == MH_MAGIC? sizeof (struct mach_header) : sizeof (struct mach_header_64);
r_buf_set_bytes (dbuf, data, addend);
cmdptr = data + addend;
/* Write load commands */
for (cmd = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
r_buf_append_bytes (dbuf, (ut8*)lc, lc->cmdsize);
cmdptr += lc->cmdsize;
}
cmdptr = data + addend;
/* Write segments */
for (cmd = linkedit_offset = 0; cmd < mh->ncmds; cmd++) {
struct load_command *lc = (struct load_command *)cmdptr;
cmdptr += lc->cmdsize;
switch (lc->cmd) {
case LC_SEGMENT:
{
/* Write segment and patch offset */
struct segment_command *seg = (struct segment_command *)lc;
int t = seg->filesize;
if (seg->fileoff + seg->filesize > bin->size || seg->fileoff > bin->size) {
eprintf ("malformed dyldcache\n");
free (ret);
r_buf_free (dbuf);
return NULL;
}
r_buf_append_bytes (dbuf, bin->b->buf+seg->fileoff, t);
r_bin_dyldcache_apply_patch (dbuf, dbuf->length, (ut64)((size_t)&seg->fileoff - (size_t)data));
/* Patch section offsets */
int sect_offset = seg->fileoff - libsz;
libsz = dbuf->length;
if (!strcmp (seg->segname, "__LINKEDIT")) {
linkedit_offset = sect_offset;
}
if (seg->nsects > 0) {
struct section *sects = (struct section *)((ut8 *)seg + sizeof(struct segment_command));
int nsect;
for (nsect = 0; nsect < seg->nsects; nsect++) {
if (sects[nsect].offset > libsz) {
r_bin_dyldcache_apply_patch (dbuf, sects[nsect].offset - sect_offset,
(ut64)((size_t)§s[nsect].offset - (size_t)data));
}
}
}
}
break;
case LC_SYMTAB:
{
struct symtab_command *st = (struct symtab_command *)lc;
NZ_OFFSET (st->symoff);
NZ_OFFSET (st->stroff);
}
break;
case LC_DYSYMTAB:
{
struct dysymtab_command *st = (struct dysymtab_command *)lc;
NZ_OFFSET (st->tocoff);
NZ_OFFSET (st->modtaboff);
NZ_OFFSET (st->extrefsymoff);
NZ_OFFSET (st->indirectsymoff);
NZ_OFFSET (st->extreloff);
NZ_OFFSET (st->locreloff);
}
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
{
struct dyld_info_command *st = (struct dyld_info_command *)lc;
NZ_OFFSET (st->rebase_off);
NZ_OFFSET (st->bind_off);
NZ_OFFSET (st->weak_bind_off);
NZ_OFFSET (st->lazy_bind_off);
NZ_OFFSET (st->export_off);
}
break;
}
}
/* Fill r_bin_dyldcache_lib_t ret */
ret->b = dbuf;
strncpy (ret->path, libname, sizeof (ret->path) - 1);
ret->size = libsz;
return ret;
}
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: MediaControlsProgressView::MediaControlsProgressView(
base::RepeatingCallback<void(double)> seek_callback)
: seek_callback_(std::move(seek_callback)) {
SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical, kProgressViewInsets));
progress_bar_ = AddChildView(std::make_unique<views::ProgressBar>(5, false));
progress_bar_->SetBorder(views::CreateEmptyBorder(kProgressBarInsets));
gfx::Font default_font;
int font_size_delta = kProgressTimeFontSize - default_font.GetFontSize();
gfx::Font font = default_font.Derive(font_size_delta, gfx::Font::NORMAL,
gfx::Font::Weight::NORMAL);
gfx::FontList font_list(font);
auto time_view = std::make_unique<views::View>();
auto* time_view_layout =
time_view->SetLayoutManager(std::make_unique<views::FlexLayout>());
time_view_layout->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetMainAxisAlignment(views::LayoutAlignment::kCenter)
.SetCrossAxisAlignment(views::LayoutAlignment::kCenter)
.SetCollapseMargins(true);
auto progress_time = std::make_unique<views::Label>();
progress_time->SetFontList(font_list);
progress_time->SetEnabledColor(SK_ColorWHITE);
progress_time->SetAutoColorReadabilityEnabled(false);
progress_time_ = time_view->AddChildView(std::move(progress_time));
auto time_spacing = std::make_unique<views::View>();
time_spacing->SetPreferredSize(kTimeSpacingSize);
time_spacing->SetProperty(views::kFlexBehaviorKey,
views::FlexSpecification::ForSizeRule(
views::MinimumFlexSizeRule::kPreferred,
views::MaximumFlexSizeRule::kUnbounded));
time_view->AddChildView(std::move(time_spacing));
auto duration = std::make_unique<views::Label>();
duration->SetFontList(font_list);
duration->SetEnabledColor(SK_ColorWHITE);
duration->SetAutoColorReadabilityEnabled(false);
duration_ = time_view->AddChildView(std::move(duration));
AddChildView(std::move(time_view));
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
if (is_being_destroyed_)
return;
frame_tree_.ReplicatePageFocus(is_focused);
}
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 svc_rdma_get_write_arrays(struct rpcrdma_msg *rmsgp,
struct rpcrdma_write_array **write,
struct rpcrdma_write_array **reply)
{
__be32 *p;
p = (__be32 *)&rmsgp->rm_body.rm_chunks[0];
/* Read list */
while (*p++ != xdr_zero)
p += 5;
/* Write list */
if (*p != xdr_zero) {
*write = (struct rpcrdma_write_array *)p;
while (*p++ != xdr_zero)
p += 1 + be32_to_cpu(*p) * 4;
} else {
*write = NULL;
p++;
}
/* Reply chunk */
if (*p != xdr_zero)
*reply = (struct rpcrdma_write_array *)p;
else
*reply = NULL;
}
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 void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri,
unsigned long resolution,
unsigned long ticks)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_tread *r, r1;
struct timespec tstamp;
int prev, append = 0;
memset(&tstamp, 0, sizeof(tstamp));
spin_lock(&tu->qlock);
if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) |
(1 << SNDRV_TIMER_EVENT_TICK))) == 0) {
spin_unlock(&tu->qlock);
return;
}
if (tu->last_resolution != resolution || ticks > 0) {
if (timer_tstamp_monotonic)
ktime_get_ts(&tstamp);
else
getnstimeofday(&tstamp);
}
if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) &&
tu->last_resolution != resolution) {
r1.event = SNDRV_TIMER_EVENT_RESOLUTION;
r1.tstamp = tstamp;
r1.val = resolution;
snd_timer_user_append_to_tqueue(tu, &r1);
tu->last_resolution = resolution;
append++;
}
if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0)
goto __wake;
if (ticks == 0)
goto __wake;
if (tu->qused > 0) {
prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
r = &tu->tqueue[prev];
if (r->event == SNDRV_TIMER_EVENT_TICK) {
r->tstamp = tstamp;
r->val += ticks;
append++;
goto __wake;
}
}
r1.event = SNDRV_TIMER_EVENT_TICK;
r1.tstamp = tstamp;
r1.val = ticks;
snd_timer_user_append_to_tqueue(tu, &r1);
append++;
__wake:
spin_unlock(&tu->qlock);
if (append == 0)
return;
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static const EVP_CIPHER * php_openssl_get_evp_cipher_from_algo(long algo) { /* {{{ */
switch (algo) {
#ifndef OPENSSL_NO_RC2
case PHP_OPENSSL_CIPHER_RC2_40:
return EVP_rc2_40_cbc();
break;
case PHP_OPENSSL_CIPHER_RC2_64:
return EVP_rc2_64_cbc();
break;
case PHP_OPENSSL_CIPHER_RC2_128:
return EVP_rc2_cbc();
break;
#endif
#ifndef OPENSSL_NO_DES
case PHP_OPENSSL_CIPHER_DES:
return EVP_des_cbc();
break;
case PHP_OPENSSL_CIPHER_3DES:
return EVP_des_ede3_cbc();
break;
#endif
default:
return NULL;
break;
}
}
/* }}} */
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: ProcMapWindow(ClientPtr client)
{
WindowPtr pWin;
REQUEST(xResourceReq);
int rc;
REQUEST_SIZE_MATCH(xResourceReq);
rc = dixLookupWindow(&pWin, stuff->id, client, DixShowAccess);
if (rc != Success)
return rc;
MapWindow(pWin, client);
/* update cache to say it is mapped */
return Success;
}
CWE ID: CWE-369
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: ContentEncoding::GetEncryptionByIndex(unsigned long idx) const {
const ptrdiff_t count = encryption_entries_end_ - encryption_entries_;
assert(count >= 0);
if (idx >= static_cast<unsigned long>(count))
return NULL;
return encryption_entries_[idx];
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: close_uzbl (WebKitWebView *page, GArray *argv, GString *result) {
(void)page;
(void)argv;
(void)result;
gtk_main_quit ();
}
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: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr,
int total_subobj_len, int offset)
{
int hexdump = FALSE;
int subobj_type, subobj_len;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
while (total_subobj_len > 0 && hexdump == FALSE ) {
subobj_type = EXTRACT_8BITS(obj_tptr + offset);
subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1);
ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u",
tok2str(lmp_data_link_subobj,
"Unknown",
subobj_type),
subobj_type,
subobj_len));
if (subobj_len < 4) {
ND_PRINT((ndo, " (too short)"));
break;
}
if ((subobj_len % 4) != 0) {
ND_PRINT((ndo, " (not a multiple of 4)"));
break;
}
if (total_subobj_len < subobj_len) {
ND_PRINT((ndo, " (goes past the end of the object)"));
break;
}
switch(subobj_type) {
case INT_SWITCHING_TYPE_SUBOBJ:
ND_PRINT((ndo, "\n\t Switching Type: %s (%u)",
tok2str(gmpls_switch_cap_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 2)),
EXTRACT_8BITS(obj_tptr + offset + 2)));
ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)",
tok2str(gmpls_encoding_values,
"Unknown",
EXTRACT_8BITS(obj_tptr + offset + 3)),
EXTRACT_8BITS(obj_tptr + offset + 3)));
bw.i = EXTRACT_32BITS(obj_tptr+offset+4);
ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
bw.i = EXTRACT_32BITS(obj_tptr+offset+8);
ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case WAVELENGTH_SUBOBJ:
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+offset+4)));
break;
default:
/* Any Unknown Subobject ==> Exit loop */
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
offset+=subobj_len;
}
return (hexdump);
}
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 DaemonProcessTest::LaunchNetworkProcess() {
terminal_id_ = 0;
daemon_process_->OnChannelConnected();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: TIFFFdOpen(int ifd, const char* name, const char* mode)
{
TIFF* tif;
int fSuppressMap;
int m;
fSuppressMap=0;
for (m=0; mode[m]!=0; m++)
{
if (mode[m]=='u')
{
fSuppressMap=1;
break;
}
}
tif = TIFFClientOpen(name, mode, (thandle_t)ifd,
_tiffReadProc, _tiffWriteProc,
_tiffSeekProc, _tiffCloseProc, _tiffSizeProc,
fSuppressMap ? _tiffDummyMapProc : _tiffMapProc,
fSuppressMap ? _tiffDummyUnmapProc : _tiffUnmapProc);
if (tif)
tif->tif_fd = ifd;
return (tif);
}
CWE ID: CWE-369
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: ~FragmentPaintPropertyTreeBuilder() {
full_context_.force_subtree_update |= property_added_or_removed_;
#if DCHECK_IS_ON()
if (properties_)
PaintPropertyTreePrinter::UpdateDebugNames(object_, *properties_);
#endif
}
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 void __exit pcd_exit(void)
{
struct pcd_unit *cd;
int unit;
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
if (cd->present) {
del_gendisk(cd->disk);
pi_release(cd->pi);
unregister_cdrom(&cd->info);
}
blk_cleanup_queue(cd->disk->queue);
blk_mq_free_tag_set(&cd->tag_set);
put_disk(cd->disk);
}
unregister_blkdev(major, name);
pi_unregister_driver(par_drv);
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: int mdiobus_unregister_device(struct mdio_device *mdiodev)
{
if (mdiodev->bus->mdio_map[mdiodev->addr] != mdiodev)
return -EINVAL;
mdiodev->bus->mdio_map[mdiodev->addr] = NULL;
return 0;
}
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: static int ext4_writepage(struct page *page,
struct writeback_control *wbc)
{
int ret = 0;
loff_t size;
unsigned int len;
struct buffer_head *page_bufs;
struct inode *inode = page->mapping->host;
trace_ext4_writepage(inode, page);
size = i_size_read(inode);
if (page->index == size >> PAGE_CACHE_SHIFT)
len = size & ~PAGE_CACHE_MASK;
else
len = PAGE_CACHE_SIZE;
if (page_has_buffers(page)) {
page_bufs = page_buffers(page);
if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
ext4_bh_delay_or_unwritten)) {
/*
* We don't want to do block allocation
* So redirty the page and return
* We may reach here when we do a journal commit
* via journal_submit_inode_data_buffers.
* If we don't have mapping block we just ignore
* them. We can also reach here via shrink_page_list
*/
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
} else {
/*
* The test for page_has_buffers() is subtle:
* We know the page is dirty but it lost buffers. That means
* that at some moment in time after write_begin()/write_end()
* has been called all buffers have been clean and thus they
* must have been written at least once. So they are all
* mapped and we can happily proceed with mapping them
* and writing the page.
*
* Try to initialize the buffer_heads and check whether
* all are mapped and non delay. We don't want to
* do block allocation here.
*/
ret = block_prepare_write(page, 0, len,
noalloc_get_block_write);
if (!ret) {
page_bufs = page_buffers(page);
/* check whether all are mapped and non delay */
if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
ext4_bh_delay_or_unwritten)) {
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
} else {
/*
* We can't do block allocation here
* so just redity the page and unlock
* and return
*/
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
/* now mark the buffer_heads as dirty and uptodate */
block_commit_write(page, 0, len);
}
if (PageChecked(page) && ext4_should_journal_data(inode)) {
/*
* It's mmapped pagecache. Add buffers and journal it. There
* doesn't seem much point in redirtying the page here.
*/
ClearPageChecked(page);
return __ext4_journalled_writepage(page, len);
}
if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
ret = nobh_writepage(page, noalloc_get_block_write, wbc);
else
ret = block_write_full_page(page, noalloc_get_block_write,
wbc);
return ret;
}
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: std::string GetUploadData(const std::string& brand) {
DCHECK(!brand.empty());
std::string data(kPostXml);
const std::string placeholder("__BRANDCODE_PLACEHOLDER__");
size_t placeholder_pos = data.find(placeholder);
DCHECK(placeholder_pos != std::string::npos);
data.replace(placeholder_pos, placeholder.size(), brand);
return data;
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: void PacketDefragPktSetupParent(Packet *parent)
{
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(parent);
/* disable payload (not packet) inspection on the parent, as the payload
* is the packet we will now run through the system separately. We do
* check it against the ip/port/other header checks though */
DecodeSetNoPayloadInspectionFlag(parent);
}
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: xdr_krb5_principal(XDR *xdrs, krb5_principal *objp)
{
int ret;
char *p = NULL;
krb5_principal pr = NULL;
static krb5_context context = NULL;
/* using a static context here is ugly, but should work
ok, and the other solutions are even uglier */
if (!context &&
kadm5_init_krb5_context(&context))
return(FALSE);
switch(xdrs->x_op) {
case XDR_ENCODE:
if (*objp) {
if((ret = krb5_unparse_name(context, *objp, &p)) != 0)
return FALSE;
}
if(!xdr_nullstring(xdrs, &p))
return FALSE;
if (p) free(p);
break;
case XDR_DECODE:
if(!xdr_nullstring(xdrs, &p))
return FALSE;
if (p) {
ret = krb5_parse_name(context, p, &pr);
if(ret != 0)
return FALSE;
*objp = pr;
free(p);
} else
*objp = NULL;
break;
case XDR_FREE:
if(*objp != NULL)
krb5_free_principal(context, *objp);
break;
}
return TRUE;
}
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: x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid = ARR_SIZE(insn_regs_intel) / 2;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
while (first <= last) {
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
mid = (first + last) / 2;
}
return 0;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: unsigned WebGLRenderingContextBase::CurrentMaxGLContexts() {
MutexLocker locker(WebGLContextLimitMutex());
DCHECK(webgl_context_limits_initialized_);
return IsMainThread() ? max_active_webgl_contexts_
: max_active_webgl_contexts_on_worker_;
}
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: status_t OMXNodeInstance::updateGraphicBufferInMeta_l(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer, OMX_BUFFERHEADERTYPE *header) {
if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) {
return BAD_VALUE;
}
BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate);
bufferMeta->setGraphicBuffer(graphicBuffer);
if (mMetadataType[portIndex] == kMetadataBufferTypeGrallocSource
&& header->nAllocLen >= sizeof(VideoGrallocMetadata)) {
VideoGrallocMetadata &metadata = *(VideoGrallocMetadata *)(header->pBuffer);
metadata.eType = kMetadataBufferTypeGrallocSource;
metadata.pHandle = graphicBuffer == NULL ? NULL : graphicBuffer->handle;
} else if (mMetadataType[portIndex] == kMetadataBufferTypeANWBuffer
&& header->nAllocLen >= sizeof(VideoNativeMetadata)) {
VideoNativeMetadata &metadata = *(VideoNativeMetadata *)(header->pBuffer);
metadata.eType = kMetadataBufferTypeANWBuffer;
metadata.pBuffer = graphicBuffer == NULL ? NULL : graphicBuffer->getNativeBuffer();
metadata.nFenceFd = -1;
} else {
CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x bad type (%d) or size (%u)",
portString(portIndex), portIndex, buffer, mMetadataType[portIndex], header->nAllocLen);
return BAD_VALUE;
}
CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x := %p",
portString(portIndex), portIndex, buffer,
graphicBuffer == NULL ? NULL : graphicBuffer->handle);
return OK;
}
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: SYSCALL_DEFINE1(inotify_init1, int, flags)
{
struct fsnotify_group *group;
struct user_struct *user;
int ret;
/* Check the IN_* constants for consistency. */
BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK);
if (flags & ~(IN_CLOEXEC | IN_NONBLOCK))
return -EINVAL;
user = get_current_user();
if (unlikely(atomic_read(&user->inotify_devs) >=
inotify_max_user_instances)) {
ret = -EMFILE;
goto out_free_uid;
}
/* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */
group = inotify_new_group(user, inotify_max_queued_events);
if (IS_ERR(group)) {
ret = PTR_ERR(group);
goto out_free_uid;
}
atomic_inc(&user->inotify_devs);
ret = anon_inode_getfd("inotify", &inotify_fops, group,
O_RDONLY | flags);
if (ret >= 0)
return ret;
atomic_dec(&user->inotify_devs);
out_free_uid:
free_uid(user);
return ret;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: irc_server_add_to_infolist (struct t_infolist *infolist,
struct t_irc_server *server)
{
struct t_infolist_item *ptr_item;
if (!infolist || !server)
return 0;
ptr_item = weechat_infolist_new_item (infolist);
if (!ptr_item)
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "name", server->name))
return 0;
if (!weechat_infolist_new_var_pointer (ptr_item, "buffer", server->buffer))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "buffer_name",
(server->buffer) ?
weechat_buffer_get_string (server->buffer, "name") : ""))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "buffer_short_name",
(server->buffer) ?
weechat_buffer_get_string (server->buffer, "short_name") : ""))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "addresses",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_ADDRESSES)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "proxy",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_PROXY)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "ipv6",
IRC_SERVER_OPTION_BOOLEAN(server, IRC_SERVER_OPTION_IPV6)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "ssl",
IRC_SERVER_OPTION_BOOLEAN(server, IRC_SERVER_OPTION_SSL)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "ssl_cert",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_SSL_CERT)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "ssl_dhkey_size",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_SSL_DHKEY_SIZE)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "ssl_verify",
IRC_SERVER_OPTION_BOOLEAN(server, IRC_SERVER_OPTION_SSL_VERIFY)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "password",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_PASSWORD)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "sasl_mechanism",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_SASL_MECHANISM)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "sasl_username",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_SASL_USERNAME)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "sasl_password",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_SASL_PASSWORD)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "autoconnect",
IRC_SERVER_OPTION_BOOLEAN(server, IRC_SERVER_OPTION_AUTOCONNECT)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "autoreconnect",
IRC_SERVER_OPTION_BOOLEAN(server, IRC_SERVER_OPTION_AUTORECONNECT)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "autoreconnect_delay",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_AUTORECONNECT_DELAY)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "nicks",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_NICKS)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "username",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_USERNAME)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "realname",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_REALNAME)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "local_hostname",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_LOCAL_HOSTNAME)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "command",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_COMMAND)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "command_delay",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_COMMAND_DELAY)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "autojoin",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_AUTOJOIN)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "autorejoin",
IRC_SERVER_OPTION_BOOLEAN(server, IRC_SERVER_OPTION_AUTOREJOIN)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "autorejoin_delay",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_AUTOREJOIN_DELAY)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "connection_timeout",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_CONNECTION_TIMEOUT)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "anti_flood_prio_high",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_ANTI_FLOOD_PRIO_HIGH)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "anti_flood_prio_low",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_ANTI_FLOOD_PRIO_LOW)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "away_check",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_AWAY_CHECK)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "away_check_max_nicks",
IRC_SERVER_OPTION_INTEGER(server, IRC_SERVER_OPTION_AWAY_CHECK_MAX_NICKS)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "default_msg_part",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_DEFAULT_MSG_PART)))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "default_msg_quit",
IRC_SERVER_OPTION_STRING(server, IRC_SERVER_OPTION_DEFAULT_MSG_QUIT)))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "temp_server", server->temp_server))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "index_current_address", server->index_current_address))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "current_address", server->current_address))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "current_ip", server->current_ip))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "current_port", server->current_port))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "sock", server->sock))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "is_connected", server->is_connected))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "ssl_connected", server->ssl_connected))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "unterminated_message", server->unterminated_message))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "nick", server->nick))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "nick_modes", server->nick_modes))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "isupport", server->isupport))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "prefix_modes", server->prefix_modes))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "prefix_chars", server->prefix_chars))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "reconnect_delay", server->reconnect_delay))
return 0;
if (!weechat_infolist_new_var_time (ptr_item, "reconnect_start", server->reconnect_start))
return 0;
if (!weechat_infolist_new_var_time (ptr_item, "command_time", server->command_time))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "reconnect_join", server->reconnect_join))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "disable_autojoin", server->disable_autojoin))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "is_away", server->is_away))
return 0;
if (!weechat_infolist_new_var_string (ptr_item, "away_message", server->away_message))
return 0;
if (!weechat_infolist_new_var_time (ptr_item, "away_time", server->away_time))
return 0;
if (!weechat_infolist_new_var_integer (ptr_item, "lag", server->lag))
return 0;
if (!weechat_infolist_new_var_buffer (ptr_item, "lag_check_time", &(server->lag_check_time), sizeof (struct timeval)))
return 0;
if (!weechat_infolist_new_var_time (ptr_item, "lag_next_check", server->lag_next_check))
return 0;
if (!weechat_infolist_new_var_time (ptr_item, "lag_last_refresh", server->lag_last_refresh))
return 0;
if (!weechat_infolist_new_var_time (ptr_item, "last_user_message", server->last_user_message))
return 0;
if (!weechat_infolist_new_var_time (ptr_item, "last_away_check", server->last_away_check))
return 0;
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: static int unix_stream_splice_actor(struct sk_buff *skb,
int skip, int chunk,
struct unix_stream_read_state *state)
{
return skb_splice_bits(skb, state->socket->sk,
UNIXCB(skb).consumed + skip,
state->pipe, chunk, state->splice_flags,
skb_unix_socket_splice);
}
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: dump_keywords(vector_t *keydump, int level, FILE *fp)
{
unsigned int i;
keyword_t *keyword_vec;
char file_name[21];
if (!level) {
snprintf(file_name, sizeof(file_name), "/tmp/keywords.%d", getpid());
fp = fopen(file_name, "w");
if (!fp)
return;
}
for (i = 0; i < vector_size(keydump); i++) {
keyword_vec = vector_slot(keydump, i);
fprintf(fp, "%*sKeyword : %s (%s)\n", level * 2, "", keyword_vec->string, keyword_vec->active ? "active": "disabled");
if (keyword_vec->sub)
dump_keywords(keyword_vec->sub, level + 1, fp);
}
if (!level)
fclose(fp);
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: void PostScript_MetaHandler::setTokenInfo(TokenFlag tFlag,XMP_Int64 offset,XMP_Int64 length)
{
if (!(docInfoFlags&tFlag)&&tFlag>=kPS_ADOContainsXMP && tFlag<=kPS_EndPostScript)
{
size_t index=0;
XMP_Uns64 flag=tFlag;
while(flag>>=1) index++;
fileTokenInfo[index].offsetStart=offset;
fileTokenInfo[index].tokenlen=length;
docInfoFlags|=tFlag;
}
}
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: virtual void ResetModel() {
last_pts_ = 0;
bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz;
frame_number_ = 0;
tot_frame_number_ = 0;
first_drop_ = 0;
num_drops_ = 0;
for (int i = 0; i < 3; ++i) {
bits_total_[i] = 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: set_hunkmax (void)
{
if (!p_line)
p_line = (char **) malloc (hunkmax * sizeof *p_line);
if (!p_len)
p_len = (size_t *) malloc (hunkmax * sizeof *p_len);
if (!p_Char)
p_Char = malloc (hunkmax * sizeof *p_Char);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void OfflinePageModelTaskified::CreateArchivesDirectoryIfNeeded() {
archive_manager_->EnsureArchivesDirCreated(base::Bind([]() {}));
}
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: static QQuickWebViewPrivate* createPrivateObject(QQuickWebView* publicObject)
{
if (s_flickableViewportEnabled)
return new QQuickWebViewFlickablePrivate(publicObject);
return new QQuickWebViewLegacyPrivate(publicObject);
}
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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionObjMethodWithArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 3)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->objMethodWithArgs(intArg, strArg, objArg)));
return JSValue::encode(result);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: ~ScopedCommitStateResetter() {
if (!disabled_) {
render_frame_host_->set_nav_entry_id(0);
}
}
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: long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) {
assert(pReader);
long long total, available;
long status = pReader->Length(&total, &available);
if (status < 0) // error
return status;
pos = 0;
long long end = (available >= 1024) ? 1024 : available;
for (;;) {
unsigned char b = 0;
while (pos < end) {
status = pReader->Read(pos, 1, &b);
if (status < 0) // error
return status;
if (b == 0x1A)
break;
++pos;
}
if (b != 0x1A) {
if (pos >= 1024)
return E_FILE_FORMAT_INVALID; // don't bother looking anymore
if ((total >= 0) && ((total - available) < 5))
return E_FILE_FORMAT_INVALID;
return available + 5; // 5 = 4-byte ID + 1st byte of size
}
if ((total >= 0) && ((total - pos) < 5))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < 5)
return pos + 5; // try again later
long len;
const long long result = ReadUInt(pReader, pos, len);
if (result < 0) // error
return result;
if (result == 0x0A45DFA3) { // EBML Header ID
pos += len; // consume ID
break;
}
++pos; // throw away just the 0x1A byte, and try again
}
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return result;
if (result > 0) // need more data
return result;
assert(len > 0);
assert(len <= 8);
if ((total >= 0) && ((total - pos) < len))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < len)
return pos + len; // try again later
result = ReadUInt(pReader, pos, len);
if (result < 0) // error
return result;
pos += len; // consume size field
if ((total >= 0) && ((total - pos) < result))
return E_FILE_FORMAT_INVALID;
if ((available - pos) < result)
return pos + result;
end = pos + result;
Init();
while (pos < end) {
long long id, size;
status = ParseElementHeader(pReader, pos, end, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
return E_FILE_FORMAT_INVALID;
if (id == 0x0286) { // version
m_version = UnserializeUInt(pReader, pos, size);
if (m_version <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x02F7) { // read version
m_readVersion = UnserializeUInt(pReader, pos, size);
if (m_readVersion <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x02F2) { // max id length
m_maxIdLength = UnserializeUInt(pReader, pos, size);
if (m_maxIdLength <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x02F3) { // max size length
m_maxSizeLength = UnserializeUInt(pReader, pos, size);
if (m_maxSizeLength <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0282) { // doctype
if (m_docType)
return E_FILE_FORMAT_INVALID;
status = UnserializeString(pReader, pos, size, m_docType);
if (status) // error
return status;
} else if (id == 0x0287) { // doctype version
m_docTypeVersion = UnserializeUInt(pReader, pos, size);
if (m_docTypeVersion <= 0)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x0285) { // doctype read version
m_docTypeReadVersion = UnserializeUInt(pReader, pos, size);
if (m_docTypeReadVersion <= 0)
return E_FILE_FORMAT_INVALID;
}
pos += size;
}
assert(pos == end);
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 void ptrace_link(struct task_struct *child, struct task_struct *new_parent)
{
rcu_read_lock();
__ptrace_link(child, new_parent, __task_cred(new_parent));
rcu_read_unlock();
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void efx_start_port(struct efx_nic *efx)
{
netif_dbg(efx, ifup, efx->net_dev, "start port\n");
BUG_ON(efx->port_enabled);
mutex_lock(&efx->mac_lock);
efx->port_enabled = true;
/* efx_mac_work() might have been scheduled after efx_stop_port(),
* and then cancelled by efx_flush_all() */
efx->type->push_multicast_hash(efx);
efx->mac_op->reconfigure(efx);
mutex_unlock(&efx->mac_lock);
}
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 RenderFrameImpl::OnHostZoomClientRequest(
mojom::HostZoomAssociatedRequest request) {
DCHECK(!host_zoom_binding_.is_bound());
host_zoom_binding_.Bind(std::move(request),
GetTaskRunner(blink::TaskType::kInternalIPC));
}
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: static noinline int btrfs_mksubvol(struct path *parent,
char *name, int namelen,
struct btrfs_root *snap_src,
u64 *async_transid, bool readonly,
struct btrfs_qgroup_inherit **inherit)
{
struct inode *dir = parent->dentry->d_inode;
struct dentry *dentry;
int error;
mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT);
dentry = lookup_one_len(name, parent->dentry, namelen);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
error = -EEXIST;
if (dentry->d_inode)
goto out_dput;
error = btrfs_may_create(dir, dentry);
if (error)
goto out_dput;
down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0)
goto out_up_read;
if (snap_src) {
error = create_snapshot(snap_src, dentry, name, namelen,
async_transid, readonly, inherit);
} else {
error = create_subvol(BTRFS_I(dir)->root, dentry,
name, namelen, async_transid, inherit);
}
if (!error)
fsnotify_mkdir(dir, dentry);
out_up_read:
up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&dir->i_mutex);
return error;
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: static int dbpageConnect(
sqlite3 *db,
void *pAux,
int argc, const char *const*argv,
sqlite3_vtab **ppVtab,
char **pzErr
){
DbpageTable *pTab = 0;
int rc = SQLITE_OK;
rc = sqlite3_declare_vtab(db,
"CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
if( rc==SQLITE_OK ){
pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
}
assert( rc==SQLITE_OK || pTab==0 );
if( rc==SQLITE_OK ){
memset(pTab, 0, sizeof(DbpageTable));
pTab->db = db;
}
*ppVtab = (sqlite3_vtab*)pTab;
return rc;
}
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: void Document::BindDocumentInterfaceBroker(
mojo::ScopedMessagePipeHandle js_handle) {
if (!GetFrame())
return;
GetFrame()->BindDocumentInterfaceBroker(std::move(js_handle));
}
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: void ptrace_triggered(struct perf_event *bp, int nmi,
struct perf_sample_data *data, struct pt_regs *regs)
{
struct perf_event_attr attr;
/*
* Disable the breakpoint request here since ptrace has defined a
* one-shot behaviour for breakpoint exceptions in PPC64.
* The SIGTRAP signal is generated automatically for us in do_dabr().
* We don't have to do anything about that here
*/
attr = bp->attr;
attr.disabled = true;
modify_user_hw_breakpoint(bp, &attr);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: http_copyheader(struct worker *w, int fd, struct http *to,
const struct http *fm, unsigned n)
{
CHECK_OBJ_NOTNULL(fm, HTTP_MAGIC);
CHECK_OBJ_NOTNULL(to, HTTP_MAGIC);
assert(n < fm->shd);
Tcheck(fm->hd[n]);
if (to->nhd < to->shd) {
to->hd[to->nhd] = fm->hd[n];
to->hdf[to->nhd] = 0;
to->nhd++;
} else {
VSC_C_main->losthdr++;
WSLR(w, SLT_LostHeader, fd, fm->hd[n]);
}
}
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: _XcursorThemeInherits (const char *full)
{
char line[8192];
char *result = NULL;
FILE *f;
if (!full)
return NULL;
f = fopen (full, "r");
if (f)
{
while (fgets (line, sizeof (line), f))
{
if (!strncmp (line, "Inherits", 8))
{
char *l = line + 8;
char *r;
while (*l == ' ') l++;
if (*l != '=') continue;
l++;
while (*l == ' ') l++;
result = malloc (strlen (l));
if (result)
{
r = result;
while (*l)
{
while (XcursorSep(*l) || XcursorWhite (*l)) l++;
if (!*l)
break;
if (r != result)
*r++ = ':';
while (*l && !XcursorWhite(*l) &&
!XcursorSep(*l))
*r++ = *l++;
}
*r++ = '\0';
}
break;
}
}
fclose (f);
}
return result;
}
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 iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb)
{
int error = 0;
struct cxio_rdev *rdev;
rdev = (struct cxio_rdev *)tdev->ulp;
if (cxio_fatal_error(rdev)) {
kfree_skb(skb);
return -EIO;
}
error = cxgb3_ofld_send(tdev, skb);
if (error < 0)
kfree_skb(skb);
return error;
}
CWE ID:
Target: 1
Example 2:
Code: static inline MagickBooleanType IsPoint(const char *point)
{
char
*p;
double
value;
value=StringToDouble(point,&p);
return((fabs(value) < MagickEpsilon) && (p == point) ? MagickFalse :
MagickTrue);
}
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 inSymtab(SdbHash *hash, struct symbol_t *symbols, const char *name, ut64 addr) {
bool found;
const char *key = sdb_fmt ("%s.%"PFMT64x, name, addr);
(void)sdb_ht_find (hash, key, &found);
if (found) {
return true;
}
sdb_ht_insert (hash, key, "1");
return false;
}
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 int simulate_llsc(struct pt_regs *regs, unsigned int opcode)
{
if ((opcode & OPCODE) == LL) {
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
1, 0, regs, 0);
return simulate_ll(regs, opcode);
}
if ((opcode & OPCODE) == SC) {
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS,
1, 0, regs, 0);
return simulate_sc(regs, opcode);
}
return -1; /* Must be something else ... */
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: TEE_Result syscall_cipher_update(unsigned long state, const void *src,
size_t src_len, void *dst, uint64_t *dst_len)
{
return tee_svc_cipher_update_helper(state, false /* last_block */,
src, src_len, dst, dst_len);
}
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 add_pending_object(struct rev_info *revs,
struct object *obj, const char *name)
{
add_pending_object_with_mode(revs, obj, name, S_IFINVALID);
}
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 PropertyTreeManager::SetupRootEffectNode() {
cc::EffectTree& effect_tree = property_trees_.effect_tree;
effect_tree.clear();
property_trees_.element_id_to_effect_node_index.clear();
cc::EffectNode& effect_node =
*effect_tree.Node(effect_tree.Insert(cc::EffectNode(), kInvalidNodeId));
DCHECK_EQ(effect_node.id, kSecondaryRootNodeId);
static UniqueObjectId unique_id = NewUniqueObjectId();
effect_node.stable_id =
CompositorElementIdFromUniqueObjectId(unique_id).ToInternalValue();
effect_node.transform_id = kRealRootNodeId;
effect_node.clip_id = kSecondaryRootNodeId;
effect_node.has_render_surface = true;
root_layer_->SetEffectTreeIndex(effect_node.id);
current_effect_id_ = effect_node.id;
current_effect_type_ = CcEffectType::kEffect;
current_effect_ = EffectPaintPropertyNode::Root();
current_clip_ = current_effect_->OutputClip();
}
CWE ID:
Target: 1
Example 2:
Code: config_insert( const char* attrName, const char* attrValue )
{
if( ! (attrName && attrValue) ) {
return;
}
insert( attrName, attrValue, ConfigTab, TABLESIZE );
}
CWE ID: CWE-134
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 Image *ReadSCREENSHOTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
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=(Image *) NULL;
#if defined(MAGICKCORE_WINGDI32_DELEGATE)
{
BITMAPINFO
bmi;
DISPLAY_DEVICE
device;
HBITMAP
bitmap,
bitmapOld;
HDC
bitmapDC,
hDC;
Image
*screen;
int
i;
MagickBooleanType
status;
register PixelPacket
*q;
register ssize_t
x;
RGBTRIPLE
*p;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
i=0;
device.cb = sizeof(device);
image=(Image *) NULL;
while(EnumDisplayDevices(NULL,i,&device,0) && ++i)
{
if ((device.StateFlags & DISPLAY_DEVICE_ACTIVE) != DISPLAY_DEVICE_ACTIVE)
continue;
hDC=CreateDC(device.DeviceName,device.DeviceName,NULL,NULL);
if (hDC == (HDC) NULL)
ThrowReaderException(CoderError,"UnableToCreateDC");
screen=AcquireImage(image_info);
screen->columns=(size_t) GetDeviceCaps(hDC,HORZRES);
screen->rows=(size_t) GetDeviceCaps(hDC,VERTRES);
screen->storage_class=DirectClass;
status=SetImageExtent(screen,screen->columns,screen->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image == (Image *) NULL)
image=screen;
else
AppendImageToList(&image,screen);
bitmapDC=CreateCompatibleDC(hDC);
if (bitmapDC == (HDC) NULL)
{
DeleteDC(hDC);
ThrowReaderException(CoderError,"UnableToCreateDC");
}
(void) ResetMagickMemory(&bmi,0,sizeof(BITMAPINFO));
bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth=(LONG) screen->columns;
bmi.bmiHeader.biHeight=(-1)*(LONG) screen->rows;
bmi.bmiHeader.biPlanes=1;
bmi.bmiHeader.biBitCount=24;
bmi.bmiHeader.biCompression=BI_RGB;
bitmap=CreateDIBSection(hDC,&bmi,DIB_RGB_COLORS,(void **) &p,NULL,0);
if (bitmap == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
bitmapOld=(HBITMAP) SelectObject(bitmapDC,bitmap);
if (bitmapOld == (HBITMAP) NULL)
{
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
ThrowReaderException(CoderError,"UnableToCreateBitmap");
}
BitBlt(bitmapDC,0,0,(int) screen->columns,(int) screen->rows,hDC,0,0,
SRCCOPY);
(void) SelectObject(bitmapDC,bitmapOld);
for (y=0; y < (ssize_t) screen->rows; y++)
{
q=QueueAuthenticPixels(screen,0,y,screen->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) screen->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(p->rgbtRed));
SetPixelGreen(q,ScaleCharToQuantum(p->rgbtGreen));
SetPixelBlue(q,ScaleCharToQuantum(p->rgbtBlue));
SetPixelOpacity(q,OpaqueOpacity);
p++;
q++;
}
if (SyncAuthenticPixels(screen,exception) == MagickFalse)
break;
}
DeleteDC(hDC);
DeleteDC(bitmapDC);
DeleteObject(bitmap);
}
}
#elif defined(MAGICKCORE_X11_DELEGATE)
{
const char
*option;
XImportInfo
ximage_info;
(void) exception;
XGetImportInfo(&ximage_info);
option=GetImageOption(image_info,"x:screen");
if (option != (const char *) NULL)
ximage_info.screen=IsMagickTrue(option);
option=GetImageOption(image_info,"x:silent");
if (option != (const char *) NULL)
ximage_info.silent=IsMagickTrue(option);
image=XImportImage(image_info,&ximage_info);
}
#endif
return(image);
}
CWE ID: CWE-772
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 upnp_event_prepare(struct upnp_event_notify * obj)
{
static const char notifymsg[] =
"NOTIFY %s HTTP/1.1\r\n"
"Host: %s%s\r\n"
#if (UPNP_VERSION_MAJOR == 1) && (UPNP_VERSION_MINOR == 0)
"Content-Type: text/xml\r\n" /* UDA v1.0 */
#else
"Content-Type: text/xml; charset=\"utf-8\"\r\n" /* UDA v1.1 or later */
#endif
"Content-Length: %d\r\n"
"NT: upnp:event\r\n"
"NTS: upnp:propchange\r\n"
"SID: %s\r\n"
"SEQ: %u\r\n"
"Connection: close\r\n"
"Cache-Control: no-cache\r\n"
"\r\n"
"%.*s\r\n";
char * xml;
int l;
if(obj->sub == NULL) {
obj->state = EError;
return;
}
switch(obj->sub->service) {
case EWanCFG:
xml = getVarsWANCfg(&l);
break;
case EWanIPC:
xml = getVarsWANIPCn(&l);
break;
#ifdef ENABLE_L3F_SERVICE
case EL3F:
xml = getVarsL3F(&l);
break;
#endif
#ifdef ENABLE_6FC_SERVICE
case E6FC:
xml = getVars6FC(&l);
break;
#endif
#ifdef ENABLE_DP_SERVICE
case EDP:
xml = getVarsDP(&l);
break;
#endif
default:
xml = NULL;
l = 0;
}
obj->buffersize = 1024;
obj->buffer = malloc(obj->buffersize);
if(!obj->buffer) {
syslog(LOG_ERR, "%s: malloc returned NULL", "upnp_event_prepare");
if(xml) {
free(xml);
}
obj->state = EError;
return;
}
obj->tosend = snprintf(obj->buffer, obj->buffersize, notifymsg,
obj->path, obj->addrstr, obj->portstr, l+2,
obj->sub->uuid, obj->sub->seq,
l, xml);
if(xml) {
free(xml);
xml = NULL;
}
obj->state = ESending;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: raptor_option_value_is_numeric(const raptor_option option)
{
raptor_option_value_type t = raptor_options_list[option].value_type;
return t == RAPTOR_OPTION_VALUE_TYPE_BOOL ||
t == RAPTOR_OPTION_VALUE_TYPE_INT;
}
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 RList *relocs(RBinFile *arch) {
struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj;
RList *list = r_list_newf ((RListFree)free);
int i, len, n_got, amount;
if (!list || !obj) {
r_list_free (list);
return NULL;
}
if (obj->hdr->flags & FLAT_FLAG_GOTPIC) {
n_got = get_ngot_entries (obj);
if (n_got) {
amount = n_got * sizeof (ut32);
if (amount < n_got || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *got_table = calloc (1, n_got * sizeof (ut32));
if (got_table) {
ut32 offset = 0;
for (i = 0; i < n_got ; offset += 4, i++) {
ut32 got_entry;
if (obj->hdr->data_start + offset + 4 > obj->size ||
obj->hdr->data_start + offset + 4 < offset) {
break;
}
len = r_buf_read_at (obj->b, obj->hdr->data_start + offset,
(ut8 *)&got_entry, sizeof (ut32));
if (!VALID_GOT_ENTRY (got_entry) || len != sizeof (ut32)) {
break;
}
got_table[i].addr_to_patch = got_entry;
got_table[i].data_offset = got_entry + BFLT_HDR_SIZE;
}
obj->n_got = n_got;
obj->got_table = got_table;
}
}
}
if (obj->hdr->reloc_count > 0) {
int n_reloc = obj->hdr->reloc_count;
amount = n_reloc * sizeof (struct reloc_struct_t);
if (amount < n_reloc || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *reloc_table = calloc (1, amount + 1);
if (!reloc_table) {
goto out_error;
}
amount = n_reloc * sizeof (ut32);
if (amount < n_reloc || amount > UT32_MAX) {
free (reloc_table);
goto out_error;
}
ut32 *reloc_pointer_table = calloc (1, amount + 1);
if (!reloc_pointer_table) {
free (reloc_table);
goto out_error;
}
if (obj->hdr->reloc_start + amount > obj->size ||
obj->hdr->reloc_start + amount < amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, obj->hdr->reloc_start,
(ut8 *)reloc_pointer_table, amount);
if (len != amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
for (i = 0; i < obj->hdr->reloc_count; i++) {
ut32 reloc_offset =
r_swap_ut32 (reloc_pointer_table[i]) +
BFLT_HDR_SIZE;
if (reloc_offset < obj->hdr->bss_end && reloc_offset < obj->size) {
ut32 reloc_fixed, reloc_data_offset;
if (reloc_offset + sizeof (ut32) > obj->size ||
reloc_offset + sizeof (ut32) < reloc_offset) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, reloc_offset,
(ut8 *)&reloc_fixed,
sizeof (ut32));
if (len != sizeof (ut32)) {
eprintf ("problem while reading relocation entries\n");
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
reloc_data_offset = r_swap_ut32 (reloc_fixed) + BFLT_HDR_SIZE;
reloc_table[i].addr_to_patch = reloc_offset;
reloc_table[i].data_offset = reloc_data_offset;
RBinReloc *reloc = R_NEW0 (RBinReloc);
if (reloc) {
reloc->type = R_BIN_RELOC_32;
reloc->paddr = reloc_table[i].addr_to_patch;
reloc->vaddr = reloc->paddr;
r_list_append (list, reloc);
}
}
}
free (reloc_pointer_table);
obj->reloc_table = reloc_table;
}
return list;
out_error:
r_list_free (list);
return NULL;
}
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: ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
u_char *p;
size_t slen, rlen;
int r, ssh1cipher;
if (!compat20) {
ssh1cipher = cipher_ctx_get_number(state->receive_context);
slen = cipher_get_keyiv_len(state->send_context);
rlen = cipher_get_keyiv_len(state->receive_context);
if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
(r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
(r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
(r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0 ||
(r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
(r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0 ||
(r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
return r;
} else {
if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
(r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
(r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
return r;
}
slen = cipher_get_keycontext(state->send_context, NULL);
rlen = cipher_get_keycontext(state->receive_context, NULL);
if ((r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->send_context, p) != (int)slen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
(r = sshbuf_put_stringb(m, state->input)) != 0 ||
(r = sshbuf_put_stringb(m, state->output)) != 0)
return r;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void server_connect_init(SERVER_REC *server)
{
const char *str;
g_return_if_fail(server != NULL);
MODULE_DATA_INIT(server);
server->type = module_get_uniq_id("SERVER", 0);
server_ref(server);
server->nick = g_strdup(server->connrec->nick);
if (server->connrec->username == NULL || *server->connrec->username == '\0') {
g_free_not_null(server->connrec->username);
str = g_get_user_name();
if (*str == '\0') str = "unknown";
server->connrec->username = g_strdup(str);
}
if (server->connrec->realname == NULL || *server->connrec->realname == '\0') {
g_free_not_null(server->connrec->realname);
str = g_get_real_name();
if (*str == '\0') str = server->connrec->username;
server->connrec->realname = g_strdup(str);
}
server->tag = server_create_tag(server->connrec);
server->connect_tag = -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: formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
}
CWE ID: CWE-476
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 splice_pipe_to_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, nbuf;
bool input_wakeup = false;
retry:
ret = ipipe_prep(ipipe, flags);
if (ret)
return ret;
ret = opipe_prep(opipe, flags);
if (ret)
return ret;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
if (!ipipe->nrbufs && !ipipe->writers)
break;
/*
* Cannot make any progress, because either the input
* pipe is empty or the output pipe is full.
*/
if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) {
/* Already processed some buffers, break */
if (ret)
break;
if (flags & SPLICE_F_NONBLOCK) {
ret = -EAGAIN;
break;
}
/*
* We raced with another reader/writer and haven't
* managed to process any buffers. A zero return
* value means EOF, so retry instead.
*/
pipe_unlock(ipipe);
pipe_unlock(opipe);
goto retry;
}
ibuf = ipipe->bufs + ipipe->curbuf;
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
obuf = opipe->bufs + nbuf;
if (len >= ibuf->len) {
/*
* Simply move the whole buffer from ipipe to opipe
*/
*obuf = *ibuf;
ibuf->ops = NULL;
opipe->nrbufs++;
ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1);
ipipe->nrbufs--;
input_wakeup = true;
} else {
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
obuf->len = len;
opipe->nrbufs++;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
ret += obuf->len;
len -= obuf->len;
} while (len);
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
if (input_wakeup)
wakeup_pipe_writers(ipipe);
return ret;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void rtnetlink_rcv(struct sk_buff *skb)
{
rtnl_lock();
netlink_rcv_skb(skb, &rtnetlink_rcv_msg);
rtnl_unlock();
}
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: const bthl_interface_t *btif_hl_get_interface(){
BTIF_TRACE_EVENT("%s", __FUNCTION__);
return &bthlInterface;
}
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: void RenderMessageFilter::GetPluginsCallback(
IPC::Message* reply_msg,
const std::vector<webkit::WebPluginInfo>& all_plugins) {
PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter();
std::vector<webkit::WebPluginInfo> plugins;
int child_process_id = -1;
int routing_id = MSG_ROUTING_NONE;
for (size_t i = 0; i < all_plugins.size(); ++i) {
webkit::WebPluginInfo plugin(all_plugins[i]);
if (!filter || filter->IsPluginEnabled(child_process_id,
routing_id,
resource_context_,
GURL(),
GURL(),
&plugin)) {
plugins.push_back(plugin);
}
}
ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins);
Send(reply_msg);
}
CWE ID: CWE-287
Target: 1
Example 2:
Code: void QQuickWebViewPrivate::onComponentComplete()
{
if (m_deferedUrlToLoad.isEmpty())
return;
q_ptr->setUrl(m_deferedUrlToLoad);
}
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: vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec)
{
struct drm_vc4_submit_cl *args = exec->args;
void *temp = NULL;
void *bin;
int ret = 0;
uint32_t bin_offset = 0;
uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size,
16);
uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size;
uint32_t exec_size = uniforms_offset + args->uniforms_size;
uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) *
args->shader_rec_count);
struct vc4_bo *bo;
if (shader_rec_offset < args->bin_cl_size ||
uniforms_offset < shader_rec_offset ||
exec_size < uniforms_offset ||
args->shader_rec_count >= (UINT_MAX /
sizeof(struct vc4_shader_state)) ||
temp_size < exec_size) {
DRM_ERROR("overflow in exec arguments\n");
goto fail;
}
/* Allocate space where we'll store the copied in user command lists
* and shader records.
*
* We don't just copy directly into the BOs because we need to
* read the contents back for validation, and I think the
* bo->vaddr is uncached access.
*/
temp = drm_malloc_ab(temp_size, 1);
if (!temp) {
DRM_ERROR("Failed to allocate storage for copying "
"in bin/render CLs.\n");
ret = -ENOMEM;
goto fail;
}
bin = temp + bin_offset;
exec->shader_rec_u = temp + shader_rec_offset;
exec->uniforms_u = temp + uniforms_offset;
exec->shader_state = temp + exec_size;
exec->shader_state_size = args->shader_rec_count;
if (copy_from_user(bin,
(void __user *)(uintptr_t)args->bin_cl,
args->bin_cl_size)) {
ret = -EFAULT;
goto fail;
}
if (copy_from_user(exec->shader_rec_u,
(void __user *)(uintptr_t)args->shader_rec,
args->shader_rec_size)) {
ret = -EFAULT;
goto fail;
}
if (copy_from_user(exec->uniforms_u,
(void __user *)(uintptr_t)args->uniforms,
args->uniforms_size)) {
ret = -EFAULT;
goto fail;
}
bo = vc4_bo_create(dev, exec_size, true);
if (IS_ERR(bo)) {
DRM_ERROR("Couldn't allocate BO for binning\n");
ret = PTR_ERR(bo);
goto fail;
}
exec->exec_bo = &bo->base;
list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head,
&exec->unref_list);
exec->ct0ca = exec->exec_bo->paddr + bin_offset;
exec->bin_u = bin;
exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset;
exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset;
exec->shader_rec_size = args->shader_rec_size;
exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset;
exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset;
exec->uniforms_size = args->uniforms_size;
ret = vc4_validate_bin_cl(dev,
exec->exec_bo->vaddr + bin_offset,
bin,
exec);
if (ret)
goto fail;
ret = vc4_validate_shader_recs(dev, exec);
if (ret)
goto fail;
/* Block waiting on any previous rendering into the CS's VBO,
* IB, or textures, so that pixels are actually written by the
* time we try to read them.
*/
ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true);
fail:
drm_free_large(temp);
return ret;
}
CWE ID: CWE-388
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 CreatePersistentHistogramAllocator() {
allocator_memory_.reset(new char[kAllocatorMemorySize]);
GlobalHistogramAllocator::ReleaseForTesting();
memset(allocator_memory_.get(), 0, kAllocatorMemorySize);
GlobalHistogramAllocator::GetCreateHistogramResultHistogram();
GlobalHistogramAllocator::CreateWithPersistentMemory(
allocator_memory_.get(), kAllocatorMemorySize, 0, 0,
"PersistentHistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: JsVarFloat stringToFloatWithRadix(
const char *s, //!< The string to be converted to a float
int forceRadix, //!< The radix of the string data, or 0 to guess
const char **endOfFloat //!< If nonzero, this is set to the point at which the float finished in the string
) {
while (isWhitespace(*s)) s++;
bool isNegated = false;
if (*s == '-') {
isNegated = true;
s++;
} else if (*s == '+') {
s++;
}
const char *numberStart = s;
if (endOfFloat) (*endOfFloat)=s;
int radix = getRadix(&s, forceRadix, 0);
if (!radix) return NAN;
JsVarFloat v = 0;
JsVarFloat mul = 0.1;
while (*s) {
int digit = chtod(*s);
if (digit<0 || digit>=radix)
break;
v = (v*radix) + digit;
s++;
}
if (radix == 10) {
if (*s == '.') {
s++; // skip .
while (*s) {
if (*s >= '0' && *s <= '9')
v += mul*(*s - '0');
else break;
mul /= 10;
s++;
}
}
if (*s == 'e' || *s == 'E') {
s++; // skip E
bool isENegated = false;
if (*s == '-' || *s == '+') {
isENegated = *s=='-';
s++;
}
int e = 0;
while (*s) {
if (*s >= '0' && *s <= '9')
e = (e*10) + (*s - '0');
else break;
s++;
}
if (isENegated) e=-e;
while (e>0) {
v*=10;
e--;
}
while (e<0) {
v/=10;
e++;
}
}
}
if (endOfFloat) (*endOfFloat)=s;
if (numberStart==s || (numberStart[0]=='.' && numberStart[1]==0)) return NAN;
if (isNegated) return -v;
return v;
}
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: ip6_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
register const struct ip6_hdr *ip6;
register int advance;
u_int len;
const u_char *ipend;
register const u_char *cp;
register u_int payload_len;
int nh;
int fragmented = 0;
u_int flow;
ip6 = (const struct ip6_hdr *)bp;
ND_TCHECK(*ip6);
if (length < sizeof (struct ip6_hdr)) {
ND_PRINT((ndo, "truncated-ip6 %u", length));
return;
}
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IP6 "));
if (IP6_VERSION(ip6) != 6) {
ND_PRINT((ndo,"version error: %u != 6", IP6_VERSION(ip6)));
return;
}
payload_len = EXTRACT_16BITS(&ip6->ip6_plen);
len = payload_len + sizeof(struct ip6_hdr);
if (length < len)
ND_PRINT((ndo, "truncated-ip6 - %u bytes missing!",
len - length));
if (ndo->ndo_vflag) {
flow = EXTRACT_32BITS(&ip6->ip6_flow);
ND_PRINT((ndo, "("));
#if 0
/* rfc1883 */
if (flow & 0x0f000000)
ND_PRINT((ndo, "pri 0x%02x, ", (flow & 0x0f000000) >> 24));
if (flow & 0x00ffffff)
ND_PRINT((ndo, "flowlabel 0x%06x, ", flow & 0x00ffffff));
#else
/* RFC 2460 */
if (flow & 0x0ff00000)
ND_PRINT((ndo, "class 0x%02x, ", (flow & 0x0ff00000) >> 20));
if (flow & 0x000fffff)
ND_PRINT((ndo, "flowlabel 0x%05x, ", flow & 0x000fffff));
#endif
ND_PRINT((ndo, "hlim %u, next-header %s (%u) payload length: %u) ",
ip6->ip6_hlim,
tok2str(ipproto_values,"unknown",ip6->ip6_nxt),
ip6->ip6_nxt,
payload_len));
}
/*
* Cut off the snapshot length to the end of the IP payload.
*/
ipend = bp + len;
if (ipend < ndo->ndo_snapend)
ndo->ndo_snapend = ipend;
cp = (const u_char *)ip6;
advance = sizeof(struct ip6_hdr);
nh = ip6->ip6_nxt;
while (cp < ndo->ndo_snapend && advance > 0) {
cp += advance;
len -= advance;
if (cp == (const u_char *)(ip6 + 1) &&
nh != IPPROTO_TCP && nh != IPPROTO_UDP &&
nh != IPPROTO_DCCP && nh != IPPROTO_SCTP) {
ND_PRINT((ndo, "%s > %s: ", ip6addr_string(ndo, &ip6->ip6_src),
ip6addr_string(ndo, &ip6->ip6_dst)));
}
switch (nh) {
case IPPROTO_HOPOPTS:
advance = hbhopt_print(ndo, cp);
if (advance < 0)
return;
nh = *cp;
break;
case IPPROTO_DSTOPTS:
advance = dstopt_print(ndo, cp);
if (advance < 0)
return;
nh = *cp;
break;
case IPPROTO_FRAGMENT:
advance = frag6_print(ndo, cp, (const u_char *)ip6);
if (advance < 0 || ndo->ndo_snapend <= cp + advance)
return;
nh = *cp;
fragmented = 1;
break;
case IPPROTO_MOBILITY_OLD:
case IPPROTO_MOBILITY:
/*
* XXX - we don't use "advance"; RFC 3775 says that
* the next header field in a mobility header
* should be IPPROTO_NONE, but speaks of
* the possiblity of a future extension in
* which payload can be piggybacked atop a
* mobility header.
*/
advance = mobility_print(ndo, cp, (const u_char *)ip6);
nh = *cp;
return;
case IPPROTO_ROUTING:
advance = rt6_print(ndo, cp, (const u_char *)ip6);
nh = *cp;
break;
case IPPROTO_SCTP:
sctp_print(ndo, cp, (const u_char *)ip6, len);
return;
case IPPROTO_DCCP:
dccp_print(ndo, cp, (const u_char *)ip6, len);
return;
case IPPROTO_TCP:
tcp_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_UDP:
udp_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_ICMPV6:
icmp6_print(ndo, cp, len, (const u_char *)ip6, fragmented);
return;
case IPPROTO_AH:
advance = ah_print(ndo, cp);
nh = *cp;
break;
case IPPROTO_ESP:
{
int enh, padlen;
advance = esp_print(ndo, cp, len, (const u_char *)ip6, &enh, &padlen);
nh = enh & 0xff;
len -= padlen;
break;
}
case IPPROTO_IPCOMP:
{
ipcomp_print(ndo, cp);
/*
* Either this has decompressed the payload and
* printed it, in which case there's nothing more
* to do, or it hasn't, in which case there's
* nothing more to do.
*/
advance = -1;
break;
}
case IPPROTO_PIM:
pim_print(ndo, cp, len, (const u_char *)ip6);
return;
case IPPROTO_OSPF:
ospf6_print(ndo, cp, len);
return;
case IPPROTO_IPV6:
ip6_print(ndo, cp, len);
return;
case IPPROTO_IPV4:
ip_print(ndo, cp, len);
return;
case IPPROTO_PGM:
pgm_print(ndo, cp, len, (const u_char *)ip6);
return;
case IPPROTO_GRE:
gre_print(ndo, cp, len);
return;
case IPPROTO_RSVP:
rsvp_print(ndo, cp, len);
return;
case IPPROTO_NONE:
ND_PRINT((ndo, "no next header"));
return;
default:
ND_PRINT((ndo, "ip-proto-%d %d", nh, len));
return;
}
}
return;
trunc:
ND_PRINT((ndo, "[|ip6]"));
}
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: magic_getparam(struct magic_set *ms, int param, void *val)
{
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
*(size_t *)val = ms->indir_max;
return 0;
case MAGIC_PARAM_NAME_MAX:
*(size_t *)val = ms->name_max;
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
*(size_t *)val = ms->elf_phnum_max;
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
*(size_t *)val = ms->elf_shnum_max;
return 0;
default:
errno = EINVAL;
return -1;
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out,
word32* outlen)
{
int err;
if (private_key == NULL || public_key == NULL || out == NULL ||
outlen == NULL) {
return BAD_FUNC_ARG;
}
#ifdef WOLF_CRYPTO_DEV
if (private_key->devId != INVALID_DEVID) {
err = wc_CryptoDev_Ecdh(private_key, public_key, out, outlen);
if (err != NOT_COMPILED_IN)
return err;
}
#endif
/* type valid? */
if (private_key->type != ECC_PRIVATEKEY &&
private_key->type != ECC_PRIVATEKEY_ONLY) {
return ECC_BAD_ARG_E;
}
/* Verify domain params supplied */
if (wc_ecc_is_valid_idx(private_key->idx) == 0 ||
wc_ecc_is_valid_idx(public_key->idx) == 0) {
return ECC_BAD_ARG_E;
}
/* Verify curve id matches */
if (private_key->dp->id != public_key->dp->id) {
return ECC_BAD_ARG_E;
}
#ifdef WOLFSSL_ATECC508A
err = atcatls_ecdh(private_key->slot, public_key->pubkey_raw, out);
if (err != ATCA_SUCCESS) {
err = BAD_COND_E;
}
*outlen = private_key->dp->size;
#else
err = wc_ecc_shared_secret_ex(private_key, &public_key->pubkey, out, outlen);
#endif /* WOLFSSL_ATECC508A */
return err;
}
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: void ReportRequestHeaders(std::map<std::string, std::string>* request_headers,
const std::string& url,
const std::string& headers) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
EXPECT_FALSE(base::ContainsKey(*request_headers, url));
(*request_headers)[url] = headers;
}
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 void perf_event_for_each_child(struct perf_event *event,
void (*func)(struct perf_event *))
{
struct perf_event *child;
WARN_ON_ONCE(event->ctx->parent_ctx);
mutex_lock(&event->child_mutex);
func(event);
list_for_each_entry(child, &event->child_list, child_list)
func(child);
mutex_unlock(&event->child_mutex);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for (i = 0; i < MAX_SERVERSTATUSREQUESTS; i++) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
if (!serverStatus) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "%s", s);
if (serverStatus->print) {
Com_Printf("Server settings:\n");
while (*s) {
for (i = 0; i < 2 && *s; i++) {
if (*s == '\\')
s++;
l = 0;
while (*s) {
info[l++] = *s;
if (l >= MAX_INFO_STRING-1)
break;
s++;
if (*s == '\\') {
break;
}
}
info[l] = '\0';
if (i) {
Com_Printf("%s\n", info);
}
else {
Com_Printf("%-24s", info);
}
}
}
}
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
if (serverStatus->print) {
Com_Printf("\nPlayers:\n");
Com_Printf("num: score: ping: name:\n");
}
for (i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++) {
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\%s", s);
if (serverStatus->print) {
score = ping = 0;
sscanf(s, "%d %d", &score, &ping);
s = strchr(s, ' ');
if (s)
s = strchr(s+1, ' ');
if (s)
s++;
else
s = "unknown";
Com_Printf("%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen(serverStatus->string);
Com_sprintf(&serverStatus->string[len], sizeof(serverStatus->string)-len, "\\");
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
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 int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);
int32_t len;
uint8_t command;
uint8_t *outbuf;
int rc;
command = buf[0];
outbuf = (uint8_t *)r->iov.iov_base;
DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]);
#ifdef DEBUG_SCSI
{
int i;
for (i = 1; i < r->req.cmd.len; i++) {
printf(" 0x%02x", buf[i]);
}
printf("\n");
}
#endif
switch (command) {
case TEST_UNIT_READY:
case INQUIRY:
case MODE_SENSE:
case MODE_SENSE_10:
case RESERVE:
case RESERVE_10:
case RELEASE:
case RELEASE_10:
case START_STOP:
case ALLOW_MEDIUM_REMOVAL:
case READ_CAPACITY_10:
case READ_TOC:
case GET_CONFIGURATION:
case SERVICE_ACTION_IN_16:
case VERIFY_10:
rc = scsi_disk_emulate_command(r, outbuf);
if (rc < 0) {
return 0;
}
r->iov.iov_len = rc;
break;
case SYNCHRONIZE_CACHE:
bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH);
r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r);
if (r->req.aiocb == NULL) {
scsi_flush_complete(r, -EIO);
}
return 0;
case READ_6:
case READ_10:
case READ_12:
case READ_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba)
goto illegal_lba;
r->sector = r->req.cmd.lba * s->cluster_size;
r->sector_count = len * s->cluster_size;
break;
case WRITE_6:
case WRITE_10:
case WRITE_12:
case WRITE_16:
case WRITE_VERIFY_10:
case WRITE_VERIFY_12:
case WRITE_VERIFY_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("Write %s(sector %" PRId64 ", count %d)\n",
(command & 0xe) == 0xe ? "And Verify " : "",
r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba)
goto illegal_lba;
r->sector = r->req.cmd.lba * s->cluster_size;
r->sector_count = len * s->cluster_size;
break;
case MODE_SELECT:
DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);
/* We don't support mode parameter changes.
Allow the mode parameter header + block descriptors only. */
if (r->req.cmd.xfer > 12) {
goto fail;
}
break;
case MODE_SELECT_10:
DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);
/* We don't support mode parameter changes.
Allow the mode parameter header + block descriptors only. */
if (r->req.cmd.xfer > 16) {
goto fail;
}
break;
case SEEK_6:
case SEEK_10:
DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10,
r->req.cmd.lba);
if (r->req.cmd.lba > s->max_lba) {
goto illegal_lba;
}
break;
case WRITE_SAME_16:
len = r->req.cmd.xfer / s->qdev.blocksize;
DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n",
r->req.cmd.lba, len);
if (r->req.cmd.lba > s->max_lba) {
goto illegal_lba;
}
/*
* We only support WRITE SAME with the unmap bit set for now.
*/
if (!(buf[1] & 0x8)) {
goto fail;
}
rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size,
len * s->cluster_size);
if (rc < 0) {
/* XXX: better error code ?*/
goto fail;
}
break;
case REQUEST_SENSE:
abort();
default:
DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);
scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));
return 0;
fail:
scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
return 0;
illegal_lba:
scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
return 0;
}
if (r->sector_count == 0 && r->iov.iov_len == 0) {
scsi_req_complete(&r->req, GOOD);
}
len = r->sector_count * 512 + r->iov.iov_len;
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
return -len;
} else {
if (!r->sector_count)
r->sector_count = -1;
return len;
}
}
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: IW_IMPL(unsigned int) iw_get_ui16le(const iw_byte *b)
{
return b[0] | (b[1]<<8);
}
CWE ID: CWE-682
Target: 1
Example 2:
Code: unblock_all_signals(void)
{
unsigned long flags;
spin_lock_irqsave(¤t->sighand->siglock, flags);
current->notifier = NULL;
current->notifier_data = NULL;
recalc_sigpending();
spin_unlock_irqrestore(¤t->sighand->siglock, flags);
}
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: FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
{
FLAC__uint32 x;
unsigned bits, used_bits = 0;
FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
decoder->private_->stream_info.is_last = is_last;
decoder->private_->stream_info.length = length;
bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
return false; /* read_callback_ sets the state for us */
decoder->private_->stream_info.data.stream_info.min_blocksize = x;
used_bits += bits;
bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
return false; /* read_callback_ sets the state for us */
decoder->private_->stream_info.data.stream_info.max_blocksize = x;
used_bits += bits;
bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
return false; /* read_callback_ sets the state for us */
decoder->private_->stream_info.data.stream_info.min_framesize = x;
used_bits += bits;
bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
return false; /* read_callback_ sets the state for us */
decoder->private_->stream_info.data.stream_info.max_framesize = x;
used_bits += bits;
bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
return false; /* read_callback_ sets the state for us */
decoder->private_->stream_info.data.stream_info.sample_rate = x;
used_bits += bits;
bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
return false; /* read_callback_ sets the state for us */
decoder->private_->stream_info.data.stream_info.channels = x+1;
used_bits += bits;
bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
return false; /* read_callback_ sets the state for us */
decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
used_bits += bits;
bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
return false; /* read_callback_ sets the state for us */
used_bits += bits;
if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
return false; /* read_callback_ sets the state for us */
used_bits += 16*8;
/* skip the rest of the block */
FLAC__ASSERT(used_bits % 8 == 0);
length -= (used_bits / 8);
if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
return false; /* read_callback_ sets the state for us */
return true;
}
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: int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*) header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void RenderThreadImpl::AddObserver(content::RenderProcessObserver* observer) {
observers_.AddObserver(observer);
}
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 xdr_init_decode_pages(struct xdr_stream *xdr, struct xdr_buf *buf,
struct page **pages, unsigned int len)
{
memset(buf, 0, sizeof(*buf));
buf->pages = pages;
buf->page_len = len;
buf->buflen = len;
buf->len = len;
xdr_init_decode(xdr, buf, NULL);
}
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: long Cluster::HasBlockEntries(
const Segment* pSegment,
long long off, //relative to start of segment payload
long long& pos,
long& len)
{
assert(pSegment);
assert(off >= 0); //relative to segment
IMkvReader* const pReader = pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
pos = pSegment->m_start + off; //absolute
if ((total >= 0) && (pos >= total))
return 0; //we don't even have a complete cluster
const long long segment_stop =
(pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size;
long long cluster_stop = -1; //interpreted later to mean "unknown size"
{
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //need more data
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + len) > total))
return 0;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return static_cast<long>(id);
if (id != 0x0F43B675) //weird: not cluster ID
return -1; //generic error
pos += len; //consume Cluster ID field
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + len) > total))
return 0;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
if (size == 0)
return 0; //cluster does not have entries
pos += len; //consume size field
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size != unknown_size)
{
cluster_stop = pos + size;
assert(cluster_stop >= 0);
if ((segment_stop >= 0) && (cluster_stop > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && (cluster_stop > total))
return 0; //cluster does not have any entries
}
}
for (;;)
{
if ((cluster_stop >= 0) && (pos >= cluster_stop))
return 0; //no entries detected
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //need more data
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return static_cast<long>(id);
if (id == 0x0F43B675) //Cluster ID
return 0; //no entries found
if (id == 0x0C53BB6B) //Cues ID
return 0; //no entries found
pos += len; //consume id field
if ((cluster_stop >= 0) && (pos >= cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //underflow
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not supported inside cluster
if ((cluster_stop >= 0) && ((pos + size) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (id == 0x20) //BlockGroup ID
return 1; //have at least one entry
if (id == 0x23) //SimpleBlock ID
return 1; //have at least one entry
pos += size; //consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool GpuCommandBufferStub::OnMessageReceived(const IPC::Message& message) {
FastSetActiveURL(active_url_, active_url_hash_);
if (decoder_.get() &&
message.type() != GpuCommandBufferMsg_Echo::ID &&
message.type() != GpuCommandBufferMsg_RetireSyncPoint::ID &&
message.type() != GpuCommandBufferMsg_WaitSyncPoint::ID) {
if (!MakeCurrent())
return false;
}
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(GpuCommandBufferStub, message)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_Initialize,
OnInitialize);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_SetGetBuffer,
OnSetGetBuffer);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_SetSharedStateBuffer,
OnSetSharedStateBuffer);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_SetParent,
OnSetParent);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Echo, OnEcho);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_GetState, OnGetState);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_GetStateFast,
OnGetStateFast);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_AsyncFlush, OnAsyncFlush);
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_Rescheduled, OnRescheduled);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_CreateTransferBuffer,
OnCreateTransferBuffer);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_RegisterTransferBuffer,
OnRegisterTransferBuffer);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_DestroyTransferBuffer,
OnDestroyTransferBuffer);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_GetTransferBuffer,
OnGetTransferBuffer);
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_CreateVideoDecoder,
OnCreateVideoDecoder)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyVideoDecoder,
OnDestroyVideoDecoder)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SetSurfaceVisible,
OnSetSurfaceVisible)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DiscardBackbuffer,
OnDiscardBackbuffer)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_EnsureBackbuffer,
OnEnsureBackbuffer)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_RetireSyncPoint,
OnRetireSyncPoint)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_WaitSyncPoint,
OnWaitSyncPoint)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalSyncPoint,
OnSignalSyncPoint)
IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SendClientManagedMemoryStats,
OnReceivedClientManagedMemoryStats)
IPC_MESSAGE_HANDLER(
GpuCommandBufferMsg_SetClientHasMemoryAllocationChangedCallback,
OnSetClientHasMemoryAllocationChangedCallback)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
ScheduleDelayedWork(kHandleMoreWorkPeriodMs);
DCHECK(handled);
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: static int _php_libxml_free_error(xmlErrorPtr error)
{
/* This will free the libxml alloc'd memory */
xmlResetError(error);
return 1;
}
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: bool RenderWidgetHostViewAura::ShouldFastACK(uint64 surface_id) {
ui::Texture* container = image_transport_clients_[surface_id];
DCHECK(container);
if (can_lock_compositor_ == NO_PENDING_RENDERER_FRAME ||
can_lock_compositor_ == NO_PENDING_COMMIT ||
resize_locks_.empty())
return false;
gfx::Size container_size = ConvertSizeToDIP(this, container->size());
ResizeLockList::iterator it = resize_locks_.begin();
while (it != resize_locks_.end()) {
if ((*it)->expected_size() == container_size)
break;
++it;
}
return it == resize_locks_.end() || ++it != resize_locks_.end();
}
CWE ID:
Target: 1
Example 2:
Code: FindRequestManager* WebContentsImpl::GetFindRequestManager() {
for (WebContentsImpl* contents = this; contents;
contents = contents->GetOuterWebContents()) {
if (contents->find_request_manager_)
return contents->find_request_manager_.get();
}
return nullptr;
}
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 int l2cap_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) {
err = -EBADFD;
goto done;
}
switch (l2cap_pi(sk)->mode) {
case L2CAP_MODE_BASIC:
break;
case L2CAP_MODE_ERTM:
if (enable_ertm)
break;
/* fall through */
default:
err = -ENOTSUPP;
goto done;
}
if (!l2cap_pi(sk)->psm) {
bdaddr_t *src = &bt_sk(sk)->src;
u16 psm;
err = -EINVAL;
write_lock_bh(&l2cap_sk_list.lock);
for (psm = 0x1001; psm < 0x1100; psm += 2)
if (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) {
l2cap_pi(sk)->psm = cpu_to_le16(psm);
l2cap_pi(sk)->sport = cpu_to_le16(psm);
err = 0;
break;
}
write_unlock_bh(&l2cap_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
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: static SUB_STATE_RETURN read_state_machine(SSL *s)
{
OSSL_STATEM *st = &s->statem;
int ret, mt;
unsigned long len = 0;
int (*transition) (SSL *s, int mt);
PACKET pkt;
MSG_PROCESS_RETURN(*process_message) (SSL *s, PACKET *pkt);
WORK_STATE(*post_process_message) (SSL *s, WORK_STATE wst);
unsigned long (*max_message_size) (SSL *s);
void (*cb) (const SSL *ssl, int type, int val) = NULL;
cb = get_callback(s);
if (s->server) {
transition = ossl_statem_server_read_transition;
process_message = ossl_statem_server_process_message;
max_message_size = ossl_statem_server_max_message_size;
post_process_message = ossl_statem_server_post_process_message;
} else {
transition = ossl_statem_client_read_transition;
process_message = ossl_statem_client_process_message;
max_message_size = ossl_statem_client_max_message_size;
post_process_message = ossl_statem_client_post_process_message;
}
if (st->read_state_first_init) {
s->first_packet = 1;
st->read_state_first_init = 0;
}
while (1) {
switch (st->read_state) {
case READ_STATE_HEADER:
/* Get the state the peer wants to move to */
if (SSL_IS_DTLS(s)) {
/*
* In DTLS we get the whole message in one go - header and body
*/
ret = dtls_get_message(s, &mt, &len);
} else {
ret = tls_get_message_header(s, &mt);
}
if (ret == 0) {
/* Could be non-blocking IO */
return SUB_STATE_ERROR;
}
if (cb != NULL) {
/* Notify callback of an impending state change */
if (s->server)
cb(s, SSL_CB_ACCEPT_LOOP, 1);
else
cb(s, SSL_CB_CONNECT_LOOP, 1);
}
/*
* Validate that we are allowed to move to the new state and move
* to that state if so
*/
if (!transition(s, mt)) {
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
if (s->s3->tmp.message_size > max_message_size(s)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
SSLerr(SSL_F_READ_STATE_MACHINE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
return SUB_STATE_ERROR;
}
st->read_state = READ_STATE_BODY;
/* Fall through */
if (!PACKET_buf_init(&pkt, s->init_msg, len)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
return SUB_STATE_ERROR;
}
ret = process_message(s, &pkt);
/* Discard the packet data */
s->init_num = 0;
switch (ret) {
case MSG_PROCESS_ERROR:
return SUB_STATE_ERROR;
case MSG_PROCESS_FINISHED_READING:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
case MSG_PROCESS_CONTINUE_PROCESSING:
st->read_state = READ_STATE_POST_PROCESS;
st->read_state_work = WORK_MORE_A;
break;
default:
st->read_state = READ_STATE_HEADER;
break;
}
break;
case READ_STATE_POST_PROCESS:
st->read_state_work = post_process_message(s, st->read_state_work);
switch (st->read_state_work) {
default:
return SUB_STATE_ERROR;
case WORK_FINISHED_CONTINUE:
st->read_state = READ_STATE_HEADER;
break;
case WORK_FINISHED_STOP:
if (SSL_IS_DTLS(s)) {
dtls1_stop_timer(s);
}
return SUB_STATE_FINISHED;
}
break;
default:
/* Shouldn't happen */
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_READ_STATE_MACHINE, ERR_R_INTERNAL_ERROR);
ossl_statem_set_error(s);
return SUB_STATE_ERROR;
}
}
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: bool RenderBox::includeHorizontalScrollbarSize() const
{
return hasOverflowClip() && !layer()->hasOverlayScrollbars()
&& (style()->overflowX() == OSCROLL || style()->overflowX() == OAUTO);
}
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: virtual bool IsURLAcceptableForWebUI(
BrowserContext* browser_context, const GURL& url) const {
return HasWebUIScheme(url);
}
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: standard_info_part1(standard_display *dp, png_structp pp, png_infop pi)
{
if (png_get_bit_depth(pp, pi) != dp->bit_depth)
png_error(pp, "validate: bit depth changed");
if (png_get_color_type(pp, pi) != dp->colour_type)
png_error(pp, "validate: color type changed");
if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE)
png_error(pp, "validate: filter type changed");
if (png_get_interlace_type(pp, pi) != dp->interlace_type)
png_error(pp, "validate: interlacing changed");
if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE)
png_error(pp, "validate: compression type changed");
dp->w = png_get_image_width(pp, pi);
if (dp->w != standard_width(pp, dp->id))
png_error(pp, "validate: image width changed");
dp->h = png_get_image_height(pp, pi);
if (dp->h != standard_height(pp, dp->id))
png_error(pp, "validate: image height changed");
/* Record (but don't check at present) the input sBIT according to the colour
* type information.
*/
{
png_color_8p sBIT = 0;
if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT)
{
int sBIT_invalid = 0;
if (sBIT == 0)
png_error(pp, "validate: unexpected png_get_sBIT result");
if (dp->colour_type & PNG_COLOR_MASK_COLOR)
{
if (sBIT->red == 0 || sBIT->red > dp->bit_depth)
sBIT_invalid = 1;
else
dp->red_sBIT = sBIT->red;
if (sBIT->green == 0 || sBIT->green > dp->bit_depth)
sBIT_invalid = 1;
else
dp->green_sBIT = sBIT->green;
if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth)
sBIT_invalid = 1;
else
dp->blue_sBIT = sBIT->blue;
}
else /* !COLOR */
{
if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth)
sBIT_invalid = 1;
else
dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray;
}
/* All 8 bits in tRNS for a palette image are significant - see the
* spec.
*/
if (dp->colour_type & PNG_COLOR_MASK_ALPHA)
{
if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth)
sBIT_invalid = 1;
else
dp->alpha_sBIT = sBIT->alpha;
}
if (sBIT_invalid)
png_error(pp, "validate: sBIT value out of range");
}
}
/* Important: this is validating the value *before* any transforms have been
* put in place. It doesn't matter for the standard tests, where there are
* no transforms, but it does for other tests where rowbytes may change after
* png_read_update_info.
*/
if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id))
png_error(pp, "validate: row size changed");
/* Validate the colour type 3 palette (this can be present on other color
* types.)
*/
standard_palette_validate(dp, pp, pi);
/* In any case always check for a tranparent color (notice that the
* colour type 3 case must not give a successful return on the get_tRNS call
* with these arguments!)
*/
{
png_color_16p trans_color = 0;
if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS)
{
if (trans_color == 0)
png_error(pp, "validate: unexpected png_get_tRNS (color) result");
switch (dp->colour_type)
{
case 0:
dp->transparent.red = dp->transparent.green = dp->transparent.blue =
trans_color->gray;
dp->is_transparent = 1;
break;
case 2:
dp->transparent.red = trans_color->red;
dp->transparent.green = trans_color->green;
dp->transparent.blue = trans_color->blue;
dp->is_transparent = 1;
break;
case 3:
/* Not expected because it should result in the array case
* above.
*/
png_error(pp, "validate: unexpected png_get_tRNS result");
break;
default:
png_error(pp, "validate: invalid tRNS chunk with alpha image");
}
}
}
/* Read the number of passes - expected to match the value used when
* creating the image (interlaced or not). This has the side effect of
* turning on interlace handling (if do_interlace is not set.)
*/
dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type);
if (!dp->do_interlace && dp->npasses != png_set_interlace_handling(pp))
png_error(pp, "validate: file changed interlace type");
/* Caller calls png_read_update_info or png_start_read_image now, then calls
* part2.
*/
}
CWE ID:
Target: 1
Example 2:
Code: void PepperMediaDeviceManager::OnStreamGenerationFailed(
int request_id,
content::MediaStreamRequestResult result) {}
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: OMX_ERRORTYPE SimpleSoftOMXComponent::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamPortDefinition:
{
OMX_PARAM_PORTDEFINITIONTYPE *defParams =
(OMX_PARAM_PORTDEFINITIONTYPE *)params;
if (!isValidOMXParam(defParams)) {
return OMX_ErrorBadParameter;
}
if (defParams->nPortIndex >= mPorts.size()
|| defParams->nSize
!= sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) {
return OMX_ErrorUndefined;
}
const PortInfo *port =
&mPorts.itemAt(defParams->nPortIndex);
memcpy(defParams, &port->mDef, sizeof(port->mDef));
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
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: kvp_respond_to_host(char *key, char *value, int error)
{
struct hv_kvp_msg *kvp_msg;
struct hv_kvp_msg_enumerate *kvp_data;
char *key_name;
struct icmsg_hdr *icmsghdrp;
int keylen, valuelen;
u32 buf_len;
struct vmbus_channel *channel;
u64 req_id;
/*
* If a transaction is not active; log and return.
*/
if (!kvp_transaction.active) {
/*
* This is a spurious call!
*/
pr_warn("KVP: Transaction not active\n");
return;
}
/*
* Copy the global state for completing the transaction. Note that
* only one transaction can be active at a time.
*/
buf_len = kvp_transaction.recv_len;
channel = kvp_transaction.recv_channel;
req_id = kvp_transaction.recv_req_id;
kvp_transaction.active = false;
if (channel->onchannel_callback == NULL)
/*
* We have raced with util driver being unloaded;
* silently return.
*/
return;
icmsghdrp = (struct icmsg_hdr *)
&recv_buffer[sizeof(struct vmbuspipe_hdr)];
kvp_msg = (struct hv_kvp_msg *)
&recv_buffer[sizeof(struct vmbuspipe_hdr) +
sizeof(struct icmsg_hdr)];
kvp_data = &kvp_msg->kvp_data;
key_name = key;
/*
* If the error parameter is set, terminate the host's enumeration.
*/
if (error) {
/*
* We don't support this index or the we have timedout;
* terminate the host-side iteration by returning an error.
*/
icmsghdrp->status = HV_E_FAIL;
goto response_done;
}
/*
* The windows host expects the key/value pair to be encoded
* in utf16.
*/
keylen = utf8s_to_utf16s(key_name, strlen(key_name),
(wchar_t *)kvp_data->data.key);
kvp_data->data.key_size = 2*(keylen + 1); /* utf16 encoding */
valuelen = utf8s_to_utf16s(value, strlen(value),
(wchar_t *)kvp_data->data.value);
kvp_data->data.value_size = 2*(valuelen + 1); /* utf16 encoding */
kvp_data->data.value_type = REG_SZ; /* all our values are strings */
icmsghdrp->status = HV_S_OK;
response_done:
icmsghdrp->icflags = ICMSGHDRFLAG_TRANSACTION | ICMSGHDRFLAG_RESPONSE;
vmbus_sendpacket(channel, recv_buffer, buf_len, req_id,
VM_PKT_DATA_INBAND, 0);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int yr_object_structure_set_member(
YR_OBJECT* object,
YR_OBJECT* member)
{
YR_STRUCTURE_MEMBER* sm;
assert(object->type == OBJECT_TYPE_STRUCTURE);
if (yr_object_lookup_field(object, member->identifier) != NULL)
return ERROR_DUPLICATED_STRUCTURE_MEMBER;
sm = (YR_STRUCTURE_MEMBER*) yr_malloc(sizeof(YR_STRUCTURE_MEMBER));
if (sm == NULL)
return ERROR_INSUFFICIENT_MEMORY;
member->parent = object;
sm->object = member;
sm->next = object_as_structure(object)->members;
object_as_structure(object)->members = sm;
return ERROR_SUCCESS;
}
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 qeth_setadp_promisc_mode(struct qeth_card *card)
{
enum qeth_ipa_promisc_modes mode;
struct net_device *dev = card->dev;
struct qeth_cmd_buffer *iob;
struct qeth_ipa_cmd *cmd;
QETH_CARD_TEXT(card, 4, "setprom");
if (((dev->flags & IFF_PROMISC) &&
(card->info.promisc_mode == SET_PROMISC_MODE_ON)) ||
(!(dev->flags & IFF_PROMISC) &&
(card->info.promisc_mode == SET_PROMISC_MODE_OFF)))
return;
mode = SET_PROMISC_MODE_OFF;
if (dev->flags & IFF_PROMISC)
mode = SET_PROMISC_MODE_ON;
QETH_CARD_TEXT_(card, 4, "mode:%x", mode);
iob = qeth_get_adapter_cmd(card, IPA_SETADP_SET_PROMISC_MODE,
sizeof(struct qeth_ipacmd_setadpparms));
cmd = (struct qeth_ipa_cmd *)(iob->data + IPA_PDU_HEADER_SIZE);
cmd->data.setadapterparms.data.mode = mode;
qeth_send_ipa_cmd(card, iob, qeth_setadp_promisc_mode_cb, NULL);
}
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: CString fileSystemRepresentation(const String&)
{
ASSERT_NOT_REACHED();
return "";
}
CWE ID:
Target: 1
Example 2:
Code: void platform_driver_unregister(struct platform_driver *drv)
{
driver_unregister(&drv->driver);
}
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: void RenderViewImpl::OnResolveTapDisambiguation(double timestamp_seconds,
gfx::Point tap_viewport_offset,
bool is_long_press) {
webview()->ResolveTapDisambiguation(timestamp_seconds, tap_viewport_offset,
is_long_press);
}
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: bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index,
struct drm_display_mode *mode)
{
struct radeon_mode_info *mode_info = &rdev->mode_info;
ATOM_ANALOG_TV_INFO *tv_info;
ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2;
ATOM_DTD_FORMAT *dtd_timings;
int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info);
u8 frev, crev;
u16 data_offset, misc;
if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL,
&frev, &crev, &data_offset))
return false;
switch (crev) {
case 1:
tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset);
if (index > MAX_SUPPORTED_TV_TIMING)
return false;
mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total);
mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp);
mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart);
mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) +
le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth);
mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total);
mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp);
mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart);
mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) +
le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth);
mode->flags = 0;
misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess);
if (misc & ATOM_VSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NVSYNC;
if (misc & ATOM_HSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NHSYNC;
if (misc & ATOM_COMPOSITESYNC)
mode->flags |= DRM_MODE_FLAG_CSYNC;
if (misc & ATOM_INTERLACE)
mode->flags |= DRM_MODE_FLAG_INTERLACE;
if (misc & ATOM_DOUBLE_CLOCK_MODE)
mode->flags |= DRM_MODE_FLAG_DBLSCAN;
mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10;
if (index == 1) {
/* PAL timings appear to have wrong values for totals */
mode->crtc_htotal -= 1;
mode->crtc_vtotal -= 1;
}
break;
case 2:
tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset);
if (index > MAX_SUPPORTED_TV_TIMING_V1_2)
return false;
dtd_timings = &tv_info_v1_2->aModeTimings[index];
mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) +
le16_to_cpu(dtd_timings->usHBlanking_Time);
mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive);
mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) +
le16_to_cpu(dtd_timings->usHSyncOffset);
mode->crtc_hsync_end = mode->crtc_hsync_start +
le16_to_cpu(dtd_timings->usHSyncWidth);
mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) +
le16_to_cpu(dtd_timings->usVBlanking_Time);
mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive);
mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) +
le16_to_cpu(dtd_timings->usVSyncOffset);
mode->crtc_vsync_end = mode->crtc_vsync_start +
le16_to_cpu(dtd_timings->usVSyncWidth);
mode->flags = 0;
misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess);
if (misc & ATOM_VSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NVSYNC;
if (misc & ATOM_HSYNC_POLARITY)
mode->flags |= DRM_MODE_FLAG_NHSYNC;
if (misc & ATOM_COMPOSITESYNC)
mode->flags |= DRM_MODE_FLAG_CSYNC;
if (misc & ATOM_INTERLACE)
mode->flags |= DRM_MODE_FLAG_INTERLACE;
if (misc & ATOM_DOUBLE_CLOCK_MODE)
mode->flags |= DRM_MODE_FLAG_DBLSCAN;
mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10;
break;
}
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void virtio_net_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
{
VirtIONet *n = VIRTIO_NET(vdev);
struct virtio_net_ctrl_hdr ctrl;
virtio_net_ctrl_ack status = VIRTIO_NET_ERR;
VirtQueueElement elem;
size_t s;
struct iovec *iov;
unsigned int iov_cnt;
while (virtqueue_pop(vq, &elem)) {
if (iov_size(elem.in_sg, elem.in_num) < sizeof(status) ||
iov_size(elem.out_sg, elem.out_num) < sizeof(ctrl)) {
error_report("virtio-net ctrl missing headers");
exit(1);
}
iov = elem.out_sg;
iov_cnt = elem.out_num;
s = iov_to_buf(iov, iov_cnt, 0, &ctrl, sizeof(ctrl));
iov_discard_front(&iov, &iov_cnt, sizeof(ctrl));
if (s != sizeof(ctrl)) {
status = VIRTIO_NET_ERR;
} else if (ctrl.class == VIRTIO_NET_CTRL_RX) {
status = virtio_net_handle_rx_mode(n, ctrl.cmd, iov, iov_cnt);
} else if (ctrl.class == VIRTIO_NET_CTRL_MAC) {
status = virtio_net_handle_mac(n, ctrl.cmd, iov, iov_cnt);
} else if (ctrl.class == VIRTIO_NET_CTRL_VLAN) {
status = virtio_net_handle_vlan_table(n, ctrl.cmd, iov, iov_cnt);
} else if (ctrl.class == VIRTIO_NET_CTRL_MQ) {
status = virtio_net_handle_mq(n, ctrl.cmd, iov, iov_cnt);
} else if (ctrl.class == VIRTIO_NET_CTRL_GUEST_OFFLOADS) {
status = virtio_net_handle_offloads(n, ctrl.cmd, iov, iov_cnt);
}
s = iov_from_buf(elem.in_sg, elem.in_num, 0, &status, sizeof(status));
assert(s == sizeof(status));
virtqueue_push(vq, &elem, sizeof(status));
virtio_notify(vdev, vq);
}
}
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: gfx::Font Label::GetDefaultFont() {
return ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont);
}
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: long long Block::GetTime(const Cluster* pCluster) const
{
assert(pCluster);
const long long tc = GetTimeCode(pCluster);
const Segment* const pSegment = pCluster->m_pSegment;
const SegmentInfo* const pInfo = pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long ns = tc * scale;
return ns;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
unsigned long pfn, unsigned long size, pgprot_t prot)
{
pgd_t *pgd;
unsigned long next;
unsigned long end = addr + PAGE_ALIGN(size);
struct mm_struct *mm = vma->vm_mm;
int err;
/*
* Physically remapped pages are special. Tell the
* rest of the world about it:
* VM_IO tells people not to look at these pages
* (accesses can have side effects).
* VM_PFNMAP tells the core MM that the base pages are just
* raw PFN mappings, and do not have a "struct page" associated
* with them.
* VM_DONTEXPAND
* Disable vma merging and expanding with mremap().
* VM_DONTDUMP
* Omit vma from core dump, even when VM_IO turned off.
*
* There's a horrible special case to handle copy-on-write
* behaviour that some programs depend on. We mark the "original"
* un-COW'ed pages by matching them up with "vma->vm_pgoff".
* See vm_normal_page() for details.
*/
if (is_cow_mapping(vma->vm_flags)) {
if (addr != vma->vm_start || end != vma->vm_end)
return -EINVAL;
vma->vm_pgoff = pfn;
}
err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
if (err)
return -EINVAL;
vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
BUG_ON(addr >= end);
pfn -= addr >> PAGE_SHIFT;
pgd = pgd_offset(mm, addr);
flush_cache_range(vma, addr, end);
do {
next = pgd_addr_end(addr, end);
err = remap_pud_range(mm, pgd, addr, next,
pfn + (addr >> PAGE_SHIFT), prot);
if (err)
break;
} while (pgd++, addr = next, addr != end);
if (err)
untrack_pfn(vma, pfn, PAGE_ALIGN(size));
return err;
}
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 int misaligned_load(struct pt_regs *regs,
__u32 opcode,
int displacement_not_indexed,
int width_shift,
int do_sign_extend)
{
/* Return -1 for a fault, 0 for OK */
int error;
int destreg;
__u64 address;
error = generate_and_check_address(regs, opcode,
displacement_not_indexed, width_shift, &address);
if (error < 0) {
return error;
}
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, address);
destreg = (opcode >> 4) & 0x3f;
if (user_mode(regs)) {
__u64 buffer;
if (!access_ok(VERIFY_READ, (unsigned long) address, 1UL<<width_shift)) {
return -1;
}
if (__copy_user(&buffer, (const void *)(int)address, (1 << width_shift)) > 0) {
return -1; /* fault */
}
switch (width_shift) {
case 1:
if (do_sign_extend) {
regs->regs[destreg] = (__u64)(__s64) *(__s16 *) &buffer;
} else {
regs->regs[destreg] = (__u64) *(__u16 *) &buffer;
}
break;
case 2:
regs->regs[destreg] = (__u64)(__s64) *(__s32 *) &buffer;
break;
case 3:
regs->regs[destreg] = buffer;
break;
default:
printk("Unexpected width_shift %d in misaligned_load, PC=%08lx\n",
width_shift, (unsigned long) regs->pc);
break;
}
} else {
/* kernel mode - we can take short cuts since if we fault, it's a genuine bug */
__u64 lo, hi;
switch (width_shift) {
case 1:
misaligned_kernel_word_load(address, do_sign_extend, ®s->regs[destreg]);
break;
case 2:
asm ("ldlo.l %1, 0, %0" : "=r" (lo) : "r" (address));
asm ("ldhi.l %1, 3, %0" : "=r" (hi) : "r" (address));
regs->regs[destreg] = lo | hi;
break;
case 3:
asm ("ldlo.q %1, 0, %0" : "=r" (lo) : "r" (address));
asm ("ldhi.q %1, 7, %0" : "=r" (hi) : "r" (address));
regs->regs[destreg] = lo | hi;
break;
default:
printk("Unexpected width_shift %d in misaligned_load, PC=%08lx\n",
width_shift, (unsigned long) regs->pc);
break;
}
}
return 0;
}
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: mojo::ScopedSharedBufferMapping FakePlatformSensorProvider::GetMapping(
mojom::SensorType type) {
return CreateSharedBufferIfNeeded() ? MapSharedBufferForType(type) : nullptr;
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: void WebMediaPlayerImpl::FlingingStarted() {
DCHECK(main_task_runner_->BelongsToCurrentThread());
DCHECK(!disable_pipeline_auto_suspend_);
disable_pipeline_auto_suspend_ = true;
video_decode_stats_reporter_.reset();
ScheduleRestart();
}
CWE ID: CWE-732
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: DictionaryValue* PasswordSpecificsDataToValue(
const sync_pb::PasswordSpecificsData& proto) {
DictionaryValue* value = new DictionaryValue();
SET_INT32(scheme);
SET_STR(signon_realm);
SET_STR(origin);
SET_STR(action);
SET_STR(username_element);
SET_STR(username_value);
SET_STR(password_element);
value->SetString("password_value", "<redacted>");
SET_BOOL(ssl_valid);
SET_BOOL(preferred);
SET_INT64(date_created);
SET_BOOL(blacklisted);
return value;
}
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: image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
this->next->mod(this->next, that, pp, display);
}
CWE ID:
Target: 1
Example 2:
Code: xdr_krb5_key_salt_tuple(XDR *xdrs, krb5_key_salt_tuple *objp)
{
if (!xdr_krb5_enctype(xdrs, &objp->ks_enctype))
return FALSE;
if (!xdr_krb5_salttype(xdrs, &objp->ks_salttype))
return FALSE;
return 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: static av_cold int rpza_decode_init(AVCodecContext *avctx)
{
RpzaContext *s = avctx->priv_data;
s->avctx = avctx;
avctx->pix_fmt = AV_PIX_FMT_RGB555;
avcodec_get_frame_defaults(&s->frame);
return 0;
}
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: BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
int sx, sy;
int i;
int ncx, ncy, nc, cs, cx, cy;
int x, y, ylo, yhi, xlo, xhi;
int vers, fmt;
t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */
unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */
int chunkNum = 0;
int chunkMax = 0;
uLongf chunkLen;
int chunkPos = 0;
int compMax = 0;
int bytesPerPixel;
char *compBuf = NULL; /* So we can gdFree it with impunity. */
gdImagePtr im;
/* Get the header */
im =
_gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy,
&chunkIdx);
if (im == NULL) {
/* No need to free chunkIdx as _gd2CreateFromFile does it for us. */
return 0;
}
bytesPerPixel = im->trueColor ? 4 : 1;
nc = ncx * ncy;
if (gd2_compressed (fmt)) {
/* Find the maximum compressed chunk size. */
compMax = 0;
for (i = 0; (i < nc); i++) {
if (chunkIdx[i].size > compMax) {
compMax = chunkIdx[i].size;
};
};
compMax++;
/* Allocate buffers */
chunkMax = cs * bytesPerPixel * cs;
chunkBuf = gdCalloc (chunkMax, 1);
if (!chunkBuf) {
goto fail;
}
compBuf = gdCalloc (compMax, 1);
if (!compBuf) {
goto fail;
}
GD2_DBG (printf ("Largest compressed chunk is %d bytes\n", compMax));
};
/* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */
/* goto fail2; */
/* }; */
/* Read the data... */
for (cy = 0; (cy < ncy); cy++) {
for (cx = 0; (cx < ncx); cx++) {
ylo = cy * cs;
yhi = ylo + cs;
if (yhi > im->sy) {
yhi = im->sy;
};
GD2_DBG (printf
("Processing Chunk %d (%d, %d), y from %d to %d\n",
chunkNum, cx, cy, ylo, yhi));
if (gd2_compressed (fmt)) {
chunkLen = chunkMax;
if (!_gd2ReadChunk (chunkIdx[chunkNum].offset,
compBuf,
chunkIdx[chunkNum].size,
(char *) chunkBuf, &chunkLen, in)) {
GD2_DBG (printf ("Error reading comproessed chunk\n"));
goto fail;
};
chunkPos = 0;
};
for (y = ylo; (y < yhi); y++) {
xlo = cx * cs;
xhi = xlo + cs;
if (xhi > im->sx) {
xhi = im->sx;
};
/*GD2_DBG(printf("y=%d: ",y)); */
if (!gd2_compressed (fmt)) {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
if (!gdGetInt (&im->tpixels[y][x], in)) {
/*printf("EOF while reading\n"); */
/*gdImageDestroy(im); */
/*return 0; */
im->tpixels[y][x] = 0;
}
} else {
int ch;
if (!gdGetByte (&ch, in)) {
/*printf("EOF while reading\n"); */
/*gdImageDestroy(im); */
/*return 0; */
ch = 0;
}
im->pixels[y][x] = ch;
}
}
} else {
for (x = xlo; x < xhi; x++) {
if (im->trueColor) {
/* 2.0.1: work around a gcc bug by being verbose.
TBB */
int a = chunkBuf[chunkPos++] << 24;
int r = chunkBuf[chunkPos++] << 16;
int g = chunkBuf[chunkPos++] << 8;
int b = chunkBuf[chunkPos++];
/* 2.0.11: tpixels */
im->tpixels[y][x] = a + r + g + b;
} else {
im->pixels[y][x] = chunkBuf[chunkPos++];
}
};
};
/*GD2_DBG(printf("\n")); */
};
chunkNum++;
};
};
GD2_DBG (printf ("Freeing memory\n"));
gdFree (chunkBuf);
gdFree (compBuf);
gdFree (chunkIdx);
GD2_DBG (printf ("Done\n"));
return im;
fail:
gdImageDestroy (im);
if (chunkBuf) {
gdFree (chunkBuf);
}
if (compBuf) {
gdFree (compBuf);
}
if (chunkIdx) {
gdFree (chunkIdx);
}
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void EnterpriseEnrollmentScreen::OnClientLoginFailure(
const GoogleServiceAuthError& error) {
HandleAuthError(error);
}
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: parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,
Buffer* buf, int *err, gchar **err_info)
{
guint8 *pd;
gchar line[COSINE_LINE_LENGTH];
int i, hex_lines, n, caplen = 0;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, COSINE_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (empty_line(line)) {
break;
}
if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers");
return FALSE;
}
caplen += n;
}
phdr->caplen = caplen;
return TRUE;
}
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: static int do_dentry_open(struct file *f,
int (*open)(struct inode *, struct file *),
const struct cred *cred)
{
static const struct file_operations empty_fops = {};
struct inode *inode;
int error;
f->f_mode = OPEN_FMODE(f->f_flags) | FMODE_LSEEK |
FMODE_PREAD | FMODE_PWRITE;
if (unlikely(f->f_flags & O_PATH))
f->f_mode = FMODE_PATH;
path_get(&f->f_path);
inode = f->f_inode = f->f_path.dentry->d_inode;
if (f->f_mode & FMODE_WRITE) {
error = __get_file_write_access(inode, f->f_path.mnt);
if (error)
goto cleanup_file;
if (!special_file(inode->i_mode))
file_take_write(f);
}
f->f_mapping = inode->i_mapping;
file_sb_list_add(f, inode->i_sb);
if (unlikely(f->f_mode & FMODE_PATH)) {
f->f_op = &empty_fops;
return 0;
}
f->f_op = fops_get(inode->i_fop);
if (unlikely(WARN_ON(!f->f_op))) {
error = -ENODEV;
goto cleanup_all;
}
error = security_file_open(f, cred);
if (error)
goto cleanup_all;
error = break_lease(inode, f->f_flags);
if (error)
goto cleanup_all;
if (!open)
open = f->f_op->open;
if (open) {
error = open(inode, f);
if (error)
goto cleanup_all;
}
if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)
i_readcount_inc(inode);
f->f_flags &= ~(O_CREAT | O_EXCL | O_NOCTTY | O_TRUNC);
file_ra_state_init(&f->f_ra, f->f_mapping->host->i_mapping);
return 0;
cleanup_all:
fops_put(f->f_op);
file_sb_list_del(f);
if (f->f_mode & FMODE_WRITE) {
put_write_access(inode);
if (!special_file(inode->i_mode)) {
/*
* We don't consider this a real
* mnt_want/drop_write() pair
* because it all happenend right
* here, so just reset the state.
*/
file_reset_write(f);
__mnt_drop_write(f->f_path.mnt);
}
}
cleanup_file:
path_put(&f->f_path);
f->f_path.mnt = NULL;
f->f_path.dentry = NULL;
f->f_inode = NULL;
return error;
}
CWE ID: CWE-17
Target: 1
Example 2:
Code: xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenameFunc func)
{
xmlOutputBufferCreateFilenameFunc old;
xmlMutexLock(xmlThrDefMutex);
old = xmlOutputBufferCreateFilenameValueThrDef;
#ifdef LIBXML_OUTPUT_ENABLED
if (old == NULL) {
old = __xmlOutputBufferCreateFilename;
}
#endif
xmlOutputBufferCreateFilenameValueThrDef = func;
xmlMutexUnlock(xmlThrDefMutex);
return(old);
}
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 int change_mount_flags(struct vfsmount *mnt, int ms_flags)
{
int error = 0;
int readonly_request = 0;
if (ms_flags & MS_RDONLY)
readonly_request = 1;
if (readonly_request == __mnt_is_readonly(mnt))
return 0;
if (mnt->mnt_flags & MNT_LOCK_READONLY)
return -EPERM;
if (readonly_request)
error = mnt_make_readonly(real_mount(mnt));
else
__mnt_unmake_readonly(real_mount(mnt));
return error;
}
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 PluginInfoMessageFilter::Context::GrantAccess(
const ChromeViewHostMsg_GetPluginInfo_Status& status,
const FilePath& path) const {
if (status.value == ChromeViewHostMsg_GetPluginInfo_Status::kAllowed ||
status.value == ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay) {
ChromePluginServiceFilter::GetInstance()->AuthorizePlugin(
render_process_id_, path);
}
}
CWE ID: CWE-287
Target: 1
Example 2:
Code: AudioRendererAlgorithm::~AudioRendererAlgorithm() {}
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: gfx::Rect ideal_bounds(int i) const { return tab_strip_->ideal_bounds(i); }
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: kdc_process_for_user(kdc_realm_t *kdc_active_realm,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_pa_for_user *for_user;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_for_user(&req_data, &for_user);
if (code)
return code;
code = verify_for_user_checksum(kdc_context, tgs_session, for_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_for_user(kdc_context, for_user);
return code;
}
*s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user));
if (*s4u_x509_user == NULL) {
krb5_free_pa_for_user(kdc_context, for_user);
return ENOMEM;
}
(*s4u_x509_user)->user_id.user = for_user->user;
for_user->user = NULL;
krb5_free_pa_for_user(kdc_context, for_user);
return 0;
}
CWE ID: CWE-617
Target: 1
Example 2:
Code: int bio_add_pc_page(struct request_queue *q, struct bio *bio, struct page
*page, unsigned int len, unsigned int offset)
{
int retried_segments = 0;
struct bio_vec *bvec;
/*
* cloned bio must not modify vec list
*/
if (unlikely(bio_flagged(bio, BIO_CLONED)))
return 0;
if (((bio->bi_iter.bi_size + len) >> 9) > queue_max_hw_sectors(q))
return 0;
/*
* For filesystems with a blocksize smaller than the pagesize
* we will often be called with the same page as last time and
* a consecutive offset. Optimize this special case.
*/
if (bio->bi_vcnt > 0) {
struct bio_vec *prev = &bio->bi_io_vec[bio->bi_vcnt - 1];
if (page == prev->bv_page &&
offset == prev->bv_offset + prev->bv_len) {
prev->bv_len += len;
bio->bi_iter.bi_size += len;
goto done;
}
/*
* If the queue doesn't support SG gaps and adding this
* offset would create a gap, disallow it.
*/
if (bvec_gap_to_prev(q, prev, offset))
return 0;
}
if (bio->bi_vcnt >= bio->bi_max_vecs)
return 0;
/*
* setup the new entry, we might clear it again later if we
* cannot add the page
*/
bvec = &bio->bi_io_vec[bio->bi_vcnt];
bvec->bv_page = page;
bvec->bv_len = len;
bvec->bv_offset = offset;
bio->bi_vcnt++;
bio->bi_phys_segments++;
bio->bi_iter.bi_size += len;
/*
* Perform a recount if the number of segments is greater
* than queue_max_segments(q).
*/
while (bio->bi_phys_segments > queue_max_segments(q)) {
if (retried_segments)
goto failed;
retried_segments = 1;
blk_recount_segments(q, bio);
}
/* If we may be able to merge these biovecs, force a recount */
if (bio->bi_vcnt > 1 && (BIOVEC_PHYS_MERGEABLE(bvec-1, bvec)))
bio_clear_flag(bio, BIO_SEG_VALID);
done:
return len;
failed:
bvec->bv_page = NULL;
bvec->bv_len = 0;
bvec->bv_offset = 0;
bio->bi_vcnt--;
bio->bi_iter.bi_size -= len;
blk_recount_segments(q, bio);
return 0;
}
CWE ID: CWE-772
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: R_API int r_bin_dump_strings(RBinFile *a, int min) {
get_strings (a, min, 1);
return 0;
}
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: long Cluster::GetNext(
const BlockEntry* pCurr,
const BlockEntry*& pNext) const
{
assert(pCurr);
assert(m_entries);
assert(m_entries_count > 0);
size_t idx = pCurr->GetIndex();
assert(idx < size_t(m_entries_count));
assert(m_entries[idx] == pCurr);
++idx;
if (idx >= size_t(m_entries_count))
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pNext = NULL;
return status;
}
if (status > 0)
{
pNext = NULL;
return 0;
}
assert(m_entries);
assert(m_entries_count > 0);
assert(idx < size_t(m_entries_count));
}
pNext = m_entries[idx];
assert(pNext);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: StringValue* MakeInt64Value(int64 x) {
return Value::CreateStringValue(base::Int64ToString(x));
}
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: static int read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
struct segment *seg;
/* Check that the playlist is still needed before opening a new
* segment. */
if (v->ctx && v->ctx->nb_streams) {
v->needed = 0;
for (i = 0; i < v->n_main_streams; i++) {
if (v->main_streams[i]->discard < AVDISCARD_ALL) {
v->needed = 1;
break;
}
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
/* If this is a live stream and the reload interval has elapsed since
* the last playlist reload, reload the playlists now. */
reload_interval = default_reload_interval(v);
reload:
if (!v->finished &&
av_gettime_relative() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
/* If we need to reload the playlist again below (if
* there's still no more segments), switch to a reload
* interval of half the target duration. */
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime_relative() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
/* Enough time has elapsed since the last reload */
goto reload;
}
seg = current_segment(v);
/* load/update Media Initialization Section, if any */
ret = update_init_section(v, seg);
if (ret)
return ret;
ret = open_input(c, v, seg);
if (ret < 0) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
v->cur_seq_no += 1;
goto reload;
}
just_opened = 1;
}
if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
/* Push init section out first before first actual segment */
int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
memcpy(buf, v->init_sec_buf, copy_size);
v->init_sec_buf_read_offset += copy_size;
return copy_size;
}
ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
/* Intercept ID3 tags here, elementary audio streams are required
* to convey timestamps using them in the beginning of each segment. */
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ff_format_io_close(v->parent, &v->input);
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
}
CWE ID: CWE-835
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: CronTab::initRegexObject() {
if ( ! CronTab::regex.isInitialized() ) {
const char *errptr;
int erroffset;
MyString pattern( CRONTAB_PARAMETER_PATTERN ) ;
if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) {
MyString error = "CronTab: Failed to compile Regex - ";
error += pattern;
EXCEPT( const_cast<char*>(error.Value()));
}
}
}
CWE ID: CWE-134
Target: 1
Example 2:
Code: static int ecryptfs_write_headers_virt(char *page_virt, size_t max,
size_t *size,
struct ecryptfs_crypt_stat *crypt_stat,
struct dentry *ecryptfs_dentry)
{
int rc;
size_t written;
size_t offset;
offset = ECRYPTFS_FILE_SIZE_BYTES;
write_ecryptfs_marker((page_virt + offset), &written);
offset += written;
ecryptfs_write_crypt_stat_flags((page_virt + offset), crypt_stat,
&written);
offset += written;
ecryptfs_write_header_metadata((page_virt + offset), crypt_stat,
&written);
offset += written;
rc = ecryptfs_generate_key_packet_set((page_virt + offset), crypt_stat,
ecryptfs_dentry, &written,
max - offset);
if (rc)
ecryptfs_printk(KERN_WARNING, "Error generating key packet "
"set; rc = [%d]\n", rc);
if (size) {
offset += written;
*size = offset;
}
return rc;
}
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 WebPageSerializerImpl::openTagToString(Element* element,
SerializeDomParam* param)
{
bool needSkip;
StringBuilder result;
result.append(preActionBeforeSerializeOpenTag(element, param, &needSkip));
if (needSkip)
return;
result.append('<');
result.append(element->nodeName().lower());
AttributeCollection attributes = element->attributes();
AttributeCollection::iterator end = attributes.end();
for (AttributeCollection::iterator it = attributes.begin(); it != end; ++it) {
result.append(' ');
result.append(it->name().toString());
result.appendLiteral("=\"");
if (!it->value().isEmpty()) {
const String& attrValue = it->value();
const QualifiedName& attrName = it->name();
if (element->hasLegalLinkAttribute(attrName)) {
if (attrValue.startsWith("javascript:", TextCaseInsensitive)) {
result.append(attrValue);
} else {
WebLocalFrameImpl* subFrame = WebLocalFrameImpl::fromFrameOwnerElement(element);
String completeURL = subFrame ? subFrame->frame()->document()->url() :
param->document->completeURL(attrValue);
if (m_localLinks.contains(completeURL)) {
if (!param->directoryName.isEmpty()) {
result.appendLiteral("./");
result.append(param->directoryName);
result.append('/');
}
result.append(m_localLinks.get(completeURL));
} else {
result.append(completeURL);
}
}
} else {
if (param->isHTMLDocument)
result.append(m_htmlEntities.convertEntitiesInString(attrValue));
else
result.append(m_xmlEntities.convertEntitiesInString(attrValue));
}
}
result.append('\"');
}
String addedContents = postActionAfterSerializeOpenTag(element, param);
if (element->hasChildren() || param->haveAddedContentsBeforeEnd)
result.append('>');
result.append(addedContents);
saveHTMLContentToBuffer(result.toString(), param);
}
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: bool AffiliationFetcher::ParseResponse(
AffiliationFetcherDelegate::Result* result) const {
std::string serialized_response;
if (!fetcher_->GetResponseAsString(&serialized_response)) {
NOTREACHED();
}
affiliation_pb::LookupAffiliationResponse response;
if (!response.ParseFromString(serialized_response))
return false;
result->reserve(requested_facet_uris_.size());
std::map<FacetURI, size_t> facet_uri_to_class_index;
for (int i = 0; i < response.affiliation_size(); ++i) {
const affiliation_pb::Affiliation& equivalence_class(
response.affiliation(i));
AffiliatedFacets affiliated_uris;
for (int j = 0; j < equivalence_class.facet_size(); ++j) {
const std::string& uri_spec(equivalence_class.facet(j));
FacetURI uri = FacetURI::FromPotentiallyInvalidSpec(uri_spec);
if (!uri.is_valid())
continue;
affiliated_uris.push_back(uri);
}
if (affiliated_uris.empty())
continue;
for (const FacetURI& uri : affiliated_uris) {
if (!facet_uri_to_class_index.count(uri))
facet_uri_to_class_index[uri] = result->size();
if (facet_uri_to_class_index[uri] !=
facet_uri_to_class_index[affiliated_uris[0]]) {
return false;
}
}
if (facet_uri_to_class_index[affiliated_uris[0]] == result->size())
result->push_back(affiliated_uris);
}
for (const FacetURI& uri : requested_facet_uris_) {
if (!facet_uri_to_class_index.count(uri))
result->push_back(AffiliatedFacets(1, uri));
}
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: asmlinkage __visible void kvm_spurious_fault(void)
{
/* Fault while not rebooting. We want the trace. */
BUG();
}
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: void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(target)
if(ctcptype == CtcpQuery) {
if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "VERSION"))
return;
reply(nickFromMask(prefix), "VERSION", QString("Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org")
.arg(Quassel::buildInfo().plainVersionString)
.arg(Quassel::buildInfo().buildDate));
emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP VERSION request by %1").arg(prefix));
} else {
str.append(tr(" with arguments: %1").arg(param));
emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str);
}
}
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: int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
struct inet_sock *inet = inet_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
__be16 orig_sport, orig_dport;
__be32 daddr, nexthop;
struct flowi4 fl4;
struct rtable *rt;
int err;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < sizeof(struct sockaddr_in))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
nexthop = daddr = usin->sin_addr.s_addr;
if (inet->opt != NULL && inet->opt->srr) {
if (daddr == 0)
return -EINVAL;
nexthop = inet->opt->faddr;
}
orig_sport = inet->inet_sport;
orig_dport = usin->sin_port;
rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
IPPROTO_DCCP,
orig_sport, orig_dport, sk, true);
if (IS_ERR(rt))
return PTR_ERR(rt);
if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
ip_rt_put(rt);
return -ENETUNREACH;
}
if (inet->opt == NULL || !inet->opt->srr)
daddr = rt->rt_dst;
if (inet->inet_saddr == 0)
inet->inet_saddr = rt->rt_src;
inet->inet_rcv_saddr = inet->inet_saddr;
inet->inet_dport = usin->sin_port;
inet->inet_daddr = daddr;
inet_csk(sk)->icsk_ext_hdr_len = 0;
if (inet->opt != NULL)
inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen;
/*
* Socket identity is still unknown (sport may be zero).
* However we set state to DCCP_REQUESTING and not releasing socket
* lock select source port, enter ourselves into the hash tables and
* complete initialization after this.
*/
dccp_set_state(sk, DCCP_REQUESTING);
err = inet_hash_connect(&dccp_death_row, sk);
if (err != 0)
goto failure;
rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport,
inet->inet_sport, inet->inet_dport, sk);
if (IS_ERR(rt)) {
rt = NULL;
goto failure;
}
/* OK, now commit destination to socket. */
sk_setup_caps(sk, &rt->dst);
dp->dccps_iss = secure_dccp_sequence_number(inet->inet_saddr,
inet->inet_daddr,
inet->inet_sport,
inet->inet_dport);
inet->inet_id = dp->dccps_iss ^ jiffies;
err = dccp_connect(sk);
rt = NULL;
if (err != 0)
goto failure;
out:
return err;
failure:
/*
* This unhashes the socket and releases the local port, if necessary.
*/
dccp_set_state(sk, DCCP_CLOSED);
ip_rt_put(rt);
sk->sk_route_caps = 0;
inet->inet_dport = 0;
goto out;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: Editor::RevealSelectionScope::RevealSelectionScope(Editor* editor)
: m_editor(editor) {
++m_editor->m_preventRevealSelection;
}
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 ContentSecurityPolicy::UpgradeInsecureRequests() {
insecure_request_policy_ |= kUpgradeInsecureRequests;
}
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 int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->private;
pte_t *pte, ptent;
spinlock_t *ptl;
struct page *page;
split_huge_page_pmd(walk->mm, pmd);
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE) {
ptent = *pte;
if (!pte_present(ptent))
continue;
page = vm_normal_page(vma, addr, ptent);
if (!page)
continue;
if (PageReserved(page))
continue;
/* Clear accessed and referenced bits. */
ptep_test_and_clear_young(vma, addr, pte);
ClearPageReferenced(page);
}
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static irqreturn_t acpi_irq(int irq, void *dev_id)
{
u32 handled;
handled = (*acpi_irq_handler) (acpi_irq_context);
if (handled) {
acpi_irq_handled++;
return IRQ_HANDLED;
} else {
acpi_irq_not_handled++;
return IRQ_NONE;
}
}
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: externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
const char **nextPtr) {
const char *next = s;
int tok;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case XML_TOK_NONE: /* start == end */
default:
break;
}
}
/* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.
However, when parsing an external subset, doProlog will not accept a BOM
as valid, and report a syntax error, so we have to skip the BOM
*/
else if (tok == XML_TOK_BOM) {
s = next;
tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
parser->m_processor = prologProcessor;
return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
(XML_Bool)! parser->m_parsingStatus.finalBuffer);
}
CWE ID: CWE-611
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 TestFlashMessageLoop::DestroyMessageLoopResourceTask(int32_t unused) {
if (message_loop_) {
delete message_loop_;
message_loop_ = NULL;
} else {
PP_NOTREACHED();
}
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: add_async_iorequest(uint32 device, uint32 file, uint32 id, uint32 major, uint32 length,
DEVICE_FNS * fns, uint32 total_timeout, uint32 interval_timeout, uint8 * buffer,
uint32 offset)
{
struct async_iorequest *iorq;
if (g_iorequest == NULL)
{
g_iorequest = (struct async_iorequest *) xmalloc(sizeof(struct async_iorequest));
if (!g_iorequest)
return False;
g_iorequest->fd = 0;
g_iorequest->next = NULL;
}
iorq = g_iorequest;
while (iorq->fd != 0)
{
/* create new element if needed */
if (iorq->next == NULL)
{
iorq->next =
(struct async_iorequest *) xmalloc(sizeof(struct async_iorequest));
if (!iorq->next)
return False;
iorq->next->fd = 0;
iorq->next->next = NULL;
}
iorq = iorq->next;
}
iorq->device = device;
iorq->fd = file;
iorq->id = id;
iorq->major = major;
iorq->length = length;
iorq->partial_len = 0;
iorq->fns = fns;
iorq->timeout = total_timeout;
iorq->itv_timeout = interval_timeout;
iorq->buffer = buffer;
iorq->offset = offset;
return True;
}
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 ppp_unattached_ioctl(struct net *net, struct ppp_file *pf,
struct file *file, unsigned int cmd, unsigned long arg)
{
int unit, err = -EFAULT;
struct ppp *ppp;
struct channel *chan;
struct ppp_net *pn;
int __user *p = (int __user *)arg;
switch (cmd) {
case PPPIOCNEWUNIT:
/* Create a new ppp unit */
if (get_user(unit, p))
break;
ppp = ppp_create_interface(net, unit, file, &err);
if (!ppp)
break;
file->private_data = &ppp->file;
err = -EFAULT;
if (put_user(ppp->file.index, p))
break;
err = 0;
break;
case PPPIOCATTACH:
/* Attach to an existing ppp unit */
if (get_user(unit, p))
break;
err = -ENXIO;
pn = ppp_pernet(net);
mutex_lock(&pn->all_ppp_mutex);
ppp = ppp_find_unit(pn, unit);
if (ppp) {
atomic_inc(&ppp->file.refcnt);
file->private_data = &ppp->file;
err = 0;
}
mutex_unlock(&pn->all_ppp_mutex);
break;
case PPPIOCATTCHAN:
if (get_user(unit, p))
break;
err = -ENXIO;
pn = ppp_pernet(net);
spin_lock_bh(&pn->all_channels_lock);
chan = ppp_find_channel(pn, unit);
if (chan) {
atomic_inc(&chan->file.refcnt);
file->private_data = &chan->file;
err = 0;
}
spin_unlock_bh(&pn->all_channels_lock);
break;
default:
err = -ENOTTY;
}
return err;
}
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: TEE_Result syscall_asymm_operate(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *src_data, size_t src_len,
void *dst_data, uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen64;
size_t dlen;
struct tee_obj *o;
void *label = NULL;
size_t label_len = 0;
size_t n;
int salt_len;
TEE_Attribute *params = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) src_data, src_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64));
if (res != TEE_SUCCESS)
return res;
dlen = dlen64;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * num_params);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_GENERIC;
goto out;
}
switch (cs->algo) {
case TEE_ALG_RSA_NOPAD:
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsanopad_encrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsanopad_decrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else {
/*
* We will panic because "the mode is not compatible
* with the function"
*/
res = TEE_ERROR_GENERIC;
}
break;
case TEE_ALG_RSAES_PKCS1_V1_5:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
for (n = 0; n < num_params; n++) {
if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
label = params[n].content.ref.buffer;
label_len = params[n].content.ref.length;
break;
}
}
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr,
label, label_len,
src_data, src_len,
dst_data, &dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsaes_decrypt(
cs->algo, o->attr, label, label_len,
src_data, src_len, dst_data, &dlen);
} else {
res = TEE_ERROR_BAD_PARAMETERS;
}
break;
#if defined(CFG_CRYPTO_RSASSA_NA1)
case TEE_ALG_RSASSA_PKCS1_V1_5:
#endif
case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
if (cs->mode != TEE_MODE_SIGN) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params, src_len);
res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len,
src_data, src_len, dst_data,
&dlen);
break;
case TEE_ALG_DSA_SHA1:
case TEE_ALG_DSA_SHA224:
case TEE_ALG_DSA_SHA256:
res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
case TEE_ALG_ECDSA_P192:
case TEE_ALG_ECDSA_P224:
case TEE_ALG_ECDSA_P256:
case TEE_ALG_ECDSA_P384:
case TEE_ALG_ECDSA_P521:
res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
default:
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
out:
free(params);
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2;
dlen64 = dlen;
res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: PHP_METHOD(Phar, getSupportedCompression)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
array_init(return_value);
phar_request_initialize(TSRMLS_C);
if (PHAR_G(has_zlib)) {
add_next_index_stringl(return_value, "GZ", 2, 1);
}
if (PHAR_G(has_bz2)) {
add_next_index_stringl(return_value, "BZIP2", 5, 1);
}
}
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: ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
{
ASN1_INTEGER *ret;
int len, j;
if (ai == NULL)
ret = M_ASN1_INTEGER_new();
else
ret = ai;
if (ret == NULL) {
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR);
goto err;
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (BN_is_negative(bn))
ret->type = V_ASN1_NEG_INTEGER;
else
ret->type = V_ASN1_INTEGER;
if (ret->length < len + 4) {
unsigned char *new_data = OPENSSL_realloc(ret->data, len + 4);
if (!new_data) {
ASN1err(ASN1_F_BN_TO_ASN1_INTEGER, ERR_R_MALLOC_FAILURE);
goto err;
}
ret->data = new_data;
}
ret->length = BN_bn2bin(bn, ret->data);
/* Correct zero case */
if (!ret->length) {
ret->data[0] = 0;
ret->length = 1;
}
return (ret);
err:
if (ret != ai)
M_ASN1_INTEGER_free(ret);
return (NULL);
}
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: static JSValueRef updateTouchPointCallback(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
if (argumentCount < 3)
return JSValueMakeUndefined(context);
int index = static_cast<int>(JSValueToNumber(context, arguments[0], exception));
ASSERT(!exception || !*exception);
int x = static_cast<int>(JSValueToNumber(context, arguments[1], exception));
ASSERT(!exception || !*exception);
int y = static_cast<int>(JSValueToNumber(context, arguments[2], exception));
ASSERT(!exception || !*exception);
if (index < 0 || index >= (int)touches.size())
return JSValueMakeUndefined(context);
BlackBerry::Platform::TouchPoint& touch = touches[index];
IntPoint pos(x, y);
touch.m_pos = pos;
touch.m_screenPos = pos;
touch.m_state = BlackBerry::Platform::TouchPoint::TouchMoved;
return JSValueMakeUndefined(context);
}
CWE ID:
Target: 1
Example 2:
Code: int __cond_resched_lock(spinlock_t *lock)
{
int resched = should_resched();
int ret = 0;
lockdep_assert_held(lock);
if (spin_needbreak(lock) || resched) {
spin_unlock(lock);
if (resched)
__cond_resched();
else
cpu_relax();
ret = 1;
spin_lock(lock);
}
return ret;
}
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 ContainerNode::parserInsertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node& nextChild)
{
ASSERT(newChild);
ASSERT(nextChild.parentNode() == this);
ASSERT(!newChild->isDocumentFragment());
ASSERT(!isHTMLTemplateElement(this));
if (nextChild.previousSibling() == newChild || &nextChild == newChild) // nothing to do
return;
if (!checkParserAcceptChild(*newChild))
return;
RefPtrWillBeRawPtr<Node> protect(this);
while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode())
parent->parserRemoveChild(*newChild);
if (document() != newChild->document())
document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
{
EventDispatchForbiddenScope assertNoEventDispatch;
ScriptForbiddenScope forbidScript;
treeScope().adoptIfNeeded(*newChild);
insertBeforeCommon(nextChild, *newChild);
newChild->updateAncestorConnectedSubframeCountForInsertion();
ChildListMutationScope(*this).childAdded(*newChild);
}
notifyNodeInserted(*newChild, ChildrenChangeSourceParser);
}
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: image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->bit_depth == 16)
{
that->sample_depth = that->bit_depth = 8;
if (that->red_sBIT > 8) that->red_sBIT = 8;
if (that->green_sBIT > 8) that->green_sBIT = 8;
if (that->blue_sBIT > 8) that->blue_sBIT = 8;
if (that->alpha_sBIT > 8) that->alpha_sBIT = 8;
/* Prior to 1.5.4 png_set_strip_16 would use an 'accurate' method if this
* configuration option is set. From 1.5.4 the flag is never set and the
* 'scale' API (above) must be used.
*/
# ifdef PNG_READ_ACCURATE_SCALE_SUPPORTED
# if PNG_LIBPNG_VER >= 10504
# error PNG_READ_ACCURATE_SCALE should not be set
# endif
/* The strip 16 algorithm drops the low 8 bits rather than calculating
* 1/257, so we need to adjust the permitted errors appropriately:
* Notice that this is only relevant prior to the addition of the
* png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!)
*/
{
PNG_CONST double d = (255-128.5)/65535;
that->rede += d;
that->greene += d;
that->bluee += d;
that->alphae += d;
}
# endif
}
this->next->mod(this->next, that, pp, display);
}
CWE ID:
Target: 1
Example 2:
Code: static int rdp_recv_tpkt_pdu(rdpRdp* rdp, STREAM* s)
{
UINT16 length;
UINT16 pduType;
UINT16 pduLength;
UINT16 pduSource;
UINT16 channelId;
UINT16 securityFlags;
BYTE* nextp;
if (!rdp_read_header(rdp, s, &length, &channelId))
{
printf("Incorrect RDP header.\n");
return -1;
}
if (rdp->settings->DisableEncryption)
{
if (!rdp_read_security_header(s, &securityFlags))
return -1;
if (securityFlags & (SEC_ENCRYPT | SEC_REDIRECTION_PKT))
{
if (!rdp_decrypt(rdp, s, length - 4, securityFlags))
{
printf("rdp_decrypt failed\n");
return -1;
}
}
if (securityFlags & SEC_REDIRECTION_PKT)
{
/*
* [MS-RDPBCGR] 2.2.13.2.1
* - no share control header, nor the 2 byte pad
*/
s->p -= 2;
rdp_recv_enhanced_security_redirection_packet(rdp, s);
return -1;
}
}
if (channelId != MCS_GLOBAL_CHANNEL_ID)
{
if (!freerdp_channel_process(rdp->instance, s, channelId))
return -1;
}
else
{
while (stream_get_left(s) > 3)
{
stream_get_mark(s, nextp);
if (!rdp_read_share_control_header(s, &pduLength, &pduType, &pduSource))
return -1;
nextp += pduLength;
rdp->settings->PduSource = pduSource;
switch (pduType)
{
case PDU_TYPE_DATA:
if (rdp_recv_data_pdu(rdp, s) < 0)
{
printf("rdp_recv_data_pdu failed\n");
return -1;
}
break;
case PDU_TYPE_DEACTIVATE_ALL:
if (!rdp_recv_deactivate_all(rdp, s))
return -1;
break;
case PDU_TYPE_SERVER_REDIRECTION:
if (!rdp_recv_enhanced_security_redirection_packet(rdp, s))
return -1;
break;
default:
printf("incorrect PDU type: 0x%04X\n", pduType);
break;
}
stream_set_mark(s, nextp);
}
}
return 0;
}
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: gfx::Image GetTabAlertIndicatorImage(TabAlertState alert_state,
SkColor button_color) {
const gfx::VectorIcon* icon = nullptr;
switch (alert_state) {
case TabAlertState::AUDIO_PLAYING:
icon = &kTabAudioIcon;
break;
case TabAlertState::AUDIO_MUTING:
icon = &kTabAudioMutingIcon;
break;
case TabAlertState::MEDIA_RECORDING:
icon = &kTabMediaRecordingIcon;
break;
case TabAlertState::TAB_CAPTURING:
icon = &kTabMediaCapturingIcon;
break;
case TabAlertState::BLUETOOTH_CONNECTED:
icon = &kTabBluetoothConnectedIcon;
break;
case TabAlertState::USB_CONNECTED:
icon = &kTabUsbConnectedIcon;
break;
case TabAlertState::NONE:
return gfx::Image();
}
DCHECK(icon);
return gfx::Image(gfx::CreateVectorIcon(*icon, 16, button_color));
}
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 void *skcipher_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_skcipher(name, type, mask);
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: scoped_refptr<base::SingleThreadTaskRunner> Document::GetTaskRunner(
TaskType type) {
DCHECK(IsMainThread());
if (ContextDocument() && ContextDocument()->GetFrame())
return ContextDocument()->GetFrame()->GetTaskRunner(type);
return Thread::Current()->GetTaskRunner();
}
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: status_t Parcel::readInt32Vector(std::vector<int32_t>* val) const {
return readTypedVector(val, &Parcel::readInt32);
}
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 int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_cipher rcipher;
strlcpy(rcipher.type, "cipher", sizeof(rcipher.type));
rcipher.blocksize = alg->cra_blocksize;
rcipher.min_keysize = alg->cra_cipher.cia_min_keysize;
rcipher.max_keysize = alg->cra_cipher.cia_max_keysize;
if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER,
sizeof(struct crypto_report_cipher), &rcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
CWE ID:
Target: 1
Example 2:
Code: projid_t from_kprojid(struct user_namespace *targ, kprojid_t kprojid)
{
/* Map the uid from a global kernel uid */
return map_id_up(&targ->projid_map, __kprojid_val(kprojid));
}
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: void RenderWidgetHostViewAura::WasShown() {
if (!host_->is_hidden())
return;
host_->WasShown();
if (!current_surface_ && host_->is_accelerated_compositing_active() &&
!released_front_lock_.get()) {
released_front_lock_ = GetCompositor()->GetCompositorLock();
}
AdjustSurfaceProtection();
#if defined(OS_WIN)
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(ui::GetHiddenWindow(), ShowWindowsCallback, lparam);
#endif
}
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: void EnterpriseEnrollmentScreen::OnAuthCancelled() {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentCancelled,
policy::kMetricEnrollmentSize);
auth_fetcher_.reset();
registrar_.reset();
g_browser_process->browser_policy_connector()->DeviceStopAutoRetry();
get_screen_observer()->OnExit(
ScreenObserver::ENTERPRISE_ENROLLMENT_CANCELLED);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void _WM_do_control_dummy(struct _mdi *mdi, struct _event_data *data) {
#ifdef DEBUG_MIDI
uint8_t ch = data->channel;
MIDI_EVENT_DEBUG(__FUNCTION__, ch, data->data.value);
#else
UNUSED(data);
#endif
UNUSED(mdi);
}
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 struct nfs4_unlockdata *nfs4_alloc_unlockdata(struct file_lock *fl,
struct nfs_open_context *ctx,
struct nfs4_lock_state *lsp,
struct nfs_seqid *seqid)
{
struct nfs4_unlockdata *p;
struct inode *inode = lsp->ls_state->inode;
p = kzalloc(sizeof(*p), GFP_NOFS);
if (p == NULL)
return NULL;
p->arg.fh = NFS_FH(inode);
p->arg.fl = &p->fl;
p->arg.seqid = seqid;
p->res.seqid = seqid;
p->lsp = lsp;
atomic_inc(&lsp->ls_count);
/* Ensure we don't close file until we're done freeing locks! */
p->ctx = get_nfs_open_context(ctx);
memcpy(&p->fl, fl, sizeof(p->fl));
p->server = NFS_SERVER(inode);
return p;
}
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 v8::Handle<v8::Value> overloadedMethod11Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod11");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
EXCEPTION_BLOCK(int, arg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
TestObj::overloadedMethod1(arg);
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: void TestFocusTraversal(RenderViewHost* render_view_host, bool reverse) {
const char kGetFocusedElementJS[] =
"window.domAutomationController.send(getFocusedElement());";
const char* kExpectedIDs[] = { "textEdit", "searchButton", "luckyButton",
"googleLink", "gmailLink", "gmapLink" };
SCOPED_TRACE(base::StringPrintf("TestFocusTraversal: reverse=%d", reverse));
ui::KeyboardCode key = ui::VKEY_TAB;
#if defined(OS_MACOSX)
key = reverse ? ui::VKEY_BACKTAB : ui::VKEY_TAB;
#elif defined(OS_WIN)
if (base::win::GetVersion() < base::win::VERSION_VISTA)
return;
#endif
for (size_t i = 0; i < 2; ++i) {
SCOPED_TRACE(base::StringPrintf("focus outer loop: %" PRIuS, i));
ASSERT_TRUE(IsViewFocused(VIEW_ID_OMNIBOX));
#if defined(OS_MACOSX)
if (ui_controls::IsFullKeyboardAccessEnabled()) {
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), key, false, reverse, false, false));
if (reverse) {
for (int j = 0; j < 3; ++j) {
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), key, false, reverse, false, false));
}
}
}
#endif
if (reverse) {
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), key, false, reverse, false, false,
content::NOTIFICATION_ALL,
content::NotificationService::AllSources()));
}
for (size_t j = 0; j < arraysize(kExpectedIDs); ++j) {
SCOPED_TRACE(base::StringPrintf("focus inner loop %" PRIuS, j));
const size_t index = reverse ? arraysize(kExpectedIDs) - 1 - j : j;
bool is_editable_node = index == 0;
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWaitWithDetails(
browser(), key, false, reverse, false, false,
content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
content::Source<RenderViewHost>(render_view_host),
content::Details<bool>(&is_editable_node)));
std::string focused_id;
EXPECT_TRUE(content::ExecuteScriptAndExtractString(
render_view_host, kGetFocusedElementJS, &focused_id));
EXPECT_STREQ(kExpectedIDs[index], focused_id.c_str());
}
#if defined(OS_MACOSX)
chrome::FocusLocationBar(browser());
#else
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), key, false, reverse, false, false,
chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER,
content::Source<Browser>(browser())));
EXPECT_TRUE(
IsViewFocused(reverse ? VIEW_ID_OMNIBOX : VIEW_ID_LOCATION_ICON));
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), key, false, reverse, false, false,
content::NOTIFICATION_ALL,
content::NotificationService::AllSources()));
#endif
content::RunAllPendingInMessageLoop();
EXPECT_TRUE(
IsViewFocused(reverse ? VIEW_ID_LOCATION_ICON : VIEW_ID_OMNIBOX));
if (reverse) {
ASSERT_TRUE(ui_test_utils::SendKeyPressAndWait(
browser(), key, false, false, false, false,
content::NOTIFICATION_ALL,
content::NotificationService::AllSources()));
}
}
}
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: wiki_show_page(HttpResponse *res, char *wikitext, char *page)
{
char *html_clean_wikitext = NULL;
http_response_printf_alloc_buffer(res, strlen(wikitext)*2);
wiki_show_header(res, page, TRUE);
html_clean_wikitext = util_htmlize(wikitext, strlen(wikitext));
wiki_print_data_as_html(res, html_clean_wikitext);
wiki_show_footer(res);
http_response_send(res);
exit(0);
}
CWE ID: CWE-22
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: xfs_attr3_leaf_list_int(
struct xfs_buf *bp,
struct xfs_attr_list_context *context)
{
struct attrlist_cursor_kern *cursor;
struct xfs_attr_leafblock *leaf;
struct xfs_attr3_icleaf_hdr ichdr;
struct xfs_attr_leaf_entry *entries;
struct xfs_attr_leaf_entry *entry;
int retval;
int i;
trace_xfs_attr_list_leaf(context);
leaf = bp->b_addr;
xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf);
entries = xfs_attr3_leaf_entryp(leaf);
cursor = context->cursor;
cursor->initted = 1;
/*
* Re-find our place in the leaf block if this is a new syscall.
*/
if (context->resynch) {
entry = &entries[0];
for (i = 0; i < ichdr.count; entry++, i++) {
if (be32_to_cpu(entry->hashval) == cursor->hashval) {
if (cursor->offset == context->dupcnt) {
context->dupcnt = 0;
break;
}
context->dupcnt++;
} else if (be32_to_cpu(entry->hashval) >
cursor->hashval) {
context->dupcnt = 0;
break;
}
}
if (i == ichdr.count) {
trace_xfs_attr_list_notfound(context);
return 0;
}
} else {
entry = &entries[0];
i = 0;
}
context->resynch = 0;
/*
* We have found our place, start copying out the new attributes.
*/
retval = 0;
for (; i < ichdr.count; entry++, i++) {
if (be32_to_cpu(entry->hashval) != cursor->hashval) {
cursor->hashval = be32_to_cpu(entry->hashval);
cursor->offset = 0;
}
if (entry->flags & XFS_ATTR_INCOMPLETE)
continue; /* skip incomplete entries */
if (entry->flags & XFS_ATTR_LOCAL) {
xfs_attr_leaf_name_local_t *name_loc =
xfs_attr3_leaf_name_local(leaf, i);
retval = context->put_listent(context,
entry->flags,
name_loc->nameval,
(int)name_loc->namelen,
be16_to_cpu(name_loc->valuelen),
&name_loc->nameval[name_loc->namelen]);
if (retval)
return retval;
} else {
xfs_attr_leaf_name_remote_t *name_rmt =
xfs_attr3_leaf_name_remote(leaf, i);
int valuelen = be32_to_cpu(name_rmt->valuelen);
if (context->put_value) {
xfs_da_args_t args;
memset((char *)&args, 0, sizeof(args));
args.dp = context->dp;
args.whichfork = XFS_ATTR_FORK;
args.valuelen = valuelen;
args.value = kmem_alloc(valuelen, KM_SLEEP | KM_NOFS);
args.rmtblkno = be32_to_cpu(name_rmt->valueblk);
args.rmtblkcnt = xfs_attr3_rmt_blocks(
args.dp->i_mount, valuelen);
retval = xfs_attr_rmtval_get(&args);
if (retval)
return retval;
retval = context->put_listent(context,
entry->flags,
name_rmt->name,
(int)name_rmt->namelen,
valuelen,
args.value);
kmem_free(args.value);
} else {
retval = context->put_listent(context,
entry->flags,
name_rmt->name,
(int)name_rmt->namelen,
valuelen,
NULL);
}
if (retval)
return retval;
}
if (context->seen_enough)
break;
cursor->offset++;
}
trace_xfs_attr_list_leaf_end(context);
return retval;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: void CL_Rcon_f( void ) {
char message[MAX_RCON_MESSAGE];
netadr_t to;
if ( !rcon_client_password->string[0] ) {
Com_Printf ("You must set 'rconpassword' before\n"
"issuing an rcon command.\n");
return;
}
message[0] = -1;
message[1] = -1;
message[2] = -1;
message[3] = -1;
message[4] = 0;
Q_strcat (message, MAX_RCON_MESSAGE, "rcon ");
Q_strcat (message, MAX_RCON_MESSAGE, rcon_client_password->string);
Q_strcat (message, MAX_RCON_MESSAGE, " ");
Q_strcat (message, MAX_RCON_MESSAGE, Cmd_Cmd()+5);
if ( clc.state >= CA_CONNECTED ) {
to = clc.netchan.remoteAddress;
} else {
if (!strlen(rconAddress->string)) {
Com_Printf ("You must either be connected,\n"
"or set the 'rconAddress' cvar\n"
"to issue rcon commands\n");
return;
}
NET_StringToAdr (rconAddress->string, &to, NA_UNSPEC);
if (to.port == 0) {
to.port = BigShort (PORT_SERVER);
}
}
NET_SendPacket (NS_CLIENT, strlen(message)+1, message, to);
}
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 void update_devnum(struct usb_device *udev, int devnum)
{
/* The address for a WUSB device is managed by wusbcore. */
if (!udev->wusb)
udev->devnum = devnum;
}
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: exsltFuncFunctionFunction (xmlXPathParserContextPtr ctxt, int nargs) {
xmlXPathObjectPtr oldResult, ret;
exsltFuncData *data;
exsltFuncFunctionData *func;
xmlNodePtr paramNode, oldInsert, fake;
int oldBase;
xsltStackElemPtr params = NULL, param;
xsltTransformContextPtr tctxt = xsltXPathGetTransformContext(ctxt);
int i, notSet;
struct objChain {
struct objChain *next;
xmlXPathObjectPtr obj;
};
struct objChain *savedObjChain = NULL, *savedObj;
/*
* retrieve func:function template
*/
data = (exsltFuncData *) xsltGetExtData (tctxt,
EXSLT_FUNCTIONS_NAMESPACE);
oldResult = data->result;
data->result = NULL;
func = (exsltFuncFunctionData*) xmlHashLookup2 (data->funcs,
ctxt->context->functionURI,
ctxt->context->function);
/*
* params handling
*/
if (nargs > func->nargs) {
xsltGenericError(xsltGenericErrorContext,
"{%s}%s: called with too many arguments\n",
ctxt->context->functionURI, ctxt->context->function);
ctxt->error = XPATH_INVALID_ARITY;
return;
}
if (func->content != NULL) {
paramNode = func->content->prev;
}
else
paramNode = NULL;
if ((paramNode == NULL) && (func->nargs != 0)) {
xsltGenericError(xsltGenericErrorContext,
"exsltFuncFunctionFunction: nargs != 0 and "
"param == NULL\n");
return;
}
if (tctxt->funcLevel > MAX_FUNC_RECURSION) {
xsltGenericError(xsltGenericErrorContext,
"{%s}%s: detected a recursion\n",
ctxt->context->functionURI, ctxt->context->function);
ctxt->error = XPATH_MEMORY_ERROR;
return;
}
tctxt->funcLevel++;
/*
* We have a problem with the evaluation of function parameters.
* The original library code did not evaluate XPath expressions until
* the last moment. After version 1.1.17 of the libxslt, the logic
* of other parts of the library was changed, and the evaluation of
* XPath expressions within parameters now takes place as soon as the
* parameter is parsed/evaluated (xsltParseStylesheetCallerParam).
* This means that the parameters need to be evaluated in lexical
* order (since a variable is "in scope" as soon as it is declared).
* However, on entry to this routine, the values (from the caller) are
* in reverse order (held on the XPath context variable stack). To
* accomplish what is required, I have added code to pop the XPath
* objects off of the stack at the beginning and save them, then use
* them (in the reverse order) as the params are evaluated. This
* requires an xmlMalloc/xmlFree for each param set by the caller,
* which is not very nice. There is probably a much better solution
* (like change other code to delay the evaluation).
*/
/*
* In order to give the function params and variables a new 'scope'
* we change varsBase in the context.
*/
oldBase = tctxt->varsBase;
tctxt->varsBase = tctxt->varsNr;
/* If there are any parameters */
if (paramNode != NULL) {
/* Fetch the stored argument values from the caller */
for (i = 0; i < nargs; i++) {
savedObj = xmlMalloc(sizeof(struct objChain));
savedObj->next = savedObjChain;
savedObj->obj = valuePop(ctxt);
savedObjChain = savedObj;
}
/*
* Prepare to process params in reverse order. First, go to
* the beginning of the param chain.
*/
for (i = 1; i <= func->nargs; i++) {
if (paramNode->prev == NULL)
break;
paramNode = paramNode->prev;
}
/*
* i has total # params found, nargs is number which are present
* as arguments from the caller
* Calculate the number of un-set parameters
*/
notSet = func->nargs - nargs;
for (; i > 0; i--) {
param = xsltParseStylesheetCallerParam (tctxt, paramNode);
if (i > notSet) { /* if parameter value set */
param->computed = 1;
if (param->value != NULL)
xmlXPathFreeObject(param->value);
savedObj = savedObjChain; /* get next val from chain */
param->value = savedObj->obj;
savedObjChain = savedObjChain->next;
xmlFree(savedObj);
}
xsltLocalVariablePush(tctxt, param, -1);
param->next = params;
params = param;
paramNode = paramNode->next;
}
}
/*
* actual processing
*/
fake = xmlNewDocNode(tctxt->output, NULL,
(const xmlChar *)"fake", NULL);
oldInsert = tctxt->insert;
tctxt->insert = fake;
xsltApplyOneTemplate (tctxt, xmlXPathGetContextNode(ctxt),
func->content, NULL, NULL);
xsltLocalVariablePop(tctxt, tctxt->varsBase, -2);
tctxt->insert = oldInsert;
tctxt->varsBase = oldBase; /* restore original scope */
if (params != NULL)
xsltFreeStackElemList(params);
if (data->error != 0)
goto error;
if (data->result != NULL) {
ret = data->result;
} else
ret = xmlXPathNewCString("");
data->result = oldResult;
/*
* It is an error if the instantiation of the template results in
* the generation of result nodes.
*/
if (fake->children != NULL) {
#ifdef LIBXML_DEBUG_ENABLED
xmlDebugDumpNode (stderr, fake, 1);
#endif
xsltGenericError(xsltGenericErrorContext,
"{%s}%s: cannot write to result tree while "
"executing a function\n",
ctxt->context->functionURI, ctxt->context->function);
xmlFreeNode(fake);
goto error;
}
xmlFreeNode(fake);
valuePush(ctxt, ret);
error:
/*
* IMPORTANT: This enables previously tree fragments marked as
* being results of a function, to be garbage-collected after
* the calling process exits.
*/
xsltExtensionInstructionResultFinalize(tctxt);
tctxt->funcLevel--;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct sock *__sco_get_sock_by_addr(bdaddr_t *ba)
{
struct sock *sk;
struct hlist_node *node;
sk_for_each(sk, node, &sco_sk_list.head)
if (!bacmp(&bt_sk(sk)->src, ba))
goto found;
sk = NULL;
found:
return sk;
}
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: void RenderProcessHostImpl::RemoveObserver(
RenderProcessHostObserver* observer) {
observers_.RemoveObserver(observer);
}
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 Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue) {
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline void __poke_user_per(struct task_struct *child,
addr_t addr, addr_t data)
{
struct per_struct_kernel *dummy = NULL;
/*
* There are only three fields in the per_info struct that the
* debugger user can write to.
* 1) cr9: the debugger wants to set a new PER event mask
* 2) starting_addr: the debugger wants to set a new starting
* address to use with the PER event mask.
* 3) ending_addr: the debugger wants to set a new ending
* address to use with the PER event mask.
* The user specified PER event mask and the start and end
* addresses are used only if single stepping is not in effect.
* Writes to any other field in per_info are ignored.
*/
if (addr == (addr_t) &dummy->cr9)
/* PER event mask of the user specified per set. */
child->thread.per_user.control =
data & (PER_EVENT_MASK | PER_CONTROL_MASK);
else if (addr == (addr_t) &dummy->starting_addr)
/* Starting address of the user specified per set. */
child->thread.per_user.start = data;
else if (addr == (addr_t) &dummy->ending_addr)
/* Ending address of the user specified per set. */
child->thread.per_user.end = data;
}
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 BrowserCommandController::UpdateCommandsForFullscreenMode(
FullScreenMode fullscreen_mode) {
const bool show_main_ui =
IsShowingMainUI(fullscreen_mode != FULLSCREEN_DISABLED);
bool main_not_fullscreen = show_main_ui &&
(fullscreen_mode == FULLSCREEN_DISABLED);
command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, show_main_ui);
command_updater_.UpdateCommandEnabled(
IDC_SHOW_AS_TAB,
!browser_->is_type_tabbed() && fullscreen_mode == FULLSCREEN_DISABLED);
command_updater_.UpdateCommandEnabled(IDC_FOCUS_TOOLBAR, show_main_ui);
command_updater_.UpdateCommandEnabled(IDC_FOCUS_LOCATION, show_main_ui);
command_updater_.UpdateCommandEnabled(IDC_FOCUS_SEARCH, show_main_ui);
command_updater_.UpdateCommandEnabled(
IDC_FOCUS_MENU_BAR, main_not_fullscreen);
command_updater_.UpdateCommandEnabled(
IDC_FOCUS_NEXT_PANE, main_not_fullscreen);
command_updater_.UpdateCommandEnabled(
IDC_FOCUS_PREVIOUS_PANE, main_not_fullscreen);
command_updater_.UpdateCommandEnabled(
IDC_FOCUS_BOOKMARKS, main_not_fullscreen);
command_updater_.UpdateCommandEnabled(IDC_DEVELOPER_MENU, show_main_ui);
command_updater_.UpdateCommandEnabled(IDC_FEEDBACK, show_main_ui);
command_updater_.UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP,
show_main_ui && profile()->GetOriginalProfile()->IsSyncAccessible());
const bool options_enabled = show_main_ui &&
IncognitoModePrefs::GetAvailability(
profile()->GetPrefs()) != IncognitoModePrefs::FORCED;
command_updater_.UpdateCommandEnabled(IDC_OPTIONS, options_enabled);
command_updater_.UpdateCommandEnabled(IDC_IMPORT_SETTINGS, options_enabled);
command_updater_.UpdateCommandEnabled(IDC_EDIT_SEARCH_ENGINES, show_main_ui);
command_updater_.UpdateCommandEnabled(IDC_VIEW_PASSWORDS, show_main_ui);
command_updater_.UpdateCommandEnabled(IDC_ABOUT, show_main_ui);
command_updater_.UpdateCommandEnabled(IDC_SHOW_APP_MENU, show_main_ui);
#if defined (ENABLE_PROFILING) && !defined(NO_TCMALLOC)
command_updater_.UpdateCommandEnabled(IDC_PROFILING_ENABLED, show_main_ui);
#endif
bool fullscreen_enabled = !browser_->is_type_panel() &&
!browser_->is_app() &&
fullscreen_mode != FULLSCREEN_METRO_SNAP;
#if defined(OS_MACOSX)
int tabIndex = chrome::IndexOfFirstBlockedTab(browser_->tab_strip_model());
bool has_blocked_tab = tabIndex != browser_->tab_strip_model()->count();
fullscreen_enabled &= !has_blocked_tab;
#endif
command_updater_.UpdateCommandEnabled(IDC_FULLSCREEN, fullscreen_enabled);
command_updater_.UpdateCommandEnabled(IDC_PRESENTATION_MODE,
fullscreen_enabled);
UpdateCommandsForBookmarkBar();
UpdateCommandsForMultipleProfiles();
}
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 int rock_continue(struct rock_state *rs)
{
int ret = 1;
int blocksize = 1 << rs->inode->i_blkbits;
const int min_de_size = offsetof(struct rock_ridge, u);
kfree(rs->buffer);
rs->buffer = NULL;
if ((unsigned)rs->cont_offset > blocksize - min_de_size ||
(unsigned)rs->cont_size > blocksize ||
(unsigned)(rs->cont_offset + rs->cont_size) > blocksize) {
printk(KERN_NOTICE "rock: corrupted directory entry. "
"extent=%d, offset=%d, size=%d\n",
rs->cont_extent, rs->cont_offset, rs->cont_size);
ret = -EIO;
goto out;
}
if (rs->cont_extent) {
struct buffer_head *bh;
rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL);
if (!rs->buffer) {
ret = -ENOMEM;
goto out;
}
ret = -EIO;
bh = sb_bread(rs->inode->i_sb, rs->cont_extent);
if (bh) {
memcpy(rs->buffer, bh->b_data + rs->cont_offset,
rs->cont_size);
put_bh(bh);
rs->chr = rs->buffer;
rs->len = rs->cont_size;
rs->cont_extent = 0;
rs->cont_size = 0;
rs->cont_offset = 0;
return 0;
}
printk("Unable to read rock-ridge attributes\n");
}
out:
kfree(rs->buffer);
rs->buffer = NULL;
return ret;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: PHP_FUNCTION(time)
{
RETURN_LONG((long)time(NULL));
}
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 BrowserLauncherItemController::Init() {
tab_model_->AddObserver(this);
ash::LauncherItemStatus app_status =
ash::wm::IsActiveWindow(window_) ?
ash::STATUS_ACTIVE : ash::STATUS_RUNNING;
if (type() != TYPE_TABBED) {
launcher_controller()->CreateAppLauncherItem(this, app_id(), app_status);
} else {
launcher_controller()->CreateTabbedLauncherItem(
this,
is_incognito_ ? ChromeLauncherController::STATE_INCOGNITO :
ChromeLauncherController::STATE_NOT_INCOGNITO,
app_status);
}
if (tab_model_->GetActiveTabContents())
UpdateLauncher(tab_model_->GetActiveTabContents());
}
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: sp<VBRISeeker> VBRISeeker::CreateFromSource(
const sp<DataSource> &source, off64_t post_id3_pos) {
off64_t pos = post_id3_pos;
uint8_t header[4];
ssize_t n = source->readAt(pos, header, sizeof(header));
if (n < (ssize_t)sizeof(header)) {
return NULL;
}
uint32_t tmp = U32_AT(&header[0]);
size_t frameSize;
int sampleRate;
if (!GetMPEGAudioFrameSize(tmp, &frameSize, &sampleRate)) {
return NULL;
}
pos += sizeof(header) + 32;
uint8_t vbriHeader[26];
n = source->readAt(pos, vbriHeader, sizeof(vbriHeader));
if (n < (ssize_t)sizeof(vbriHeader)) {
return NULL;
}
if (memcmp(vbriHeader, "VBRI", 4)) {
return NULL;
}
size_t numFrames = U32_AT(&vbriHeader[14]);
int64_t durationUs =
numFrames * 1000000ll * (sampleRate >= 32000 ? 1152 : 576) / sampleRate;
ALOGV("duration = %.2f secs", durationUs / 1E6);
size_t numEntries = U16_AT(&vbriHeader[18]);
size_t entrySize = U16_AT(&vbriHeader[22]);
size_t scale = U16_AT(&vbriHeader[20]);
ALOGV("%zu entries, scale=%zu, size_per_entry=%zu",
numEntries,
scale,
entrySize);
size_t totalEntrySize = numEntries * entrySize;
uint8_t *buffer = new uint8_t[totalEntrySize];
n = source->readAt(pos + sizeof(vbriHeader), buffer, totalEntrySize);
if (n < (ssize_t)totalEntrySize) {
delete[] buffer;
buffer = NULL;
return NULL;
}
sp<VBRISeeker> seeker = new VBRISeeker;
seeker->mBasePos = post_id3_pos + frameSize;
if (durationUs) {
seeker->mDurationUs = durationUs;
}
off64_t offset = post_id3_pos;
for (size_t i = 0; i < numEntries; ++i) {
uint32_t numBytes;
switch (entrySize) {
case 1: numBytes = buffer[i]; break;
case 2: numBytes = U16_AT(buffer + 2 * i); break;
case 3: numBytes = U24_AT(buffer + 3 * i); break;
default:
{
CHECK_EQ(entrySize, 4u);
numBytes = U32_AT(buffer + 4 * i); break;
}
}
numBytes *= scale;
seeker->mSegments.push(numBytes);
ALOGV("entry #%zu: %u offset %#016llx", i, numBytes, (long long)offset);
offset += numBytes;
}
delete[] buffer;
buffer = NULL;
ALOGI("Found VBRI header.");
return seeker;
}
CWE ID:
Target: 1
Example 2:
Code: ImageDataNaClBackend::ImageDataNaClBackend()
: map_count_(0) {
}
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: error::Error GLES2DecoderPassthroughImpl::DoTraceEndCHROMIUM() {
if (!gpu_tracer_->End(kTraceCHROMIUM)) {
InsertError(GL_INVALID_OPERATION, "No trace to end");
return error::kNoError;
}
debug_marker_manager_.PopGroup();
return error::kNoError;
}
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: pop_decoder_state (DECODER_STATE ds)
{
if (!ds->idx)
{
fprintf (stderr, "ERROR: decoder stack underflow!\n");
abort ();
}
ds->cur = ds->stack[--ds->idx];
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
bool notify) {
ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
if (connectionIndex < 0) {
ALOGW("Attempted to unregister already unregistered input channel '%s'",
inputChannel->getName().string());
return BAD_VALUE;
}
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
mConnectionsByFd.removeItemsAt(connectionIndex);
if (connection->monitor) {
removeMonitorChannelLocked(inputChannel);
}
mLooper->removeFd(inputChannel->getFd());
nsecs_t currentTime = now();
abortBrokenDispatchCycleLocked(currentTime, connection, notify);
connection->status = Connection::STATUS_ZOMBIE;
return OK;
}
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 Layer::IsContainerForFixedPositionLayers() const {
if (!transform_.IsIdentityOrTranslation())
return true;
if (parent_ && !parent_->transform_.IsIdentityOrTranslation())
return true;
return is_container_for_fixed_position_layers_;
}
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 void UpdatePropertyHandler(
void* object, const ImePropertyList& prop_list) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
LOG(ERROR) << "Not on UI thread";
return;
}
InputMethodLibraryImpl* input_method_library =
static_cast<InputMethodLibraryImpl*>(object);
input_method_library->UpdateProperty(prop_list);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void faad_initbits_rev(bitfile *ld, void *buffer,
uint32_t bits_in_buffer)
{
uint32_t tmp;
int32_t index;
ld->buffer_size = bit2byte(bits_in_buffer);
index = (bits_in_buffer+31)/32 - 1;
ld->start = (uint32_t*)buffer + index - 2;
tmp = getdword((uint32_t*)buffer + index);
ld->bufa = tmp;
tmp = getdword((uint32_t*)buffer + index - 1);
ld->bufb = tmp;
ld->tail = (uint32_t*)buffer + index;
ld->bits_left = bits_in_buffer % 32;
if (ld->bits_left == 0)
ld->bits_left = 32;
ld->bytes_left = ld->buffer_size;
ld->error = 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: void SetFilterCallback(const FilterCallback& callback) {
callback_ = callback;
}
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: bool AXObject::isHiddenForTextAlternativeCalculation() const {
if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "false"))
return false;
if (getLayoutObject())
return getLayoutObject()->style()->visibility() != EVisibility::kVisible;
Document* document = getDocument();
if (!document || !document->frame())
return false;
if (Node* node = getNode()) {
if (node->isConnected() && node->isElementNode()) {
RefPtr<ComputedStyle> style =
document->ensureStyleResolver().styleForElement(toElement(node));
return style->display() == EDisplay::kNone ||
style->visibility() != EVisibility::kVisible;
}
}
return false;
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: pfetch (lin line)
{
return p_line[line];
}
CWE ID: CWE-78
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 MSG_ReadLong( msg_t *msg ) {
int c;
c = MSG_ReadBits( msg, 32 );
if ( msg->readcount > msg->cursize ) {
c = -1;
}
return c;
}
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: init_ctx_reselect(OM_uint32 *minor_status, spnego_gss_ctx_id_t sc,
OM_uint32 acc_negState, gss_OID supportedMech,
gss_buffer_t *responseToken, gss_buffer_t *mechListMIC,
OM_uint32 *negState, send_token_flag *tokflag)
{
OM_uint32 tmpmin;
size_t i;
generic_gss_release_oid(&tmpmin, &sc->internal_mech);
gss_delete_sec_context(&tmpmin, &sc->ctx_handle,
GSS_C_NO_BUFFER);
/* Find supportedMech in sc->mech_set. */
for (i = 0; i < sc->mech_set->count; i++) {
if (g_OID_equal(supportedMech, &sc->mech_set->elements[i]))
break;
}
if (i == sc->mech_set->count)
return GSS_S_DEFECTIVE_TOKEN;
sc->internal_mech = &sc->mech_set->elements[i];
/*
* Windows 2003 and earlier don't correctly send a
* negState of request-mic when counter-proposing a
* mechanism. They probably don't handle mechListMICs
* properly either.
*/
if (acc_negState != REQUEST_MIC)
return GSS_S_DEFECTIVE_TOKEN;
sc->mech_complete = 0;
sc->mic_reqd = 1;
*negState = REQUEST_MIC;
*tokflag = CONT_TOKEN_SEND;
return GSS_S_CONTINUE_NEEDED;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: void TransportTexture::OnChannelConnected(int32 peer_pid) {
}
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 asf_probe(AVProbeData *pd)
{
/* check file header */
if (!ff_guidcmp(pd->buf, &ff_asf_header))
return AVPROBE_SCORE_MAX;
else
return 0;
}
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: OMX_ERRORTYPE SoftAACEncoder2::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_encoder.aac",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPortFormat:
{
const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
(const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
if (formatParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
if (formatParams->nIndex > 0) {
return OMX_ErrorNoMore;
}
if ((formatParams->nPortIndex == 0
&& formatParams->eEncoding != OMX_AUDIO_CodingPCM)
|| (formatParams->nPortIndex == 1
&& formatParams->eEncoding != OMX_AUDIO_CodingAAC)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAac:
{
OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
(OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
if (aacParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mBitRate = aacParams->nBitRate;
mNumChannels = aacParams->nChannels;
mSampleRate = aacParams->nSampleRate;
if (aacParams->eAACProfile != OMX_AUDIO_AACObjectNull) {
mAACProfile = aacParams->eAACProfile;
}
if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 0;
mSBRRatio = 0;
} else if ((aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 1;
} else if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR)
&& (aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) {
mSBRMode = 1;
mSBRRatio = 2;
} else {
mSBRMode = -1; // codec default sbr mode
mSBRRatio = 0;
}
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
mNumChannels = pcmParams->nChannels;
mSampleRate = pcmParams->nSamplingRate;
if (setAudioParams() != OK) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ff_h264_hl_decode_mb(H264Context *h)
{
const int mb_xy = h->mb_xy;
const int mb_type = h->cur_pic.mb_type[mb_xy];
int is_complex = CONFIG_SMALL || h->is_complex ||
IS_INTRA_PCM(mb_type) || h->qscale == 0;
if (CHROMA444(h)) {
if (is_complex || h->pixel_shift)
hl_decode_mb_444_complex(h);
else
hl_decode_mb_444_simple_8(h);
} else if (is_complex) {
hl_decode_mb_complex(h);
} else if (h->pixel_shift) {
hl_decode_mb_simple_16(h);
} else
hl_decode_mb_simple_8(h);
}
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 svc_rdma_sendto(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
struct rpcrdma_msg *rdma_argp;
struct rpcrdma_msg *rdma_resp;
struct rpcrdma_write_array *wr_ary, *rp_ary;
int ret;
int inline_bytes;
struct page *res_page;
struct svc_rdma_req_map *vec;
u32 inv_rkey;
__be32 *p;
dprintk("svcrdma: sending response for rqstp=%p\n", rqstp);
/* Get the RDMA request header. The receive logic always
* places this at the start of page 0.
*/
rdma_argp = page_address(rqstp->rq_pages[0]);
svc_rdma_get_write_arrays(rdma_argp, &wr_ary, &rp_ary);
inv_rkey = 0;
if (rdma->sc_snd_w_inv)
inv_rkey = svc_rdma_get_inv_rkey(rdma_argp, wr_ary, rp_ary);
/* Build an req vec for the XDR */
vec = svc_rdma_get_req_map(rdma);
ret = svc_rdma_map_xdr(rdma, &rqstp->rq_res, vec, wr_ary != NULL);
if (ret)
goto err0;
inline_bytes = rqstp->rq_res.len;
/* Create the RDMA response header. xprt->xpt_mutex,
* acquired in svc_send(), serializes RPC replies. The
* code path below that inserts the credit grant value
* into each transport header runs only inside this
* critical section.
*/
ret = -ENOMEM;
res_page = alloc_page(GFP_KERNEL);
if (!res_page)
goto err0;
rdma_resp = page_address(res_page);
p = &rdma_resp->rm_xid;
*p++ = rdma_argp->rm_xid;
*p++ = rdma_argp->rm_vers;
*p++ = rdma->sc_fc_credits;
*p++ = rp_ary ? rdma_nomsg : rdma_msg;
/* Start with empty chunks */
*p++ = xdr_zero;
*p++ = xdr_zero;
*p = xdr_zero;
/* Send any write-chunk data and build resp write-list */
if (wr_ary) {
ret = send_write_chunks(rdma, wr_ary, rdma_resp, rqstp, vec);
if (ret < 0)
goto err1;
inline_bytes -= ret + xdr_padsize(ret);
}
/* Send any reply-list data and update resp reply-list */
if (rp_ary) {
ret = send_reply_chunks(rdma, rp_ary, rdma_resp, rqstp, vec);
if (ret < 0)
goto err1;
inline_bytes -= ret;
}
/* Post a fresh Receive buffer _before_ sending the reply */
ret = svc_rdma_post_recv(rdma, GFP_KERNEL);
if (ret)
goto err1;
ret = send_reply(rdma, rqstp, res_page, rdma_resp, vec,
inline_bytes, inv_rkey);
if (ret < 0)
goto err0;
svc_rdma_put_req_map(rdma, vec);
dprintk("svcrdma: send_reply returns %d\n", ret);
return ret;
err1:
put_page(res_page);
err0:
svc_rdma_put_req_map(rdma, vec);
pr_err("svcrdma: Could not send reply, err=%d. Closing transport.\n",
ret);
set_bit(XPT_CLOSE, &rdma->sc_xprt.xpt_flags);
return -ENOTCONN;
}
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 mincore_unmapped_range(unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
walk->private += __mincore_unmapped_range(addr, end,
walk->vma, walk->private);
return 0;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: dissect_u3v_descriptors(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, void *data _U_)
{
guint8 type;
gint offset = 0;
proto_item * ti;
proto_tree * sub_tree;
guint32 version;
/* The descriptor must at least have a length and type field. */
if (tvb_reported_length(tvb) < 2) {
return 0;
}
/* skip len */
type = tvb_get_guint8(tvb, 1);
/* Check for U3V device info descriptor. */
if (type != DESCRIPTOR_TYPE_U3V_INTERFACE) {
return 0;
}
ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor);
/* bLength */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bLength, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* bDescriptorType */
ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bDescriptorType, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_item_append_text(ti, " (U3V INTERFACE)");
offset++;
/* bDescriptorSubtype */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bDescriptorSubtype, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* bGenCPVersion */
if (!tvb_bytes_exist(tvb, offset, 4)) {
/* Version not completely in buffer -> break dissection here. */
return offset;
}
version = tvb_get_letohl(tvb, offset);
ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bGenCPVersion, tvb, offset, 4, ENC_NA);
proto_item_append_text(ti, ": %u.%u", version >> 16, version & 0xFFFF);
sub_tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor_gencp_version);
proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bGenCPVersion_minor, tvb, offset, 4, ENC_LITTLE_ENDIAN);
proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bGenCPVersion_major, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* bU3VVersion */
if (!tvb_bytes_exist(tvb, offset, 4)) {
/* Version not completely in buffer -> break dissection here. */
return offset;
}
version = tvb_get_letohl(tvb, offset);
ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bU3VVersion, tvb, offset, 4, ENC_NA);
proto_item_append_text(ti, ": %u.%u", version >> 16, version & 0xFFFF);
sub_tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor_u3v_version);
proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bU3VVersion_minor, tvb, offset, 4, ENC_LITTLE_ENDIAN);
proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bU3VVersion_major, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
/* iDeviceGUID */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iDeviceGUID, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iVendorName */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iVendorName, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iModelName */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iModelName, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iFamilyName */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iFamilyName, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iDeviceVersion */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iDeviceVersion, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iManufacturerInfo */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iManufacturerInfo, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iSerialNumber */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iSerialNumber, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* iUserDefinedName */
proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iUserDefinedName, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* bmSpeedSupport */
proto_tree_add_bitmask(tree, tvb, offset, hf_u3v_device_info_descriptor_bmSpeedSupport,
ett_u3v_device_info_descriptor_speed_support, speed_support_fields, ENC_LITTLE_ENDIAN);
offset++;
return offset;
}
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: ops_expand(regex_t* reg, int n)
{
#define MIN_OPS_EXPAND_SIZE 4
#ifdef USE_DIRECT_THREADED_CODE
enum OpCode* cp;
#endif
Operation* p;
size_t size;
if (n <= 0) n = MIN_OPS_EXPAND_SIZE;
n += reg->ops_alloc;
size = sizeof(Operation) * n;
p = (Operation* )xrealloc(reg->ops, size);
CHECK_NULL_RETURN_MEMERR(p);
#ifdef USE_DIRECT_THREADED_CODE
size = sizeof(enum OpCode) * n;
cp = (enum OpCode* )xrealloc(reg->ocs, size);
CHECK_NULL_RETURN_MEMERR(cp);
reg->ocs = cp;
#endif
reg->ops = p;
reg->ops_alloc = n;
if (reg->ops_used == 0)
reg->ops_curr = 0;
else
reg->ops_curr = reg->ops + (reg->ops_used - 1);
return ONIG_NORMAL;
}
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: uint32 ResourceTracker::GetLiveObjectsForInstance(
PP_Instance instance) const {
InstanceMap::const_iterator found = instance_map_.find(instance);
if (found == instance_map_.end())
return 0;
return static_cast<uint32>(found->second->resources.size() +
found->second->object_vars.size());
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void BrowserView::UpdateDevToolsForContents(TabContents* tab_contents) {
DevToolsWindow* new_devtools_window = tab_contents ?
DevToolsWindow::GetDockedInstanceForInspectedTab(
tab_contents->web_contents()) : NULL;
if (devtools_window_ == new_devtools_window) {
if (!new_devtools_window ||
(new_devtools_window->dock_side() == devtools_dock_side_)) {
return;
}
}
if (devtools_window_ != new_devtools_window) {
devtools_container_->SetWebContents(new_devtools_window ?
new_devtools_window->tab_contents()->web_contents() : NULL);
}
if (devtools_window_) {
if (devtools_dock_side_ == DEVTOOLS_DOCK_SIDE_RIGHT) {
devtools_window_->SetWidth(
contents_split_->width() - contents_split_->divider_offset());
} else {
devtools_window_->SetHeight(
contents_split_->height() - contents_split_->divider_offset());
}
}
bool should_hide = devtools_window_ && (!new_devtools_window ||
devtools_dock_side_ != new_devtools_window->dock_side());
bool should_show = new_devtools_window && (!devtools_window_ || should_hide);
if (should_hide)
HideDevToolsContainer();
devtools_window_ = new_devtools_window;
if (should_show) {
devtools_dock_side_ = new_devtools_window->dock_side();
ShowDevToolsContainer();
} else if (new_devtools_window) {
UpdateDevToolsSplitPosition();
}
}
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 DownloadFileManager::RenameInProgressDownloadFile(
DownloadId global_id,
const FilePath& full_path,
bool overwrite_existing_file,
const RenameCompletionCallback& callback) {
VLOG(20) << __FUNCTION__ << "()" << " id = " << global_id
<< " full_path = \"" << full_path.value() << "\"";
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(callback, FilePath()));
return;
}
VLOG(20) << __FUNCTION__ << "()"
<< " download_file = " << download_file->DebugString();
FilePath new_path(full_path);
if (!overwrite_existing_file) {
int uniquifier =
file_util::GetUniquePathNumber(new_path, FILE_PATH_LITERAL(""));
if (uniquifier > 0) {
new_path = new_path.InsertBeforeExtensionASCII(
StringPrintf(" (%d)", uniquifier));
}
}
net::Error rename_error = download_file->Rename(new_path);
if (net::OK != rename_error) {
CancelDownloadOnRename(global_id, rename_error);
new_path.clear();
}
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(callback, new_path));
}
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: static void cstm(JF, js_Ast *stm)
{
js_Ast *target;
int loop, cont, then, end;
emitline(J, F, stm);
switch (stm->type) {
case AST_FUNDEC:
break;
case STM_BLOCK:
cstmlist(J, F, stm->a);
break;
case STM_EMPTY:
if (F->script) {
emit(J, F, OP_POP);
emit(J, F, OP_UNDEF);
}
break;
case STM_VAR:
cvarinit(J, F, stm->a);
break;
case STM_IF:
if (stm->c) {
cexp(J, F, stm->a);
then = emitjump(J, F, OP_JTRUE);
cstm(J, F, stm->c);
end = emitjump(J, F, OP_JUMP);
label(J, F, then);
cstm(J, F, stm->b);
label(J, F, end);
} else {
cexp(J, F, stm->a);
end = emitjump(J, F, OP_JFALSE);
cstm(J, F, stm->b);
label(J, F, end);
}
break;
case STM_DO:
loop = here(J, F);
cstm(J, F, stm->a);
cont = here(J, F);
cexp(J, F, stm->b);
emitjumpto(J, F, OP_JTRUE, loop);
labeljumps(J, F, stm->jumps, here(J,F), cont);
break;
case STM_WHILE:
loop = here(J, F);
cexp(J, F, stm->a);
end = emitjump(J, F, OP_JFALSE);
cstm(J, F, stm->b);
emitjumpto(J, F, OP_JUMP, loop);
label(J, F, end);
labeljumps(J, F, stm->jumps, here(J,F), loop);
break;
case STM_FOR:
case STM_FOR_VAR:
if (stm->type == STM_FOR_VAR) {
cvarinit(J, F, stm->a);
} else {
if (stm->a) {
cexp(J, F, stm->a);
emit(J, F, OP_POP);
}
}
loop = here(J, F);
if (stm->b) {
cexp(J, F, stm->b);
end = emitjump(J, F, OP_JFALSE);
} else {
end = 0;
}
cstm(J, F, stm->d);
cont = here(J, F);
if (stm->c) {
cexp(J, F, stm->c);
emit(J, F, OP_POP);
}
emitjumpto(J, F, OP_JUMP, loop);
if (end)
label(J, F, end);
labeljumps(J, F, stm->jumps, here(J,F), cont);
break;
case STM_FOR_IN:
case STM_FOR_IN_VAR:
cexp(J, F, stm->b);
emit(J, F, OP_ITERATOR);
loop = here(J, F);
{
emit(J, F, OP_NEXTITER);
end = emitjump(J, F, OP_JFALSE);
cassignforin(J, F, stm);
if (F->script) {
emit(J, F, OP_ROT2);
cstm(J, F, stm->c);
emit(J, F, OP_ROT2);
} else {
cstm(J, F, stm->c);
}
emitjumpto(J, F, OP_JUMP, loop);
}
label(J, F, end);
labeljumps(J, F, stm->jumps, here(J,F), loop);
break;
case STM_SWITCH:
cswitch(J, F, stm->a, stm->b);
labeljumps(J, F, stm->jumps, here(J,F), 0);
break;
case STM_LABEL:
cstm(J, F, stm->b);
/* skip consecutive labels */
while (stm->type == STM_LABEL)
stm = stm->b;
/* loops and switches have already been labelled */
if (!isloop(stm->type) && stm->type != STM_SWITCH)
labeljumps(J, F, stm->jumps, here(J,F), 0);
break;
case STM_BREAK:
if (stm->a) {
target = breaktarget(J, F, stm, stm->a->string);
if (!target)
jsC_error(J, stm, "break label '%s' not found", stm->a->string);
} else {
target = breaktarget(J, F, stm, NULL);
if (!target)
jsC_error(J, stm, "unlabelled break must be inside loop or switch");
}
cexit(J, F, STM_BREAK, stm, target);
addjump(J, F, STM_BREAK, target, emitjump(J, F, OP_JUMP));
break;
case STM_CONTINUE:
if (stm->a) {
target = continuetarget(J, F, stm, stm->a->string);
if (!target)
jsC_error(J, stm, "continue label '%s' not found", stm->a->string);
} else {
target = continuetarget(J, F, stm, NULL);
if (!target)
jsC_error(J, stm, "continue must be inside loop");
}
cexit(J, F, STM_CONTINUE, stm, target);
addjump(J, F, STM_CONTINUE, target, emitjump(J, F, OP_JUMP));
break;
case STM_RETURN:
if (stm->a)
cexp(J, F, stm->a);
else
emit(J, F, OP_UNDEF);
target = returntarget(J, F, stm);
if (!target)
jsC_error(J, stm, "return not in function");
cexit(J, F, STM_RETURN, stm, target);
emit(J, F, OP_RETURN);
break;
case STM_THROW:
cexp(J, F, stm->a);
emit(J, F, OP_THROW);
break;
case STM_WITH:
cexp(J, F, stm->a);
emit(J, F, OP_WITH);
cstm(J, F, stm->b);
emit(J, F, OP_ENDWITH);
break;
case STM_TRY:
if (stm->b && stm->c) {
if (stm->d)
ctrycatchfinally(J, F, stm->a, stm->b, stm->c, stm->d);
else
ctrycatch(J, F, stm->a, stm->b, stm->c);
} else {
ctryfinally(J, F, stm->a, stm->d);
}
break;
case STM_DEBUGGER:
emit(J, F, OP_DEBUGGER);
break;
default:
if (F->script) {
emit(J, F, OP_POP);
cexp(J, F, stm);
} else {
cexp(J, F, stm);
emit(J, F, OP_POP);
}
break;
}
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: FormAttributeTargetObserver::FormAttributeTargetObserver(const AtomicString& id, FormAssociatedElement* element)
: IdTargetObserver(toHTMLElement(element)->treeScope().idTargetObserverRegistry(), id)
, m_element(element)
{
}
CWE ID: CWE-287
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 parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
*ntime, header[228];
unsigned char *cb1 = NULL, *cb2 = NULL;
size_t cb1_len, cb2_len, alloc_len;
bool clean, ret = false;
int merkles, i;
json_t *arr;
arr = json_array_get(val, 4);
if (!arr || !json_is_array(arr))
goto out;
merkles = json_array_size(arr);
job_id = json_array_string(val, 0);
prev_hash = __json_array_string(val, 1);
coinbase1 = json_array_string(val, 2);
coinbase2 = json_array_string(val, 3);
bbversion = __json_array_string(val, 5);
nbit = __json_array_string(val, 6);
ntime = __json_array_string(val, 7);
clean = json_is_true(json_array_get(val, 8));
if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
/* Annoying but we must not leak memory */
if (job_id)
free(job_id);
if (coinbase1)
free(coinbase1);
if (coinbase2)
free(coinbase2);
goto out;
}
cg_wlock(&pool->data_lock);
free(pool->swork.job_id);
pool->swork.job_id = job_id;
snprintf(pool->prev_hash, 65, "%s", prev_hash);
cb1_len = strlen(coinbase1) / 2;
cb2_len = strlen(coinbase2) / 2;
snprintf(pool->bbversion, 9, "%s", bbversion);
snprintf(pool->nbit, 9, "%s", nbit);
snprintf(pool->ntime, 9, "%s", ntime);
pool->swork.clean = clean;
alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
pool->nonce2_offset = cb1_len + pool->n1_len;
for (i = 0; i < pool->merkles; i++)
free(pool->swork.merkle_bin[i]);
if (merkles) {
pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
sizeof(char *) * merkles + 1);
for (i = 0; i < merkles; i++) {
char *merkle = json_array_string(arr, i);
pool->swork.merkle_bin[i] = malloc(32);
if (unlikely(!pool->swork.merkle_bin[i]))
quit(1, "Failed to malloc pool swork merkle_bin");
if (opt_protocol)
applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
free(merkle);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
goto out_unlock;
}
}
}
pool->merkles = merkles;
if (clean)
pool->nonce2 = 0;
#if 0
header_len = strlen(pool->bbversion) +
strlen(pool->prev_hash);
/* merkle_hash */ 32 +
strlen(pool->ntime) +
strlen(pool->nbit) +
/* nonce */ 8 +
/* workpadding */ 96;
#endif
snprintf(header, 225,
"%s%s%s%s%s%s%s",
pool->bbversion,
pool->prev_hash,
blank_merkle,
pool->ntime,
pool->nbit,
"00000000", /* nonce */
workpadding);
ret = hex2bin(pool->header_bin, header, 112);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
goto out_unlock;
}
cb1 = alloca(cb1_len);
ret = hex2bin(cb1, coinbase1, cb1_len);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
goto out_unlock;
}
cb2 = alloca(cb2_len);
ret = hex2bin(cb2, coinbase2, cb2_len);
if (unlikely(!ret)) {
applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
goto out_unlock;
}
free(pool->coinbase);
align_len(&alloc_len);
pool->coinbase = calloc(alloc_len, 1);
if (unlikely(!pool->coinbase))
quit(1, "Failed to calloc pool coinbase in parse_notify");
memcpy(pool->coinbase, cb1, cb1_len);
memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
if (opt_debug) {
char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
free(cb);
}
out_unlock:
cg_wunlock(&pool->data_lock);
if (opt_protocol) {
applog(LOG_DEBUG, "job_id: %s", job_id);
applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
applog(LOG_DEBUG, "bbversion: %s", bbversion);
applog(LOG_DEBUG, "nbit: %s", nbit);
applog(LOG_DEBUG, "ntime: %s", ntime);
applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
}
free(coinbase1);
free(coinbase2);
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
if (pool == current_pool())
opt_work_update = true;
out:
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: check_entry_size_and_hooks(struct ip6t_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) {
uint8_t ead, eal, fcs;
uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset;
uint8_t* p_start = p_data;
uint16_t len;
if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) {
RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len);
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data);
if (!ead) {
RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)");
return (RFC_EVENT_BAD_FRAME);
}
RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data);
RFCOMM_PARSE_LEN_FIELD(eal, len, p_data);
p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */
p_buf->offset += (3 + !ead + !eal);
/* handle credit if credit based flow control */
if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) &&
(p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) {
p_frame->credit = *p_data++;
p_buf->len--;
p_buf->offset++;
} else
p_frame->credit = 0;
if (p_buf->len != len) {
RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len);
return (RFC_EVENT_BAD_FRAME);
}
fcs = *(p_data + len);
/* All control frames that we are sending are sent with P=1, expect */
/* reply with F=1 */
/* According to TS 07.10 spec ivalid frames are discarded without */
/* notification to the sender */
switch (p_frame->type) {
case RFCOMM_SABME:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad SABME");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_SABME);
case RFCOMM_UA:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UA");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_UA);
case RFCOMM_DM:
if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len ||
!RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DM");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DM);
case RFCOMM_DISC:
if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) ||
!p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) ||
!rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad DISC");
return (RFC_EVENT_BAD_FRAME);
} else
return (RFC_EVENT_DISC);
case RFCOMM_UIH:
if (!RFCOMM_VALID_DLCI(p_frame->dlci)) {
RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI");
return (RFC_EVENT_BAD_FRAME);
} else if (!rfc_check_fcs(2, p_start, fcs)) {
RFCOMM_TRACE_ERROR("Bad UIH - FCS");
return (RFC_EVENT_BAD_FRAME);
} else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) {
/* we assume that this is ok to allow bad implementations to work */
RFCOMM_TRACE_ERROR("Bad UIH - response");
return (RFC_EVENT_UIH);
} else
return (RFC_EVENT_UIH);
}
return (RFC_EVENT_BAD_FRAME);
}
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 kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
{
int r;
r = vcpu_load(vcpu);
BUG_ON(r);
kvm_mmu_unload(vcpu);
vcpu_put(vcpu);
}
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 MojoVideoEncodeAccelerator::Encode(const scoped_refptr<VideoFrame>& frame,
bool force_keyframe) {
DVLOG(2) << __func__ << " tstamp=" << frame->timestamp();
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK_EQ(PIXEL_FORMAT_I420, frame->format());
DCHECK_EQ(VideoFrame::STORAGE_SHMEM, frame->storage_type());
DCHECK(frame->shared_memory_handle().IsValid());
const size_t allocation_size = frame->shared_memory_handle().GetSize();
mojo::ScopedSharedBufferHandle handle =
mojo::WrapSharedMemoryHandle(frame->shared_memory_handle().Duplicate(),
allocation_size, true /* read_only */);
const size_t y_offset = frame->shared_memory_offset();
const size_t u_offset = y_offset + frame->data(VideoFrame::kUPlane) -
frame->data(VideoFrame::kYPlane);
const size_t v_offset = y_offset + frame->data(VideoFrame::kVPlane) -
frame->data(VideoFrame::kYPlane);
scoped_refptr<MojoSharedBufferVideoFrame> mojo_frame =
MojoSharedBufferVideoFrame::Create(
frame->format(), frame->coded_size(), frame->visible_rect(),
frame->natural_size(), std::move(handle), allocation_size, y_offset,
u_offset, v_offset, frame->stride(VideoFrame::kYPlane),
frame->stride(VideoFrame::kUPlane),
frame->stride(VideoFrame::kVPlane), frame->timestamp());
DCHECK(vea_.is_bound());
vea_->Encode(mojo_frame, force_keyframe,
base::Bind(&KeepVideoFrameAlive, frame));
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: bool Send(IPC::Message* msg) { return render_frame_host->Send(msg); }
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: struct svc_rdma_req_map *svc_rdma_get_req_map(struct svcxprt_rdma *xprt)
{
struct svc_rdma_req_map *map = NULL;
spin_lock(&xprt->sc_map_lock);
if (list_empty(&xprt->sc_maps))
goto out_empty;
map = list_first_entry(&xprt->sc_maps,
struct svc_rdma_req_map, free);
list_del_init(&map->free);
spin_unlock(&xprt->sc_map_lock);
out:
map->count = 0;
return map;
out_empty:
spin_unlock(&xprt->sc_map_lock);
/* Pre-allocation amount was incorrect */
map = alloc_req_map(GFP_NOIO);
if (map)
goto out;
WARN_ONCE(1, "svcrdma: empty request map list?\n");
return NULL;
}
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: void FrameSelection::MoveRangeSelection(const VisiblePosition& base_position,
const VisiblePosition& extent_position,
TextGranularity granularity) {
SelectionInDOMTree new_selection =
SelectionInDOMTree::Builder()
.SetBaseAndExtentDeprecated(base_position.DeepEquivalent(),
extent_position.DeepEquivalent())
.SetAffinity(base_position.Affinity())
.SetIsHandleVisible(IsHandleVisible())
.Build();
if (new_selection.IsNone())
return;
const VisibleSelection& visible_selection =
CreateVisibleSelectionWithGranularity(new_selection, granularity);
if (visible_selection.IsNone())
return;
SelectionInDOMTree::Builder builder;
if (visible_selection.IsBaseFirst()) {
builder.SetBaseAndExtent(visible_selection.Start(),
visible_selection.End());
} else {
builder.SetBaseAndExtent(visible_selection.End(),
visible_selection.Start());
}
builder.SetAffinity(visible_selection.Affinity());
builder.SetIsHandleVisible(IsHandleVisible());
SetSelection(builder.Build(), SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetGranularity(granularity)
.Build());
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void V8TestObject::DoubleAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_doubleAttribute_Getter");
test_object_v8_internal::DoubleAttributeAttributeGetter(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: std::string utf16ToUtf8(const StringPiece16& utf16) {
ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
if (utf8Length <= 0) {
return {};
}
std::string utf8;
utf8.resize(utf8Length);
utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin());
return utf8;
}
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: bit_catenate(VarBit *arg1, VarBit *arg2)
{
VarBit *result;
int bitlen1,
bitlen2,
bytelen,
bit1pad,
bit2shift;
bits8 *pr,
*pa;
bitlen1 = VARBITLEN(arg1);
bitlen2 = VARBITLEN(arg2);
bytelen = VARBITTOTALLEN(bitlen1 + bitlen2);
result = (VarBit *) palloc(bytelen);
SET_VARSIZE(result, bytelen);
VARBITLEN(result) = bitlen1 + bitlen2;
/* Copy the first bitstring in */
memcpy(VARBITS(result), VARBITS(arg1), VARBITBYTES(arg1));
/* Copy the second bit string */
bit1pad = VARBITPAD(arg1);
if (bit1pad == 0)
{
memcpy(VARBITS(result) + VARBITBYTES(arg1), VARBITS(arg2),
VARBITBYTES(arg2));
}
else if (bitlen2 > 0)
{
/* We need to shift all the bits to fit */
bit2shift = BITS_PER_BYTE - bit1pad;
pr = VARBITS(result) + VARBITBYTES(arg1) - 1;
for (pa = VARBITS(arg2); pa < VARBITEND(arg2); pa++)
{
*pr |= ((*pa >> bit2shift) & BITMASK);
pr++;
if (pr < VARBITEND(result))
*pr = (*pa << bit1pad) & BITMASK;
}
}
return result;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: ModuleExport size_t RegisterVIFFImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("VIFF","VIFF","Khoros Visualization image");
entry->decoder=(DecodeImageHandler *) ReadVIFFImage;
entry->encoder=(EncodeImageHandler *) WriteVIFFImage;
entry->magick=(IsImageFormatHandler *) IsVIFF;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("VIFF","XV","Khoros Visualization image");
entry->decoder=(DecodeImageHandler *) ReadVIFFImage;
entry->encoder=(EncodeImageHandler *) WriteVIFFImage;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
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 rekey_seq_generator(struct work_struct *work)
{
struct keydata *keyptr = &ip_keydata[1 ^ (ip_cnt & 1)];
get_random_bytes(keyptr->secret, sizeof(keyptr->secret));
keyptr->count = (ip_cnt & COUNT_MASK) << HASH_BITS;
smp_wmb();
ip_cnt++;
schedule_delayed_work(&rekey_work,
round_jiffies_relative(REKEY_INTERVAL));
}
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: int proxy_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC)
{
zval **login, **password;
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login"), (void **)&login) == SUCCESS) {
unsigned char* buf;
int len;
smart_str auth = {0};
smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login));
smart_str_appendc(&auth, ':');
if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password"), (void **)&password) == SUCCESS) {
smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password));
}
smart_str_0(&auth);
smart_str_appendl(soap_headers, (char*)buf, len);
smart_str_append_const(soap_headers, "\r\n");
efree(buf);
smart_str_free(&auth);
return 1;
}
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: void TabStripModel::ForgetAllOpeners() {
TabContentsDataVector::const_iterator iter = contents_data_.begin();
for (; iter != contents_data_.end(); ++iter)
(*iter)->ForgetOpener();
}
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: __xml_private_clean(xml_private_t *p)
{
if(p) {
CRM_ASSERT(p->check == XML_PRIVATE_MAGIC);
free(p->user);
p->user = NULL;
if(p->acls) {
g_list_free_full(p->acls, __xml_acl_free);
p->acls = NULL;
}
if(p->deleted_paths) {
g_list_free_full(p->deleted_paths, free);
p->deleted_paths = NULL;
}
}
}
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* H264SwDecMalloc(u32 size) {
return malloc(size);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int lzo_compress(struct crypto_tfm *tfm, const u8 *src,
unsigned int slen, u8 *dst, unsigned int *dlen)
{
struct lzo_ctx *ctx = crypto_tfm_ctx(tfm);
size_t tmp_len = *dlen; /* size_t(ulong) <-> uint on 64 bit */
int err;
err = lzo1x_1_compress(src, slen, dst, &tmp_len, ctx->lzo_comp_mem);
if (err != LZO_E_OK)
return -EINVAL;
*dlen = tmp_len;
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: void* Type_MPE_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return (void*) cmsPipelineDup((cmsPipeline*) Ptr);
cmsUNUSED_PARAMETER(n);
cmsUNUSED_PARAMETER(self);
}
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 int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
{
struct tun_struct *tun;
struct tun_file *tfile = file->private_data;
struct net_device *dev;
int err;
if (tfile->detached)
return -EINVAL;
dev = __dev_get_by_name(net, ifr->ifr_name);
if (dev) {
if (ifr->ifr_flags & IFF_TUN_EXCL)
return -EBUSY;
if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
tun = netdev_priv(dev);
else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
tun = netdev_priv(dev);
else
return -EINVAL;
if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
!!(tun->flags & IFF_MULTI_QUEUE))
return -EINVAL;
if (tun_not_capable(tun))
return -EPERM;
err = security_tun_dev_open(tun->security);
if (err < 0)
return err;
err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);
if (err < 0)
return err;
if (tun->flags & IFF_MULTI_QUEUE &&
(tun->numqueues + tun->numdisabled > 1)) {
/* One or more queue has already been attached, no need
* to initialize the device again.
*/
return 0;
}
}
else {
char *name;
unsigned long flags = 0;
int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
MAX_TAP_QUEUES : 1;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
err = security_tun_dev_create();
if (err < 0)
return err;
/* Set dev type */
if (ifr->ifr_flags & IFF_TUN) {
/* TUN device */
flags |= IFF_TUN;
name = "tun%d";
} else if (ifr->ifr_flags & IFF_TAP) {
/* TAP device */
flags |= IFF_TAP;
name = "tap%d";
} else
return -EINVAL;
if (*ifr->ifr_name)
name = ifr->ifr_name;
dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
NET_NAME_UNKNOWN, tun_setup, queues,
queues);
if (!dev)
return -ENOMEM;
dev_net_set(dev, net);
dev->rtnl_link_ops = &tun_link_ops;
dev->ifindex = tfile->ifindex;
dev->sysfs_groups[0] = &tun_attr_group;
tun = netdev_priv(dev);
tun->dev = dev;
tun->flags = flags;
tun->txflt.count = 0;
tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
tun->align = NET_SKB_PAD;
tun->filter_attached = false;
tun->sndbuf = tfile->socket.sk->sk_sndbuf;
tun->rx_batched = 0;
tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
if (!tun->pcpu_stats) {
err = -ENOMEM;
goto err_free_dev;
}
spin_lock_init(&tun->lock);
err = security_tun_dev_alloc_security(&tun->security);
if (err < 0)
goto err_free_stat;
tun_net_init(dev);
tun_flow_init(tun);
dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX;
dev->features = dev->hw_features | NETIF_F_LLTX;
dev->vlan_features = dev->features &
~(NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX);
INIT_LIST_HEAD(&tun->disabled);
err = tun_attach(tun, file, false);
if (err < 0)
goto err_free_flow;
err = register_netdevice(tun->dev);
if (err < 0)
goto err_detach;
}
netif_carrier_on(tun->dev);
tun_debug(KERN_INFO, tun, "tun_set_iff\n");
tun->flags = (tun->flags & ~TUN_FEATURES) |
(ifr->ifr_flags & TUN_FEATURES);
/* Make sure persistent devices do not get stuck in
* xoff state.
*/
if (netif_running(tun->dev))
netif_tx_wake_all_queues(tun->dev);
strcpy(ifr->ifr_name, tun->dev->name);
return 0;
err_detach:
tun_detach_all(dev);
/* register_netdevice() already called tun_free_netdev() */
goto err_free_dev;
err_free_flow:
tun_flow_uninit(tun);
security_tun_dev_free_security(tun->security);
err_free_stat:
free_percpu(tun->pcpu_stats);
err_free_dev:
free_netdev(dev);
return err;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void bn_GF2m_mul_1x1(BN_ULONG *r1, BN_ULONG *r0, const BN_ULONG a,
const BN_ULONG b)
{
register BN_ULONG h, l, s;
BN_ULONG tab[8], top2b = a >> 30;
register BN_ULONG a1, a2, a4;
a1 = a & (0x3FFFFFFF);
a2 = a1 << 1;
a4 = a2 << 1;
tab[0] = 0;
tab[1] = a1;
tab[2] = a2;
tab[3] = a1 ^ a2;
tab[4] = a4;
tab[5] = a1 ^ a4;
tab[6] = a2 ^ a4;
tab[7] = a1 ^ a2 ^ a4;
s = tab[b & 0x7];
l = s;
s = tab[b >> 3 & 0x7];
l ^= s << 3;
h = s >> 29;
s = tab[b >> 6 & 0x7];
l ^= s << 6;
h ^= s >> 26;
s = tab[b >> 9 & 0x7];
l ^= s << 9;
h ^= s >> 23;
s = tab[b >> 12 & 0x7];
l ^= s << 12;
h ^= s >> 20;
s = tab[b >> 15 & 0x7];
l ^= s << 15;
h ^= s >> 17;
s = tab[b >> 18 & 0x7];
l ^= s << 18;
h ^= s >> 14;
s = tab[b >> 21 & 0x7];
l ^= s << 21;
h ^= s >> 11;
s = tab[b >> 24 & 0x7];
l ^= s << 24;
h ^= s >> 8;
s = tab[b >> 27 & 0x7];
l ^= s << 27;
h ^= s >> 5;
s = tab[b >> 30];
l ^= s << 30;
h ^= s >> 2;
/* compensate for the top two bits of a */
if (top2b & 01) {
l ^= b << 30;
h ^= b >> 2;
}
if (top2b & 02) {
l ^= b << 31;
h ^= b >> 1;
}
*r1 = h;
*r0 = l;
}
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: T1_ToBool( PS_Parser parser )
{
return ps_tobool( &parser->cursor, parser->limit );
}
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 icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb)
{
struct ipcm_cookie ipc;
struct rtable *rt = skb_rtable(skb);
struct net *net = dev_net(rt->dst.dev);
struct sock *sk;
struct inet_sock *inet;
__be32 daddr;
if (ip_options_echo(&icmp_param->replyopts, skb))
return;
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
inet = inet_sk(sk);
icmp_param->data.icmph.checksum = 0;
inet->tos = ip_hdr(skb)->tos;
daddr = ipc.addr = rt->rt_src;
ipc.opt = NULL;
ipc.tx_flags = 0;
if (icmp_param->replyopts.optlen) {
ipc.opt = &icmp_param->replyopts;
if (ipc.opt->srr)
daddr = icmp_param->replyopts.faddr;
}
{
struct flowi4 fl4 = {
.daddr = daddr,
.saddr = rt->rt_spec_dst,
.flowi4_tos = RT_TOS(ip_hdr(skb)->tos),
.flowi4_proto = IPPROTO_ICMP,
};
security_skb_classify_flow(skb, flowi4_to_flowi(&fl4));
rt = ip_route_output_key(net, &fl4);
if (IS_ERR(rt))
goto out_unlock;
}
if (icmpv4_xrlim_allow(net, rt, icmp_param->data.icmph.type,
icmp_param->data.icmph.code))
icmp_push_reply(icmp_param, &ipc, &rt);
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: HTMLFormControlElement* HTMLFormElement::defaultButton() const
{
for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
if (!m_associatedElements[i]->isFormControlElement())
continue;
HTMLFormControlElement* control = toHTMLFormControlElement(m_associatedElements[i]);
if (control->isSuccessfulSubmitButton())
return control;
}
return 0;
}
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: Ins_FLIPRGON( TT_ExecContext exc,
FT_Long* args )
{
FT_UShort I, K, L;
#ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL
/* See `ttinterp.h' for details on backward compatibility mode. */
if ( SUBPIXEL_HINTING_MINIMAL &&
exc->backward_compatibility &&
exc->iupx_called &&
exc->iupy_called )
return;
#endif
K = (FT_UShort)args[1];
L = (FT_UShort)args[0];
if ( BOUNDS( K, exc->pts.n_points ) ||
BOUNDS( L, exc->pts.n_points ) )
{
if ( exc->pedantic_hinting )
exc->error = FT_THROW( Invalid_Reference );
return;
}
for ( I = L; I <= K; I++ )
exc->pts.tags[I] |= FT_CURVE_TAG_ON;
}
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: int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = s->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_table, new_l1_bytes);
if (ret < 0) {
error_setg(errp, "Failed to read l1 table for snapshot");
g_free(new_l1_table);
return ret;
}
/* Switch the L1 table */
g_free(s->l1_table);
s->l1_size = sn->l1_size;
s->l1_table_offset = sn->l1_table_offset;
s->l1_table = new_l1_table;
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void testUriComponents() {
UriParserStateA stateA;
UriUriA uriA;
stateA.uri = &uriA;
const char * const input = "http" "://" "sourceforge.net" "/" "project" "/"
"platformdownload.php" "?" "group_id=182840";
TEST_ASSERT(0 == uriParseUriA(&stateA, input));
TEST_ASSERT(uriA.scheme.first == input);
TEST_ASSERT(uriA.scheme.afterLast == input + 4);
TEST_ASSERT(uriA.userInfo.first == NULL);
TEST_ASSERT(uriA.userInfo.afterLast == NULL);
TEST_ASSERT(uriA.hostText.first == input + 4 + 3);
TEST_ASSERT(uriA.hostText.afterLast == input + 4 + 3 + 15);
TEST_ASSERT(uriA.hostData.ipFuture.first == NULL);
TEST_ASSERT(uriA.hostData.ipFuture.afterLast == NULL);
TEST_ASSERT(uriA.portText.first == NULL);
TEST_ASSERT(uriA.portText.afterLast == NULL);
TEST_ASSERT(uriA.pathHead->text.first == input + 4 + 3 + 15 + 1);
TEST_ASSERT(uriA.pathHead->text.afterLast == input + 4 + 3 + 15 + 1 + 7);
TEST_ASSERT(uriA.pathHead->next->text.first == input + 4 + 3 + 15 + 1 + 7 + 1);
TEST_ASSERT(uriA.pathHead->next->text.afterLast == input + 4 + 3 + 15 + 1 + 7 + 1 + 20);
TEST_ASSERT(uriA.pathHead->next->next == NULL);
TEST_ASSERT(uriA.pathTail == uriA.pathHead->next);
TEST_ASSERT(uriA.query.first == input + 4 + 3 + 15 + 1 + 7 + 1 + 20 + 1);
TEST_ASSERT(uriA.query.afterLast == input + 4 + 3 + 15 + 1 + 7 + 1 + 20 + 1 + 15);
TEST_ASSERT(uriA.fragment.first == NULL);
TEST_ASSERT(uriA.fragment.afterLast == NULL);
uriFreeUriMembersA(&uriA);
}
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: SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
{
struct kioctx *ioctx = NULL;
unsigned long ctx;
long ret;
ret = get_user(ctx, ctxp);
if (unlikely(ret))
goto out;
ret = -EINVAL;
if (unlikely(ctx || nr_events == 0)) {
pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
ctx, nr_events);
goto out;
}
ioctx = ioctx_alloc(nr_events);
ret = PTR_ERR(ioctx);
if (!IS_ERR(ioctx)) {
ret = put_user(ioctx->user_id, ctxp);
if (ret)
io_destroy(ioctx);
put_ioctx(ioctx);
}
out:
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: int handle_popc(u32 insn, struct pt_regs *regs)
{
u64 value;
int ret, i, rd = ((insn >> 25) & 0x1f);
int from_kernel = (regs->tstate & TSTATE_PRIV) != 0;
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);
if (insn & 0x2000) {
maybe_flush_windows(0, 0, rd, from_kernel);
value = sign_extend_imm13(insn);
} else {
maybe_flush_windows(0, insn & 0x1f, rd, from_kernel);
value = fetch_reg(insn & 0x1f, regs);
}
for (ret = 0, i = 0; i < 16; i++) {
ret += popc_helper[value & 0xf];
value >>= 4;
}
if (rd < 16) {
if (rd)
regs->u_regs[rd] = ret;
} else {
if (test_thread_flag(TIF_32BIT)) {
struct reg_window32 __user *win32;
win32 = (struct reg_window32 __user *)((unsigned long)((u32)regs->u_regs[UREG_FP]));
put_user(ret, &win32->locals[rd - 16]);
} else {
struct reg_window __user *win;
win = (struct reg_window __user *)(regs->u_regs[UREG_FP] + STACK_BIAS);
put_user(ret, &win->locals[rd - 16]);
}
}
advance(regs);
return 1;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: String AudioHandler::ChannelInterpretation() {
switch (new_channel_interpretation_) {
case AudioBus::kSpeakers:
return "speakers";
case AudioBus::kDiscrete:
return "discrete";
}
NOTREACHED();
return "";
}
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: void CustomButton::GetAccessibleState(ui::AXViewState* state) {
Button::GetAccessibleState(state);
switch (state_) {
case STATE_HOVERED:
state->AddStateFlag(ui::AX_STATE_HOVERED);
break;
case STATE_PRESSED:
state->AddStateFlag(ui::AX_STATE_PRESSED);
break;
case STATE_DISABLED:
state->AddStateFlag(ui::AX_STATE_DISABLED);
break;
case STATE_NORMAL:
case STATE_COUNT:
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: void TaskManagerView::Init() {
table_model_.reset(new TaskManagerTableModel(model_));
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_TASK_COLUMN,
ui::TableColumn::LEFT, -1, 1));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN,
ui::TableColumn::LEFT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PHYSICAL_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SHARED_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_CPU_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_NET_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_PROCESS_ID_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(
IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(
IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_FPS_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(ui::TableColumn(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
columns_.push_back(
ui::TableColumn(IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN,
ui::TableColumn::RIGHT, -1, 0));
columns_.back().sortable = true;
tab_table_ = new BackgroundColorGroupTableView(
table_model_.get(), columns_, highlight_background_resources_);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROFILE_NAME_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PROCESS_ID_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SHARED_MEM_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_PRIVATE_MEM_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_IMAGE_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_SCRIPTS_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_WEBCORE_CSS_CACHE_COLUMN,
false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_SQLITE_MEMORY_USED_COLUMN,
false);
tab_table_->SetColumnVisibility(
IDS_TASK_MANAGER_JAVASCRIPT_MEMORY_ALLOCATED_COLUMN, false);
tab_table_->SetColumnVisibility(IDS_TASK_MANAGER_GOATS_TELEPORTED_COLUMN,
false);
UpdateStatsCounters();
tab_table_->SetObserver(this);
tab_table_->set_context_menu_controller(this);
set_context_menu_controller(this);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kPurgeMemoryButton)) {
purge_memory_button_ = new views::NativeTextButton(this,
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_PURGE_MEMORY));
}
kill_button_ = new views::NativeTextButton(
this, l10n_util::GetStringUTF16(IDS_TASK_MANAGER_KILL));
kill_button_->AddAccelerator(ui::Accelerator(ui::VKEY_E, false, false,
false));
kill_button_->SetAccessibleKeyboardShortcut(L"E");
kill_button_->set_prefix_type(views::TextButtonBase::PREFIX_SHOW);
about_memory_link_ = new views::Link(
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_ABOUT_MEMORY_LINK));
about_memory_link_->set_listener(this);
OnSelectionChanged();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void WebsiteSettingsPopupView::HandleLinkClickedAsync(views::Link* source) {
if (source == cookie_dialog_link_) {
presenter_->RecordWebsiteSettingsAction(
WebsiteSettings::WEBSITE_SETTINGS_COOKIES_DIALOG_OPENED);
if (web_contents_ != NULL)
new CollectedCookiesViews(web_contents_);
} else if (source == certificate_dialog_link_) {
gfx::NativeWindow parent = GetAnchorView() ?
GetAnchorView()->GetWidget()->GetNativeWindow() : nullptr;
presenter_->RecordWebsiteSettingsAction(
WebsiteSettings::WEBSITE_SETTINGS_CERTIFICATE_DIALOG_OPENED);
ShowCertificateViewerByID(web_contents_, parent, cert_id_);
} else if (source == help_center_link_) {
web_contents_->OpenURL(content::OpenURLParams(
GURL(chrome::kPageInfoHelpCenterURL), content::Referrer(),
NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_LINK, false));
presenter_->RecordWebsiteSettingsAction(
WebsiteSettings::WEBSITE_SETTINGS_CONNECTION_HELP_OPENED);
} else if (source == site_settings_link_) {
web_contents_->OpenURL(content::OpenURLParams(
GURL(chrome::kChromeUIContentSettingsURL), content::Referrer(),
NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_LINK, false));
presenter_->RecordWebsiteSettingsAction(
WebsiteSettings::WEBSITE_SETTINGS_SITE_SETTINGS_OPENED);
} else {
NOTREACHED();
}
}
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 ClipboardMessageFilter::OnReadImage(ui::ClipboardType type,
IPC::Message* reply_msg) {
SkBitmap bitmap = GetClipboard()->ReadImage(type);
#if defined(USE_X11)
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(
&ClipboardMessageFilter::OnReadImageReply, this, bitmap, reply_msg));
#else
OnReadImageReply(bitmap, reply_msg);
#endif
}
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: pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,
int atomic)
{
unsigned long copy;
while (len > 0) {
while (!iov->iov_len)
iov++;
copy = min_t(unsigned long, len, iov->iov_len);
if (atomic) {
if (__copy_to_user_inatomic(iov->iov_base, from, copy))
return -EFAULT;
} else {
if (copy_to_user(iov->iov_base, from, copy))
return -EFAULT;
}
from += copy;
len -= copy;
iov->iov_base += copy;
iov->iov_len -= copy;
}
return 0;
}
CWE ID: CWE-17
Target: 1
Example 2:
Code: int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r)
{
return(ASN1_item_verify(ASN1_ITEM_rptr(NETSCAPE_SPKAC),
a->sig_algor,a->signature,a->spkac,r));
}
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: ExecCommand(const WCHAR *argv0, const WCHAR *cmdline, DWORD timeout)
{
DWORD exit_code;
STARTUPINFOW si;
PROCESS_INFORMATION pi;
DWORD proc_flags = CREATE_NO_WINDOW|CREATE_UNICODE_ENVIRONMENT;
WCHAR *cmdline_dup = NULL;
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
/* CreateProcess needs a modifiable cmdline: make a copy */
cmdline_dup = wcsdup(cmdline);
if (cmdline_dup && CreateProcessW(argv0, cmdline_dup, NULL, NULL, FALSE,
proc_flags, NULL, NULL, &si, &pi) )
{
WaitForSingleObject(pi.hProcess, timeout ? timeout : INFINITE);
if (!GetExitCodeProcess(pi.hProcess, &exit_code))
{
MsgToEventLog(M_SYSERR, TEXT("ExecCommand: Error getting exit_code:"));
exit_code = GetLastError();
}
else if (exit_code == STILL_ACTIVE)
{
exit_code = WAIT_TIMEOUT; /* Windows error code 0x102 */
/* kill without impunity */
TerminateProcess(pi.hProcess, exit_code);
MsgToEventLog(M_ERR, TEXT("ExecCommand: \"%s %s\" killed after timeout"),
argv0, cmdline);
}
else if (exit_code)
{
MsgToEventLog(M_ERR, TEXT("ExecCommand: \"%s %s\" exited with status = %lu"),
argv0, cmdline, exit_code);
}
else
{
MsgToEventLog(M_INFO, TEXT("ExecCommand: \"%s %s\" completed"), argv0, cmdline);
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else
{
exit_code = GetLastError();
MsgToEventLog(M_SYSERR, TEXT("ExecCommand: could not run \"%s %s\" :"),
argv0, cmdline);
}
free(cmdline_dup);
return exit_code;
}
CWE ID: CWE-415
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 SyncManager::SyncInternal::OnIPAddressChanged() {
DVLOG(1) << "IP address change detected";
if (!observing_ip_address_changes_) {
DVLOG(1) << "IP address change dropped.";
return;
}
#if defined (OS_CHROMEOS)
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&SyncInternal::OnIPAddressChangedImpl,
weak_ptr_factory_.GetWeakPtr()),
kChromeOSNetworkChangeReactionDelayHackMsec);
#else
OnIPAddressChangedImpl();
#endif // defined(OS_CHROMEOS)
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void free_nested(struct vcpu_vmx *vmx)
{
if (!vmx->nested.vmxon)
return;
vmx->nested.vmxon = false;
free_vpid(vmx->nested.vpid02);
nested_release_vmcs12(vmx);
if (vmx->nested.msr_bitmap) {
free_page((unsigned long)vmx->nested.msr_bitmap);
vmx->nested.msr_bitmap = NULL;
}
if (enable_shadow_vmcs) {
vmcs_clear(vmx->vmcs01.shadow_vmcs);
free_vmcs(vmx->vmcs01.shadow_vmcs);
vmx->vmcs01.shadow_vmcs = NULL;
}
kfree(vmx->nested.cached_vmcs12);
/* Unpin physical memory we referred to in current vmcs02 */
if (vmx->nested.apic_access_page) {
nested_release_page(vmx->nested.apic_access_page);
vmx->nested.apic_access_page = NULL;
}
if (vmx->nested.virtual_apic_page) {
nested_release_page(vmx->nested.virtual_apic_page);
vmx->nested.virtual_apic_page = NULL;
}
if (vmx->nested.pi_desc_page) {
kunmap(vmx->nested.pi_desc_page);
nested_release_page(vmx->nested.pi_desc_page);
vmx->nested.pi_desc_page = NULL;
vmx->nested.pi_desc = NULL;
}
nested_free_all_saved_vmcss(vmx);
}
CWE ID: CWE-388
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 reds_mig_finished(int completed)
{
spice_info(NULL);
reds->mig_inprogress = TRUE;
if (reds->src_do_seamless_migrate && completed) {
reds_migrate_channels_seamless();
} else {
main_channel_migrate_src_complete(reds->main_channel, completed);
}
if (completed) {
reds_mig_fill_wait_disconnect();
} else {
reds_mig_cleanup();
}
reds_mig_release();
}
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 HistogramsCallback() {
MockHistogramsCallback();
QuitMessageLoop();
}
CWE ID: CWE-94
Target: 1
Example 2:
Code: bt_status_t btsock_l2cap_cleanup()
{
pthread_mutex_lock(&state_lock);
pth = -1;
while (socks)
btsock_l2cap_free_l(socks);
pthread_mutex_unlock(&state_lock);
return BT_STATUS_SUCCESS;
}
CWE ID: CWE-284
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: QQuickWebViewFlickablePrivate::~QQuickWebViewFlickablePrivate()
{
m_viewportHandler->disconnect();
}
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: void InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params,
int nav_entry_id,
bool did_create_new_entry,
const GURL& url,
ui::PageTransition transition) {
params->nav_entry_id = nav_entry_id;
params->url = url;
params->referrer = Referrer();
params->transition = transition;
params->redirects = std::vector<GURL>();
params->should_update_history = false;
params->searchable_form_url = GURL();
params->searchable_form_encoding = std::string();
params->did_create_new_entry = did_create_new_entry;
params->gesture = NavigationGestureUser;
params->was_within_same_document = false;
params->method = "GET";
params->page_state = PageState::CreateFromURL(url);
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: Ins_MD( INS_ARG )
{
FT_UShort K, L;
FT_F26Dot6 D;
K = (FT_UShort)args[1];
L = (FT_UShort)args[0];
if( BOUNDS( L, CUR.zp0.n_points ) ||
BOUNDS( K, CUR.zp1.n_points ) )
{
if ( CUR.pedantic_hinting )
{
CUR.error = TT_Err_Invalid_Reference;
return;
}
D = 0;
}
else
{
if ( CUR.opcode & 1 )
D = CUR_Func_project( CUR.zp0.cur + L, CUR.zp1.cur + K );
else
{
FT_Vector* vec1 = CUR.zp0.orus + L;
FT_Vector* vec2 = CUR.zp1.orus + K;
if ( CUR.metrics.x_scale == CUR.metrics.y_scale )
{
/* this should be faster */
D = CUR_Func_dualproj( vec1, vec2 );
D = TT_MULFIX( D, CUR.metrics.x_scale );
}
else
{
FT_Vector vec;
vec.x = TT_MULFIX( vec1->x - vec2->x, CUR.metrics.x_scale );
vec.y = TT_MULFIX( vec1->y - vec2->y, CUR.metrics.y_scale );
D = CUR_fast_dualproj( &vec );
}
}
}
args[0] = D;
}
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 _snd_timer_stop(struct snd_timer_instance * timeri,
int keep_flag, int event)
{
struct snd_timer *timer;
unsigned long flags;
if (snd_BUG_ON(!timeri))
return -ENXIO;
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) {
if (!keep_flag) {
spin_lock_irqsave(&slave_active_lock, flags);
timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
spin_unlock_irqrestore(&slave_active_lock, flags);
}
goto __end;
}
timer = timeri->timer;
if (!timer)
return -EINVAL;
spin_lock_irqsave(&timer->lock, flags);
list_del_init(&timeri->ack_list);
list_del_init(&timeri->active_list);
if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) &&
!(--timer->running)) {
timer->hw.stop(timer);
if (timer->flags & SNDRV_TIMER_FLG_RESCHED) {
timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
snd_timer_reschedule(timer, 0);
if (timer->flags & SNDRV_TIMER_FLG_CHANGE) {
timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
timer->hw.start(timer);
}
}
}
if (!keep_flag)
timeri->flags &=
~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START);
spin_unlock_irqrestore(&timer->lock, flags);
__end:
if (event != SNDRV_TIMER_EVENT_RESOLUTION)
snd_timer_notify1(timeri, event);
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 void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static X509_STORE * setup_verify(zval * calist)
{
X509_STORE *store;
X509_LOOKUP * dir_lookup, * file_lookup;
int ndirs = 0, nfiles = 0;
zval * item;
zend_stat_t sb;
store = X509_STORE_new();
if (store == NULL) {
return NULL;
}
if (calist && (Z_TYPE_P(calist) == IS_ARRAY)) {
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(calist), item) {
convert_to_string_ex(item);
if (VCWD_STAT(Z_STRVAL_P(item), &sb) == -1) {
php_error_docref(NULL, E_WARNING, "unable to stat %s", Z_STRVAL_P(item));
continue;
}
if ((sb.st_mode & S_IFREG) == S_IFREG) {
file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
if (file_lookup == NULL || !X509_LOOKUP_load_file(file_lookup, Z_STRVAL_P(item), X509_FILETYPE_PEM)) {
php_error_docref(NULL, E_WARNING, "error loading file %s", Z_STRVAL_P(item));
} else {
nfiles++;
}
file_lookup = NULL;
} else {
dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
if (dir_lookup == NULL || !X509_LOOKUP_add_dir(dir_lookup, Z_STRVAL_P(item), X509_FILETYPE_PEM)) {
php_error_docref(NULL, E_WARNING, "error loading directory %s", Z_STRVAL_P(item));
} else {
ndirs++;
}
dir_lookup = NULL;
}
} ZEND_HASH_FOREACH_END();
}
if (nfiles == 0) {
file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
if (file_lookup) {
X509_LOOKUP_load_file(file_lookup, NULL, X509_FILETYPE_DEFAULT);
}
}
if (ndirs == 0) {
dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
if (dir_lookup) {
X509_LOOKUP_add_dir(dir_lookup, NULL, X509_FILETYPE_DEFAULT);
}
}
return store;
}
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: void WebGLRenderingContextBase::bufferSubData(GLenum target,
int64_t offset,
DOMArrayBuffer* data) {
if (isContextLost())
return;
DCHECK(data);
BufferSubDataImpl(target, offset, data->ByteLength(), data->Data());
}
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: gfx::Rect AutofillPopupBaseView::CalculateClippingBounds() const {
if (parent_widget_)
return parent_widget_->GetClientAreaBoundsInScreen();
return PopupViewCommon().GetWindowBounds(delegate_->container_view());
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: SECURITY_STATUS SEC_ENTRY ImportSecurityContextA(SEC_CHAR* pszPackage, PSecBuffer pPackedContext, HANDLE pToken, PCtxtHandle phContext)
{
return SEC_E_OK;
}
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: smp_fetch_base(const struct arg *args, struct sample *smp, const char *kw, void *private)
{
struct http_txn *txn;
char *ptr, *end, *beg;
struct hdr_ctx ctx;
struct chunk *temp;
CHECK_HTTP_MESSAGE_FIRST();
txn = smp->strm->txn;
ctx.idx = 0;
if (!http_find_header2("Host", 4, txn->req.chn->buf->p, &txn->hdr_idx, &ctx) || !ctx.vlen)
return smp_fetch_path(args, smp, kw, private);
/* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */
temp = get_trash_chunk();
memcpy(temp->str, ctx.line + ctx.val, ctx.vlen);
smp->data.type = SMP_T_STR;
smp->data.u.str.str = temp->str;
smp->data.u.str.len = ctx.vlen;
/* now retrieve the path */
end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l;
beg = http_get_path(txn);
if (!beg)
beg = end;
for (ptr = beg; ptr < end && *ptr != '?'; ptr++);
if (beg < ptr && *beg == '/') {
memcpy(smp->data.u.str.str + smp->data.u.str.len, beg, ptr - beg);
smp->data.u.str.len += ptr - beg;
}
smp->flags = SMP_F_VOL_1ST;
return 1;
}
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: void DecoderTest::RunLoop(CompressedVideoSource *video) {
vpx_codec_dec_cfg_t dec_cfg = {0};
Decoder* const decoder = codec_->CreateDecoder(dec_cfg, 0);
ASSERT_TRUE(decoder != NULL);
for (video->Begin(); video->cxdata(); video->Next()) {
PreDecodeFrameHook(*video, decoder);
vpx_codec_err_t res_dec = decoder->DecodeFrame(video->cxdata(),
video->frame_size());
ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError();
DxDataIterator dec_iter = decoder->GetDxData();
const vpx_image_t *img = NULL;
while ((img = dec_iter.Next()))
DecompressedFrameHook(*img, video->frame_number());
}
delete decoder;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void VirtualAuthenticator::GetUniqueId(GetUniqueIdCallback callback) {
std::move(callback).Run(unique_id_);
}
CWE ID: CWE-22
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 TabStrip::ResizeLayoutTabs() {
if (tab_count() == 0)
return;
RemoveMessageLoopObserver();
in_tab_close_ = false;
available_width_for_tabs_ = -1;
int pinned_tab_count = GetPinnedTabCount();
if (pinned_tab_count == tab_count()) {
return;
}
StartResizeLayoutAnimation();
}
CWE ID: CWE-20
Output: | 0 |
Subsets and Splits