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: bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
if (networks == NULL)
return false;
base::ThreadRestrictions::AssertIOAllowed();
ifaddrs* interfaces;
if (getifaddrs(&interfaces) < 0) {
PLOG(ERROR) << "getifaddrs";
return false;
}
std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter;
#if defined(OS_MACOSX) && !defined(OS_IOS)
ip_attributes_getter = base::MakeUnique<internal::IPAttributesGetterMac>();
#endif
bool result = internal::IfaddrsToNetworkInterfaceList(
policy, interfaces, ip_attributes_getter.get(), networks);
freeifaddrs(interfaces);
return result;
}
CWE ID: CWE-311
Target: 1
Example 2:
Code: static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF *p_ssp_key_notif)
{
bt_bdaddr_t bd_addr;
bt_bdname_t bd_name;
UINT32 cod;
int dev_type;
BTIF_TRACE_DEBUG("%s", __FUNCTION__);
/* Remote properties update */
if (!btif_get_device_type(p_ssp_key_notif->bd_addr, &dev_type))
{
dev_type = BT_DEVICE_TYPE_BREDR;
}
btif_update_remote_properties(p_ssp_key_notif->bd_addr, p_ssp_key_notif->bd_name,
p_ssp_key_notif->dev_class, (tBT_DEVICE_TYPE) dev_type);
bdcpy(bd_addr.address, p_ssp_key_notif->bd_addr);
memcpy(bd_name.name, p_ssp_key_notif->bd_name, BD_NAME_LEN);
bond_state_changed(BT_STATUS_SUCCESS, &bd_addr, BT_BOND_STATE_BONDING);
pairing_cb.is_ssp = TRUE;
cod = devclass2uint(p_ssp_key_notif->dev_class);
if (cod == 0) {
LOG_DEBUG("%s cod is 0, set as unclassified", __func__);
cod = COD_UNCLASSIFIED;
}
HAL_CBACK(bt_hal_cbacks, ssp_request_cb, &bd_addr, &bd_name,
cod, BT_SSP_VARIANT_PASSKEY_NOTIFICATION,
p_ssp_key_notif->passkey);
}
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: void ib_uverbs_release_uevent(struct ib_uverbs_file *file,
struct ib_uevent_object *uobj)
{
struct ib_uverbs_event *evt, *tmp;
spin_lock_irq(&file->async_file->lock);
list_for_each_entry_safe(evt, tmp, &uobj->event_list, obj_list) {
list_del(&evt->list);
kfree(evt);
}
spin_unlock_irq(&file->async_file->lock);
}
CWE ID: CWE-264
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud;
size_t rem;
ssize_t ret;
fud = fuse_get_dev(out);
if (!fud)
return -EPERM;
pipe_lock(pipe);
bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),
GFP_KERNEL);
if (!bufs) {
pipe_unlock(pipe);
return -ENOMEM;
}
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len) {
pipe_unlock(pipe);
goto out;
}
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
pipe_buf_get(pipe, ibuf);
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, 0, NULL);
cs.pipebufs = bufs;
cs.nr_segs = nbuf;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fud, &cs, len);
pipe_lock(pipe);
for (idx = 0; idx < nbuf; idx++)
pipe_buf_release(pipe, &bufs[idx]);
pipe_unlock(pipe);
out:
kvfree(bufs);
return ret;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: Ins_RTDG( TT_ExecContext exc )
{
exc->GS.round_state = TT_Round_To_Double_Grid;
exc->func_round = (TT_Round_Func)Round_To_Double_Grid;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int transport_read_layer(rdpTransport* transport, UINT8* data, int bytes)
{
int read = 0;
int status = -1;
while (read < bytes)
{
if (transport->layer == TRANSPORT_LAYER_TLS)
status = tls_read(transport->TlsIn, data + read, bytes - read);
else if (transport->layer == TRANSPORT_LAYER_TCP)
status = tcp_read(transport->TcpIn, data + read, bytes - read);
else if (transport->layer == TRANSPORT_LAYER_TSG)
status = tsg_read(transport->tsg, data + read, bytes - read);
/* blocking means that we can't continue until this is read */
if (!transport->blocking)
return status;
if (status < 0)
return status;
read += status;
if (status == 0)
{
/*
* instead of sleeping, we should wait timeout on the
* socket but this only happens on initial connection
*/
USleep(transport->SleepInterval);
}
}
return read;
}
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 mk_request_error(int http_status, struct client_session *cs,
struct session_request *sr) {
int ret, fd;
mk_ptr_t message, *page = 0;
struct error_page *entry;
struct mk_list *head;
struct file_info finfo;
mk_header_set_http_status(sr, http_status);
/*
* We are nice sending error pages for clients who at least respect
* the especification
*/
if (http_status != MK_CLIENT_LENGTH_REQUIRED &&
http_status != MK_CLIENT_BAD_REQUEST &&
http_status != MK_CLIENT_REQUEST_ENTITY_TOO_LARGE) {
/* Lookup a customized error page */
mk_list_foreach(head, &sr->host_conf->error_pages) {
entry = mk_list_entry(head, struct error_page, _head);
if (entry->status != http_status) {
continue;
}
/* validate error file */
ret = mk_file_get_info(entry->real_path, &finfo);
if (ret == -1) {
break;
}
/* open file */
fd = open(entry->real_path, config->open_flags);
if (fd == -1) {
break;
}
sr->fd_file = fd;
sr->bytes_to_send = finfo.size;
sr->headers.content_length = finfo.size;
sr->headers.real_length = finfo.size;
memcpy(&sr->file_info, &finfo, sizeof(struct file_info));
mk_header_send(cs->socket, cs, sr);
return mk_http_send_file(cs, sr);
}
}
mk_ptr_reset(&message);
switch (http_status) {
case MK_CLIENT_BAD_REQUEST:
page = mk_request_set_default_page("Bad Request",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_FORBIDDEN:
page = mk_request_set_default_page("Forbidden",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_NOT_FOUND:
mk_string_build(&message.data, &message.len,
"The requested URL was not found on this server.");
page = mk_request_set_default_page("Not Found",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_REQUEST_ENTITY_TOO_LARGE:
mk_string_build(&message.data, &message.len,
"The request entity is too large.");
page = mk_request_set_default_page("Entity too large",
message,
sr->host_conf->host_signature);
mk_ptr_free(&message);
break;
case MK_CLIENT_METHOD_NOT_ALLOWED:
page = mk_request_set_default_page("Method Not Allowed",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_CLIENT_REQUEST_TIMEOUT:
case MK_CLIENT_LENGTH_REQUIRED:
break;
case MK_SERVER_NOT_IMPLEMENTED:
page = mk_request_set_default_page("Method Not Implemented",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_INTERNAL_ERROR:
page = mk_request_set_default_page("Internal Server Error",
sr->uri,
sr->host_conf->host_signature);
break;
case MK_SERVER_HTTP_VERSION_UNSUP:
mk_ptr_reset(&message);
page = mk_request_set_default_page("HTTP Version Not Supported",
message,
sr->host_conf->host_signature);
break;
}
if (page) {
sr->headers.content_length = page->len;
}
sr->headers.location = NULL;
sr->headers.cgi = SH_NOCGI;
sr->headers.pconnections_left = 0;
sr->headers.last_modified = -1;
if (!page) {
mk_ptr_reset(&sr->headers.content_type);
}
else {
mk_ptr_set(&sr->headers.content_type, "text/html\r\n");
}
mk_header_send(cs->socket, cs, sr);
if (page) {
if (sr->method != MK_HTTP_METHOD_HEAD)
mk_socket_send(cs->socket, page->data, page->len);
mk_ptr_free(page);
mk_mem_free(page);
}
/* Turn off TCP_CORK */
mk_server_cork_flag(cs->socket, TCP_CORK_OFF);
return EXIT_ERROR;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void LayerWebKitThread::setFrame(const FloatRect& rect)
{
if (rect == m_frame)
return;
m_frame = rect;
setNeedsDisplay();
}
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 char *string_of_NPPVariable(int variable)
{
const char *str;
switch (variable) {
#define _(VAL) case VAL: str = #VAL; break;
_(NPPVpluginNameString);
_(NPPVpluginDescriptionString);
_(NPPVpluginWindowBool);
_(NPPVpluginTransparentBool);
_(NPPVjavaClass);
_(NPPVpluginWindowSize);
_(NPPVpluginTimerInterval);
_(NPPVpluginScriptableInstance);
_(NPPVpluginScriptableIID);
_(NPPVjavascriptPushCallerBool);
_(NPPVpluginKeepLibraryInMemory);
_(NPPVpluginNeedsXEmbed);
_(NPPVpluginScriptableNPObject);
_(NPPVformValue);
#undef _
default:
switch (variable & 0xff) {
#define _(VAL, VAR) case VAL: str = #VAR; break
_(10, NPPVpluginScriptableInstance);
#undef _
default:
str = "<unknown variable>";
break;
}
break;
}
return str;
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ID3::removeUnsynchronizationV2_4(bool iTunesHack) {
size_t oldSize = mSize;
size_t offset = 0;
while (mSize >= 10 && offset <= mSize - 10) {
if (!memcmp(&mData[offset], "\0\0\0\0", 4)) {
break;
}
size_t dataSize;
if (iTunesHack) {
dataSize = U32_AT(&mData[offset + 4]);
} else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) {
return false;
}
if (dataSize > mSize - 10 - offset) {
return false;
}
uint16_t flags = U16_AT(&mData[offset + 8]);
uint16_t prevFlags = flags;
if (flags & 1) {
if (mSize < 14 || mSize - 14 < offset || dataSize < 4) {
return false;
}
memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14);
mSize -= 4;
dataSize -= 4;
flags &= ~1;
}
if (flags & 2) {
size_t readOffset = offset + 11;
size_t writeOffset = offset + 11;
for (size_t i = 0; i + 1 < dataSize; ++i) {
if (mData[readOffset - 1] == 0xff
&& mData[readOffset] == 0x00) {
++readOffset;
--mSize;
--dataSize;
}
mData[writeOffset++] = mData[readOffset++];
}
memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset);
flags &= ~2;
}
if (flags != prevFlags || iTunesHack) {
WriteSyncsafeInteger(&mData[offset + 4], dataSize);
mData[offset + 8] = flags >> 8;
mData[offset + 9] = flags & 0xff;
}
offset += 10 + dataSize;
}
memset(&mData[mSize], 0, oldSize - mSize);
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Performance::BuildJSONValue(V8ObjectBuilder& builder) const {
builder.AddNumber("timeOrigin", timeOrigin());
}
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 MemBackendImpl::EvictIfNeeded() {
if (current_size_ <= max_size_)
return;
int target_size = std::max(0, max_size_ - kDefaultEvictionSize);
base::LinkNode<MemEntryImpl>* entry = lru_list_.head();
while (current_size_ > target_size && entry != lru_list_.end()) {
MemEntryImpl* to_doom = entry->value();
entry = entry->next();
if (!to_doom->InUse())
to_doom->Doom();
}
}
CWE ID: CWE-416
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 UDPSocketWin::InternalConnect(const IPEndPoint& address) {
DCHECK(!is_connected());
DCHECK(!remote_address_.get());
int addr_family = address.GetSockAddrFamily();
int rv = CreateSocket(addr_family);
if (rv < 0)
return rv;
if (bind_type_ == DatagramSocket::RANDOM_BIND) {
size_t addr_size =
addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize;
IPAddressNumber addr_any(addr_size);
rv = RandomBind(addr_any);
}
if (rv < 0) {
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv);
Close();
return rv;
}
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len))
return ERR_ADDRESS_INVALID;
rv = connect(socket_, storage.addr, storage.addr_len);
if (rv < 0) {
int result = MapSystemError(WSAGetLastError());
Close();
return result;
}
remote_address_.reset(new IPEndPoint(address));
return rv;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: int isofs_get_blocks(struct inode *inode, sector_t iblock,
struct buffer_head **bh, unsigned long nblocks)
{
unsigned long b_off = iblock;
unsigned offset, sect_size;
unsigned int firstext;
unsigned long nextblk, nextoff;
int section, rv, error;
struct iso_inode_info *ei = ISOFS_I(inode);
error = -EIO;
rv = 0;
if (iblock != b_off) {
printk(KERN_DEBUG "%s: block number too large\n", __func__);
goto abort;
}
offset = 0;
firstext = ei->i_first_extent;
sect_size = ei->i_section_size >> ISOFS_BUFFER_BITS(inode);
nextblk = ei->i_next_section_block;
nextoff = ei->i_next_section_offset;
section = 0;
while (nblocks) {
/* If we are *way* beyond the end of the file, print a message.
* Access beyond the end of the file up to the next page boundary
* is normal, however because of the way the page cache works.
* In this case, we just return 0 so that we can properly fill
* the page with useless information without generating any
* I/O errors.
*/
if (b_off > ((inode->i_size + PAGE_CACHE_SIZE - 1) >> ISOFS_BUFFER_BITS(inode))) {
printk(KERN_DEBUG "%s: block >= EOF (%lu, %llu)\n",
__func__, b_off,
(unsigned long long)inode->i_size);
goto abort;
}
/* On the last section, nextblk == 0, section size is likely to
* exceed sect_size by a partial block, and access beyond the
* end of the file will reach beyond the section size, too.
*/
while (nextblk && (b_off >= (offset + sect_size))) {
struct inode *ninode;
offset += sect_size;
ninode = isofs_iget(inode->i_sb, nextblk, nextoff);
if (IS_ERR(ninode)) {
error = PTR_ERR(ninode);
goto abort;
}
firstext = ISOFS_I(ninode)->i_first_extent;
sect_size = ISOFS_I(ninode)->i_section_size >> ISOFS_BUFFER_BITS(ninode);
nextblk = ISOFS_I(ninode)->i_next_section_block;
nextoff = ISOFS_I(ninode)->i_next_section_offset;
iput(ninode);
if (++section > 100) {
printk(KERN_DEBUG "%s: More than 100 file sections ?!?"
" aborting...\n", __func__);
printk(KERN_DEBUG "%s: block=%lu firstext=%u sect_size=%u "
"nextblk=%lu nextoff=%lu\n", __func__,
b_off, firstext, (unsigned) sect_size,
nextblk, nextoff);
goto abort;
}
}
if (*bh) {
map_bh(*bh, inode->i_sb, firstext + b_off - offset);
} else {
*bh = sb_getblk(inode->i_sb, firstext+b_off-offset);
if (!*bh)
goto abort;
}
bh++; /* Next buffer head */
b_off++; /* Next buffer offset */
nblocks--;
rv++;
}
error = 0;
abort:
return rv != 0 ? rv : error;
}
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 void ParseCommon(map_string_t *settings, const char *conf_filename)
{
const char *value;
value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir");
if (value)
{
g_settings_sWatchCrashdumpArchiveDir = xstrdup(value);
remove_map_string_item(settings, "WatchCrashdumpArchiveDir");
}
value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize");
if (value)
{
char *end;
errno = 0;
unsigned long ul = strtoul(value, &end, 10);
if (errno || end == value || *end != '\0' || ul > INT_MAX)
error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value);
else
g_settings_nMaxCrashReportsSize = ul;
remove_map_string_item(settings, "MaxCrashReportsSize");
}
value = get_map_string_item_or_NULL(settings, "DumpLocation");
if (value)
{
g_settings_dump_location = xstrdup(value);
remove_map_string_item(settings, "DumpLocation");
}
else
g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION);
value = get_map_string_item_or_NULL(settings, "DeleteUploaded");
if (value)
{
g_settings_delete_uploaded = string_to_bool(value);
remove_map_string_item(settings, "DeleteUploaded");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled");
if (value)
{
g_settings_autoreporting = string_to_bool(value);
remove_map_string_item(settings, "AutoreportingEnabled");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEvent");
if (value)
{
g_settings_autoreporting_event = xstrdup(value);
remove_map_string_item(settings, "AutoreportingEvent");
}
else
g_settings_autoreporting_event = xstrdup("report_uReport");
value = get_map_string_item_or_NULL(settings, "ShortenedReporting");
if (value)
{
g_settings_shortenedreporting = string_to_bool(value);
remove_map_string_item(settings, "ShortenedReporting");
}
else
g_settings_shortenedreporting = 0;
GHashTableIter iter;
const char *name;
/*char *value; - already declared */
init_map_string_iter(&iter, settings);
while (next_map_string_iter(&iter, &name, &value))
{
error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename);
}
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static char* cJSON_strdup( const char* str )
{
size_t len;
char* copy;
len = strlen( str ) + 1;
if ( ! ( copy = (char*) cJSON_malloc( len ) ) )
return 0;
memcpy( copy, str, len );
return copy;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline int qeth_create_skb_frag(struct qeth_qdio_buffer *qethbuffer,
struct qdio_buffer_element *element,
struct sk_buff **pskb, int offset, int *pfrag, int data_len)
{
struct page *page = virt_to_page(element->addr);
if (*pskb == NULL) {
if (qethbuffer->rx_skb) {
/* only if qeth_card.options.cq == QETH_CQ_ENABLED */
*pskb = qethbuffer->rx_skb;
qethbuffer->rx_skb = NULL;
} else {
*pskb = dev_alloc_skb(QETH_RX_PULL_LEN + ETH_HLEN);
if (!(*pskb))
return -ENOMEM;
}
skb_reserve(*pskb, ETH_HLEN);
if (data_len <= QETH_RX_PULL_LEN) {
memcpy(skb_put(*pskb, data_len), element->addr + offset,
data_len);
} else {
get_page(page);
memcpy(skb_put(*pskb, QETH_RX_PULL_LEN),
element->addr + offset, QETH_RX_PULL_LEN);
skb_fill_page_desc(*pskb, *pfrag, page,
offset + QETH_RX_PULL_LEN,
data_len - QETH_RX_PULL_LEN);
(*pskb)->data_len += data_len - QETH_RX_PULL_LEN;
(*pskb)->len += data_len - QETH_RX_PULL_LEN;
(*pskb)->truesize += data_len - QETH_RX_PULL_LEN;
(*pfrag)++;
}
} else {
get_page(page);
skb_fill_page_desc(*pskb, *pfrag, page, offset, data_len);
(*pskb)->data_len += data_len;
(*pskb)->len += data_len;
(*pskb)->truesize += data_len;
(*pfrag)++;
}
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void option_import_marks(const char *marks,
int from_stream, int ignore_missing)
{
if (import_marks_file) {
if (from_stream)
die("Only one import-marks command allowed per stream");
/* read previous mark file */
if(!import_marks_file_from_stream)
read_marks();
}
import_marks_file = make_fast_import_path(marks);
safe_create_leading_directories_const(import_marks_file);
import_marks_file_from_stream = from_stream;
import_marks_file_ignore_missing = ignore_missing;
}
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 SyncManager::MaybeSetSyncTabsInNigoriNode(
ModelTypeSet enabled_types) {
DCHECK(thread_checker_.CalledOnValidThread());
data_->MaybeSetSyncTabsInNigoriNode(enabled_types);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
access |= PFERR_WRITE_MASK;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
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 RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
bool was_created = render_frame_created_;
render_frame_created_ = created;
if (delegate_ && (created != was_created)) {
if (created) {
SetUpMojoIfNeeded();
delegate_->RenderFrameCreated(this);
} else {
delegate_->RenderFrameDeleted(this);
}
}
if (created && render_widget_host_)
render_widget_host_->InitForFrame();
if (enabled_bindings_ && created) {
if (!frame_bindings_control_)
GetRemoteAssociatedInterfaces()->GetInterface(&frame_bindings_control_);
frame_bindings_control_->AllowBindings(enabled_bindings_);
}
}
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: vrrp_print_stats(void)
{
FILE *file;
file = fopen (stats_file, "w");
if (!file) {
log_message(LOG_INFO, "Can't open %s (%d: %s)",
stats_file, errno, strerror(errno));
return;
}
list l = vrrp_data->vrrp;
element e;
vrrp_t *vrrp;
for (e = LIST_HEAD(l); e; ELEMENT_NEXT(e)) {
vrrp = ELEMENT_DATA(e);
fprintf(file, "VRRP Instance: %s\n", vrrp->iname);
fprintf(file, " Advertisements:\n");
fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->advert_rcvd);
fprintf(file, " Sent: %d\n", vrrp->stats->advert_sent);
fprintf(file, " Became master: %d\n", vrrp->stats->become_master);
fprintf(file, " Released master: %d\n",
vrrp->stats->release_master);
fprintf(file, " Packet Errors:\n");
fprintf(file, " Length: %" PRIu64 "\n", vrrp->stats->packet_len_err);
fprintf(file, " TTL: %" PRIu64 "\n", vrrp->stats->ip_ttl_err);
fprintf(file, " Invalid Type: %" PRIu64 "\n",
vrrp->stats->invalid_type_rcvd);
fprintf(file, " Advertisement Interval: %" PRIu64 "\n",
vrrp->stats->advert_interval_err);
fprintf(file, " Address List: %" PRIu64 "\n",
vrrp->stats->addr_list_err);
fprintf(file, " Authentication Errors:\n");
fprintf(file, " Invalid Type: %d\n",
vrrp->stats->invalid_authtype);
#ifdef _WITH_VRRP_AUTH_
fprintf(file, " Type Mismatch: %d\n",
vrrp->stats->authtype_mismatch);
fprintf(file, " Failure: %d\n",
vrrp->stats->auth_failure);
#endif
fprintf(file, " Priority Zero:\n");
fprintf(file, " Received: %" PRIu64 "\n", vrrp->stats->pri_zero_rcvd);
fprintf(file, " Sent: %" PRIu64 "\n", vrrp->stats->pri_zero_sent);
}
fclose(file);
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: void BrowserView::ActiveTabChanged(TabContents* old_contents,
TabContents* new_contents,
int index,
bool user_gesture) {
DCHECK(new_contents);
if (contents_->preview_web_contents() == new_contents->web_contents()) {
contents_->MakePreviewContentsActiveContents();
views::WebView* old_container = contents_container_;
contents_container_ = preview_controller_->release_preview_container();
old_container->SetWebContents(NULL);
delete old_container;
}
bool change_tab_contents =
contents_container_->web_contents() != new_contents->web_contents();
if (change_tab_contents)
contents_container_->SetWebContents(NULL);
InfoBarTabHelper* new_infobar_tab_helper =
InfoBarTabHelper::FromWebContents(new_contents->web_contents());
infobar_container_->ChangeTabContents(new_infobar_tab_helper);
if (bookmark_bar_view_.get()) {
bookmark_bar_view_->SetBookmarkBarState(
browser_->bookmark_bar_state(),
BookmarkBar::DONT_ANIMATE_STATE_CHANGE,
browser_->search_model()->mode());
}
UpdateUIForContents(new_contents);
UpdateDevToolsForContents(new_contents);
if (change_tab_contents) {
contents_container_->SetWebContents(new_contents->web_contents());
#if defined(USE_AURA)
if (contents_->preview_web_contents()) {
ui::Layer* preview_layer =
contents_->preview_web_contents()->GetNativeView()->layer();
preview_layer->parent()->StackAtTop(preview_layer);
}
#endif
}
if (!browser_->tab_strip_model()->closing_all() && GetWidget()->IsActive() &&
GetWidget()->IsVisible()) {
new_contents->web_contents()->GetView()->RestoreFocus();
}
UpdateTitleBar();
MaybeStackBookmarkBarAtTop();
}
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: R_API int r_flag_unset(RFlag *f, RFlagItem *item) {
remove_offsetmap (f, item);
ht_delete (f->ht_name, item->name);
r_list_delete_data (f->flags, item);
return true;
}
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 handle_pte_fault(struct mm_struct *mm,
struct vm_area_struct *vma, unsigned long address,
pte_t *pte, pmd_t *pmd, unsigned int flags)
{
pte_t entry;
spinlock_t *ptl;
/*
* some architectures can have larger ptes than wordsize,
* e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and CONFIG_32BIT=y,
* so READ_ONCE or ACCESS_ONCE cannot guarantee atomic accesses.
* The code below just needs a consistent view for the ifs and
* we later double check anyway with the ptl lock held. So here
* a barrier will do.
*/
entry = *pte;
barrier();
if (!pte_present(entry)) {
if (pte_none(entry)) {
if (vma->vm_ops) {
if (likely(vma->vm_ops->fault))
return do_fault(mm, vma, address, pte,
pmd, flags, entry);
}
return do_anonymous_page(mm, vma, address,
pte, pmd, flags);
}
return do_swap_page(mm, vma, address,
pte, pmd, flags, entry);
}
if (pte_protnone(entry))
return do_numa_page(mm, vma, address, entry, pte, pmd);
ptl = pte_lockptr(mm, pmd);
spin_lock(ptl);
if (unlikely(!pte_same(*pte, entry)))
goto unlock;
if (flags & FAULT_FLAG_WRITE) {
if (!pte_write(entry))
return do_wp_page(mm, vma, address,
pte, pmd, ptl, entry);
entry = pte_mkdirty(entry);
}
entry = pte_mkyoung(entry);
if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) {
update_mmu_cache(vma, address, pte);
} else {
/*
* This is needed only for protection faults but the arch code
* is not yet telling us if this is a protection fault or not.
* This still avoids useless tlb flushes for .text page faults
* with threads.
*/
if (flags & FAULT_FLAG_WRITE)
flush_tlb_fix_spurious_fault(vma, address);
}
unlock:
pte_unmap_unlock(pte, ptl);
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool encode_search_options_request(void *mem_ctx, void *in, DATA_BLOB *out)
{
struct ldb_search_options_control *lsoc = talloc_get_type(in, struct ldb_search_options_control);
struct asn1_data *data = asn1_init(mem_ctx);
if (!data) return false;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) {
return false;
}
if (!asn1_write_Integer(data, lsoc->search_options)) {
return false;
}
if (!asn1_pop_tag(data)) {
return false;
}
*out = data_blob_talloc(mem_ctx, data->data, data->length);
if (out->data == NULL) {
return false;
}
talloc_free(data);
return true;
}
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: IndexedDBDispatcher::~IndexedDBDispatcher() {
g_idb_dispatcher_tls.Pointer()->Set(NULL);
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void file_sb_list_del(struct file *file)
{
if (!list_empty(&file->f_u.fu_list)) {
lg_local_lock_cpu(&files_lglock, file_list_cpu(file));
list_del_init(&file->f_u.fu_list);
lg_local_unlock_cpu(&files_lglock, file_list_cpu(file));
}
}
CWE ID: CWE-17
Target: 1
Example 2:
Code: static h2o_http2_conn_t *create_conn(h2o_context_t *ctx, h2o_hostconf_t **hosts, h2o_socket_t *sock, struct timeval connected_at)
{
static const h2o_conn_callbacks_t callbacks = {get_sockname, get_peername, push_path};
h2o_http2_conn_t *conn = h2o_mem_alloc(sizeof(*conn));
/* init the connection */
memset(conn, 0, sizeof(*conn));
conn->super.ctx = ctx;
conn->super.hosts = hosts;
conn->super.connected_at = connected_at;
conn->super.callbacks = &callbacks;
conn->sock = sock;
conn->peer_settings = H2O_HTTP2_SETTINGS_DEFAULT;
conn->streams = kh_init(h2o_http2_stream_t);
h2o_http2_scheduler_init(&conn->scheduler);
conn->state = H2O_HTTP2_CONN_STATE_OPEN;
h2o_linklist_insert(&ctx->http2._conns, &conn->_conns);
conn->_read_expect = expect_preface;
conn->_input_header_table.hpack_capacity = conn->_input_header_table.hpack_max_capacity =
H2O_HTTP2_SETTINGS_DEFAULT.header_table_size;
h2o_http2_window_init(&conn->_input_window, &H2O_HTTP2_SETTINGS_DEFAULT);
conn->_output_header_table.hpack_capacity = H2O_HTTP2_SETTINGS_HOST.header_table_size;
h2o_linklist_init_anchor(&conn->_pending_reqs);
h2o_buffer_init(&conn->_write.buf, &wbuf_buffer_prototype);
h2o_linklist_init_anchor(&conn->_write.streams_to_proceed);
conn->_write.timeout_entry.cb = emit_writereq;
h2o_http2_window_init(&conn->_write.window, &conn->peer_settings);
return conn;
}
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 CSSDefaultStyleSheets::loadSimpleDefaultStyle()
{
ASSERT(!defaultStyle);
ASSERT(!simpleDefaultStyleSheet);
defaultStyle = RuleSet::create().leakPtr();
defaultPrintStyle = defaultStyle;
defaultQuirksStyle = RuleSet::create().leakPtr();
simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval());
}
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: void PPB_Buffer_Proxy::OnMsgCreate(
PP_Instance instance,
uint32_t size,
HostResource* result_resource,
ppapi::proxy::SerializedHandle* result_shm_handle) {
result_shm_handle->set_null_shmem();
HostDispatcher* dispatcher = HostDispatcher::GetForInstance(instance);
if (!dispatcher)
return;
thunk::EnterResourceCreation enter(instance);
if (enter.failed())
return;
PP_Resource local_buffer_resource = enter.functions()->CreateBuffer(instance,
size);
if (local_buffer_resource == 0)
return;
thunk::EnterResourceNoLock<thunk::PPB_BufferTrusted_API> trusted_buffer(
local_buffer_resource, false);
if (trusted_buffer.failed())
return;
int local_fd;
if (trusted_buffer.object()->GetSharedMemory(&local_fd) != PP_OK)
return;
result_resource->SetHostResource(instance, local_buffer_resource);
base::PlatformFile platform_file =
#if defined(OS_WIN)
reinterpret_cast<HANDLE>(static_cast<intptr_t>(local_fd));
#elif defined(OS_POSIX)
local_fd;
#else
#error Not implemented.
#endif
result_shm_handle->set_shmem(
dispatcher->ShareHandleWithRemote(platform_file, false), size);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: ProactiveTabFreezeAndDiscardParams GetTestProactiveDiscardParams() {
ProactiveTabFreezeAndDiscardParams params = {};
params.should_proactively_discard = true;
params.low_occluded_timeout = kLowOccludedTimeout;
params.moderate_occluded_timeout = kModerateOccludedTimeout;
params.high_occluded_timeout = kHighOccludedTimeout;
params.low_loaded_tab_count = kLowLoadedTabCount;
params.moderate_loaded_tab_count = kModerateLoadedTabCount;
params.high_loaded_tab_count = kHighLoadedTabCount;
params.freeze_timeout = kFreezeTimeout;
return params;
}
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 tcp_conn_t *tcp_conn_accept(struct tcp_sock_t *sock)
{
struct tcp_conn_t *conn = calloc(1, sizeof *conn);
if (conn == NULL) {
ERR("Calloc for connection struct failed");
goto error;
}
conn->sd = accept(sock->sd, NULL, NULL);
if (conn->sd < 0) {
ERR("accept failed");
goto error;
}
return conn;
error:
if (conn != NULL)
free(conn);
return NULL;
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: setPath(JsonbIterator **it, Datum *path_elems,
bool *path_nulls, int path_len,
JsonbParseState **st, int level, Jsonb *newval, bool create)
{
JsonbValue v;
JsonbValue *res = NULL;
int r;
if (path_nulls[level])
elog(ERROR, "path element at the position %d is NULL", level + 1);
switch (r)
{
case WJB_BEGIN_ARRAY:
(void) pushJsonbValue(st, r, NULL);
setPathArray(it, path_elems, path_nulls, path_len, st, level,
newval, v.val.array.nElems, create);
r = JsonbIteratorNext(it, &v, false);
Assert(r == WJB_END_ARRAY);
res = pushJsonbValue(st, r, NULL);
break;
case WJB_BEGIN_OBJECT:
(void) pushJsonbValue(st, r, NULL);
setPathObject(it, path_elems, path_nulls, path_len, st, level,
newval, v.val.object.nPairs, create);
r = JsonbIteratorNext(it, &v, true);
Assert(r == WJB_END_OBJECT);
res = pushJsonbValue(st, r, NULL);
break;
case WJB_ELEM:
case WJB_VALUE:
res = pushJsonbValue(st, r, &v);
break;
default:
elog(ERROR, "impossible state");
}
return res;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
int
pixel;
register ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
length=(size_t) (*compact_pixels++);
packets--;
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
if (((ssize_t) length+i) > (ssize_t) number_pixels)
length=number_pixels-(size_t) i;
pixel=(*compact_pixels++);
packets--;
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
i+=8;
break;
}
case 4:
{
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
i+=2;
break;
}
case 2:
{
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
i+=4;
break;
}
default:
{
*pixels++=(unsigned char) pixel;
i++;
break;
}
}
}
continue;
}
length++;
if (((ssize_t) length+i) > (ssize_t) number_pixels)
length=number_pixels-(size_t) i;
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
i+=8;
break;
}
case 4:
{
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
i+=2;
break;
}
case 2:
{
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
i+=4;
break;
}
default:
{
*pixels++=(*compact_pixels);
i++;
break;
}
}
compact_pixels++;
}
}
return(i);
}
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 set_channels(AVFormatContext *avctx, AVStream *st, int channels)
{
if (channels <= 0) {
av_log(avctx, AV_LOG_ERROR, "Channel count %d invalid.\n", channels);
return AVERROR_INVALIDDATA;
}
st->codecpar->channels = channels;
st->codecpar->channel_layout = (st->codecpar->channels == 1) ? AV_CH_LAYOUT_MONO
: AV_CH_LAYOUT_STEREO;
return 0;
}
CWE ID: CWE-834
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 char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const char *key)
{
{
size_t len;
const char *p;
char c;
int ret = 1;
for (p = key; (c = *p); p++) {
/* valid characters are a..z,A..Z,0..9 */
if (!((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == ','
|| c == '-')) {
ret = 0;
break;
}
}
len = p - key;
/* Somewhat arbitrary length limit here, but should be way more than
anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */
if (len == 0 || len > 128) {
ret = 0;
}
return ret;
}
static char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const char *key)
{
size_t key_len;
const char *p;
int i;
int n;
key_len = strlen(key);
if (key_len <= data->dirdepth ||
buflen < (strlen(data->basedir) + 2 * data->dirdepth + key_len + 5 + sizeof(FILE_PREFIX))) {
return NULL;
}
p = key;
memcpy(buf, data->basedir, data->basedir_len);
n = data->basedir_len;
buf[n++] = PHP_DIR_SEPARATOR;
for (i = 0; i < (int)data->dirdepth; i++) {
buf[n++] = *p++;
buf[n++] = PHP_DIR_SEPARATOR;
}
memcpy(buf + n, FILE_PREFIX, sizeof(FILE_PREFIX) - 1);
n += sizeof(FILE_PREFIX) - 1;
memcpy(buf + n, key, key_len);
n += key_len;
ps_files_close(data);
if (!ps_files_valid_key(key)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'");
PS(invalid_session_id) = 1;
return;
}
if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
return;
}
if (data->fd != -1) {
#ifdef PHP_WIN32
/* On Win32 locked files that are closed without being explicitly unlocked
will be unlocked only when "system resources become available". */
flock(data->fd, LOCK_UN);
#endif
close(data->fd);
data->fd = -1;
}
}
static void ps_files_open(ps_files *data, const char *key TSRMLS_DC)
{
char buf[MAXPATHLEN];
if (data->fd < 0 || !data->lastkey || strcmp(key, data->lastkey)) {
if (data->lastkey) {
efree(data->lastkey);
data->lastkey = NULL;
}
ps_files_close(data);
if (!ps_files_valid_key(key)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'");
PS(invalid_session_id) = 1;
return;
}
if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
return;
}
data->lastkey = estrdup(key);
data->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY, data->filemode);
if (data->fd != -1) {
#ifndef PHP_WIN32
/* check to make sure that the opened file is not a symlink, linking to data outside of allowable dirs */
if (PG(open_basedir)) {
struct stat sbuf;
if (fstat(data->fd, &sbuf)) {
close(data->fd);
return;
}
if (S_ISLNK(sbuf.st_mode) && php_check_open_basedir(buf TSRMLS_CC)) {
close(data->fd);
return;
}
}
#endif
flock(data->fd, LOCK_EX);
#ifdef F_SETFD
# ifndef FD_CLOEXEC
# define FD_CLOEXEC 1
# endif
if (fcntl(data->fd, F_SETFD, FD_CLOEXEC)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s (%d)", data->fd, strerror(errno), errno);
}
#endif
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "open(%s, O_RDWR) failed: %s (%d)", buf, strerror(errno), errno);
}
}
}
static int ps_files_cleanup_dir(const char *dirname, int maxlifetime TSRMLS_DC)
{
DIR *dir;
char dentry[sizeof(struct dirent) + MAXPATHLEN];
struct dirent *entry = (struct dirent *) &dentry;
struct stat sbuf;
char buf[MAXPATHLEN];
time_t now;
int nrdels = 0;
size_t dirname_len;
dir = opendir(dirname);
if (!dir) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "ps_files_cleanup_dir: opendir(%s) failed: %s (%d)", dirname, strerror(errno), errno);
return (0);
}
time(&now);
return (nrdels);
}
#define PS_FILES_DATA ps_files *data = PS_GET_MOD_DATA()
PS_OPEN_FUNC(files)
(now - sbuf.st_mtime) > maxlifetime) {
VCWD_UNLINK(buf);
nrdels++;
}
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void ion_vm_close(struct vm_area_struct *vma)
{
struct ion_buffer *buffer = vma->vm_private_data;
struct ion_vma_list *vma_list, *tmp;
pr_debug("%s\n", __func__);
mutex_lock(&buffer->lock);
list_for_each_entry_safe(vma_list, tmp, &buffer->vmas, list) {
if (vma_list->vma != vma)
continue;
list_del(&vma_list->list);
kfree(vma_list);
pr_debug("%s: deleting %p\n", __func__, vma);
break;
}
mutex_unlock(&buffer->lock);
}
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 Parcel::freeDataNoInit()
{
if (mOwner) {
LOG_ALLOC("Parcel %p: freeing other owner data", this);
mOwner(this, mData, mDataSize, mObjects, mObjectsSize, mOwnerCookie);
} else {
LOG_ALLOC("Parcel %p: freeing allocated data", this);
releaseObjects();
if (mData) {
LOG_ALLOC("Parcel %p: freeing with %zu capacity", this, mDataCapacity);
pthread_mutex_lock(&gParcelGlobalAllocSizeLock);
if (mDataCapacity <= gParcelGlobalAllocSize) {
gParcelGlobalAllocSize = gParcelGlobalAllocSize - mDataCapacity;
} else {
gParcelGlobalAllocSize = 0;
}
if (gParcelGlobalAllocCount > 0) {
gParcelGlobalAllocCount--;
}
pthread_mutex_unlock(&gParcelGlobalAllocSizeLock);
free(mData);
}
if (mObjects) free(mObjects);
}
}
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: bool PermissionUtil::GetPermissionType(ContentSettingsType type,
PermissionType* out) {
if (type == CONTENT_SETTINGS_TYPE_GEOLOCATION) {
*out = PermissionType::GEOLOCATION;
} else if (type == CONTENT_SETTINGS_TYPE_NOTIFICATIONS) {
*out = PermissionType::NOTIFICATIONS;
} else if (type == CONTENT_SETTINGS_TYPE_PUSH_MESSAGING) {
*out = PermissionType::PUSH_MESSAGING;
} else if (type == CONTENT_SETTINGS_TYPE_MIDI_SYSEX) {
*out = PermissionType::MIDI_SYSEX;
} else if (type == CONTENT_SETTINGS_TYPE_DURABLE_STORAGE) {
*out = PermissionType::DURABLE_STORAGE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA) {
*out = PermissionType::VIDEO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC) {
*out = PermissionType::AUDIO_CAPTURE;
} else if (type == CONTENT_SETTINGS_TYPE_BACKGROUND_SYNC) {
*out = PermissionType::BACKGROUND_SYNC;
} else if (type == CONTENT_SETTINGS_TYPE_PLUGINS) {
*out = PermissionType::FLASH;
#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
} else if (type == CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER) {
*out = PermissionType::PROTECTED_MEDIA_IDENTIFIER;
#endif
} else {
return false;
}
return true;
}
CWE ID:
Target: 1
Example 2:
Code: void AutofillDialogViews::UpdateAccountChooser() {
account_chooser_->Update();
bool show_loading = delegate_->ShouldShowSpinner();
if (show_loading != loading_shield_->visible()) {
if (show_loading) {
loading_shield_height_ = std::max(kInitialLoadingShieldHeight,
GetContentsBounds().height());
ShowDialogInMode(LOADING);
} else {
bool show_sign_in = delegate_->ShouldShowSignInWebView();
ShowDialogInMode(show_sign_in ? SIGN_IN : DETAIL_INPUT);
}
InvalidateLayout();
ContentsPreferredSizeChanged();
}
if (footnote_view_) {
const base::string16 text = delegate_->LegalDocumentsText();
legal_document_view_->SetText(text);
if (!text.empty()) {
const std::vector<gfx::Range>& link_ranges =
delegate_->LegalDocumentLinks();
for (size_t i = 0; i < link_ranges.size(); ++i) {
views::StyledLabel::RangeStyleInfo link_range_info =
views::StyledLabel::RangeStyleInfo::CreateForLink();
link_range_info.disable_line_wrapping = false;
legal_document_view_->AddStyleRange(link_ranges[i], link_range_info);
}
}
footnote_view_->SetVisible(!text.empty());
ContentsPreferredSizeChanged();
}
if (GetWidget())
GetWidget()->UpdateWindowTitle();
}
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: mainloop_gio_refcount(mainloop_io_t *client)
{
/* This is evil
* Looking at the giochannel header file, ref_count is the first member of channel
* So cheat...
*/
if(client && client->channel) {
int *ref = (void*)client->channel;
return *ref;
}
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: static int snd_ctl_elem_add(struct snd_ctl_file *file,
struct snd_ctl_elem_info *info, int replace)
{
struct snd_card *card = file->card;
struct snd_kcontrol kctl, *_kctl;
unsigned int access;
long private_size;
struct user_element *ue;
int idx, err;
if (!replace && card->user_ctl_count >= MAX_USER_CONTROLS)
return -ENOMEM;
if (info->count < 1)
return -EINVAL;
access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE :
(info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE|
SNDRV_CTL_ELEM_ACCESS_INACTIVE|
SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE));
info->id.numid = 0;
memset(&kctl, 0, sizeof(kctl));
down_write(&card->controls_rwsem);
_kctl = snd_ctl_find_id(card, &info->id);
err = 0;
if (_kctl) {
if (replace)
err = snd_ctl_remove(card, _kctl);
else
err = -EBUSY;
} else {
if (replace)
err = -ENOENT;
}
up_write(&card->controls_rwsem);
if (err < 0)
return err;
memcpy(&kctl.id, &info->id, sizeof(info->id));
kctl.count = info->owner ? info->owner : 1;
access |= SNDRV_CTL_ELEM_ACCESS_USER;
if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED)
kctl.info = snd_ctl_elem_user_enum_info;
else
kctl.info = snd_ctl_elem_user_info;
if (access & SNDRV_CTL_ELEM_ACCESS_READ)
kctl.get = snd_ctl_elem_user_get;
if (access & SNDRV_CTL_ELEM_ACCESS_WRITE)
kctl.put = snd_ctl_elem_user_put;
if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) {
kctl.tlv.c = snd_ctl_elem_user_tlv;
access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
}
switch (info->type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
case SNDRV_CTL_ELEM_TYPE_INTEGER:
private_size = sizeof(long);
if (info->count > 128)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER64:
private_size = sizeof(long long);
if (info->count > 64)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_ENUMERATED:
private_size = sizeof(unsigned int);
if (info->count > 128 || info->value.enumerated.items == 0)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_BYTES:
private_size = sizeof(unsigned char);
if (info->count > 512)
return -EINVAL;
break;
case SNDRV_CTL_ELEM_TYPE_IEC958:
private_size = sizeof(struct snd_aes_iec958);
if (info->count != 1)
return -EINVAL;
break;
default:
return -EINVAL;
}
private_size *= info->count;
ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL);
if (ue == NULL)
return -ENOMEM;
ue->info = *info;
ue->info.access = 0;
ue->elem_data = (char *)ue + sizeof(*ue);
ue->elem_data_size = private_size;
if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) {
err = snd_ctl_elem_init_enum_names(ue);
if (err < 0) {
kfree(ue);
return err;
}
}
kctl.private_free = snd_ctl_elem_user_free;
_kctl = snd_ctl_new(&kctl, access);
if (_kctl == NULL) {
kfree(ue->priv_data);
kfree(ue);
return -ENOMEM;
}
_kctl->private_data = ue;
for (idx = 0; idx < _kctl->count; idx++)
_kctl->vd[idx].owner = file;
err = snd_ctl_add(card, _kctl);
if (err < 0)
return err;
down_write(&card->controls_rwsem);
card->user_ctl_count++;
up_write(&card->controls_rwsem);
return 0;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int file_cb(
const git_diff_delta *delta,
float progress,
void *payload)
{
struct diff_data *diff_data = payload;
GIT_UNUSED(progress);
if (delta->old_file.path)
diff_data->old_path = git__strdup(delta->old_file.path);
if (delta->new_file.path)
diff_data->new_path = git__strdup(delta->new_file.path);
git_oid_cpy(&diff_data->old_id, &delta->old_file.id);
git_oid_cpy(&diff_data->new_id, &delta->new_file.id);
return 0;
}
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: R_API ut64 r_bin_java_annotation_default_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
if (attr) {
size += 6;
size += r_bin_java_element_value_calc_size (attr->info.annotation_default_attr.default_value);
}
return size;
}
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 tty_open(struct inode *inode, struct file *filp)
{
struct tty_struct *tty = NULL;
int noctty, retval;
struct tty_driver *driver;
int index;
dev_t device = inode->i_rdev;
unsigned saved_flags = filp->f_flags;
nonseekable_open(inode, filp);
retry_open:
noctty = filp->f_flags & O_NOCTTY;
index = -1;
retval = 0;
mutex_lock(&tty_mutex);
tty_lock();
if (device == MKDEV(TTYAUX_MAJOR, 0)) {
tty = get_current_tty();
if (!tty) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENXIO;
}
driver = tty_driver_kref_get(tty->driver);
index = tty->index;
filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
/* noctty = 1; */
/* FIXME: Should we take a driver reference ? */
tty_kref_put(tty);
goto got_driver;
}
#ifdef CONFIG_VT
if (device == MKDEV(TTY_MAJOR, 0)) {
extern struct tty_driver *console_driver;
driver = tty_driver_kref_get(console_driver);
index = fg_console;
noctty = 1;
goto got_driver;
}
#endif
if (device == MKDEV(TTYAUX_MAJOR, 1)) {
struct tty_driver *console_driver = console_device(&index);
if (console_driver) {
driver = tty_driver_kref_get(console_driver);
if (driver) {
/* Don't let /dev/console block */
filp->f_flags |= O_NONBLOCK;
noctty = 1;
goto got_driver;
}
}
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
driver = get_tty_driver(device, &index);
if (!driver) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
got_driver:
if (!tty) {
/* check whether we're reopening an existing tty */
tty = tty_driver_lookup_tty(driver, inode, index);
if (IS_ERR(tty)) {
tty_unlock();
mutex_unlock(&tty_mutex);
return PTR_ERR(tty);
}
}
if (tty) {
retval = tty_reopen(tty);
if (retval)
tty = ERR_PTR(retval);
} else
tty = tty_init_dev(driver, index, 0);
mutex_unlock(&tty_mutex);
tty_driver_kref_put(driver);
if (IS_ERR(tty)) {
tty_unlock();
return PTR_ERR(tty);
}
retval = tty_add_file(tty, filp);
if (retval) {
tty_unlock();
tty_release(inode, filp);
return retval;
}
check_tty_count(tty, "tty_open");
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
noctty = 1;
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "opening %s...", tty->name);
#endif
if (tty->ops->open)
retval = tty->ops->open(tty, filp);
else
retval = -ENODEV;
filp->f_flags = saved_flags;
if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) &&
!capable(CAP_SYS_ADMIN))
retval = -EBUSY;
if (retval) {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "error %d in opening %s...", retval,
tty->name);
#endif
tty_unlock(); /* need to call tty_release without BTM */
tty_release(inode, filp);
if (retval != -ERESTARTSYS)
return retval;
if (signal_pending(current))
return retval;
schedule();
/*
* Need to reset f_op in case a hangup happened.
*/
tty_lock();
if (filp->f_op == &hung_up_tty_fops)
filp->f_op = &tty_fops;
tty_unlock();
goto retry_open;
}
tty_unlock();
mutex_lock(&tty_mutex);
tty_lock();
spin_lock_irq(¤t->sighand->siglock);
if (!noctty &&
current->signal->leader &&
!current->signal->tty &&
tty->session == NULL)
__proc_set_tty(current, tty);
spin_unlock_irq(¤t->sighand->siglock);
tty_unlock();
mutex_unlock(&tty_mutex);
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: static int deflate_comp_init(struct deflate_ctx *ctx)
{
int ret = 0;
struct z_stream_s *stream = &ctx->comp_stream;
stream->workspace = vzalloc(zlib_deflate_workspacesize(
-DEFLATE_DEF_WINBITS, DEFLATE_DEF_MEMLEVEL));
if (!stream->workspace) {
ret = -ENOMEM;
goto out;
}
ret = zlib_deflateInit2(stream, DEFLATE_DEF_LEVEL, Z_DEFLATED,
-DEFLATE_DEF_WINBITS, DEFLATE_DEF_MEMLEVEL,
Z_DEFAULT_STRATEGY);
if (ret != Z_OK) {
ret = -EINVAL;
goto out_free;
}
out:
return ret;
out_free:
vfree(stream->workspace);
goto out;
}
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: static void sctp_add_backlog(struct sock *sk, struct sk_buff *skb)
{
struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk;
struct sctp_ep_common *rcvr = chunk->rcvr;
/* Hold the assoc/ep while hanging on the backlog queue.
* This way, we know structures we need will not disappear from us
*/
if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type)
sctp_association_hold(sctp_assoc(rcvr));
else if (SCTP_EP_TYPE_SOCKET == rcvr->type)
sctp_endpoint_hold(sctp_ep(rcvr));
else
BUG();
sk_add_backlog(sk, skb);
}
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: userauth_hostbased(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
struct sshbuf *b;
struct sshkey *key = NULL;
char *pkalg, *cuser, *chost;
u_char *pkblob, *sig;
size_t alen, blen, slen;
int r, pktype, authenticated = 0;
if (!authctxt->valid) {
debug2("%s: disabled because of invalid user", __func__);
return 0;
}
/* XXX use sshkey_froms() */
if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 ||
(r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 ||
(r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 ||
(r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 ||
(r = sshpkt_get_string(ssh, &sig, &slen)) != 0)
fatal("%s: packet parsing: %s", __func__, ssh_err(r));
debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__,
cuser, chost, pkalg, slen);
#ifdef DEBUG_PK
debug("signature:");
sshbuf_dump_data(sig, siglen, stderr);
#endif
pktype = sshkey_type_from_name(pkalg);
if (pktype == KEY_UNSPEC) {
/* this is perfectly legal */
logit("%s: unsupported public key algorithm: %s",
__func__, pkalg);
goto done;
}
if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) {
error("%s: key_from_blob: %s", __func__, ssh_err(r));
goto done;
}
if (key == NULL) {
error("%s: cannot decode key: %s", __func__, pkalg);
goto done;
}
if (key->type != pktype) {
error("%s: type mismatch for decoded key "
"(received %d, expected %d)", __func__, key->type, pktype);
goto done;
}
if (sshkey_type_plain(key->type) == KEY_RSA &&
(ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
error("Refusing RSA key because peer uses unsafe "
"signature format");
goto done;
}
if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) {
logit("%s: key type %s not in HostbasedAcceptedKeyTypes",
__func__, sshkey_type(key));
goto done;
}
if ((b = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
/* reconstruct packet */
if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 ||
(r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->user)) != 0 ||
(r = sshbuf_put_cstring(b, authctxt->service)) != 0 ||
(r = sshbuf_put_cstring(b, "hostbased")) != 0 ||
(r = sshbuf_put_string(b, pkalg, alen)) != 0 ||
(r = sshbuf_put_string(b, pkblob, blen)) != 0 ||
(r = sshbuf_put_cstring(b, chost)) != 0 ||
(r = sshbuf_put_cstring(b, cuser)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
auth2_record_info(authctxt,
"client user \"%.100s\", client host \"%.100s\"", cuser, chost);
/* test for allowed key and correct signature */
authenticated = 0;
if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) &&
PRIVSEP(sshkey_verify(key, sig, slen,
sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0)
authenticated = 1;
auth2_record_key(authctxt, authenticated, key);
sshbuf_free(b);
done:
debug2("%s: authenticated %d", __func__, authenticated);
sshkey_free(key);
free(pkalg);
free(pkblob);
free(cuser);
free(chost);
free(sig);
return authenticated;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool ContentSecurityPolicy::AllowRequestWithoutIntegrity(
mojom::RequestContextType context,
const KURL& url,
RedirectStatus redirect_status,
SecurityViolationReportingPolicy reporting_policy,
CheckHeaderType check_header_type) const {
for (const auto& policy : policies_) {
if (CheckHeaderTypeMatches(check_header_type, policy->HeaderType()) &&
!policy->AllowRequestWithoutIntegrity(context, url, redirect_status,
reporting_policy))
return false;
}
return true;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: eap_print(netdissect_options *ndo,
register const u_char *cp,
u_int length)
{
const struct eap_frame_t *eap;
const u_char *tptr;
u_int tlen, type, subtype;
int count=0, len;
tptr = cp;
tlen = length;
eap = (const struct eap_frame_t *)cp;
ND_TCHECK(*eap);
/* in non-verbose mode just lets print the basic info */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s (%u) v%u, len %u",
tok2str(eap_frame_type_values, "unknown", eap->type),
eap->type,
eap->version,
EXTRACT_16BITS(eap->length)));
return;
}
ND_PRINT((ndo, "%s (%u) v%u, len %u",
tok2str(eap_frame_type_values, "unknown", eap->type),
eap->type,
eap->version,
EXTRACT_16BITS(eap->length)));
tptr += sizeof(const struct eap_frame_t);
tlen -= sizeof(const struct eap_frame_t);
switch (eap->type) {
case EAP_FRAME_TYPE_PACKET:
type = *(tptr);
len = EXTRACT_16BITS(tptr+2);
ND_PRINT((ndo, ", %s (%u), id %u, len %u",
tok2str(eap_code_values, "unknown", type),
type,
*(tptr+1),
len));
ND_TCHECK2(*tptr, len);
if (type <= 2) { /* For EAP_REQUEST and EAP_RESPONSE only */
subtype = *(tptr+4);
ND_PRINT((ndo, "\n\t\t Type %s (%u)",
tok2str(eap_type_values, "unknown", *(tptr+4)),
*(tptr + 4)));
switch (subtype) {
case EAP_TYPE_IDENTITY:
if (len - 5 > 0) {
ND_PRINT((ndo, ", Identity: "));
safeputs(ndo, tptr + 5, len - 5);
}
break;
case EAP_TYPE_NOTIFICATION:
if (len - 5 > 0) {
ND_PRINT((ndo, ", Notification: "));
safeputs(ndo, tptr + 5, len - 5);
}
break;
case EAP_TYPE_NAK:
count = 5;
/*
* one or more octets indicating
* the desired authentication
* type one octet per type
*/
while (count < len) {
ND_PRINT((ndo, " %s (%u),",
tok2str(eap_type_values, "unknown", *(tptr+count)),
*(tptr + count)));
count++;
}
break;
case EAP_TYPE_TTLS:
ND_PRINT((ndo, " TTLSv%u",
EAP_TTLS_VERSION(*(tptr + 5)))); /* fall through */
case EAP_TYPE_TLS:
ND_PRINT((ndo, " flags [%s] 0x%02x,",
bittok2str(eap_tls_flags_values, "none", *(tptr+5)),
*(tptr + 5)));
if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) {
ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6)));
}
break;
case EAP_TYPE_FAST:
ND_PRINT((ndo, " FASTv%u",
EAP_TTLS_VERSION(*(tptr + 5))));
ND_PRINT((ndo, " flags [%s] 0x%02x,",
bittok2str(eap_tls_flags_values, "none", *(tptr+5)),
*(tptr + 5)));
if (EAP_TLS_EXTRACT_BIT_L(*(tptr+5))) {
ND_PRINT((ndo, " len %u", EXTRACT_32BITS(tptr + 6)));
}
/* FIXME - TLV attributes follow */
break;
case EAP_TYPE_AKA:
case EAP_TYPE_SIM:
ND_PRINT((ndo, " subtype [%s] 0x%02x,",
tok2str(eap_aka_subtype_values, "unknown", *(tptr+5)),
*(tptr + 5)));
/* FIXME - TLV attributes follow */
break;
case EAP_TYPE_MD5_CHALLENGE:
case EAP_TYPE_OTP:
case EAP_TYPE_GTC:
case EAP_TYPE_EXPANDED_TYPES:
case EAP_TYPE_EXPERIMENTAL:
default:
break;
}
}
break;
case EAP_FRAME_TYPE_LOGOFF:
case EAP_FRAME_TYPE_ENCAP_ASF_ALERT:
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|EAP]"));
}
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: struct lib_t* MACH0_(get_libs)(struct MACH0_(obj_t)* bin) {
struct lib_t *libs;
int i;
if (!bin->nlibs)
return NULL;
if (!(libs = calloc ((bin->nlibs + 1), sizeof(struct lib_t))))
return NULL;
for (i = 0; i < bin->nlibs; i++) {
strncpy (libs[i].name, bin->libs[i], R_BIN_MACH0_STRING_LENGTH);
libs[i].name[R_BIN_MACH0_STRING_LENGTH-1] = '\0';
libs[i].last = 0;
}
libs[i].last = 1;
return libs;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void ForceShutdownPlugin(const FilePath& plugin_path) {
PluginProcessHost* plugin =
PluginService::GetInstance()->FindNpapiPluginProcess(plugin_path);
if (plugin)
plugin->ForceShutdown();
}
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 char *get_pid_environ_val(pid_t pid,char *val){
char temp[500];
int i=0;
int foundit=0;
FILE *fp;
sprintf(temp,"/proc/%d/environ",pid);
fp=fopen(temp,"r");
if(fp==NULL)
return NULL;
for(;;){
temp[i]=fgetc(fp);
if(foundit==1 && (temp[i]==0 || temp[i]=='\0' || temp[i]==EOF)){
char *ret;
temp[i]=0;
ret=malloc(strlen(temp)+10);
sprintf(ret,"%s",temp);
fclose(fp);
return ret;
}
switch(temp[i]){
case EOF:
fclose(fp);
return NULL;
case '=':
temp[i]=0;
if(!strcmp(temp,val)){
foundit=1;
}
i=0;
break;
case '\0':
i=0;
break;
default:
i++;
}
}
}
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 v8::Handle<v8::Value> excitingFunctionCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestActiveDOMObject.excitingFunction");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestActiveDOMObject* imp = V8TestActiveDOMObject::toNative(args.Holder());
if (!V8BindingSecurity::canAccessFrame(V8BindingState::Only(), imp->frame(), true))
return v8::Handle<v8::Value>();
EXCEPTION_BLOCK(Node*, nextChild, V8Node::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Node::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->excitingFunction(nextChild);
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: static void keep_curlalive(CURL *curl)
{
SOCKETTYPE sock;
curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
keep_sockalive(sock);
}
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 RenderFrameHostImpl::RenderProcessGone(SiteInstanceImpl* site_instance) {
DCHECK_EQ(site_instance_.get(), site_instance);
if (GetNavigationHandle())
GetNavigationHandle()->set_net_error_code(net::ERR_ABORTED);
ResetLoadingState();
stream_handle_.reset();
set_nav_entry_id(0);
if (is_audible_)
GetProcess()->OnMediaStreamRemoved();
}
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: KioskNextHomeInterfaceBrokerImpl::KioskNextHomeInterfaceBrokerImpl(
content::BrowserContext* context)
: connector_(content::BrowserContext::GetConnectorFor(context)->Clone()),
app_controller_(std::make_unique<AppControllerImpl>(
Profile::FromBrowserContext(context))) {}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags) {
frame_->setFrameOwnerSandboxFlags(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: int ipmi_si_add_smi(struct si_sm_io *io)
{
int rv = 0;
struct smi_info *new_smi, *dup;
if (!io->io_setup) {
if (io->addr_type == IPMI_IO_ADDR_SPACE) {
io->io_setup = ipmi_si_port_setup;
} else if (io->addr_type == IPMI_MEM_ADDR_SPACE) {
io->io_setup = ipmi_si_mem_setup;
} else {
return -EINVAL;
}
}
new_smi = kzalloc(sizeof(*new_smi), GFP_KERNEL);
if (!new_smi)
return -ENOMEM;
spin_lock_init(&new_smi->si_lock);
new_smi->io = *io;
mutex_lock(&smi_infos_lock);
dup = find_dup_si(new_smi);
if (dup) {
if (new_smi->io.addr_source == SI_ACPI &&
dup->io.addr_source == SI_SMBIOS) {
/* We prefer ACPI over SMBIOS. */
dev_info(dup->io.dev,
"Removing SMBIOS-specified %s state machine in favor of ACPI\n",
si_to_str[new_smi->io.si_type]);
cleanup_one_si(dup);
} else {
dev_info(new_smi->io.dev,
"%s-specified %s state machine: duplicate\n",
ipmi_addr_src_to_str(new_smi->io.addr_source),
si_to_str[new_smi->io.si_type]);
rv = -EBUSY;
kfree(new_smi);
goto out_err;
}
}
pr_info("Adding %s-specified %s state machine\n",
ipmi_addr_src_to_str(new_smi->io.addr_source),
si_to_str[new_smi->io.si_type]);
list_add_tail(&new_smi->link, &smi_infos);
if (initialized)
rv = try_smi_init(new_smi);
out_err:
mutex_unlock(&smi_infos_lock);
return rv;
}
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 PrintMsg_Print_Params::Reset() {
page_size = gfx::Size();
content_size = gfx::Size();
printable_area = gfx::Rect();
margin_top = 0;
margin_left = 0;
dpi = 0;
scale_factor = 1.0f;
rasterize_pdf = false;
document_cookie = 0;
selection_only = false;
supports_alpha_blend = false;
preview_ui_id = -1;
preview_request_id = 0;
is_first_request = false;
print_scaling_option = blink::kWebPrintScalingOptionSourceSize;
print_to_pdf = false;
display_header_footer = false;
title = base::string16();
url = base::string16();
should_print_backgrounds = false;
printed_doc_type = printing::SkiaDocumentType::PDF;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: parse_async_tlv(const struct ofpbuf *property,
const struct ofp14_async_prop *ap,
struct ofputil_async_cfg *ac,
enum ofp_version version, bool loose)
{
enum ofperr error;
ovs_be32 mask;
error = ofpprop_parse_be32(property, &mask);
if (error) {
return error;
}
if (ofpprop_is_experimenter(ap->prop_type)) {
/* For experimenter properties, whether a property is for the master or
* slave role is indicated by both 'type' and 'exp_type' in struct
* ofp_prop_experimenter. Check that these are consistent. */
const struct ofp_prop_experimenter *ope = property->data;
bool should_be_master = ope->type == htons(0xffff);
if (should_be_master != ap->master) {
VLOG_WARN_RL(&bad_ofmsg_rl, "async property type %#"PRIx16" "
"indicates %s role but exp_type %"PRIu32" indicates "
"%s role",
ntohs(ope->type),
should_be_master ? "master" : "slave",
ntohl(ope->exp_type),
ap->master ? "master" : "slave");
return OFPERR_OFPBPC_BAD_EXP_TYPE;
}
}
return decode_async_mask(mask, ap, version, loose, ac);
}
CWE ID: CWE-617
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: Round_Up_To_Grid( TT_ExecContext exc,
FT_F26Dot6 distance,
FT_F26Dot6 compensation )
{
FT_F26Dot6 val;
FT_UNUSED( exc );
if ( distance >= 0 )
{
val = FT_PIX_CEIL_LONG( ADD_LONG( distance, compensation ) );
if ( val < 0 )
val = 0;
}
else
{
val = NEG_LONG( FT_PIX_CEIL_LONG( SUB_LONG( compensation,
distance ) ) );
if ( val > 0 )
val = 0;
}
return val;
}
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: OJPEGPreDecode(TIFF* tif, uint16 s)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint32 m;
if (sp->subsamplingcorrect_done==0)
OJPEGSubsamplingCorrect(tif);
if (sp->readheader_done==0)
{
if (OJPEGReadHeaderInfo(tif)==0)
return(0);
}
if (sp->sos_end[s].log==0)
{
if (OJPEGReadSecondarySos(tif,s)==0)
return(0);
}
if isTiled(tif)
m=tif->tif_curtile;
else
m=tif->tif_curstrip;
if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m)))
{
if (sp->libjpeg_session_active!=0)
OJPEGLibjpegSessionAbort(tif);
sp->writeheader_done=0;
}
if (sp->writeheader_done==0)
{
sp->plane_sample_offset=(uint8)s;
sp->write_cursample=s;
sp->write_curstrile=s*tif->tif_dir.td_stripsperimage;
if ((sp->in_buffer_file_pos_log==0) ||
(sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos))
{
sp->in_buffer_source=sp->sos_end[s].in_buffer_source;
sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile;
sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos;
sp->in_buffer_file_pos_log=0;
sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo;
sp->in_buffer_togo=0;
sp->in_buffer_cur=0;
}
if (OJPEGWriteHeaderInfo(tif)==0)
return(0);
}
while (sp->write_curstrile<m)
{
if (sp->libjpeg_jpeg_query_style==0)
{
if (OJPEGPreDecodeSkipRaw(tif)==0)
return(0);
}
else
{
if (OJPEGPreDecodeSkipScanlines(tif)==0)
return(0);
}
sp->write_curstrile++;
}
return(1);
}
CWE ID: CWE-369
Target: 1
Example 2:
Code: void DevToolsUIBindings::SetDelegate(Delegate* delegate) {
delegate_.reset(delegate);
}
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 PlatformSensorProviderAndroid::CreateSensorInternal(
mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
JNIEnv* env = AttachCurrentThread();
switch (type) {
case mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES:
CreateAbsoluteOrientationEulerAnglesSensor(env, std::move(mapping),
callback);
break;
case mojom::SensorType::ABSOLUTE_ORIENTATION_QUATERNION:
CreateAbsoluteOrientationQuaternionSensor(env, std::move(mapping),
callback);
break;
case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES:
CreateRelativeOrientationEulerAnglesSensor(env, std::move(mapping),
callback);
break;
default: {
ScopedJavaLocalRef<jobject> sensor =
Java_PlatformSensorProvider_createSensor(env, j_object_,
static_cast<jint>(type));
if (!sensor.obj()) {
callback.Run(nullptr);
return;
}
auto concrete_sensor = base::MakeRefCounted<PlatformSensorAndroid>(
type, std::move(mapping), this, sensor);
callback.Run(concrete_sensor);
break;
}
}
}
CWE ID: CWE-732
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 i2c_deblock_gpio_cfg(void)
{
/* set I2C bus 1 deblocking GPIOs input, but 0 value for open drain */
qrio_gpio_direction_input(DEBLOCK_PORT1, DEBLOCK_SCL1);
qrio_gpio_direction_input(DEBLOCK_PORT1, DEBLOCK_SDA1);
qrio_set_gpio(DEBLOCK_PORT1, DEBLOCK_SCL1, 0);
qrio_set_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1, 0);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int slabstats_open(struct inode *inode, struct file *file)
{
unsigned long *n;
n = __seq_open_private(file, &slabstats_op, PAGE_SIZE);
if (!n)
return -ENOMEM;
*n = PAGE_SIZE / (2 * sizeof(unsigned long));
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void perf_event_interrupt(struct pt_regs *regs)
{
int i;
struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
struct perf_event *event;
unsigned long val;
int found = 0;
int nmi;
if (cpuhw->n_limited)
freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5),
mfspr(SPRN_PMC6));
perf_read_regs(regs);
nmi = perf_intr_is_nmi(regs);
if (nmi)
nmi_enter();
else
irq_enter();
for (i = 0; i < cpuhw->n_events; ++i) {
event = cpuhw->event[i];
if (!event->hw.idx || is_limited_pmc(event->hw.idx))
continue;
val = read_pmc(event->hw.idx);
if ((int)val < 0) {
/* event has overflowed */
found = 1;
record_and_restart(event, val, regs, nmi);
}
}
/*
* In case we didn't find and reset the event that caused
* the interrupt, scan all events and reset any that are
* negative, to avoid getting continual interrupts.
* Any that we processed in the previous loop will not be negative.
*/
if (!found) {
for (i = 0; i < ppmu->n_counter; ++i) {
if (is_limited_pmc(i + 1))
continue;
val = read_pmc(i + 1);
if ((int)val < 0)
write_pmc(i + 1, 0);
}
}
/*
* Reset MMCR0 to its normal value. This will set PMXE and
* clear FC (freeze counters) and PMAO (perf mon alert occurred)
* and thus allow interrupts to occur again.
* XXX might want to use MSR.PM to keep the events frozen until
* we get back out of this interrupt.
*/
write_mmcr0(cpuhw, cpuhw->mmcr[0]);
if (nmi)
nmi_exit();
else
irq_exit();
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int snd_ctl_elem_user_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct user_element *ue = kcontrol->private_data;
memcpy(&ucontrol->value, ue->elem_data, ue->elem_data_size);
return 0;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int complete_emulated_pio(struct kvm_vcpu *vcpu)
{
BUG_ON(!vcpu->arch.pio.count);
return complete_emulated_io(vcpu);
}
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: AppCacheBackendImpl::~AppCacheBackendImpl() {
STLDeleteValues(&hosts_);
if (service_)
service_->UnregisterBackend(this);
}
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 RenderThreadImpl::Shutdown() {
FOR_EACH_OBSERVER(
RenderProcessObserver, observers_, OnRenderProcessShutdown());
ChildThread::Shutdown();
if (memory_observer_) {
message_loop()->RemoveTaskObserver(memory_observer_.get());
memory_observer_.reset();
}
if (webkit_platform_support_) {
webkit_platform_support_->web_database_observer_impl()->
WaitForAllDatabasesToClose();
}
if (devtools_agent_message_filter_.get()) {
RemoveFilter(devtools_agent_message_filter_.get());
devtools_agent_message_filter_ = NULL;
}
RemoveFilter(audio_input_message_filter_.get());
audio_input_message_filter_ = NULL;
RemoveFilter(audio_message_filter_.get());
audio_message_filter_ = NULL;
#if defined(ENABLE_WEBRTC)
RTCPeerConnectionHandler::DestructAllHandlers();
peer_connection_factory_.reset();
#endif
RemoveFilter(vc_manager_->video_capture_message_filter());
vc_manager_.reset();
RemoveFilter(db_message_filter_.get());
db_message_filter_ = NULL;
if (file_thread_)
file_thread_->Stop();
if (compositor_output_surface_filter_.get()) {
RemoveFilter(compositor_output_surface_filter_.get());
compositor_output_surface_filter_ = NULL;
}
media_thread_.reset();
compositor_thread_.reset();
input_handler_manager_.reset();
if (input_event_filter_.get()) {
RemoveFilter(input_event_filter_.get());
input_event_filter_ = NULL;
}
embedded_worker_dispatcher_.reset();
main_thread_indexed_db_dispatcher_.reset();
if (webkit_platform_support_)
blink::shutdown();
lazy_tls.Pointer()->Set(NULL);
#if defined(OS_WIN)
NPChannelBase::CleanupChannels();
#endif
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int old_rsa_priv_decode(EVP_PKEY *pkey,
const unsigned char **pder, int derlen)
{
RSA *rsa;
if (!(rsa = d2i_RSAPrivateKey(NULL, pder, derlen))) {
RSAerr(RSA_F_OLD_RSA_PRIV_DECODE, ERR_R_RSA_LIB);
return 0;
}
EVP_PKEY_assign_RSA(pkey, rsa);
return 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: Chapters::~Chapters() {
while (m_editions_count > 0) {
Edition& e = m_editions[--m_editions_count];
e.Clear();
}
}
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: PlatformFileForTransit GetFileHandleForProcess(base::PlatformFile handle,
base::ProcessHandle process,
bool close_source_handle) {
IPC::PlatformFileForTransit out_handle;
#if defined(OS_WIN)
DWORD options = DUPLICATE_SAME_ACCESS;
if (close_source_handle)
options |= DUPLICATE_CLOSE_SOURCE;
if (!::DuplicateHandle(::GetCurrentProcess(),
handle,
process,
&out_handle,
0,
FALSE,
options)) {
out_handle = IPC::InvalidPlatformFileForTransit();
}
#elif defined(OS_POSIX)
int fd = close_source_handle ? handle : ::dup(handle);
out_handle = base::FileDescriptor(fd, true);
#else
#error Not implemented.
#endif
return out_handle;
}
CWE ID:
Target: 1
Example 2:
Code: ProcShmAttachFd(ClientPtr client)
{
int fd;
ShmDescPtr shmdesc;
REQUEST(xShmAttachFdReq);
struct stat statb;
SetReqFds(client, 1);
REQUEST_SIZE_MATCH(xShmAttachFdReq);
LEGAL_NEW_RESOURCE(stuff->shmseg, client);
if ((stuff->readOnly != xTrue) && (stuff->readOnly != xFalse)) {
client->errorValue = stuff->readOnly;
return BadValue;
}
fd = ReadFdFromClient(client);
if (fd < 0)
return BadMatch;
if (fstat(fd, &statb) < 0 || statb.st_size == 0) {
close(fd);
return BadMatch;
}
shmdesc = malloc(sizeof(ShmDescRec));
if (!shmdesc) {
close(fd);
return BadAlloc;
}
shmdesc->is_fd = TRUE;
shmdesc->addr = mmap(NULL, statb.st_size,
stuff->readOnly ? PROT_READ : PROT_READ|PROT_WRITE,
MAP_SHARED,
fd, 0);
close(fd);
if (shmdesc->addr == ((char *) -1)) {
free(shmdesc);
return BadAccess;
}
shmdesc->refcnt = 1;
shmdesc->writable = !stuff->readOnly;
shmdesc->size = statb.st_size;
shmdesc->resource = stuff->shmseg;
shmdesc->busfault = busfault_register_mmap(shmdesc->addr, shmdesc->size, ShmBusfaultNotify, shmdesc);
if (!shmdesc->busfault) {
munmap(shmdesc->addr, shmdesc->size);
free(shmdesc);
return BadAlloc;
}
shmdesc->next = Shmsegs;
Shmsegs = shmdesc;
if (!AddResource(stuff->shmseg, ShmSegType, (void *) shmdesc))
return BadAlloc;
return Success;
}
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: void StyleResolver::popParentShadowRoot(const ShadowRoot& shadowRoot)
{
ASSERT(shadowRoot.host());
m_styleTree.popStyleCache(shadowRoot);
}
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: jbig2_sd_cat(Jbig2Ctx *ctx, int n_dicts, Jbig2SymbolDict **dicts)
{
int i, j, k, symbols;
Jbig2SymbolDict *new = NULL;
/* count the imported symbols and allocate a new array */
symbols = 0;
for (i = 0; i < n_dicts; i++)
symbols += dicts[i]->n_symbols;
/* fill a new array with cloned glyph pointers */
new = jbig2_sd_new(ctx, symbols);
if (new != NULL) {
k = 0;
for (i = 0; i < n_dicts; i++)
for (j = 0; j < dicts[i]->n_symbols; j++)
new->glyphs[k++] = jbig2_image_clone(ctx, dicts[i]->glyphs[j]);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "failed to allocate new symbol dictionary");
}
return new;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int err)
{
ctx->error = err;
}
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: int ASN1_item_ndef_i2d(ASN1_VALUE *val, unsigned char **out,
const ASN1_ITEM *it)
{
return asn1_item_flags_i2d(val, out, it, ASN1_TFLG_NDEF);
}
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 BluetoothDeviceChromeOS::UnregisterAgent() {
if (!agent_.get())
return;
DCHECK(pairing_delegate_);
DCHECK(pincode_callback_.is_null());
DCHECK(passkey_callback_.is_null());
DCHECK(confirmation_callback_.is_null());
pairing_delegate_->DismissDisplayOrConfirm();
pairing_delegate_ = NULL;
agent_.reset();
VLOG(1) << object_path_.value() << ": Unregistering pairing agent";
DBusThreadManager::Get()->GetBluetoothAgentManagerClient()->
UnregisterAgent(
dbus::ObjectPath(kAgentPath),
base::Bind(&base::DoNothing),
base::Bind(&BluetoothDeviceChromeOS::OnUnregisterAgentError,
weak_ptr_factory_.GetWeakPtr()));
}
CWE ID:
Target: 1
Example 2:
Code: get_minst_from_memory(const gs_memory_t *mem)
{
#ifdef PSI_INCLUDED
extern gs_main_instance *ps_impl_get_minst( const gs_memory_t *mem );
return ps_impl_get_minst(mem);
#else
return (gs_main_instance*)mem->gs_lib_ctx->top_of_system;
#endif
}
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: bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::SubmitDecode(
const scoped_refptr<VP8Picture>& pic,
const Vp8FrameHeader* frame_hdr,
const scoped_refptr<VP8Picture>& last_frame,
const scoped_refptr<VP8Picture>& golden_frame,
const scoped_refptr<VP8Picture>& alt_frame) {
VAIQMatrixBufferVP8 iq_matrix_buf;
memset(&iq_matrix_buf, 0, sizeof(VAIQMatrixBufferVP8));
const Vp8SegmentationHeader& sgmnt_hdr = frame_hdr->segmentation_hdr;
const Vp8QuantizationHeader& quant_hdr = frame_hdr->quantization_hdr;
static_assert(arraysize(iq_matrix_buf.quantization_index) == kMaxMBSegments,
"incorrect quantization matrix size");
for (size_t i = 0; i < kMaxMBSegments; ++i) {
int q = quant_hdr.y_ac_qi;
if (sgmnt_hdr.segmentation_enabled) {
if (sgmnt_hdr.segment_feature_mode ==
Vp8SegmentationHeader::FEATURE_MODE_ABSOLUTE)
q = sgmnt_hdr.quantizer_update_value[i];
else
q += sgmnt_hdr.quantizer_update_value[i];
}
#define CLAMP_Q(q) std::min(std::max(q, 0), 127)
static_assert(arraysize(iq_matrix_buf.quantization_index[i]) == 6,
"incorrect quantization matrix size");
iq_matrix_buf.quantization_index[i][0] = CLAMP_Q(q);
iq_matrix_buf.quantization_index[i][1] = CLAMP_Q(q + quant_hdr.y_dc_delta);
iq_matrix_buf.quantization_index[i][2] = CLAMP_Q(q + quant_hdr.y2_dc_delta);
iq_matrix_buf.quantization_index[i][3] = CLAMP_Q(q + quant_hdr.y2_ac_delta);
iq_matrix_buf.quantization_index[i][4] = CLAMP_Q(q + quant_hdr.uv_dc_delta);
iq_matrix_buf.quantization_index[i][5] = CLAMP_Q(q + quant_hdr.uv_ac_delta);
#undef CLAMP_Q
}
if (!vaapi_wrapper_->SubmitBuffer(
VAIQMatrixBufferType, sizeof(VAIQMatrixBufferVP8), &iq_matrix_buf))
return false;
VAProbabilityDataBufferVP8 prob_buf;
memset(&prob_buf, 0, sizeof(VAProbabilityDataBufferVP8));
const Vp8EntropyHeader& entr_hdr = frame_hdr->entropy_hdr;
ARRAY_MEMCPY_CHECKED(prob_buf.dct_coeff_probs, entr_hdr.coeff_probs);
if (!vaapi_wrapper_->SubmitBuffer(VAProbabilityBufferType,
sizeof(VAProbabilityDataBufferVP8),
&prob_buf))
return false;
VAPictureParameterBufferVP8 pic_param;
memset(&pic_param, 0, sizeof(VAPictureParameterBufferVP8));
pic_param.frame_width = frame_hdr->width;
pic_param.frame_height = frame_hdr->height;
if (last_frame) {
scoped_refptr<VaapiDecodeSurface> last_frame_surface =
VP8PictureToVaapiDecodeSurface(last_frame);
pic_param.last_ref_frame = last_frame_surface->va_surface()->id();
} else {
pic_param.last_ref_frame = VA_INVALID_SURFACE;
}
if (golden_frame) {
scoped_refptr<VaapiDecodeSurface> golden_frame_surface =
VP8PictureToVaapiDecodeSurface(golden_frame);
pic_param.golden_ref_frame = golden_frame_surface->va_surface()->id();
} else {
pic_param.golden_ref_frame = VA_INVALID_SURFACE;
}
if (alt_frame) {
scoped_refptr<VaapiDecodeSurface> alt_frame_surface =
VP8PictureToVaapiDecodeSurface(alt_frame);
pic_param.alt_ref_frame = alt_frame_surface->va_surface()->id();
} else {
pic_param.alt_ref_frame = VA_INVALID_SURFACE;
}
pic_param.out_of_loop_frame = VA_INVALID_SURFACE;
const Vp8LoopFilterHeader& lf_hdr = frame_hdr->loopfilter_hdr;
#define FHDR_TO_PP_PF(a, b) pic_param.pic_fields.bits.a = (b)
FHDR_TO_PP_PF(key_frame, frame_hdr->IsKeyframe() ? 0 : 1);
FHDR_TO_PP_PF(version, frame_hdr->version);
FHDR_TO_PP_PF(segmentation_enabled, sgmnt_hdr.segmentation_enabled);
FHDR_TO_PP_PF(update_mb_segmentation_map,
sgmnt_hdr.update_mb_segmentation_map);
FHDR_TO_PP_PF(update_segment_feature_data,
sgmnt_hdr.update_segment_feature_data);
FHDR_TO_PP_PF(filter_type, lf_hdr.type);
FHDR_TO_PP_PF(sharpness_level, lf_hdr.sharpness_level);
FHDR_TO_PP_PF(loop_filter_adj_enable, lf_hdr.loop_filter_adj_enable);
FHDR_TO_PP_PF(mode_ref_lf_delta_update, lf_hdr.mode_ref_lf_delta_update);
FHDR_TO_PP_PF(sign_bias_golden, frame_hdr->sign_bias_golden);
FHDR_TO_PP_PF(sign_bias_alternate, frame_hdr->sign_bias_alternate);
FHDR_TO_PP_PF(mb_no_coeff_skip, frame_hdr->mb_no_skip_coeff);
FHDR_TO_PP_PF(loop_filter_disable, lf_hdr.level == 0);
#undef FHDR_TO_PP_PF
ARRAY_MEMCPY_CHECKED(pic_param.mb_segment_tree_probs, sgmnt_hdr.segment_prob);
static_assert(arraysize(sgmnt_hdr.lf_update_value) ==
arraysize(pic_param.loop_filter_level),
"loop filter level arrays mismatch");
for (size_t i = 0; i < arraysize(sgmnt_hdr.lf_update_value); ++i) {
int lf_level = lf_hdr.level;
if (sgmnt_hdr.segmentation_enabled) {
if (sgmnt_hdr.segment_feature_mode ==
Vp8SegmentationHeader::FEATURE_MODE_ABSOLUTE)
lf_level = sgmnt_hdr.lf_update_value[i];
else
lf_level += sgmnt_hdr.lf_update_value[i];
}
lf_level = std::min(std::max(lf_level, 0), 63);
pic_param.loop_filter_level[i] = lf_level;
}
static_assert(
arraysize(lf_hdr.ref_frame_delta) ==
arraysize(pic_param.loop_filter_deltas_ref_frame) &&
arraysize(lf_hdr.mb_mode_delta) ==
arraysize(pic_param.loop_filter_deltas_mode) &&
arraysize(lf_hdr.ref_frame_delta) == arraysize(lf_hdr.mb_mode_delta),
"loop filter deltas arrays size mismatch");
for (size_t i = 0; i < arraysize(lf_hdr.ref_frame_delta); ++i) {
pic_param.loop_filter_deltas_ref_frame[i] = lf_hdr.ref_frame_delta[i];
pic_param.loop_filter_deltas_mode[i] = lf_hdr.mb_mode_delta[i];
}
#define FHDR_TO_PP(a) pic_param.a = frame_hdr->a
FHDR_TO_PP(prob_skip_false);
FHDR_TO_PP(prob_intra);
FHDR_TO_PP(prob_last);
FHDR_TO_PP(prob_gf);
#undef FHDR_TO_PP
ARRAY_MEMCPY_CHECKED(pic_param.y_mode_probs, entr_hdr.y_mode_probs);
ARRAY_MEMCPY_CHECKED(pic_param.uv_mode_probs, entr_hdr.uv_mode_probs);
ARRAY_MEMCPY_CHECKED(pic_param.mv_probs, entr_hdr.mv_probs);
pic_param.bool_coder_ctx.range = frame_hdr->bool_dec_range;
pic_param.bool_coder_ctx.value = frame_hdr->bool_dec_value;
pic_param.bool_coder_ctx.count = frame_hdr->bool_dec_count;
if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType,
sizeof(pic_param), &pic_param))
return false;
VASliceParameterBufferVP8 slice_param;
memset(&slice_param, 0, sizeof(slice_param));
slice_param.slice_data_size = frame_hdr->frame_size;
slice_param.slice_data_offset = frame_hdr->first_part_offset;
slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL;
slice_param.macroblock_offset = frame_hdr->macroblock_bit_offset;
slice_param.num_of_partitions = frame_hdr->num_of_dct_partitions + 1;
slice_param.partition_size[0] =
frame_hdr->first_part_size - ((frame_hdr->macroblock_bit_offset + 7) / 8);
for (size_t i = 0; i < frame_hdr->num_of_dct_partitions; ++i)
slice_param.partition_size[i + 1] = frame_hdr->dct_partition_sizes[i];
if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType,
sizeof(VASliceParameterBufferVP8),
&slice_param))
return false;
void* non_const_ptr = const_cast<uint8_t*>(frame_hdr->data);
if (!vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType,
frame_hdr->frame_size, non_const_ptr))
return false;
scoped_refptr<VaapiDecodeSurface> dec_surface =
VP8PictureToVaapiDecodeSurface(pic);
return vaapi_dec_->DecodeSurface(dec_surface);
}
CWE ID: CWE-362
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd,
unsigned long arg)
{
struct oabi_flock64 user;
struct flock64 kernel;
mm_segment_t fs = USER_DS; /* initialized to kill a warning */
unsigned long local_arg = arg;
int ret;
switch (cmd) {
case F_OFD_GETLK:
case F_OFD_SETLK:
case F_OFD_SETLKW:
case F_GETLK64:
case F_SETLK64:
case F_SETLKW64:
if (copy_from_user(&user, (struct oabi_flock64 __user *)arg,
sizeof(user)))
return -EFAULT;
kernel.l_type = user.l_type;
kernel.l_whence = user.l_whence;
kernel.l_start = user.l_start;
kernel.l_len = user.l_len;
kernel.l_pid = user.l_pid;
local_arg = (unsigned long)&kernel;
fs = get_fs();
set_fs(KERNEL_DS);
}
ret = sys_fcntl64(fd, cmd, local_arg);
switch (cmd) {
case F_GETLK64:
if (!ret) {
user.l_type = kernel.l_type;
user.l_whence = kernel.l_whence;
user.l_start = kernel.l_start;
user.l_len = kernel.l_len;
user.l_pid = kernel.l_pid;
if (copy_to_user((struct oabi_flock64 __user *)arg,
&user, sizeof(user)))
ret = -EFAULT;
}
case F_SETLK64:
case F_SETLKW64:
set_fs(fs);
}
return ret;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void set_process_cpu_timer(struct task_struct *tsk, unsigned int clock_idx,
cputime_t *newval, cputime_t *oldval)
{
union cpu_time_count now;
struct list_head *head;
BUG_ON(clock_idx == CPUCLOCK_SCHED);
cpu_clock_sample_group_locked(clock_idx, tsk, &now);
if (oldval) {
if (!cputime_eq(*oldval, cputime_zero)) {
if (cputime_le(*oldval, now.cpu)) {
/* Just about to fire. */
*oldval = jiffies_to_cputime(1);
} else {
*oldval = cputime_sub(*oldval, now.cpu);
}
}
if (cputime_eq(*newval, cputime_zero))
return;
*newval = cputime_add(*newval, now.cpu);
/*
* If the RLIMIT_CPU timer will expire before the
* ITIMER_PROF timer, we have nothing else to do.
*/
if (tsk->signal->rlim[RLIMIT_CPU].rlim_cur
< cputime_to_secs(*newval))
return;
}
/*
* Check whether there are any process timers already set to fire
* before this one. If so, we don't have anything more to do.
*/
head = &tsk->signal->cpu_timers[clock_idx];
if (list_empty(head) ||
cputime_ge(list_first_entry(head,
struct cpu_timer_list, entry)->expires.cpu,
*newval)) {
/*
* Rejigger each thread's expiry time so that one will
* notice before we hit the process-cumulative expiry time.
*/
union cpu_time_count expires = { .sched = 0 };
expires.cpu = *newval;
process_timer_rebalance(tsk, clock_idx, expires, now);
}
}
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: my_object_get_value (MyObject *obj, guint *ret, GError **error)
{
*ret = obj->val;
return TRUE;
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: VOID ixheaacd_shiftrountine_with_rnd_hq(WORD32 *qmf_real, WORD32 *qmf_imag,
WORD32 *filter_states, WORD32 len,
WORD32 shift) {
WORD32 *filter_states_rev = filter_states + len;
WORD32 treal, timag;
WORD32 j;
for (j = (len - 1); j >= 0; j -= 2) {
WORD32 r1, r2, i1, i2;
i2 = qmf_imag[j];
r2 = qmf_real[j];
r1 = *qmf_real++;
i1 = *qmf_imag++;
timag = ixheaacd_add32(i1, r1);
timag = (ixheaacd_shl32_sat(timag, shift));
filter_states_rev[j] = timag;
treal = ixheaacd_sub32(i2, r2);
treal = (ixheaacd_shl32_sat(treal, shift));
filter_states[j] = treal;
treal = ixheaacd_sub32(i1, r1);
treal = (ixheaacd_shl32_sat(treal, shift));
*filter_states++ = treal;
timag = ixheaacd_add32(i2, r2);
timag = (ixheaacd_shl32_sat(timag, shift));
*filter_states_rev++ = timag;
}
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
loff_t len)
{
handle_t *handle;
loff_t size = i_size_read(inode);
WARN_ON(!inode_is_locked(inode));
if (offset > size || offset + len < size)
return 0;
if (EXT4_I(inode)->i_disksize >= size)
return 0;
handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
if (IS_ERR(handle))
return PTR_ERR(handle);
ext4_update_i_disksize(inode, size);
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
return 0;
}
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: int jpc_bitstream_putbits(jpc_bitstream_t *bitstream, int n, long v)
{
int m;
/* We can reliably put at most 31 bits since ISO/IEC 9899 only
guarantees that a long can represent values up to 2^31-1. */
assert(n >= 0 && n < 32);
/* Ensure that only the bits to be output are nonzero. */
assert(!(v & (~JAS_ONES(n))));
/* Put the desired number of bits to the specified bit stream. */
m = n - 1;
while (--n >= 0) {
if (jpc_bitstream_putbit(bitstream, (v >> m) & 1) == EOF) {
return EOF;
}
v <<= 1;
}
return 0;
}
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 nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
{
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
memcpy(state->stateid.data, stateid->data, sizeof(state->stateid.data));
memcpy(state->open_stateid.data, stateid->data, sizeof(state->open_stateid.data));
switch (open_flags) {
case FMODE_READ:
set_bit(NFS_O_RDONLY_STATE, &state->flags);
break;
case FMODE_WRITE:
set_bit(NFS_O_WRONLY_STATE, &state->flags);
break;
case FMODE_READ|FMODE_WRITE:
set_bit(NFS_O_RDWR_STATE, &state->flags);
}
}
CWE ID:
Target: 1
Example 2:
Code: unsigned long Tracks::GetTracksCount() const {
const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries;
assert(result >= 0);
return static_cast<unsigned long>(result);
}
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 bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kSegCountOffset = 6;
const size_t kEndCountOffset = 14;
const size_t kHeaderSize = 16;
const size_t kSegmentSize = 8; // total size of array elements for one segment
if (kEndCountOffset > size) {
return false;
}
size_t segCount = readU16(data, kSegCountOffset) >> 1;
if (kHeaderSize + segCount * kSegmentSize > size) {
return false;
}
for (size_t i = 0; i < segCount; i++) {
int end = readU16(data, kEndCountOffset + 2 * i);
int start = readU16(data, kHeaderSize + 2 * (segCount + i));
int rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i));
if (rangeOffset == 0) {
int delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i));
if (((end + delta) & 0xffff) > end - start) {
addRange(coverage, start, end + 1);
} else {
for (int j = start; j < end + 1; j++) {
if (((j + delta) & 0xffff) != 0) {
addRange(coverage, j, j + 1);
}
}
}
} else {
for (int j = start; j < end + 1; j++) {
uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset +
(i + j - start) * 2;
if (actualRangeOffset + 2 > size) {
return false;
}
int glyphId = readU16(data, actualRangeOffset);
if (glyphId != 0) {
addRange(coverage, j, j + 1);
}
}
}
}
return true;
}
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: tt_size_reset( TT_Size size,
FT_Bool only_height )
{
TT_Face face;
FT_Size_Metrics* metrics;
size->ttmetrics.valid = FALSE;
face = (TT_Face)size->root.face;
metrics = &size->metrics;
/* copy the result from base layer */
/* This bit flag, if set, indicates that the ppems must be */
/* rounded to integers. Nearly all TrueType fonts have this bit */
/* set, as hinting won't work really well otherwise. */
/* */
if ( face->header.Flags & 8 )
{
metrics->ascender =
FT_PIX_ROUND( FT_MulFix( face->root.ascender, metrics->y_scale ) );
metrics->descender =
FT_PIX_ROUND( FT_MulFix( face->root.descender, metrics->y_scale ) );
metrics->height =
FT_PIX_ROUND( FT_MulFix( face->root.height, metrics->y_scale ) );
}
size->ttmetrics.valid = TRUE;
if ( only_height )
return FT_Err_Ok;
if ( face->header.Flags & 8 )
{
metrics->x_scale = FT_DivFix( metrics->x_ppem << 6,
face->root.units_per_EM );
metrics->y_scale = FT_DivFix( metrics->y_ppem << 6,
face->root.units_per_EM );
metrics->max_advance =
FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width,
metrics->x_scale ) );
}
/* compute new transformation */
if ( metrics->x_ppem >= metrics->y_ppem )
{
size->ttmetrics.scale = metrics->x_scale;
size->ttmetrics.ppem = metrics->x_ppem;
size->ttmetrics.x_ratio = 0x10000L;
size->ttmetrics.y_ratio = FT_DivFix( metrics->y_ppem,
metrics->x_ppem );
}
else
{
size->ttmetrics.scale = metrics->y_scale;
size->ttmetrics.ppem = metrics->y_ppem;
size->ttmetrics.x_ratio = FT_DivFix( metrics->x_ppem,
metrics->y_ppem );
size->ttmetrics.y_ratio = 0x10000L;
}
#ifdef TT_USE_BYTECODE_INTERPRETER
size->cvt_ready = -1;
#endif /* TT_USE_BYTECODE_INTERPRETER */
return FT_Err_Ok;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void InspectorHandler::Wire(UberDispatcher* dispatcher) {
frontend_.reset(new Inspector::Frontend(dispatcher->channel()));
Inspector::Dispatcher::wire(dispatcher, this);
}
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 jas_image_cmpt_t *jas_image_cmpt_create0()
{
jas_image_cmpt_t *cmpt;
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
return 0;
}
memset(cmpt, 0, sizeof(jas_image_cmpt_t));
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
return cmpt;
}
CWE ID: CWE-190
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
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(ext4_mb_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) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return 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: void HTMLFormElement::copyNonAttributePropertiesFromElement(
const Element& source) {
m_wasDemoted = static_cast<const HTMLFormElement&>(source).m_wasDemoted;
HTMLElement::copyNonAttributePropertiesFromElement(source);
}
CWE ID: CWE-19
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
{
char dir_name[ITOA_MAX_LEN * 2];
struct kvm_stat_data *stat_data;
struct kvm_stats_debugfs_item *p;
if (!debugfs_initialized())
return 0;
snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
kvm->debugfs_dentry = debugfs_create_dir(dir_name,
kvm_debugfs_dir);
if (!kvm->debugfs_dentry)
return -ENOMEM;
kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
sizeof(*kvm->debugfs_stat_data),
GFP_KERNEL);
if (!kvm->debugfs_stat_data)
return -ENOMEM;
for (p = debugfs_entries; p->name; p++) {
stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
if (!stat_data)
return -ENOMEM;
stat_data->kvm = kvm;
stat_data->offset = p->offset;
kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
if (!debugfs_create_file(p->name, 0444,
kvm->debugfs_dentry,
stat_data,
stat_fops_per_vm[p->kind]))
return -ENOMEM;
}
return 0;
}
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: cib_remote_perform_op(cib_t * cib, const char *op, const char *host, const char *section,
xmlNode * data, xmlNode ** output_data, int call_options, const char *name)
{
int rc = pcmk_ok;
xmlNode *op_msg = NULL;
xmlNode *op_reply = NULL;
cib_remote_opaque_t *private = cib->variant_opaque;
if (sync_timer == NULL) {
sync_timer = calloc(1, sizeof(struct timer_rec_s));
}
if (cib->state == cib_disconnected) {
return -ENOTCONN;
}
if (output_data != NULL) {
*output_data = NULL;
}
if (op == NULL) {
crm_err("No operation specified");
return -EINVAL;
}
cib->call_id++;
/* prevent call_id from being negative (or zero) and conflicting
* with the cib_errors enum
* use 2 because we use it as (cib->call_id - 1) below
*/
if (cib->call_id < 1) {
cib->call_id = 1;
}
op_msg =
cib_create_op(cib->call_id, private->callback.token, op, host, section, data, call_options,
NULL);
if (op_msg == NULL) {
return -EPROTO;
}
crm_trace("Sending %s message to CIB service", op);
crm_send_remote_msg(private->command.session, op_msg, private->command.encrypted);
free_xml(op_msg);
if ((call_options & cib_discard_reply)) {
crm_trace("Discarding reply");
return pcmk_ok;
} else if (!(call_options & cib_sync_call)) {
return cib->call_id;
}
crm_trace("Waiting for a syncronous reply");
if (cib->call_timeout > 0) {
/* We need this, even with msgfromIPC_timeout(), because we might
* get other/older replies that don't match the active request
*/
timer_expired = FALSE;
sync_timer->call_id = cib->call_id;
sync_timer->timeout = cib->call_timeout * 1000;
sync_timer->ref = g_timeout_add(sync_timer->timeout, cib_timeout_handler, sync_timer);
}
while (timer_expired == FALSE) {
int reply_id = -1;
int msg_id = cib->call_id;
op_reply = crm_recv_remote_msg(private->command.session, private->command.encrypted);
if (op_reply == NULL) {
break;
}
crm_element_value_int(op_reply, F_CIB_CALLID, &reply_id);
CRM_CHECK(reply_id > 0, free_xml(op_reply);
if (sync_timer->ref > 0) {
g_source_remove(sync_timer->ref); sync_timer->ref = 0;}
return -ENOMSG) ;
if (reply_id == msg_id) {
break;
} else if (reply_id < msg_id) {
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else if ((reply_id - 10000) > msg_id) {
/* wrap-around case */
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else {
crm_err("Received a __future__ reply:" " %d (wanted %d)", reply_id, msg_id);
}
free_xml(op_reply);
op_reply = NULL;
}
if (sync_timer->ref > 0) {
g_source_remove(sync_timer->ref);
sync_timer->ref = 0;
}
if (timer_expired) {
return -ETIME;
}
/* if(IPC_ISRCONN(native->command_channel) == FALSE) { */
/* crm_err("CIB disconnected: %d", */
/* native->command_channel->ch_status); */
/* cib->state = cib_disconnected; */
/* } */
if (op_reply == NULL) {
crm_err("No reply message - empty");
return -ENOMSG;
}
crm_trace("Syncronous reply received");
/* Start processing the reply... */
if (crm_element_value_int(op_reply, F_CIB_RC, &rc) != 0) {
rc = -EPROTO;
}
if (rc == -pcmk_err_diff_resync) {
/* This is an internal value that clients do not and should not care about */
rc = pcmk_ok;
}
if (rc == pcmk_ok || rc == -EPERM) {
crm_log_xml_debug(op_reply, "passed");
} else {
/* } else if(rc == -ETIME) { */
crm_err("Call failed: %s", pcmk_strerror(rc));
crm_log_xml_warn(op_reply, "failed");
}
if (output_data == NULL) {
/* do nothing more */
} else if (!(call_options & cib_discard_reply)) {
xmlNode *tmp = get_message_xml(op_reply, F_CIB_CALLDATA);
if (tmp == NULL) {
crm_trace("No output in reply to \"%s\" command %d", op, cib->call_id - 1);
} else {
*output_data = copy_xml(tmp);
}
}
free_xml(op_reply);
return rc;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info,
const char *date)
{
unsigned int
day,
hour,
minute,
month,
second,
year;
png_time
ptime;
time_t
ttime;
if (date != (const char *) NULL)
{
if (sscanf(date,"%d-%d-%dT%d:%d:%dZ",&year,&month,&day,&hour,&minute,
&second) != 6)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,
"Invalid date format specified for png:tIME","`%s'",
image->filename);
return;
}
ptime.year=(png_uint_16) year;
ptime.month=(png_byte) month;
ptime.day=(png_byte) day;
ptime.hour=(png_byte) hour;
ptime.minute=(png_byte) minute;
ptime.second=(png_byte) second;
}
else
{
time(&ttime);
png_convert_from_time_t(&ptime,ttime);
}
png_set_tIME(ping,info,&ptime);
}
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: static int write_note_info(struct elf_note_info *info,
struct coredump_params *cprm)
{
int i;
struct list_head *t;
for (i = 0; i < info->numnote; i++)
if (!writenote(info->notes + i, cprm))
return 0;
/* write out the thread status notes section */
list_for_each(t, &info->thread_list) {
struct elf_thread_status *tmp =
list_entry(t, struct elf_thread_status, list);
for (i = 0; i < tmp->num_notes; i++)
if (!writenote(&tmp->notes[i], cprm))
return 0;
}
return 1;
}
CWE ID: CWE-264
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int snd_timer_user_tselect(struct file *file,
struct snd_timer_select __user *_tselect)
{
struct snd_timer_user *tu;
struct snd_timer_select tselect;
char str[32];
int err = 0;
tu = file->private_data;
mutex_lock(&tu->tread_sem);
if (tu->timeri) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
}
if (copy_from_user(&tselect, _tselect, sizeof(tselect))) {
err = -EFAULT;
goto __err;
}
sprintf(str, "application %i", current->pid);
if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE)
tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid);
if (err < 0)
goto __err;
kfree(tu->queue);
tu->queue = NULL;
kfree(tu->tqueue);
tu->tqueue = NULL;
if (tu->tread) {
tu->tqueue = kmalloc(tu->queue_size * sizeof(struct snd_timer_tread),
GFP_KERNEL);
if (tu->tqueue == NULL)
err = -ENOMEM;
} else {
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL)
err = -ENOMEM;
}
if (err < 0) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
} else {
tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST;
tu->timeri->callback = tu->tread
? snd_timer_user_tinterrupt : snd_timer_user_interrupt;
tu->timeri->ccallback = snd_timer_user_ccallback;
tu->timeri->callback_data = (void *)tu;
}
__err:
mutex_unlock(&tu->tread_sem);
return err;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: ofpact_bitmap_to_openflow(uint64_t ofpacts_bitmap, enum ofp_version version)
{
uint32_t openflow_bitmap = 0;
const struct ofpact_map *x;
for (x = get_ofpact_map(version); x->ofpat >= 0; x++) {
if (ofpacts_bitmap & (UINT64_C(1) << x->ofpact)) {
openflow_bitmap |= 1u << x->ofpat;
}
}
return htonl(openflow_bitmap);
}
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 dccp_packet(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, enum ip_conntrack_info ctinfo,
u_int8_t pf, unsigned int hooknum,
unsigned int *timeouts)
{
struct net *net = nf_ct_net(ct);
enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
struct dccp_hdr _dh, *dh;
u_int8_t type, old_state, new_state;
enum ct_dccp_roles role;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
BUG_ON(dh == NULL);
type = dh->dccph_type;
if (type == DCCP_PKT_RESET &&
!test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
/* Tear down connection immediately if only reply is a RESET */
nf_ct_kill_acct(ct, ctinfo, skb);
return NF_ACCEPT;
}
spin_lock_bh(&ct->lock);
role = ct->proto.dccp.role[dir];
old_state = ct->proto.dccp.state;
new_state = dccp_state_table[role][type][old_state];
switch (new_state) {
case CT_DCCP_REQUEST:
if (old_state == CT_DCCP_TIMEWAIT &&
role == CT_DCCP_ROLE_SERVER) {
/* Reincarnation in the reverse direction: reopen and
* reverse client/server roles. */
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_SERVER;
}
break;
case CT_DCCP_RESPOND:
if (old_state == CT_DCCP_REQUEST)
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
break;
case CT_DCCP_PARTOPEN:
if (old_state == CT_DCCP_RESPOND &&
type == DCCP_PKT_ACK &&
dccp_ack_seq(dh) == ct->proto.dccp.handshake_seq)
set_bit(IPS_ASSURED_BIT, &ct->status);
break;
case CT_DCCP_IGNORE:
/*
* Connection tracking might be out of sync, so we ignore
* packets that might establish a new connection and resync
* if the server responds with a valid Response.
*/
if (ct->proto.dccp.last_dir == !dir &&
ct->proto.dccp.last_pkt == DCCP_PKT_REQUEST &&
type == DCCP_PKT_RESPONSE) {
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_SERVER;
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
new_state = CT_DCCP_RESPOND;
break;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid packet ignored ");
return NF_ACCEPT;
case CT_DCCP_INVALID:
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid state transition ");
return -NF_ACCEPT;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
ct->proto.dccp.state = new_state;
spin_unlock_bh(&ct->lock);
if (new_state != old_state)
nf_conntrack_event_cache(IPCT_PROTOINFO, ct);
nf_ct_refresh_acct(ct, ctinfo, skb, timeouts[new_state]);
return NF_ACCEPT;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int parse_exports_table(long long *table_start)
{
int res;
int indexes = SQUASHFS_LOOKUP_BLOCKS(sBlk.s.inodes);
long long export_index_table[indexes];
res = read_fs_bytes(fd, sBlk.s.lookup_table_start,
SQUASHFS_LOOKUP_BLOCK_BYTES(sBlk.s.inodes), export_index_table);
if(res == FALSE) {
ERROR("parse_exports_table: failed to read export index table\n");
return FALSE;
}
SQUASHFS_INSWAP_LOOKUP_BLOCKS(export_index_table, indexes);
/*
* export_index_table[0] stores the start of the compressed export blocks.
* This by definition is also the end of the previous filesystem
* table - the fragment table.
*/
*table_start = export_index_table[0];
return TRUE;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int error_handler(Display *display, XErrorEvent *error)
{
trapped_error_code = error->error_code;
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: GfxPath::GfxPath() {
justMoved = gFalse;
size = 16;
n = 0;
firstX = firstY = 0;
subpaths = (GfxSubpath **)gmallocn(size, sizeof(GfxSubpath *));
}
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: SPL_METHOD(SplFileObject, fread)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) {
return;
}
if (length <= 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0");
RETURN_FALSE;
}
Z_STRVAL_P(return_value) = emalloc(length + 1);
Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length);
/* needed because recv/read/gzread doesnt put a null at the end*/
Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
Z_TYPE_P(return_value) = IS_STRING;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void WebRuntimeFeatures::enableEncryptedMedia(bool enable)
{
RuntimeEnabledFeatures::setEncryptedMediaEnabled(enable);
RuntimeEnabledFeatures::setEncryptedMediaAnyVersionEnabled(
RuntimeEnabledFeatures::encryptedMediaEnabled()
|| RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled());
}
CWE ID: CWE-94
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 SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BluetoothDeviceChromeOS::AuthorizeService(
const dbus::ObjectPath& device_path,
const std::string& uuid,
const ConfirmationCallback& callback) {
callback.Run(CANCELLED);
}
CWE ID:
Target: 1
Example 2:
Code: static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
/*
* TODO: track the cause of the nested page fault, and
* correctly fill in the high bits of exit_info_1.
*/
svm->vmcb->control.exit_code = SVM_EXIT_NPF;
svm->vmcb->control.exit_code_hi = 0;
svm->vmcb->control.exit_info_1 = (1ULL << 32);
svm->vmcb->control.exit_info_2 = fault->address;
}
svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
svm->vmcb->control.exit_info_1 |= fault->error_code;
/*
* The present bit is always zero for page structure faults on real
* hardware.
*/
if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
svm->vmcb->control.exit_info_1 &= ~1;
nested_svm_vmexit(svm);
}
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: do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
unsigned int fault)
{
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
int code = BUS_ADRERR;
up_read(&mm->mmap_sem);
/* Kernel mode? Handle exceptions or die: */
if (!(error_code & PF_USER)) {
no_context(regs, error_code, address);
return;
}
/* User-space => ok to do another page fault: */
if (is_prefetch(regs, error_code, address))
return;
tsk->thread.cr2 = address;
tsk->thread.error_code = error_code;
tsk->thread.trap_no = 14;
#ifdef CONFIG_MEMORY_FAILURE
if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {
printk(KERN_ERR
"MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",
tsk->comm, tsk->pid, address);
code = BUS_MCEERR_AR;
}
#endif
force_sig_info_fault(SIGBUS, code, address, tsk, fault);
}
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: PHP_FUNCTION(dns_get_record)
{
char *hostname;
int hostname_len;
long type_param = PHP_DNS_ANY;
zval *authns = NULL, *addtl = NULL;
int type_to_fetch;
#if defined(HAVE_DNS_SEARCH)
struct sockaddr_storage from;
uint32_t fromsize = sizeof(from);
dns_handle_t handle;
#elif defined(HAVE_RES_NSEARCH)
struct __res_state state;
struct __res_state *handle = &state;
#endif
HEADER *hp;
querybuf answer;
u_char *cp = NULL, *end = NULL;
int n, qd, an, ns = 0, ar = 0;
int type, first_query = 1, store_results = 1;
zend_bool raw = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz!z!b",
&hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) {
return;
}
if (authns) {
zval_dtor(authns);
array_init(authns);
}
if (addtl) {
zval_dtor(addtl);
array_init(addtl);
}
if (!raw) {
if ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Type '%ld' not supported", type_param);
RETURN_FALSE;
}
} else {
if ((type_param < 1) || (type_param > 0xFFFF)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Numeric DNS record type must be between 1 and 65535, '%ld' given", type_param);
RETURN_FALSE;
}
}
/* Initialize the return array */
array_init(return_value);
/* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 )
* If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 )
* store_results is used to skip storing the results retrieved in step
* NUMTYPES+1 when results were already fetched.
* - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 )
* - In case of raw mode, we query only the requestd type instead of looping type by type
* before going with the additional info stuff.
*/
if (raw) {
type = -1;
} else if (type_param == PHP_DNS_ANY) {
type = PHP_DNS_NUM_TYPES + 1;
} else {
type = 0;
}
for ( ;
type < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query;
type++
) {
first_query = 0;
switch (type) {
case -1: /* raw */
type_to_fetch = type_param;
/* skip over the rest and go directly to additional records */
type = PHP_DNS_NUM_TYPES - 1;
break;
case 0:
type_to_fetch = type_param&PHP_DNS_A ? DNS_T_A : 0;
break;
case 1:
type_to_fetch = type_param&PHP_DNS_NS ? DNS_T_NS : 0;
break;
case 2:
type_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0;
break;
case 3:
type_to_fetch = type_param&PHP_DNS_SOA ? DNS_T_SOA : 0;
break;
case 4:
type_to_fetch = type_param&PHP_DNS_PTR ? DNS_T_PTR : 0;
break;
case 5:
type_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0;
break;
case 6:
type_to_fetch = type_param&PHP_DNS_MX ? DNS_T_MX : 0;
break;
case 7:
type_to_fetch = type_param&PHP_DNS_TXT ? DNS_T_TXT : 0;
break;
case 8:
type_to_fetch = type_param&PHP_DNS_AAAA ? DNS_T_AAAA : 0;
break;
case 9:
type_to_fetch = type_param&PHP_DNS_SRV ? DNS_T_SRV : 0;
break;
case 10:
type_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0;
break;
case 11:
type_to_fetch = type_param&PHP_DNS_A6 ? DNS_T_A6 : 0;
break;
case PHP_DNS_NUM_TYPES:
store_results = 0;
continue;
default:
case (PHP_DNS_NUM_TYPES + 1):
type_to_fetch = DNS_T_ANY;
break;
}
if (type_to_fetch) {
#if defined(HAVE_DNS_SEARCH)
handle = dns_open(NULL);
if (handle == NULL) {
zval_dtor(return_value);
RETURN_FALSE;
}
#elif defined(HAVE_RES_NSEARCH)
memset(&state, 0, sizeof(state));
if (res_ninit(handle)) {
zval_dtor(return_value);
RETURN_FALSE;
}
#else
res_init();
#endif
n = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer);
if (n < 0) {
php_dns_free_handle(handle);
continue;
}
cp = answer.qb2 + HFIXEDSZ;
end = answer.qb2 + n;
hp = (HEADER *)&answer;
qd = ntohs(hp->qdcount);
an = ntohs(hp->ancount);
ns = ntohs(hp->nscount);
ar = ntohs(hp->arcount);
/* Skip QD entries, they're only used by dn_expand later on */
while (qd-- > 0) {
n = dn_skipname(cp, end);
if (n < 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to parse DNS data received");
zval_dtor(return_value);
php_dns_free_handle(handle);
RETURN_FALSE;
}
cp += n + QFIXEDSZ;
}
/* YAY! Our real answers! */
while (an-- && cp && cp < end) {
zval *retval;
cp = php_parserr(cp, &answer, type_to_fetch, store_results, raw, &retval);
if (retval != NULL && store_results) {
add_next_index_zval(return_value, retval);
}
}
if (authns || addtl) {
/* List of Authoritative Name Servers
* Process when only requesting addtl so that we can skip through the section
*/
while (ns-- > 0 && cp && cp < end) {
zval *retval = NULL;
cp = php_parserr(cp, &answer, DNS_T_ANY, authns != NULL, raw, &retval);
if (retval != NULL) {
add_next_index_zval(authns, retval);
}
}
}
if (addtl) {
/* Additional records associated with authoritative name servers */
while (ar-- > 0 && cp && cp < end) {
zval *retval = NULL;
cp = php_parserr(cp, &answer, DNS_T_ANY, 1, raw, &retval);
if (retval != NULL) {
add_next_index_zval(addtl, retval);
}
}
}
php_dns_free_handle(handle);
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int setkey(struct crypto_tfm *tfm, const u8 *key,
unsigned int keysize)
{
struct salsa20_ctx *ctx = crypto_tfm_ctx(tfm);
salsa20_keysetup(ctx, key, keysize*8, SALSA20_IV_SIZE*8);
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: QTN2QT(QTNode *in)
{
TSQuery out;
int len;
int sumlen = 0,
nnode = 0;
QTN2QTState state;
cntsize(in, &sumlen, &nnode);
len = COMPUTESIZE(nnode, sumlen);
out = (TSQuery) palloc0(len);
SET_VARSIZE(out, len);
out->size = nnode;
state.curitem = GETQUERY(out);
state.operand = state.curoperand = GETOPERAND(out);
fillQT(&state, in);
return out;
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DocumentModuleScriptFetcher::NotifyFinished(Resource* resource) {
ClearResource();
ScriptResource* script_resource = ToScriptResource(resource);
HeapVector<Member<ConsoleMessage>> error_messages;
if (!WasModuleLoadSuccessful(script_resource, &error_messages)) {
Finalize(WTF::nullopt, error_messages);
return;
}
ModuleScriptCreationParams params(
script_resource->GetResponse().Url(), script_resource->SourceText(),
script_resource->GetResourceRequest().GetFetchCredentialsMode(),
script_resource->CalculateAccessControlStatus());
Finalize(params, error_messages);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct perf_event *event = file->private_data;
void (*func)(struct perf_event *);
u32 flags = arg;
switch (cmd) {
case PERF_EVENT_IOC_ENABLE:
func = perf_event_enable;
break;
case PERF_EVENT_IOC_DISABLE:
func = perf_event_disable;
break;
case PERF_EVENT_IOC_RESET:
func = perf_event_reset;
break;
case PERF_EVENT_IOC_REFRESH:
return perf_event_refresh(event, arg);
case PERF_EVENT_IOC_PERIOD:
return perf_event_period(event, (u64 __user *)arg);
case PERF_EVENT_IOC_ID:
{
u64 id = primary_event_id(event);
if (copy_to_user((void __user *)arg, &id, sizeof(id)))
return -EFAULT;
return 0;
}
case PERF_EVENT_IOC_SET_OUTPUT:
{
int ret;
if (arg != -1) {
struct perf_event *output_event;
struct fd output;
ret = perf_fget_light(arg, &output);
if (ret)
return ret;
output_event = output.file->private_data;
ret = perf_event_set_output(event, output_event);
fdput(output);
} else {
ret = perf_event_set_output(event, NULL);
}
return ret;
}
case PERF_EVENT_IOC_SET_FILTER:
return perf_event_set_filter(event, (void __user *)arg);
default:
return -ENOTTY;
}
if (flags & PERF_IOC_FLAG_GROUP)
perf_event_for_each(event, func);
else
perf_event_for_each_child(event, func);
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 kernel_restart_prepare(char *cmd)
{
blocking_notifier_call_chain(&reboot_notifier_list, SYS_RESTART, cmd);
system_state = SYSTEM_RESTART;
usermodehelper_disable();
device_shutdown();
}
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 BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
{
RefPtr<HTMLInputElement> protector(element());
element()->setFocus(false);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: wkbReadPoint(wkbObj *w)
{
pointObj p;
wkbReadPointP(w, &p);
return p;
}
CWE ID: CWE-89
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 V8TestObject::PerWorldBindingsVoidMethodTestInterfaceEmptyArgMethodCallbackForMainWorld(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_perWorldBindingsVoidMethodTestInterfaceEmptyArg");
test_object_v8_internal::PerWorldBindingsVoidMethodTestInterfaceEmptyArgMethodForMainWorld(info);
}
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: SPL_METHOD(SplFileObject, valid)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) {
RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval);
} else {
RETVAL_BOOL(!php_stream_eof(intern->u.file.stream));
}
} /* }}} */
/* {{{ proto string SplFileObject::fgets()
CWE ID: CWE-190
Target: 1
Example 2:
Code: static void dispatchSimAuthentication(Parcel &p, RequestInfo *pRI)
{
RIL_SimAuthentication pf;
int32_t t;
status_t status;
memset(&pf, 0, sizeof(pf));
status = p.readInt32(&t);
pf.authContext = (int) t;
pf.authData = strdupReadString(p);
pf.aid = strdupReadString(p);
startRequest;
appendPrintBuf("authContext=%s, authData=%s, aid=%s", pf.authContext, pf.authData, pf.aid);
closeRequest;
printRequest(pRI->token, pRI->pCI->requestNumber);
if (status != NO_ERROR) {
goto invalid;
}
CALL_ONREQUEST(pRI->pCI->requestNumber, &pf, sizeof(pf), pRI, pRI->socket_id);
#ifdef MEMSET_FREED
memsetString(pf.authData);
memsetString(pf.aid);
#endif
free(pf.authData);
free(pf.aid);
#ifdef MEMSET_FREED
memset(&pf, 0, sizeof(pf));
#endif
return;
invalid:
invalidCommandBlock(pRI);
return;
}
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 NetworkActionPredictor::RegisterTransitionalMatches(
const string16& user_text,
const AutocompleteResult& result) {
if (user_text.length() < kMinimumUserTextLength)
return;
const string16 lower_user_text(base::i18n::ToLower(user_text));
std::vector<TransitionalMatch>::iterator match_it =
std::find(transitional_matches_.begin(), transitional_matches_.end(),
lower_user_text);
if (match_it == transitional_matches_.end()) {
TransitionalMatch transitional_match;
transitional_match.user_text = lower_user_text;
match_it = transitional_matches_.insert(transitional_matches_.end(),
transitional_match);
}
for (AutocompleteResult::const_iterator it = result.begin();
it != result.end(); ++it) {
if (std::find(match_it->urls.begin(), match_it->urls.end(),
it->destination_url) == match_it->urls.end()) {
match_it->urls.push_back(it->destination_url);
}
}
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (0 == plen) {
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[1], (plen + 7) / 8);
memcpy(&route_target, &pptr[1], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)),
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: normalizePublicId(XML_Char *publicId)
{
XML_Char *p = publicId;
XML_Char *s;
for (s = publicId; *s; s++) {
switch (*s) {
case 0x20:
case 0xD:
case 0xA:
if (p != publicId && p[-1] != 0x20)
*p++ = 0x20;
break;
default:
*p++ = *s;
}
}
if (p != publicId && p[-1] == 0x20)
--p;
*p = XML_T('\0');
}
CWE ID: CWE-611
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 uint32_t out_get_sample_rate(const struct audio_stream *stream)
{
struct stream_out *out = (struct stream_out *)stream;
return out->sample_rate;
}
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: poly_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
POLYGON *poly;
int npts;
int size;
int isopen;
char *s;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * npts;
poly = (POLYGON *) palloc0(size); /* zero any holes */
SET_VARSIZE(poly, size);
poly->npts = npts;
if ((!path_decode(FALSE, npts, str, &isopen, &s, &(poly->p[0])))
|| (*s != '\0'))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
make_bound_box(poly);
PG_RETURN_POLYGON_P(poly);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: __smb_init(int smb_command, int wct, struct cifs_tcon *tcon,
void **request_buf, void **response_buf)
{
*request_buf = cifs_buf_get();
if (*request_buf == NULL) {
/* BB should we add a retry in here if not a writepage? */
return -ENOMEM;
}
/* Although the original thought was we needed the response buf for */
/* potential retries of smb operations it turns out we can determine */
/* from the mid flags when the request buffer can be resent without */
/* having to use a second distinct buffer for the response */
if (response_buf)
*response_buf = *request_buf;
header_assemble((struct smb_hdr *) *request_buf, smb_command, tcon,
wct);
if (tcon != NULL)
cifs_stats_inc(&tcon->num_smbs_sent);
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: void LockScreenMediaControlsView::OnMouseEntered(const ui::MouseEvent& event) {
if (is_in_drag_ || contents_view_->layer()->GetAnimator()->is_animating())
return;
close_button_->SetVisible(true);
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ProfileImplIOData::LazyInitializeInternal(
ProfileParams* profile_params) const {
clear_local_state_on_exit_ = profile_params->clear_local_state_on_exit;
ChromeURLRequestContext* main_context = main_request_context();
ChromeURLRequestContext* extensions_context = extensions_request_context();
media_request_context_ = new ChromeURLRequestContext;
IOThread* const io_thread = profile_params->io_thread;
IOThread::Globals* const io_thread_globals = io_thread->globals();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
bool record_mode = chrome::kRecordModeEnabled &&
command_line.HasSwitch(switches::kRecordMode);
bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode);
ApplyProfileParamsToContext(main_context);
ApplyProfileParamsToContext(media_request_context_);
ApplyProfileParamsToContext(extensions_context);
if (http_server_properties_manager_.get())
http_server_properties_manager_->InitializeOnIOThread();
main_context->set_transport_security_state(transport_security_state());
media_request_context_->set_transport_security_state(
transport_security_state());
extensions_context->set_transport_security_state(transport_security_state());
main_context->set_net_log(io_thread->net_log());
media_request_context_->set_net_log(io_thread->net_log());
extensions_context->set_net_log(io_thread->net_log());
main_context->set_network_delegate(network_delegate());
media_request_context_->set_network_delegate(network_delegate());
main_context->set_http_server_properties(http_server_properties());
media_request_context_->set_http_server_properties(http_server_properties());
main_context->set_host_resolver(
io_thread_globals->host_resolver.get());
media_request_context_->set_host_resolver(
io_thread_globals->host_resolver.get());
main_context->set_cert_verifier(
io_thread_globals->cert_verifier.get());
media_request_context_->set_cert_verifier(
io_thread_globals->cert_verifier.get());
main_context->set_http_auth_handler_factory(
io_thread_globals->http_auth_handler_factory.get());
media_request_context_->set_http_auth_handler_factory(
io_thread_globals->http_auth_handler_factory.get());
main_context->set_fraudulent_certificate_reporter(
fraudulent_certificate_reporter());
media_request_context_->set_fraudulent_certificate_reporter(
fraudulent_certificate_reporter());
main_context->set_proxy_service(proxy_service());
media_request_context_->set_proxy_service(proxy_service());
scoped_refptr<net::CookieStore> cookie_store = NULL;
net::OriginBoundCertService* origin_bound_cert_service = NULL;
if (record_mode || playback_mode) {
cookie_store = new net::CookieMonster(
NULL, profile_params->cookie_monster_delegate);
origin_bound_cert_service = new net::OriginBoundCertService(
new net::DefaultOriginBoundCertStore(NULL));
}
if (!cookie_store) {
DCHECK(!lazy_params_->cookie_path.empty());
scoped_refptr<SQLitePersistentCookieStore> cookie_db =
new SQLitePersistentCookieStore(
lazy_params_->cookie_path,
lazy_params_->restore_old_session_cookies);
cookie_db->SetClearLocalStateOnExit(
profile_params->clear_local_state_on_exit);
cookie_store =
new net::CookieMonster(cookie_db.get(),
profile_params->cookie_monster_delegate);
if (command_line.HasSwitch(switches::kEnableRestoreSessionState))
cookie_store->GetCookieMonster()->SetPersistSessionCookies(true);
}
net::CookieMonster* extensions_cookie_store =
new net::CookieMonster(
new SQLitePersistentCookieStore(
lazy_params_->extensions_cookie_path,
lazy_params_->restore_old_session_cookies), NULL);
const char* schemes[] = {chrome::kChromeDevToolsScheme,
chrome::kExtensionScheme};
extensions_cookie_store->SetCookieableSchemes(schemes, 2);
main_context->set_cookie_store(cookie_store);
media_request_context_->set_cookie_store(cookie_store);
extensions_context->set_cookie_store(extensions_cookie_store);
if (!origin_bound_cert_service) {
DCHECK(!lazy_params_->origin_bound_cert_path.empty());
scoped_refptr<SQLiteOriginBoundCertStore> origin_bound_cert_db =
new SQLiteOriginBoundCertStore(lazy_params_->origin_bound_cert_path);
origin_bound_cert_db->SetClearLocalStateOnExit(
profile_params->clear_local_state_on_exit);
origin_bound_cert_service = new net::OriginBoundCertService(
new net::DefaultOriginBoundCertStore(origin_bound_cert_db.get()));
}
set_origin_bound_cert_service(origin_bound_cert_service);
main_context->set_origin_bound_cert_service(origin_bound_cert_service);
media_request_context_->set_origin_bound_cert_service(
origin_bound_cert_service);
net::HttpCache::DefaultBackend* main_backend =
new net::HttpCache::DefaultBackend(
net::DISK_CACHE,
lazy_params_->cache_path,
lazy_params_->cache_max_size,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
net::HttpCache* main_cache = new net::HttpCache(
main_context->host_resolver(),
main_context->cert_verifier(),
main_context->origin_bound_cert_service(),
main_context->transport_security_state(),
main_context->proxy_service(),
"", // pass empty ssl_session_cache_shard to share the SSL session cache
main_context->ssl_config_service(),
main_context->http_auth_handler_factory(),
main_context->network_delegate(),
main_context->http_server_properties(),
main_context->net_log(),
main_backend);
net::HttpCache::DefaultBackend* media_backend =
new net::HttpCache::DefaultBackend(
net::MEDIA_CACHE, lazy_params_->media_cache_path,
lazy_params_->media_cache_max_size,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE));
net::HttpNetworkSession* main_network_session = main_cache->GetSession();
net::HttpCache* media_cache =
new net::HttpCache(main_network_session, media_backend);
if (record_mode || playback_mode) {
main_cache->set_mode(
record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK);
}
main_http_factory_.reset(main_cache);
media_http_factory_.reset(media_cache);
main_context->set_http_transaction_factory(main_cache);
media_request_context_->set_http_transaction_factory(media_cache);
ftp_factory_.reset(
new net::FtpNetworkLayer(io_thread_globals->host_resolver.get()));
main_context->set_ftp_transaction_factory(ftp_factory_.get());
main_context->set_chrome_url_data_manager_backend(
chrome_url_data_manager_backend());
main_context->set_job_factory(job_factory());
media_request_context_->set_job_factory(job_factory());
extensions_context->set_job_factory(job_factory());
job_factory()->AddInterceptor(
new chrome_browser_net::ConnectInterceptor(predictor_.get()));
lazy_params_.reset();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int hns_rcb_get_common_regs_count(void)
{
return HNS_RCB_COMMON_DUMP_REG_NUM;
}
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: l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
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 filter_average_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
uint8_t tmp[64 * 64];
assert(output_width <= 64);
assert(output_height <= 64);
filter_block2d_8_c(src_ptr, src_stride, HFilter, VFilter, tmp, 64,
output_width, output_height);
block2d_average_c(tmp, 64, dst_ptr, dst_stride,
output_width, output_height);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void i8042_free_irqs(void)
{
if (i8042_aux_irq_registered)
free_irq(I8042_AUX_IRQ, i8042_platform_device);
if (i8042_kbd_irq_registered)
free_irq(I8042_KBD_IRQ, i8042_platform_device);
i8042_aux_irq_registered = i8042_kbd_irq_registered = false;
}
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: std::unique_ptr<HttpNetworkSession> CreateSession(
SpdySessionDependencies* session_deps) {
return SpdySessionDependencies::SpdyCreateSession(session_deps);
}
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: mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
uint8_t type;
switch (type = cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
size_t sz = file_pstring_length_size(m);
char *ptr1 = p->s, *ptr2 = ptr1 + sz;
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s)) {
/*
* The size of the pascal string length (sz)
* is 1, 2, or 4. We need at least 1 byte for NUL
* termination, but we've already truncated the
* string by p->s, so we need to deduct sz.
*/
len = sizeof(p->s) - sz;
}
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
if (type == FILE_BELONG)
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
if (type == FILE_BEQUAD)
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
if (type == FILE_LELONG)
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
if (type == FILE_LEQUAD)
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
if (type == FILE_MELONG)
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: const service_manager::Identity& RenderProcessHostImpl::GetChildIdentity()
const {
return child_connection_->child_identity();
}
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: int hidp_get_conninfo(struct hidp_conninfo *ci)
{
struct hidp_session *session;
int err = 0;
down_read(&hidp_session_sem);
session = __hidp_get_session(&ci->bdaddr);
if (session)
__hidp_copy_session(session, ci);
else
err = -ENOENT;
up_read(&hidp_session_sem);
return err;
}
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: main(int argc, char * * argv)
{
const char command0[] = { 0x00, 0x00 };
char command1[] = "\x01\x00urn:schemas-upnp-org:device:InternetGatewayDevice";
char command2[] = "\x02\x00uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::upnp:rootdevice";
const char command3[] = { 0x03, 0x00 };
/* old versions of minissdpd would reject a command with
* a zero length string argument */
char command3compat[] = "\x03\x00ssdp:all";
char command4[] = "\x04\x00test:test:test";
const char bad_command[] = { 0xff, 0xff };
const char overflow[] = { 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
const char command5[] = { 0x05, 0x00 };
int s;
int i;
void * tmp;
unsigned char * resp = NULL;
size_t respsize = 0;
unsigned char buf[4096];
ssize_t n;
int total = 0;
const char * sockpath = "/var/run/minissdpd.sock";
for(i=0; i<argc-1; i++) {
if(0==strcmp(argv[i], "-s"))
sockpath = argv[++i];
}
command1[1] = sizeof(command1) - 3;
command2[1] = sizeof(command2) - 3;
command3compat[1] = sizeof(command3compat) - 3;
command4[1] = sizeof(command4) - 3;
s = connect_unix_socket(sockpath);
n = SENDCOMMAND(command0, sizeof(command0));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
if(n > 0) {
printversion(buf, n);
} else {
printf("Command 0 (get version) not supported\n");
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command1, sizeof(command1) - 1);
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command2, sizeof(command2) - 1);
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
buf[0] = 0; /* Slight hack for printing num devices when 0 */
n = SENDCOMMAND(command3, sizeof(command3));
n = read(s, buf, sizeof(buf));
if(n == 0) {
printf("command3 failed, testing compatible one\n");
close(s);
s = connect_unix_socket(sockpath);
n = SENDCOMMAND(command3compat, sizeof(command3compat) - 1);
n = read(s, buf, sizeof(buf));
}
printf("Response received %d bytes\n", (int)n);
printf("Number of devices %d\n", (int)buf[0]);
while(n > 0) {
tmp = realloc(resp, respsize + n);
if(tmp == NULL) {
fprintf(stderr, "memory allocation error\n");
break;
}
resp = tmp;
respsize += n;
if (n > 0) {
memcpy(resp + total, buf, n);
total += n;
}
if (n < (ssize_t)sizeof(buf)) {
break;
}
n = read(s, buf, sizeof(buf));
printf("response received %d bytes\n", (int)n);
}
if(resp != NULL) {
printresponse(resp, total);
free(resp);
resp = NULL;
}
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command4, sizeof(command4));
/* no response for request type 4 */
n = SENDCOMMAND(bad_command, sizeof(bad_command));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(overflow, sizeof(overflow));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
if(n == 0) {
close(s);
s = connect_unix_socket(sockpath);
}
n = SENDCOMMAND(command5, sizeof(command5));
n = read(s, buf, sizeof(buf));
printf("Response received %d bytes\n", (int)n);
printresponse(buf, n);
close(s);
return 0;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: bool GLES2Implementation::GetProgramResourceNameHelper(GLuint program,
GLenum program_interface,
GLuint index,
GLsizei bufsize,
GLsizei* length,
char* name) {
DCHECK_LE(0, bufsize);
helper_->SetBucketSize(kResultBucketId, 0);
bool success = false;
{
typedef cmds::GetProgramResourceName::Result Result;
auto result = GetResultAs<Result>();
if (!result) {
return false;
}
*result = 0;
helper_->GetProgramResourceName(program, program_interface, index,
kResultBucketId, GetResultShmId(),
result.offset());
WaitForCmd();
success = !!*result;
}
if (success) {
GetResultNameHelper(bufsize, length, name);
}
return success;
}
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 MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
depth,
packet_size;
ssize_t
y;
unsigned char
*colormap,
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Allocate colormap.
*/
if (IsPaletteImage(image,&image->exception) == MagickFalse)
(void) SetImageType(image,PaletteType);
depth=GetImageQuantumDepth(image,MagickTrue);
packet_size=(size_t) (depth/8);
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size*
sizeof(*pixels));
packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size*
sizeof(*colormap));
if ((pixels == (unsigned char *) NULL) ||
(colormap == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Write colormap to file.
*/
q=colormap;
if (image->depth <= 8)
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) image->colormap[i].red;
*q++=(unsigned char) image->colormap[i].green;
*q++=(unsigned char) image->colormap[i].blue;
}
else
for (i=0; i < (ssize_t) image->colors; i++)
{
*q++=(unsigned char) ((size_t) image->colormap[i].red >> 8);
*q++=(unsigned char) image->colormap[i].red;
*q++=(unsigned char) ((size_t) image->colormap[i].green >> 8);
*q++=(unsigned char) image->colormap[i].green;
*q++=(unsigned char) ((size_t) image->colormap[i].blue >> 8);
*q++=(unsigned char) image->colormap[i].blue;
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
/*
Write image pixels to file.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->colors > 256)
*q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8);
*q++=(unsigned char) GetPixelIndex(indexes+x);
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(status);
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void * calloc(size_t n, size_t lb)
{
if (lb && n > GC_SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: TestLifecycleUnit::TestLifecycleUnit(base::TimeTicks last_focused_time,
base::ProcessHandle process_handle,
bool can_discard)
: LifecycleUnitBase(content::Visibility::VISIBLE),
last_focused_time_(last_focused_time),
process_handle_(process_handle),
can_discard_(can_discard) {}
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: horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
{
TIFFPredictorState* sp = PredictorState(tif);
tmsize_t stride = sp->stride;
uint16 *wp = (uint16*) cp0;
tmsize_t wc = cc/2;
assert((cc%(2*stride))==0);
if (wc > stride) {
wc -= stride;
wp += wc - 1;
do {
REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--)
wc -= stride;
} while (wc > 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: void br_mdb_notify(struct net_device *dev, struct net_bridge_port *port,
struct br_ip *group, int type)
{
struct br_mdb_entry entry;
entry.ifindex = port->dev->ifindex;
entry.addr.proto = group->proto;
entry.addr.u.ip4 = group->u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
entry.addr.u.ip6 = group->u.ip6;
#endif
__br_mdb_notify(dev, &entry, type);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void task_mem(struct seq_file *m, struct mm_struct *mm)
{
unsigned long data, text, lib, swap;
unsigned long hiwater_vm, total_vm, hiwater_rss, total_rss;
/*
* Note: to minimize their overhead, mm maintains hiwater_vm and
* hiwater_rss only when about to *lower* total_vm or rss. Any
* collector of these hiwater stats must therefore get total_vm
* and rss too, which will usually be the higher. Barriers? not
* worth the effort, such snapshots can always be inconsistent.
*/
hiwater_vm = total_vm = mm->total_vm;
if (hiwater_vm < mm->hiwater_vm)
hiwater_vm = mm->hiwater_vm;
hiwater_rss = total_rss = get_mm_rss(mm);
if (hiwater_rss < mm->hiwater_rss)
hiwater_rss = mm->hiwater_rss;
data = mm->total_vm - mm->shared_vm - mm->stack_vm;
text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK)) >> 10;
lib = (mm->exec_vm << (PAGE_SHIFT-10)) - text;
swap = get_mm_counter(mm, MM_SWAPENTS);
seq_printf(m,
"VmPeak:\t%8lu kB\n"
"VmSize:\t%8lu kB\n"
"VmLck:\t%8lu kB\n"
"VmPin:\t%8lu kB\n"
"VmHWM:\t%8lu kB\n"
"VmRSS:\t%8lu kB\n"
"VmData:\t%8lu kB\n"
"VmStk:\t%8lu kB\n"
"VmExe:\t%8lu kB\n"
"VmLib:\t%8lu kB\n"
"VmPTE:\t%8lu kB\n"
"VmSwap:\t%8lu kB\n",
hiwater_vm << (PAGE_SHIFT-10),
(total_vm - mm->reserved_vm) << (PAGE_SHIFT-10),
mm->locked_vm << (PAGE_SHIFT-10),
mm->pinned_vm << (PAGE_SHIFT-10),
hiwater_rss << (PAGE_SHIFT-10),
total_rss << (PAGE_SHIFT-10),
data << (PAGE_SHIFT-10),
mm->stack_vm << (PAGE_SHIFT-10), text, lib,
(PTRS_PER_PTE*sizeof(pte_t)*mm->nr_ptes) >> 10,
swap << (PAGE_SHIFT-10));
}
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: xsltNumberFormatAlpha(xmlBufferPtr buffer,
double number,
int is_upper)
{
char temp_string[sizeof(double) * CHAR_BIT * sizeof(xmlChar) + 1];
char *pointer;
int i;
char *alpha_list;
double alpha_size = (double)(sizeof(alpha_upper_list) - 1);
/* Build buffer from back */
pointer = &temp_string[sizeof(temp_string)];
*(--pointer) = 0;
alpha_list = (is_upper) ? alpha_upper_list : alpha_lower_list;
for (i = 1; i < (int)sizeof(temp_string); i++) {
number--;
*(--pointer) = alpha_list[((int)fmod(number, alpha_size))];
number /= alpha_size;
if (fabs(number) < 1.0)
break; /* for */
}
xmlBufferCCat(buffer, pointer);
}
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: cmsSEQ* CMSEXPORT cmsAllocProfileSequenceDescription(cmsContext ContextID, cmsUInt32Number n)
{
cmsSEQ* Seq;
cmsUInt32Number i;
if (n == 0) return NULL;
if (n > 255) return NULL;
Seq = (cmsSEQ*) _cmsMallocZero(ContextID, sizeof(cmsSEQ));
if (Seq == NULL) return NULL;
Seq -> ContextID = ContextID;
Seq -> seq = (cmsPSEQDESC*) _cmsCalloc(ContextID, n, sizeof(cmsPSEQDESC));
Seq -> n = n;
for (i=0; i < n; i++) {
Seq -> seq[i].Manufacturer = NULL;
Seq -> seq[i].Model = NULL;
Seq -> seq[i].Description = NULL;
}
return Seq;
}
CWE ID:
Target: 1
Example 2:
Code: void PumpLoop() {
message_loop_.RunAllPending();
}
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: smbhash(unsigned char *out, const unsigned char *in, unsigned char *key)
{
int rc;
unsigned char key2[8];
struct crypto_skcipher *tfm_des;
struct scatterlist sgin, sgout;
struct skcipher_request *req;
str_to_key(key, key2);
tfm_des = crypto_alloc_skcipher("ecb(des)", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(tfm_des)) {
rc = PTR_ERR(tfm_des);
cifs_dbg(VFS, "could not allocate des crypto API\n");
goto smbhash_err;
}
req = skcipher_request_alloc(tfm_des, GFP_KERNEL);
if (!req) {
rc = -ENOMEM;
cifs_dbg(VFS, "could not allocate des crypto API\n");
goto smbhash_free_skcipher;
}
crypto_skcipher_setkey(tfm_des, key2, 8);
sg_init_one(&sgin, in, 8);
sg_init_one(&sgout, out, 8);
skcipher_request_set_callback(req, 0, NULL, NULL);
skcipher_request_set_crypt(req, &sgin, &sgout, 8, NULL);
rc = crypto_skcipher_encrypt(req);
if (rc)
cifs_dbg(VFS, "could not encrypt crypt key rc: %d\n", rc);
skcipher_request_free(req);
smbhash_free_skcipher:
crypto_free_skcipher(tfm_des);
smbhash_err:
return rc;
}
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: bool CheckClientDownloadRequest::ShouldUploadForMalwareScan(
DownloadCheckResultReason reason) {
if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads))
return false;
if (reason != DownloadCheckResultReason::REASON_DOWNLOAD_SAFE &&
reason != DownloadCheckResultReason::REASON_DOWNLOAD_UNCOMMON &&
reason != DownloadCheckResultReason::REASON_VERDICT_UNKNOWN)
return false;
content::BrowserContext* browser_context =
content::DownloadItemUtils::GetBrowserContext(item_);
if (!browser_context)
return false;
Profile* profile = Profile::FromBrowserContext(browser_context);
if (!profile)
return false;
int send_files_for_malware_check = profile->GetPrefs()->GetInteger(
prefs::kSafeBrowsingSendFilesForMalwareCheck);
if (send_files_for_malware_check !=
SendFilesForMalwareCheckValues::SEND_DOWNLOADS &&
send_files_for_malware_check !=
SendFilesForMalwareCheckValues::SEND_UPLOADS_AND_DOWNLOADS)
return false;
return !policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().empty();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void address_space_stb(AddressSpace *as, hwaddr addr, uint32_t val,
MemTxAttrs attrs, MemTxResult *result)
{
uint8_t v = val;
MemTxResult r;
r = address_space_rw(as, addr, attrs, &v, 1, 1);
if (result) {
*result = r;
}
}
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: GF_Err trak_Size(GF_Box *s)
{
GF_Err e;
GF_TrackBox *ptr = (GF_TrackBox *)s;
if (ptr->Header) {
e = gf_isom_box_size((GF_Box *) ptr->Header);
if (e) return e;
ptr->size += ptr->Header->size;
}
if (ptr->udta) {
e = gf_isom_box_size((GF_Box *) ptr->udta);
if (e) return e;
ptr->size += ptr->udta->size;
}
if (ptr->References) {
e = gf_isom_box_size((GF_Box *) ptr->References);
if (e) return e;
ptr->size += ptr->References->size;
}
if (ptr->editBox) {
e = gf_isom_box_size((GF_Box *) ptr->editBox);
if (e) return e;
ptr->size += ptr->editBox->size;
}
if (ptr->Media) {
e = gf_isom_box_size((GF_Box *) ptr->Media);
if (e) return e;
ptr->size += ptr->Media->size;
}
if (ptr->meta) {
e = gf_isom_box_size((GF_Box *) ptr->meta);
if (e) return e;
ptr->size += ptr->meta->size;
}
if (ptr->groups) {
e = gf_isom_box_size((GF_Box *) ptr->groups);
if (e) return e;
ptr->size += ptr->groups->size;
}
return GF_OK;
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: UpdateLibrary* CrosLibrary::GetUpdateLibrary() {
return update_lib_.GetDefaultImpl(use_stub_impl_);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
struct btrfs_root *root, int *new)
{
struct inode *inode;
inode = btrfs_iget_locked(s, location, root);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
btrfs_read_locked_inode(inode);
if (!is_bad_inode(inode)) {
inode_tree_add(inode);
unlock_new_inode(inode);
if (new)
*new = 1;
} else {
unlock_new_inode(inode);
iput(inode);
inode = ERR_PTR(-ESTALE);
}
}
return inode;
}
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 bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (kFirstGroupOffset + nGroups * kGroupSize > size) {
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
CWE ID: CWE-19
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int perf_config(config_fn_t fn, void *data)
{
int ret = 0, found = 0;
char *repo_config = NULL;
const char *home = NULL;
/* Setting $PERF_CONFIG makes perf read _only_ the given config file. */
if (config_exclusive_filename)
return perf_config_from_file(fn, config_exclusive_filename, data);
if (perf_config_system() && !access(perf_etc_perfconfig(), R_OK)) {
ret += perf_config_from_file(fn, perf_etc_perfconfig(),
data);
found += 1;
}
home = getenv("HOME");
if (perf_config_global() && home) {
char *user_config = strdup(mkpath("%s/.perfconfig", home));
if (!access(user_config, R_OK)) {
ret += perf_config_from_file(fn, user_config, data);
found += 1;
}
free(user_config);
}
repo_config = perf_pathdup("config");
if (!access(repo_config, R_OK)) {
ret += perf_config_from_file(fn, repo_config, data);
found += 1;
}
free(repo_config);
if (found == 0)
return -1;
return ret;
}
CWE ID:
Target: 1
Example 2:
Code: static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
unsigned int
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
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: status_t Parcel::writeByteVector(const std::vector<uint8_t>& val) {
return writeByteVectorInternal(this, val);
}
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: download::DownloadInterruptReason DownloadManagerImpl::BeginDownloadRequest(
std::unique_ptr<net::URLRequest> url_request,
ResourceContext* resource_context,
download::DownloadUrlParameters* params) {
if (ResourceDispatcherHostImpl::Get()->is_shutdown())
return download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN;
ResourceDispatcherHostImpl::Get()->InitializeURLRequest(
url_request.get(),
Referrer(params->referrer(),
Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
params->referrer_policy())),
true, // download.
params->render_process_host_id(), params->render_view_host_routing_id(),
params->render_frame_host_routing_id(), PREVIEWS_OFF, resource_context);
url_request->set_first_party_url_policy(
net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
const GURL& url = url_request->original_url();
const net::URLRequestContext* request_context = url_request->context();
if (!request_context->job_factory()->IsHandledProtocol(url.scheme())) {
DVLOG(1) << "Download request for unsupported protocol: "
<< url.possibly_invalid_spec();
return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST;
}
std::unique_ptr<ResourceHandler> handler(
DownloadResourceHandler::CreateForNewRequest(
url_request.get(), params->request_origin(),
params->download_source(), params->follow_cross_origin_redirects()));
ResourceDispatcherHostImpl::Get()->BeginURLRequest(
std::move(url_request), std::move(handler), true, // download
params->content_initiated(), params->do_not_prompt_for_login(),
resource_context);
return download::DOWNLOAD_INTERRUPT_REASON_NONE;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: bitset_invert(BitSetRef bs)
{
int i;
for (i = 0; i < BITSET_SIZE; i++) { bs[i] = ~(bs[i]); }
}
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: error::Error GLES2DecoderImpl::HandleGetUniformBlockIndex(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
if (!feature_info_->IsWebGL2OrES3Context())
return error::kUnknownCommand;
const volatile gles2::cmds::GetUniformBlockIndex& c =
*static_cast<const volatile gles2::cmds::GetUniformBlockIndex*>(cmd_data);
Bucket* bucket = GetBucket(c.name_bucket_id);
if (!bucket) {
return error::kInvalidArguments;
}
std::string name_str;
if (!bucket->GetAsString(&name_str)) {
return error::kInvalidArguments;
}
GLuint* index = GetSharedMemoryAs<GLuint*>(
c.index_shm_id, c.index_shm_offset, sizeof(GLuint));
if (!index) {
return error::kOutOfBounds;
}
if (*index != GL_INVALID_INDEX) {
return error::kInvalidArguments;
}
Program* program = GetProgramInfoNotShader(
c.program, "glGetUniformBlockIndex");
if (!program) {
return error::kNoError;
}
*index =
api()->glGetUniformBlockIndexFn(program->service_id(), name_str.c_str());
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: vbf_stp_error(struct worker *wrk, struct busyobj *bo)
{
ssize_t l, ll, o;
double now;
uint8_t *ptr;
struct vsb *synth_body;
CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC);
CHECK_OBJ_NOTNULL(bo->fetch_objcore, OBJCORE_MAGIC);
AN(bo->fetch_objcore->flags & OC_F_BUSY);
assert(bo->director_state == DIR_S_NULL);
wrk->stats->fetch_failed++;
now = W_TIM_real(wrk);
VSLb_ts_busyobj(bo, "Error", now);
if (bo->fetch_objcore->stobj->stevedore != NULL)
ObjFreeObj(bo->wrk, bo->fetch_objcore);
HTTP_Setup(bo->beresp, bo->ws, bo->vsl, SLT_BerespMethod);
http_PutResponse(bo->beresp, "HTTP/1.1", 503, "Backend fetch failed");
http_TimeHeader(bo->beresp, "Date: ", now);
http_SetHeader(bo->beresp, "Server: Varnish");
bo->fetch_objcore->t_origin = now;
if (!VTAILQ_EMPTY(&bo->fetch_objcore->objhead->waitinglist)) {
/*
* If there is a waitinglist, it means that there is no
* grace-able object, so cache the error return for a
* short time, so the waiting list can drain, rather than
* each objcore on the waiting list sequentially attempt
* to fetch from the backend.
*/
bo->fetch_objcore->ttl = 1;
bo->fetch_objcore->grace = 5;
bo->fetch_objcore->keep = 5;
} else {
bo->fetch_objcore->ttl = 0;
bo->fetch_objcore->grace = 0;
bo->fetch_objcore->keep = 0;
}
synth_body = VSB_new_auto();
AN(synth_body);
VCL_backend_error_method(bo->vcl, wrk, NULL, bo, synth_body);
AZ(VSB_finish(synth_body));
if (wrk->handling == VCL_RET_ABANDON || wrk->handling == VCL_RET_FAIL) {
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
if (wrk->handling == VCL_RET_RETRY) {
VSB_destroy(&synth_body);
if (bo->retries++ < cache_param->max_retries)
return (F_STP_RETRY);
VSLb(bo->vsl, SLT_VCL_Error, "Too many retries, failing");
return (F_STP_FAIL);
}
assert(wrk->handling == VCL_RET_DELIVER);
bo->vfc->bo = bo;
bo->vfc->wrk = bo->wrk;
bo->vfc->oc = bo->fetch_objcore;
bo->vfc->http = bo->beresp;
bo->vfc->esi_req = bo->bereq;
if (vbf_beresp2obj(bo)) {
(void)VFP_Error(bo->vfc, "Could not get storage");
VSB_destroy(&synth_body);
return (F_STP_FAIL);
}
ll = VSB_len(synth_body);
o = 0;
while (ll > 0) {
l = ll;
if (VFP_GetStorage(bo->vfc, &l, &ptr) != VFP_OK)
break;
memcpy(ptr, VSB_data(synth_body) + o, l);
VFP_Extend(bo->vfc, l);
ll -= l;
o += l;
}
AZ(ObjSetU64(wrk, bo->fetch_objcore, OA_LEN, o));
VSB_destroy(&synth_body);
HSH_Unbusy(wrk, bo->fetch_objcore);
ObjSetState(wrk, bo->fetch_objcore, BOS_FINISHED);
return (F_STP_DONE);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: blink::WebWidgetClient* RenderViewImpl::WidgetClient() {
return static_cast<RenderWidget*>(this);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void resolveRunBasedOnScriptExtensions(Vector<CandidateRun>& runs,
CandidateRun& run, size_t i, size_t length, UScriptCode* scriptExtensions,
int extensionsLength, size_t& nextResolvedRun)
{
if (extensionsLength <= 1)
return;
if (i > 0 && matchesAdjacentRun(scriptExtensions, extensionsLength, runs[i - 1])) {
run.script = runs[i - 1].script;
return;
}
for (size_t j = i + 1; j < length; j++) {
if (runs[j].script != USCRIPT_COMMON
&& runs[j].script != USCRIPT_INHERITED
&& matchesAdjacentRun(scriptExtensions, extensionsLength, runs[j])) {
nextResolvedRun = j;
break;
}
}
}
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 SoundPool::doLoad(sp<Sample>& sample)
{
ALOGV("doLoad: loading sample sampleID=%d", sample->sampleID());
sample->startLoad();
mDecodeThread->loadSample(sample->sampleID());
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: PHP_FUNCTION(imagecreatefromxpm)
{
_php_image_create_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_GDIMG_TYPE_XPM, "XPM", gdImageCreateFromXpm, NULL);
}
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: base::TimeTicks RendererSchedulerImpl::EnableVirtualTime() {
if (main_thread_only().use_virtual_time)
return main_thread_only().initial_virtual_time;
main_thread_only().use_virtual_time = true;
DCHECK(!virtual_time_domain_);
main_thread_only().initial_virtual_time = tick_clock()->NowTicks();
virtual_time_domain_.reset(new AutoAdvancingVirtualTimeDomain(
main_thread_only().initial_virtual_time, &helper_));
RegisterTimeDomain(virtual_time_domain_.get());
virtual_time_domain_->SetObserver(this);
DCHECK(!virtual_time_control_task_queue_);
virtual_time_control_task_queue_ =
helper_.NewTaskQueue(MainThreadTaskQueue::QueueCreationParams(
MainThreadTaskQueue::QueueType::kControl));
virtual_time_control_task_queue_->SetQueuePriority(
TaskQueue::kControlPriority);
virtual_time_control_task_queue_->SetTimeDomain(virtual_time_domain_.get());
main_thread_only().use_virtual_time = true;
ForceUpdatePolicy();
virtual_time_domain_->SetCanAdvanceVirtualTime(
!main_thread_only().virtual_time_stopped);
if (main_thread_only().virtual_time_stopped)
VirtualTimePaused();
return main_thread_only().initial_virtual_time;
}
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 addDataToStreamTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().addDataToStream(blobRegistryContext->url, blobRegistryContext->streamData);
}
CWE ID:
Target: 1
Example 2:
Code: static long vhost_dev_alloc_iovecs(struct vhost_dev *dev)
{
struct vhost_virtqueue *vq;
int i;
for (i = 0; i < dev->nvqs; ++i) {
vq = dev->vqs[i];
vq->indirect = kmalloc(sizeof *vq->indirect * UIO_MAXIOV,
GFP_KERNEL);
vq->log = kmalloc(sizeof *vq->log * UIO_MAXIOV, GFP_KERNEL);
vq->heads = kmalloc(sizeof *vq->heads * UIO_MAXIOV, GFP_KERNEL);
if (!vq->indirect || !vq->log || !vq->heads)
goto err_nomem;
}
return 0;
err_nomem:
for (; i >= 0; --i)
vhost_vq_free_iovecs(dev->vqs[i]);
return -ENOMEM;
}
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: INLINE UWORD32 impeg2d_bit_stream_nxt( stream_t *ps_stream, WORD32 i4_no_of_bits)
{
UWORD32 u4_bits,u4_offset,u4_temp;
UWORD8 u4_bit_ptr;
ASSERT(i4_no_of_bits > 0);
u4_offset = ps_stream->u4_offset;
u4_bit_ptr = u4_offset & 0x1F;
u4_bits = ps_stream->u4_buf << u4_bit_ptr;
u4_bit_ptr += i4_no_of_bits;
if(32 < u4_bit_ptr)
{
/* Read bits from the next word if necessary */
u4_temp = ps_stream->u4_buf_nxt;
u4_bit_ptr &= (BITS_IN_INT - 1);
u4_temp = (u4_temp >> (BITS_IN_INT - u4_bit_ptr));
/* u4_temp consists of bits,if any that had to be read from the next word
of the buffer.The bits read from both the words are concatenated and
moved to the least significant positions of 'u4_bits'*/
u4_bits = (u4_bits >> (32 - i4_no_of_bits)) | u4_temp;
}
else
{
u4_bits = (u4_bits >> (32 - i4_no_of_bits));
}
return (u4_bits);
}
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: static void regulator_ena_gpio_free(struct regulator_dev *rdev)
{
struct regulator_enable_gpio *pin, *n;
if (!rdev->ena_pin)
return;
/* Free the GPIO only in case of no use */
list_for_each_entry_safe(pin, n, ®ulator_ena_gpio_list, list) {
if (pin->gpiod == rdev->ena_pin->gpiod) {
if (pin->request_count <= 1) {
pin->request_count = 0;
gpiod_put(pin->gpiod);
list_del(&pin->list);
kfree(pin);
} else {
pin->request_count--;
}
}
}
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: base::string16 FormatUrlWithAdjustments(
const GURL& url,
FormatUrlTypes format_types,
net::UnescapeRule::Type unescape_rules,
url::Parsed* new_parsed,
size_t* prefix_end,
base::OffsetAdjuster::Adjustments* adjustments) {
DCHECK(adjustments != NULL);
adjustments->clear();
url::Parsed parsed_temp;
if (!new_parsed)
new_parsed = &parsed_temp;
else
*new_parsed = url::Parsed();
const char kViewSource[] = "view-source";
const char kViewSourceTwice[] = "view-source:view-source:";
if (url.SchemeIs(kViewSource) &&
!base::StartsWith(url.possibly_invalid_spec(), kViewSourceTwice,
base::CompareCase::INSENSITIVE_ASCII)) {
return FormatViewSourceUrl(url, format_types, unescape_rules,
new_parsed, prefix_end, adjustments);
}
const std::string& spec = url.possibly_invalid_spec();
const url::Parsed& parsed = url.parsed_for_possibly_invalid_spec();
base::string16 url_string;
url_string.insert(
url_string.end(), spec.begin(),
spec.begin() + parsed.CountCharactersBefore(url::Parsed::USERNAME, true));
const char kHTTP[] = "http://";
const char kFTP[] = "ftp.";
bool omit_http =
(format_types & kFormatUrlOmitHTTP) &&
base::EqualsASCII(url_string, kHTTP) &&
!base::StartsWith(url.host(), kFTP, base::CompareCase::SENSITIVE);
new_parsed->scheme = parsed.scheme;
if ((format_types & kFormatUrlOmitUsernamePassword) != 0) {
new_parsed->username.reset();
new_parsed->password.reset();
if (parsed.username.is_nonempty() || parsed.password.is_nonempty()) {
if (parsed.username.is_nonempty() && parsed.password.is_nonempty()) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
static_cast<size_t>(parsed.username.begin),
static_cast<size_t>(parsed.username.len + parsed.password.len + 2),
0));
} else {
const url::Component* nonempty_component =
parsed.username.is_nonempty() ? &parsed.username : &parsed.password;
adjustments->push_back(base::OffsetAdjuster::Adjustment(
static_cast<size_t>(nonempty_component->begin),
static_cast<size_t>(nonempty_component->len + 1), 0));
}
}
} else {
AppendFormattedComponent(spec, parsed.username,
NonHostComponentTransform(unescape_rules),
&url_string, &new_parsed->username, adjustments);
if (parsed.password.is_valid())
url_string.push_back(':');
AppendFormattedComponent(spec, parsed.password,
NonHostComponentTransform(unescape_rules),
&url_string, &new_parsed->password, adjustments);
if (parsed.username.is_valid() || parsed.password.is_valid())
url_string.push_back('@');
}
if (prefix_end)
*prefix_end = static_cast<size_t>(url_string.length());
AppendFormattedComponent(spec, parsed.host, HostComponentTransform(),
&url_string, &new_parsed->host, adjustments);
if (parsed.port.is_nonempty()) {
url_string.push_back(':');
new_parsed->port.begin = url_string.length();
url_string.insert(url_string.end(), spec.begin() + parsed.port.begin,
spec.begin() + parsed.port.end());
new_parsed->port.len = url_string.length() - new_parsed->port.begin;
} else {
new_parsed->port.reset();
}
if (!(format_types & kFormatUrlOmitTrailingSlashOnBareHostname) ||
!CanStripTrailingSlash(url)) {
AppendFormattedComponent(spec, parsed.path,
NonHostComponentTransform(unescape_rules),
&url_string, &new_parsed->path, adjustments);
} else {
if (parsed.path.len > 0) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
parsed.path.begin, parsed.path.len, 0));
}
}
if (parsed.query.is_valid())
url_string.push_back('?');
AppendFormattedComponent(spec, parsed.query,
NonHostComponentTransform(unescape_rules),
&url_string, &new_parsed->query, adjustments);
if (parsed.ref.is_valid())
url_string.push_back('#');
AppendFormattedComponent(spec, parsed.ref,
NonHostComponentTransform(net::UnescapeRule::NONE),
&url_string, &new_parsed->ref, adjustments);
if (omit_http && base::StartsWith(url_string, base::ASCIIToUTF16(kHTTP),
base::CompareCase::SENSITIVE)) {
const size_t kHTTPSize = arraysize(kHTTP) - 1;
url_string = url_string.substr(kHTTPSize);
adjustments->insert(adjustments->begin(),
base::OffsetAdjuster::Adjustment(0, kHTTPSize, 0));
if (prefix_end)
*prefix_end -= kHTTPSize;
DCHECK(new_parsed->scheme.is_valid());
int delta = -(new_parsed->scheme.len + 3); // +3 for ://.
new_parsed->scheme.reset();
AdjustAllComponentsButScheme(delta, new_parsed);
}
return url_string;
}
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 ThreadableBlobRegistry::finalizeStream(const KURL& url)
{
if (isMainThread()) {
blobRegistry().finalizeStream(url);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
callOnMainThread(&finalizeStreamTask, context.leakPtr());
}
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int tsc210x_load(QEMUFile *f, void *opaque, int version_id)
{
TSC210xState *s = (TSC210xState *) opaque;
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
int i;
s->x = qemu_get_be16(f);
s->y = qemu_get_be16(f);
s->pressure = qemu_get_byte(f);
s->state = qemu_get_byte(f);
s->page = qemu_get_byte(f);
s->offset = qemu_get_byte(f);
s->command = qemu_get_byte(f);
s->irq = qemu_get_byte(f);
qemu_get_be16s(f, &s->dav);
timer_get(f, s->timer);
s->enabled = qemu_get_byte(f);
s->host_mode = qemu_get_byte(f);
s->function = qemu_get_byte(f);
s->nextfunction = qemu_get_byte(f);
s->precision = qemu_get_byte(f);
s->nextprecision = qemu_get_byte(f);
s->filter = qemu_get_byte(f);
s->pin_func = qemu_get_byte(f);
s->ref = qemu_get_byte(f);
qemu_get_be16s(f, &s->dac_power);
for (i = 0; i < 0x14; i ++)
qemu_get_be16s(f, &s->filter_data[i]);
s->busy = timer_pending(s->timer);
qemu_set_irq(s->pint, !s->irq);
qemu_set_irq(s->davint, !s->dav);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static av_always_inline int smk_get_code(BitstreamContext *bc, int *recode,
int *last)
{
register int *table = recode;
int v;
while(*table & SMK_NODE) {
if (bitstream_read_bit(bc))
table += (*table) & (~SMK_NODE);
table++;
}
v = *table;
if(v != recode[last[0]]) {
recode[last[2]] = recode[last[1]];
recode[last[1]] = recode[last[0]];
recode[last[0]] = v;
}
return v;
}
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: bool RenderViewImpl::CanUpdateLayout() {
return true;
}
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: static UINT drdynvc_process_data_first(drdynvcPlugin* drdynvc, int Sp,
int cbChId, wStream* s)
{
UINT status;
UINT32 Length;
UINT32 ChannelId;
ChannelId = drdynvc_read_variable_uint(s, cbChId);
Length = drdynvc_read_variable_uint(s, Sp);
WLog_Print(drdynvc->log, WLOG_DEBUG,
"process_data_first: Sp=%d cbChId=%d, ChannelId=%"PRIu32" Length=%"PRIu32"", Sp,
cbChId, ChannelId, Length);
status = dvcman_receive_channel_data_first(drdynvc, drdynvc->channel_mgr, ChannelId,
Length);
if (status)
return status;
return dvcman_receive_channel_data(drdynvc, drdynvc->channel_mgr, ChannelId, s);
}
CWE ID:
Target: 1
Example 2:
Code: int ping_getfrag(void *from, char *to,
int offset, int fraglen, int odd, struct sk_buff *skb)
{
struct pingfakehdr *pfh = (struct pingfakehdr *)from;
if (offset == 0) {
if (fraglen < sizeof(struct icmphdr))
BUG();
if (csum_partial_copy_fromiovecend(to + sizeof(struct icmphdr),
pfh->iov, 0, fraglen - sizeof(struct icmphdr),
&pfh->wcheck))
return -EFAULT;
} else if (offset < sizeof(struct icmphdr)) {
BUG();
} else {
if (csum_partial_copy_fromiovecend
(to, pfh->iov, offset - sizeof(struct icmphdr),
fraglen, &pfh->wcheck))
return -EFAULT;
}
#if IS_ENABLED(CONFIG_IPV6)
/* For IPv6, checksum each skb as we go along, as expected by
* icmpv6_push_pending_frames. For IPv4, accumulate the checksum in
* wcheck, it will be finalized in ping_v4_push_pending_frames.
*/
if (pfh->family == AF_INET6) {
skb->csum = pfh->wcheck;
skb->ip_summed = CHECKSUM_NONE;
pfh->wcheck = 0;
}
#endif
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void check_pointer_type_change(Notifier *notifier, void *data)
{
VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
int absolute = qemu_input_is_absolute();
if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, absolute, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_POINTER_TYPE_CHANGE);
vnc_unlock_output(vs);
vnc_flush(vs);
vnc_unlock_output(vs);
vnc_flush(vs);
}
vs->absolute = absolute;
}
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 color_sycc_to_rgb(opj_image_t *img)
{
if(img->numcomps < 3)
{
img->color_space = OPJ_CLRSPC_GRAY;
return;
}
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 2)
&& (img->comps[2].dx == 2)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 2)
&& (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */
{
sycc420_to_rgb(img);
}
else
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 2)
&& (img->comps[2].dx == 2)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 1)
&& (img->comps[2].dy == 1))/* horizontal sub-sample only */
{
sycc422_to_rgb(img);
}
else
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 1)
&& (img->comps[2].dx == 1)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 1)
&& (img->comps[2].dy == 1))/* no sub-sample */
{
sycc444_to_rgb(img);
}
else
{
fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__);
return;
}
img->color_space = OPJ_CLRSPC_SRGB;
}/* color_sycc_to_rgb() */
CWE ID: CWE-125
Target: 1
Example 2:
Code: int wc_ecc_import_point_der(byte* in, word32 inLen, const int curve_idx,
ecc_point* point)
{
int err = 0;
int compressed = 0;
int keysize;
byte pointType;
if (in == NULL || point == NULL || (curve_idx < 0) ||
(wc_ecc_is_valid_idx(curve_idx) == 0))
return ECC_BAD_ARG_E;
/* must be odd */
if ((inLen & 1) == 0) {
return ECC_BAD_ARG_E;
}
/* init point */
#ifdef ALT_ECC_SIZE
point->x = (mp_int*)&point->xyz[0];
point->y = (mp_int*)&point->xyz[1];
point->z = (mp_int*)&point->xyz[2];
alt_fp_init(point->x);
alt_fp_init(point->y);
alt_fp_init(point->z);
#else
err = mp_init_multi(point->x, point->y, point->z, NULL, NULL, NULL);
#endif
if (err != MP_OKAY)
return MEMORY_E;
/* check for point type (4, 2, or 3) */
pointType = in[0];
if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN &&
pointType != ECC_POINT_COMP_ODD) {
err = ASN_PARSE_E;
}
if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) {
#ifdef HAVE_COMP_KEY
compressed = 1;
#else
err = NOT_COMPILED_IN;
#endif
}
/* adjust to skip first byte */
inLen -= 1;
in += 1;
/* calculate key size based on inLen / 2 */
keysize = inLen>>1;
#ifdef WOLFSSL_ATECC508A
/* populate key->pubkey_raw */
XMEMCPY(key->pubkey_raw, (byte*)in, sizeof(key->pubkey_raw));
#endif
/* read data */
if (err == MP_OKAY)
err = mp_read_unsigned_bin(point->x, (byte*)in, keysize);
#ifdef HAVE_COMP_KEY
if (err == MP_OKAY && compressed == 1) { /* build y */
#ifndef WOLFSSL_SP_MATH
int did_init = 0;
mp_int t1, t2;
DECLARE_CURVE_SPECS(3)
if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY)
err = MEMORY_E;
else
did_init = 1;
/* load curve info */
if (err == MP_OKAY)
err = wc_ecc_curve_load(&ecc_sets[curve_idx], &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
ECC_CURVE_FIELD_BF));
/* compute x^3 */
if (err == MP_OKAY)
err = mp_sqr(point->x, &t1);
if (err == MP_OKAY)
err = mp_mulmod(&t1, point->x, curve->prime, &t1);
/* compute x^3 + a*x */
if (err == MP_OKAY)
err = mp_mulmod(curve->Af, point->x, curve->prime, &t2);
if (err == MP_OKAY)
err = mp_add(&t1, &t2, &t1);
/* compute x^3 + a*x + b */
if (err == MP_OKAY)
err = mp_add(&t1, curve->Bf, &t1);
/* compute sqrt(x^3 + a*x + b) */
if (err == MP_OKAY)
err = mp_sqrtmod_prime(&t1, curve->prime, &t2);
/* adjust y */
if (err == MP_OKAY) {
if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) ||
(mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) {
err = mp_mod(&t2, curve->prime, point->y);
}
else {
err = mp_submod(curve->prime, &t2, curve->prime, point->y);
}
}
if (did_init) {
mp_clear(&t2);
mp_clear(&t1);
}
wc_ecc_curve_free(curve);
#else
sp_ecc_uncompress_256(point->x, pointType, point->y);
#endif
}
#endif
if (err == MP_OKAY && compressed == 0)
err = mp_read_unsigned_bin(point->y, (byte*)in + keysize, keysize);
if (err == MP_OKAY)
err = mp_set(point->z, 1);
if (err != MP_OKAY) {
mp_clear(point->x);
mp_clear(point->y);
mp_clear(point->z);
}
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: static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
jpc_dec_tile_t *tile;
if (JAS_CAST(int, rgn->compno) >= dec->numcomps) {
jas_eprintf("invalid component number in RGN marker segment\n");
return -1;
}
switch (dec->state) {
case JPC_MH:
jpc_dec_cp_setfromrgn(dec->cp, rgn);
break;
case JPC_TPH:
if (!(tile = dec->curtile)) {
return -1;
}
if (tile->partno > 0) {
return -1;
}
jpc_dec_cp_setfromrgn(tile->cp, rgn);
break;
}
return 0;
}
CWE ID: CWE-476
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: iakerb_gss_init_sec_context(OM_uint32 *minor_status,
gss_cred_id_t claimant_cred_handle,
gss_ctx_id_t *context_handle,
gss_name_t target_name,
gss_OID mech_type,
OM_uint32 req_flags,
OM_uint32 time_req,
gss_channel_bindings_t input_chan_bindings,
gss_buffer_t input_token,
gss_OID *actual_mech_type,
gss_buffer_t output_token,
OM_uint32 *ret_flags,
OM_uint32 *time_rec)
{
OM_uint32 major_status = GSS_S_FAILURE;
krb5_error_code code;
iakerb_ctx_id_t ctx;
krb5_gss_cred_id_t kcred;
krb5_gss_name_t kname;
krb5_boolean cred_locked = FALSE;
int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT);
if (initialContextToken) {
code = iakerb_alloc_context(&ctx);
if (code != 0) {
*minor_status = code;
goto cleanup;
}
if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) {
major_status = iakerb_gss_acquire_cred(minor_status, NULL,
GSS_C_INDEFINITE,
GSS_C_NULL_OID_SET,
GSS_C_INITIATE,
&ctx->defcred, NULL, NULL);
if (GSS_ERROR(major_status))
goto cleanup;
claimant_cred_handle = ctx->defcred;
}
} else {
ctx = (iakerb_ctx_id_t)*context_handle;
if (claimant_cred_handle == GSS_C_NO_CREDENTIAL)
claimant_cred_handle = ctx->defcred;
}
kname = (krb5_gss_name_t)target_name;
major_status = kg_cred_resolve(minor_status, ctx->k5c,
claimant_cred_handle, target_name);
if (GSS_ERROR(major_status))
goto cleanup;
cred_locked = TRUE;
kcred = (krb5_gss_cred_id_t)claimant_cred_handle;
major_status = GSS_S_FAILURE;
if (initialContextToken) {
code = iakerb_get_initial_state(ctx, kcred, kname, time_req,
&ctx->state);
if (code != 0) {
*minor_status = code;
goto cleanup;
}
*context_handle = (gss_ctx_id_t)ctx;
}
if (ctx->state != IAKERB_AP_REQ) {
/* We need to do IAKERB. */
code = iakerb_initiator_step(ctx,
kcred,
kname,
time_req,
input_token,
output_token);
if (code == KRB5_BAD_MSIZE)
major_status = GSS_S_DEFECTIVE_TOKEN;
if (code != 0) {
*minor_status = code;
goto cleanup;
}
}
if (ctx->state == IAKERB_AP_REQ) {
krb5_gss_ctx_ext_rec exts;
if (cred_locked) {
k5_mutex_unlock(&kcred->lock);
cred_locked = FALSE;
}
iakerb_make_exts(ctx, &exts);
if (ctx->gssc == GSS_C_NO_CONTEXT)
input_token = GSS_C_NO_BUFFER;
/* IAKERB is finished, or we skipped to Kerberos directly. */
major_status = krb5_gss_init_sec_context_ext(minor_status,
(gss_cred_id_t) kcred,
&ctx->gssc,
target_name,
(gss_OID)gss_mech_iakerb,
req_flags,
time_req,
input_chan_bindings,
input_token,
NULL,
output_token,
ret_flags,
time_rec,
&exts);
if (major_status == GSS_S_COMPLETE) {
*context_handle = ctx->gssc;
ctx->gssc = GSS_C_NO_CONTEXT;
iakerb_release_context(ctx);
}
if (actual_mech_type != NULL)
*actual_mech_type = (gss_OID)gss_mech_krb5;
} else {
if (actual_mech_type != NULL)
*actual_mech_type = (gss_OID)gss_mech_iakerb;
if (ret_flags != NULL)
*ret_flags = 0;
if (time_rec != NULL)
*time_rec = 0;
major_status = GSS_S_CONTINUE_NEEDED;
}
cleanup:
if (cred_locked)
k5_mutex_unlock(&kcred->lock);
if (initialContextToken && GSS_ERROR(major_status)) {
iakerb_release_context(ctx);
*context_handle = GSS_C_NO_CONTEXT;
}
return major_status;
}
CWE ID: CWE-18
Target: 1
Example 2:
Code: void vsock_insert_connected(struct vsock_sock *vsk)
{
struct list_head *list = vsock_connected_sockets(
&vsk->remote_addr, &vsk->local_addr);
spin_lock_bh(&vsock_table_lock);
__vsock_insert_connected(list, vsk);
spin_unlock_bh(&vsock_table_lock);
}
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 AutofillManager::OnLoadedAutofillHeuristics(
const std::string& heuristic_xml) {
UploadRequired upload_required;
FormStructure::ParseQueryResponse(heuristic_xml,
form_structures_.get(),
&upload_required,
*metric_logger_);
}
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: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
UWORD16 u2_height;
UWORD16 u2_width;
if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND;
}
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u2_width = impeg2d_bit_stream_get(ps_stream,12);
u2_height = impeg2d_bit_stream_get(ps_stream,12);
if (0 == u2_width || 0 == u2_height)
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_FRM_HDR_DECODE_ERR;
return e_error;
}
if ((u2_width != ps_dec->u2_horizontal_size)
|| (u2_height != ps_dec->u2_vertical_size))
{
if (0 == ps_dec->u2_header_done)
{
/* This is the first time we are reading the resolution */
ps_dec->u2_horizontal_size = u2_width;
ps_dec->u2_vertical_size = u2_height;
if (0 == ps_dec->u4_frm_buf_stride)
{
ps_dec->u4_frm_buf_stride = (UWORD32) (u2_width);
}
}
else
{
if (0 == ps_dec->i4_pic_count)
{
/* Decoder has not decoded a single frame since the last
* reset/init. This implies that we have two headers in the
* input stream. So, do not indicate a resolution change, since
* this can take the decoder into an infinite loop.
*/
return (IMPEG2D_ERROR_CODES_T) IMPEG2D_FRM_HDR_DECODE_ERR;
}
else if((u2_width > ps_dec->u2_create_max_width)
|| (u2_height > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = u2_height;
ps_dec->u2_reinit_max_width = u2_width;
return e_error;
}
else
{
/* The resolution has changed */
return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED;
}
}
}
if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width)
|| (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = ps_dec->u2_vertical_size;
ps_dec->u2_reinit_max_width = ps_dec->u2_horizontal_size;
return e_error;
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* aspect_ratio_info (4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Frame rate code(4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4);
if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE)
{
return IMPEG2D_FRM_HDR_DECODE_ERR;
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* bit_rate_value (18 bits) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,18);
GET_MARKER_BIT(ps_dec,ps_stream);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,11);
/*------------------------------------------------------------------------*/
/* Quantization matrix for the intra blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
/*------------------------------------------------------------------------*/
/* Quantization matrix for the inter blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void Document::UpdateStyleAndLayoutTreeIgnorePendingStylesheets() {
if (Lifecycle().LifecyclePostponed())
return;
CHECK(Lifecycle().StateAllowsTreeMutations());
StyleEngine::IgnoringPendingStylesheet ignoring(GetStyleEngine());
if (!HaveRenderBlockingResourcesLoaded()) {
HTMLElement* body_element = body();
if (body_element && !body_element->GetLayoutObject() &&
pending_sheet_layout_ == kNoLayoutWithPendingSheets) {
pending_sheet_layout_ = kDidLayoutWithPendingSheets;
GetStyleEngine().MarkAllTreeScopesDirty();
}
if (has_nodes_with_placeholder_style_) {
SetNeedsStyleRecalc(kSubtreeStyleChange,
StyleChangeReasonForTracing::Create(
StyleChangeReason::kCleanupPlaceholderStyles));
}
}
UpdateStyleAndLayoutTree();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool extractPages (const char *srcFileName, const char *destFileName) {
char pathName[4096];
GooString *gfileName = new GooString (srcFileName);
PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL);
if (!doc->isOk()) {
error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName);
return false;
}
if (firstPage == 0 && lastPage == 0) {
firstPage = 1;
lastPage = doc->getNumPages();
}
if (lastPage == 0)
lastPage = doc->getNumPages();
if (firstPage == 0)
if (firstPage == 0)
firstPage = 1;
if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) {
error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName);
return false;
}
for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) {
snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo);
GooString *gpageName = new GooString (pathName);
{
printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>",
argDesc);
}
if (printVersion || printHelp)
exitCode = 0;
goto err0;
}
globalParams = new GlobalParams();
ok = extractPages (argv[1], argv[2]);
if (ok) {
exitCode = 0;
}
delete globalParams;
err0:
return exitCode;
}
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: int WebGraphicsContext3DCommandBufferImpl::GetGPUProcessID() {
return host_ ? host_->gpu_process_id() : 0;
}
CWE ID:
Target: 1
Example 2:
Code: bool BrowserView::CanTriggerOnMouse() const {
return !IsImmersiveModeEnabled();
}
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: SocketStreamDispatcherHost::SocketStreamDispatcherHost(
int render_process_id,
ResourceMessageFilter::URLRequestContextSelector* selector,
content::ResourceContext* resource_context)
: ALLOW_THIS_IN_INITIALIZER_LIST(ssl_delegate_weak_factory_(this)),
render_process_id_(render_process_id),
url_request_context_selector_(selector),
resource_context_(resource_context) {
DCHECK(selector);
net::WebSocketJob::EnsureInit();
}
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 jffs2_create(struct inode *dir_i, struct dentry *dentry, int mode,
struct nameidata *nd)
{
struct jffs2_raw_inode *ri;
struct jffs2_inode_info *f, *dir_f;
struct jffs2_sb_info *c;
struct inode *inode;
int ret;
ri = jffs2_alloc_raw_inode();
return -ENOMEM;
c = JFFS2_SB_INFO(dir_i->i_sb);
D1(printk(KERN_DEBUG "jffs2_create()\n"));
inode = jffs2_new_inode(dir_i, mode, ri);
if (IS_ERR(inode)) {
D1(printk(KERN_DEBUG "jffs2_new_inode() failed\n"));
return PTR_ERR(inode);
}
inode->i_op = &jffs2_file_inode_operations;
inode->i_fop = &jffs2_file_operations;
inode->i_mapping->a_ops = &jffs2_file_address_operations;
inode->i_mapping->nrpages = 0;
f = JFFS2_INODE_INFO(inode);
dir_f = JFFS2_INODE_INFO(dir_i);
ret = jffs2_do_create(c, dir_f, f, ri,
dentry->d_name.name, dentry->d_name.len);
dentry->d_name.name, dentry->d_name.len);
if (ret)
goto fail;
ret = jffs2_init_security(inode, dir_i);
if (ret)
goto fail;
ret = jffs2_init_acl(inode, dir_i);
if (ret)
goto fail;
jffs2_free_raw_inode(ri);
d_instantiate(dentry, inode);
D1(printk(KERN_DEBUG "jffs2_create: Created ino #%lu with mode %o, nlink %d(%d). nrpages %ld\n",
inode->i_ino, inode->i_mode, inode->i_nlink, f->inocache->nlink, inode->i_mapping->nrpages));
inode->i_ino, inode->i_mode, inode->i_nlink, f->inocache->nlink, inode->i_mapping->nrpages));
return 0;
fail:
make_bad_inode(inode);
iput(inode);
/***********************************************************************/
static int jffs2_unlink(struct inode *dir_i, struct dentry *dentry)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(dir_i->i_sb);
struct jffs2_inode_info *dir_f = JFFS2_INODE_INFO(dir_i);
struct jffs2_inode_info *dead_f = JFFS2_INODE_INFO(dentry->d_inode);
int ret;
uint32_t now = get_seconds();
ret = jffs2_do_unlink(c, dir_f, dentry->d_name.name,
dentry->d_name.len, dead_f, now);
if (dead_f->inocache)
dentry->d_inode->i_nlink = dead_f->inocache->nlink;
if (!ret)
dir_i->i_mtime = dir_i->i_ctime = ITIME(now);
return ret;
}
/***********************************************************************/
static int jffs2_link (struct dentry *old_dentry, struct inode *dir_i, struct dentry *dentry)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(old_dentry->d_inode->i_sb);
struct jffs2_inode_info *f = JFFS2_INODE_INFO(old_dentry->d_inode);
struct jffs2_inode_info *dir_f = JFFS2_INODE_INFO(dir_i);
int ret;
uint8_t type;
uint32_t now;
/* Don't let people make hard links to bad inodes. */
if (!f->inocache)
return -EIO;
if (S_ISDIR(old_dentry->d_inode->i_mode))
return -EPERM;
/* XXX: This is ugly */
type = (old_dentry->d_inode->i_mode & S_IFMT) >> 12;
if (!type) type = DT_REG;
now = get_seconds();
ret = jffs2_do_link(c, dir_f, f->inocache->ino, type, dentry->d_name.name, dentry->d_name.len, now);
if (!ret) {
down(&f->sem);
old_dentry->d_inode->i_nlink = ++f->inocache->nlink;
up(&f->sem);
d_instantiate(dentry, old_dentry->d_inode);
dir_i->i_mtime = dir_i->i_ctime = ITIME(now);
atomic_inc(&old_dentry->d_inode->i_count);
}
return ret;
}
/***********************************************************************/
static int jffs2_symlink (struct inode *dir_i, struct dentry *dentry, const char *target)
{
struct jffs2_inode_info *f, *dir_f;
struct jffs2_sb_info *c;
struct inode *inode;
struct jffs2_raw_inode *ri;
struct jffs2_raw_dirent *rd;
struct jffs2_full_dnode *fn;
struct jffs2_full_dirent *fd;
int namelen;
uint32_t alloclen;
struct jffs2_full_dirent *fd;
int namelen;
uint32_t alloclen;
int ret, targetlen = strlen(target);
/* FIXME: If you care. We'd need to use frags for the target
ri = jffs2_alloc_raw_inode();
if (!ri)
return -ENOMEM;
c = JFFS2_SB_INFO(dir_i->i_sb);
/* Try to reserve enough space for both node and dirent.
* Just the node will do for now, though
*/
namelen = dentry->d_name.len;
ret = jffs2_reserve_space(c, sizeof(*ri) + targetlen, &alloclen,
ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE);
if (ret) {
jffs2_free_raw_inode(ri);
return ret;
}
inode = jffs2_new_inode(dir_i, S_IFLNK | S_IRWXUGO, ri);
return ret;
}
inode = jffs2_new_inode(dir_i, S_IFLNK | S_IRWXUGO, ri);
if (IS_ERR(inode)) {
jffs2_free_raw_inode(ri);
inode->i_op = &jffs2_symlink_inode_operations;
f = JFFS2_INODE_INFO(inode);
inode->i_size = targetlen;
ri->isize = ri->dsize = ri->csize = cpu_to_je32(inode->i_size);
ri->totlen = cpu_to_je32(sizeof(*ri) + inode->i_size);
ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4));
ri->compr = JFFS2_COMPR_NONE;
ri->data_crc = cpu_to_je32(crc32(0, target, targetlen));
ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8));
fn = jffs2_write_dnode(c, f, ri, target, targetlen, ALLOC_NORMAL);
jffs2_free_raw_inode(ri);
if (IS_ERR(fn)) {
/* Eeek. Wave bye bye */
up(&f->sem);
jffs2_complete_reservation(c);
jffs2_clear_inode(inode);
return PTR_ERR(fn);
up(&f->sem);
jffs2_complete_reservation(c);
jffs2_clear_inode(inode);
return PTR_ERR(fn);
}
jffs2_complete_reservation(c);
jffs2_clear_inode(inode);
return -ENOMEM;
}
up(&f->sem);
jffs2_complete_reservation(c);
jffs2_clear_inode(inode);
return -ENOMEM;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
{
struct qstr this = QSTR_INIT("[aio]", 5);
struct file *file;
struct path path;
struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
if (IS_ERR(inode))
return ERR_CAST(inode);
inode->i_mapping->a_ops = &aio_ctx_aops;
inode->i_mapping->private_data = ctx;
inode->i_mapping->backing_dev_info = &aio_fs_backing_dev_info;
inode->i_size = PAGE_SIZE * nr_pages;
path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
if (!path.dentry) {
iput(inode);
return ERR_PTR(-ENOMEM);
}
path.mnt = mntget(aio_mnt);
d_instantiate(path.dentry, inode);
file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
if (IS_ERR(file)) {
path_put(&path);
return file;
}
file->f_flags = O_RDWR;
file->private_data = ctx;
return file;
}
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 jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *in, uint_fast16_t len)
{
uint_fast8_t tmp;
int n;
int i;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
n = 0;
if (jpc_getuint8(in, &tmp)) {
return -1;
}
++n;
compparms->qntsty = tmp & 0x1f;
compparms->numguard = (tmp >> 5) & 7;
switch (compparms->qntsty) {
case JPC_QCX_SIQNT:
compparms->numstepsizes = 1;
break;
case JPC_QCX_NOQNT:
compparms->numstepsizes = (len - n);
break;
case JPC_QCX_SEQNT:
/* XXX - this is a hack */
compparms->numstepsizes = (len - n) / 2;
break;
}
/* Ensure that the step size array is sufficiently large. */
if (compparms->numstepsizes > 3 * JPC_MAXRLVLS + 1) {
jpc_qcx_destroycompparms(compparms);
return -1;
}
if (compparms->numstepsizes > 0) {
if (!(compparms->stepsizes = jas_alloc2(compparms->numstepsizes,
sizeof(uint_fast16_t)))) {
abort();
}
for (i = 0; i < compparms->numstepsizes; ++i) {
if (compparms->qntsty == JPC_QCX_NOQNT) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
compparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3);
} else {
if (jpc_getuint16(in, &compparms->stepsizes[i])) {
return -1;
}
}
}
} else {
compparms->stepsizes = 0;
}
if (jas_stream_error(in) || jas_stream_eof(in)) {
jpc_qcx_destroycompparms(compparms);
return -1;
}
return 0;
}
CWE ID: CWE-190
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture(
const scoped_refptr<VP9Picture>& pic) {
scoped_refptr<VaapiDecodeSurface> dec_surface =
VP9PictureToVaapiDecodeSurface(pic);
dec_surface->set_visible_rect(pic->visible_rect);
vaapi_dec_->SurfaceReady(dec_surface);
return true;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: hb_shaper_get_run_language(ASS_Shaper *shaper, hb_script_t script)
{
hb_language_t lang;
if (shaper->language != HB_LANGUAGE_INVALID)
return shaper->language;
lang = script_to_language(script);
if (lang == HB_LANGUAGE_INVALID)
lang = hb_language_get_default();
return lang;
}
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 Document::setAutofocusElement(Element* element)
{
if (!element) {
m_autofocusElement = nullptr;
return;
}
if (m_hasAutofocused)
return;
m_hasAutofocused = true;
ASSERT(!m_autofocusElement);
m_autofocusElement = element;
m_taskRunner->postTask(FROM_HERE, AutofocusTask::create());
}
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: int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vmw_private *dev_priv = vmw_priv(dev);
struct vmw_user_surface *user_srf;
struct vmw_surface *srf;
struct vmw_resource *res;
struct vmw_resource *tmp;
union drm_vmw_gb_surface_create_arg *arg =
(union drm_vmw_gb_surface_create_arg *)data;
struct drm_vmw_gb_surface_create_req *req = &arg->req;
struct drm_vmw_gb_surface_create_rep *rep = &arg->rep;
struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
int ret;
uint32_t size;
uint32_t backup_handle;
if (req->multisample_count != 0)
return -EINVAL;
if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS)
return -EINVAL;
if (unlikely(vmw_user_surface_size == 0))
vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) +
128;
size = vmw_user_surface_size + 128;
/* Define a surface based on the parameters. */
ret = vmw_surface_gb_priv_define(dev,
size,
req->svga3d_flags,
req->format,
req->drm_surface_flags & drm_vmw_surface_flag_scanout,
req->mip_levels,
req->multisample_count,
req->array_size,
req->base_size,
&srf);
if (unlikely(ret != 0))
return ret;
user_srf = container_of(srf, struct vmw_user_surface, srf);
if (drm_is_primary_client(file_priv))
user_srf->master = drm_master_get(file_priv->master);
ret = ttm_read_lock(&dev_priv->reservation_sem, true);
if (unlikely(ret != 0))
return ret;
res = &user_srf->srf.res;
if (req->buffer_handle != SVGA3D_INVALID_ID) {
ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle,
&res->backup,
&user_srf->backup_base);
if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE <
res->backup_size) {
DRM_ERROR("Surface backup buffer is too small.\n");
vmw_dmabuf_unreference(&res->backup);
ret = -EINVAL;
goto out_unlock;
}
} else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer)
ret = vmw_user_dmabuf_alloc(dev_priv, tfile,
res->backup_size,
req->drm_surface_flags &
drm_vmw_surface_flag_shareable,
&backup_handle,
&res->backup,
&user_srf->backup_base);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&res);
goto out_unlock;
}
tmp = vmw_resource_reference(res);
ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime,
req->drm_surface_flags &
drm_vmw_surface_flag_shareable,
VMW_RES_SURFACE,
&vmw_user_surface_base_release, NULL);
if (unlikely(ret != 0)) {
vmw_resource_unreference(&tmp);
vmw_resource_unreference(&res);
goto out_unlock;
}
rep->handle = user_srf->prime.base.hash.key;
rep->backup_size = res->backup_size;
if (res->backup) {
rep->buffer_map_handle =
drm_vma_node_offset_addr(&res->backup->base.vma_node);
rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE;
rep->buffer_handle = backup_handle;
} else {
rep->buffer_map_handle = 0;
rep->buffer_size = 0;
rep->buffer_handle = SVGA3D_INVALID_ID;
}
vmw_resource_unreference(&res);
out_unlock:
ttm_read_unlock(&dev_priv->reservation_sem);
return ret;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void Ins_NEG( INS_ARG )
{ (void)exc;
args[0] = -args[0];
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderThreadImpl::OnMemoryStateChange(base::MemoryState state) {
if (blink_platform_impl_) {
blink::WebMemoryCoordinator::OnMemoryStateChange(
static_cast<blink::MemoryState>(state));
}
}
CWE ID: CWE-310
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 AppCacheDatabase::FindCacheForGroup(int64_t group_id,
CacheRecord* record) {
DCHECK(record);
if (!LazyOpen(kDontCreate))
return false;
static const char kSql[] =
"SELECT cache_id, group_id, online_wildcard, update_time, cache_size"
" FROM Caches WHERE group_id = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, group_id);
if (!statement.Step())
return false;
ReadCacheRecord(statement, record);
return true;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool RenderLayerScrollableArea::shouldPlaceVerticalScrollbarOnLeft() const
{
return box().style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft();
}
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: const char * util_acl_to_str(const sc_acl_entry_t *e)
{
static char line[80], buf[20];
unsigned int acl;
if (e == NULL)
return "N/A";
line[0] = 0;
while (e != NULL) {
acl = e->method;
switch (acl) {
case SC_AC_UNKNOWN:
return "N/A";
case SC_AC_NEVER:
return "NEVR";
case SC_AC_NONE:
return "NONE";
case SC_AC_CHV:
strcpy(buf, "CHV");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "%d", e->key_ref);
break;
case SC_AC_TERM:
strcpy(buf, "TERM");
break;
case SC_AC_PRO:
strcpy(buf, "PROT");
break;
case SC_AC_AUT:
strcpy(buf, "AUTH");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 4, "%d", e->key_ref);
break;
case SC_AC_SEN:
strcpy(buf, "Sec.Env. ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
case SC_AC_SCB:
strcpy(buf, "Sec.ControlByte ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "Ox%X", e->key_ref);
break;
case SC_AC_IDA:
strcpy(buf, "PKCS#15 AuthID ");
if (e->key_ref != SC_AC_KEY_REF_NONE)
sprintf(buf + 3, "#%d", e->key_ref);
break;
default:
strcpy(buf, "????");
break;
}
strcat(line, buf);
strcat(line, " ");
e = e->next;
}
line[strlen(line)-1] = 0; /* get rid of trailing space */
return line;
}
CWE ID: CWE-415
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 rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
X509_ALGOR *sigalg, ASN1_BIT_STRING *sig,
EVP_PKEY *pkey)
{
/* Sanity check: make sure it is PSS */
if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) {
RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
return -1;
}
if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey))
/* Carry on */
return 2;
return -1;
}
CWE ID:
Target: 1
Example 2:
Code: IntRect FrameView::convertFromRenderer(const RenderObject& renderer, const IntRect& rendererRect) const
{
IntRect rect = pixelSnappedIntRect(enclosingLayoutRect(renderer.localToAbsoluteQuad(FloatRect(rendererRect)).boundingBox()));
rect.moveBy(-scrollPosition());
return rect;
}
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 void inbound_data_waiting(void *context) {
eager_reader_t *reader = (eager_reader_t *)context;
data_buffer_t *buffer = (data_buffer_t *)reader->allocator->alloc(reader->buffer_size + sizeof(data_buffer_t));
if (!buffer) {
LOG_ERROR("%s couldn't aquire memory for inbound data buffer.", __func__);
return;
}
buffer->length = 0;
buffer->offset = 0;
int bytes_read = read(reader->inbound_fd, buffer->data, reader->buffer_size);
if (bytes_read > 0) {
buffer->length = bytes_read;
fixed_queue_enqueue(reader->buffers, buffer);
eventfd_write(reader->bytes_available_fd, bytes_read);
} else {
if (bytes_read == 0)
LOG_WARN("%s fd said bytes existed, but none were found.", __func__);
else
LOG_WARN("%s unable to read from file descriptor: %s", __func__, strerror(errno));
reader->allocator->free(buffer);
}
}
CWE ID: CWE-284
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 FragmentPaintPropertyTreeBuilder::UpdateSvgLocalToBorderBoxTransform() {
DCHECK(properties_);
if (!object_.IsSVGRoot())
return;
if (NeedsPaintPropertyUpdate()) {
AffineTransform transform_to_border_box =
SVGRootPainter(ToLayoutSVGRoot(object_))
.TransformToPixelSnappedBorderBox(context_.current.paint_offset);
if (!transform_to_border_box.IsIdentity() &&
NeedsSVGLocalToBorderBoxTransform(object_)) {
OnUpdate(properties_->UpdateSvgLocalToBorderBoxTransform(
context_.current.transform,
TransformPaintPropertyNode::State{transform_to_border_box}));
} else {
OnClear(properties_->ClearSvgLocalToBorderBoxTransform());
}
}
if (properties_->SvgLocalToBorderBoxTransform()) {
context_.current.transform = properties_->SvgLocalToBorderBoxTransform();
context_.current.should_flatten_inherited_transform = false;
context_.current.rendering_context_id = 0;
}
context_.current.paint_offset = LayoutPoint();
}
CWE ID:
Target: 1
Example 2:
Code: tt_cmap2_char_index( TT_CMap cmap,
FT_UInt32 char_code )
{
FT_Byte* table = cmap->data;
FT_UInt result = 0;
FT_Byte* subheader;
subheader = tt_cmap2_get_subheader( table, char_code );
if ( subheader )
{
FT_Byte* p = subheader;
FT_UInt idx = (FT_UInt)(char_code & 0xFF);
FT_UInt start, count;
FT_Int delta;
FT_UInt offset;
start = TT_NEXT_USHORT( p );
count = TT_NEXT_USHORT( p );
delta = TT_NEXT_SHORT ( p );
offset = TT_PEEK_USHORT( p );
idx -= start;
if ( idx < count && offset != 0 )
{
p += offset + 2 * idx;
idx = TT_PEEK_USHORT( p );
if ( idx != 0 )
result = (FT_UInt)( idx + delta ) & 0xFFFFU;
}
}
return result;
}
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 void fdctrl_write (void *opaque, uint32_t reg, uint32_t value)
{
FDCtrl *fdctrl = opaque;
FLOPPY_DPRINTF("write reg%d: 0x%02x\n", reg & 7, value);
reg &= 7;
switch (reg) {
case FD_REG_DOR:
fdctrl_write_dor(fdctrl, value);
break;
case FD_REG_TDR:
fdctrl_write_tape(fdctrl, value);
break;
case FD_REG_DSR:
fdctrl_write_rate(fdctrl, value);
break;
case FD_REG_FIFO:
fdctrl_write_data(fdctrl, value);
break;
case FD_REG_CCR:
fdctrl_write_ccr(fdctrl, value);
break;
default:
break;
}
}
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 hns_ppe_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return ETH_PPE_STATIC_NUM;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: CodecHandler::CodecHandler(AMediaCodec *codec) {
mCodec = codec;
}
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: static void disk_release(struct device *dev)
{
struct gendisk *disk = dev_to_disk(dev);
blk_free_devt(dev->devt);
disk_release_events(disk);
kfree(disk->random);
disk_replace_part_tbl(disk, NULL);
hd_free_part(&disk->part0);
if (disk->queue)
blk_put_queue(disk->queue);
kfree(disk);
}
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 ClientDiscardableSharedMemoryManager::AllocateCompletedOnIO(
base::SharedMemoryHandle* handle,
base::ScopedClosureRunner closure_runner,
mojo::ScopedSharedBufferHandle mojo_handle) {
size_t memory_size = 0;
bool read_only = false;
if (!mojo_handle.is_valid())
return;
auto result = mojo::UnwrapSharedMemoryHandle(std::move(mojo_handle), handle,
&memory_size, &read_only);
DCHECK_EQ(result, MOJO_RESULT_OK);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static PHP_GINIT_FUNCTION(libxml)
{
libxml_globals->stream_context = NULL;
libxml_globals->error_buffer.c = NULL;
libxml_globals->error_list = NULL;
libxml_globals->entity_loader.fci.size = 0;
libxml_globals->entity_loader_disabled = 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int do_recv_NotifyData(rpc_message_t *message, void *p_value)
{
int error;
uint64_t id;
if ((error = rpc_message_recv_uint64(message, &id)) < 0)
return error;
if (sizeof(void *) == 4 && ((uint32_t)(id >> 32)) != 0) {
npw_printf("ERROR: 64-bit viewers in 32-bit wrappers are not supported\n");
abort();
}
*((void **)p_value) = (void *)(uintptr_t)id;
return RPC_ERROR_NO_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: WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID(
int window_id,
std::string* error) {
Browser* browser = NULL;
if (!GetBrowserFromWindowID(chrome_details_, window_id, &browser, error))
return nullptr;
WebContents* contents = browser->tab_strip_model()->GetActiveWebContents();
if (!contents) {
*error = "No active web contents to capture";
return nullptr;
}
if (!extension()->permissions_data()->CanCaptureVisiblePage(
contents->GetLastCommittedURL(),
SessionTabHelper::IdForTab(contents).id(), error)) {
return nullptr;
}
return contents;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: virtual gfx::GLContext* GetGLContext() { return context_.get(); }
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int main(int argc, char *argv[])
{
FILE *iplist = NULL;
plist_t root_node = NULL;
char *plist_out = NULL;
uint32_t size = 0;
int read_size = 0;
char *plist_entire = NULL;
struct stat filestats;
options_t *options = parse_arguments(argc, argv);
if (!options)
{
print_usage(argc, argv);
return 0;
}
iplist = fopen(options->in_file, "rb");
if (!iplist) {
free(options);
return 1;
}
stat(options->in_file, &filestats);
plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1));
read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist);
fclose(iplist);
if (memcmp(plist_entire, "bplist00", 8) == 0)
{
plist_from_bin(plist_entire, read_size, &root_node);
plist_to_xml(root_node, &plist_out, &size);
}
else
{
plist_from_xml(plist_entire, read_size, &root_node);
plist_to_bin(root_node, &plist_out, &size);
}
plist_free(root_node);
free(plist_entire);
if (plist_out)
{
if (options->out_file != NULL)
{
FILE *oplist = fopen(options->out_file, "wb");
if (!oplist) {
free(options);
return 1;
}
fwrite(plist_out, size, sizeof(char), oplist);
fclose(oplist);
}
else
fwrite(plist_out, size, sizeof(char), stdout);
free(plist_out);
}
else
printf("ERROR: Failed to convert input file.\n");
free(options);
return 0;
}
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 bnep_net_setup(struct net_device *dev)
{
memset(dev->broadcast, 0xff, ETH_ALEN);
dev->addr_len = ETH_ALEN;
ether_setup(dev);
dev->netdev_ops = &bnep_netdev_ops;
dev->watchdog_timeo = HZ * 2;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static struct ip_tunnel * ipip6_tunnel_locate(struct net *net,
struct ip_tunnel_parm *parms, int create)
{
__be32 remote = parms->iph.daddr;
__be32 local = parms->iph.saddr;
struct ip_tunnel *t, **tp, *nt;
struct net_device *dev;
char name[IFNAMSIZ];
struct sit_net *sitn = net_generic(net, sit_net_id);
for (tp = __ipip6_bucket(sitn, parms); (t = *tp) != NULL; tp = &t->next) {
if (local == t->parms.iph.saddr &&
remote == t->parms.iph.daddr &&
parms->link == t->parms.link) {
if (create)
return NULL;
else
return t;
}
}
if (!create)
goto failed;
if (parms->name[0])
strlcpy(name, parms->name, IFNAMSIZ);
else
sprintf(name, "sit%%d");
dev = alloc_netdev(sizeof(*t), name, ipip6_tunnel_setup);
if (dev == NULL)
return NULL;
dev_net_set(dev, net);
if (strchr(name, '%')) {
if (dev_alloc_name(dev, name) < 0)
goto failed_free;
}
nt = netdev_priv(dev);
nt->parms = *parms;
ipip6_tunnel_init(dev);
ipip6_tunnel_clone_6rd(dev, sitn);
if (parms->i_flags & SIT_ISATAP)
dev->priv_flags |= IFF_ISATAP;
if (register_netdevice(dev) < 0)
goto failed_free;
dev_hold(dev);
ipip6_tunnel_link(sitn, nt);
return nt;
failed_free:
free_netdev(dev);
failed:
return NULL;
}
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: get_parameters(struct iperf_test *test)
{
int r = 0;
cJSON *j;
cJSON *j_p;
j = JSON_read(test->ctrl_sck);
if (j == NULL) {
i_errno = IERECVPARAMS;
r = -1;
} else {
if (test->debug) {
printf("get_parameters:\n%s\n", cJSON_Print(j));
}
if ((j_p = cJSON_GetObjectItem(j, "tcp")) != NULL)
set_protocol(test, Ptcp);
if ((j_p = cJSON_GetObjectItem(j, "udp")) != NULL)
set_protocol(test, Pudp);
if ((j_p = cJSON_GetObjectItem(j, "omit")) != NULL)
test->omit = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "server_affinity")) != NULL)
test->server_affinity = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "time")) != NULL)
test->duration = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "num")) != NULL)
test->settings->bytes = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "blockcount")) != NULL)
test->settings->blocks = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "MSS")) != NULL)
test->settings->mss = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "nodelay")) != NULL)
test->no_delay = 1;
if ((j_p = cJSON_GetObjectItem(j, "parallel")) != NULL)
test->num_streams = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "reverse")) != NULL)
iperf_set_test_reverse(test, 1);
if ((j_p = cJSON_GetObjectItem(j, "window")) != NULL)
test->settings->socket_bufsize = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "len")) != NULL)
test->settings->blksize = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "bandwidth")) != NULL)
test->settings->rate = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "burst")) != NULL)
test->settings->burst = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "TOS")) != NULL)
test->settings->tos = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "flowlabel")) != NULL)
test->settings->flowlabel = j_p->valueint;
if ((j_p = cJSON_GetObjectItem(j, "title")) != NULL)
test->title = strdup(j_p->valuestring);
if ((j_p = cJSON_GetObjectItem(j, "congestion")) != NULL)
test->congestion = strdup(j_p->valuestring);
if ((j_p = cJSON_GetObjectItem(j, "get_server_output")) != NULL)
iperf_set_test_get_server_output(test, 1);
if (test->sender && test->protocol->id == Ptcp && has_tcpinfo_retransmits())
test->sender_has_retransmits = 1;
cJSON_Delete(j);
}
return r;
}
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 inline int mount_entry_on_systemfs(struct mntent *mntent)
{
return mount_entry_on_generic(mntent, mntent->mnt_dir);
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: static long mng_get_long(unsigned char *p)
{
return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]));
}
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: ContextualSearchParams()
: version(-1),
start(base::string16::npos),
end(base::string16::npos),
now_on_tap_version(0) {}
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: hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data)
{
HashAndString *data = (HashAndString*) user_data;
gchar *in = (gchar*) val;
g_hash_table_insert (data->hash, g_strdup ((gchar*) key),
g_strjoin (" ", data->string, in, NULL));
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int AppLayerProtoDetectTest05(void)
{
AppLayerProtoDetectUnittestCtxBackup();
AppLayerProtoDetectSetup();
uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\n<HTML><BODY>Blahblah</BODY></HTML>";
const char *buf;
int r = 0;
Flow f;
AppProto pm_results[ALPROTO_MAX];
AppLayerProtoDetectThreadCtx *alpd_tctx;
memset(&f, 0x00, sizeof(f));
f.protomap = FlowGetProtoMapping(IPPROTO_TCP);
memset(pm_results, 0, sizeof(pm_results));
buf = "HTTP";
AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT);
buf = "220 ";
AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT);
AppLayerProtoDetectPrepareState();
/* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since
* it sets internal structures which depends on the above function. */
alpd_tctx = AppLayerProtoDetectGetCtxThread();
if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) {
printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\n");
goto end;
}
if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) {
printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\n");
goto end;
}
if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) {
printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\n");
goto end;
}
if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) {
printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\n");
goto end;
}
if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) {
printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\n");
goto end;
}
if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) {
printf("alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\n");
goto end;
}
uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx,
&f,
l7data, sizeof(l7data),
STREAM_TOCLIENT,
IPPROTO_TCP,
pm_results);
if (cnt != 1 && pm_results[0] != ALPROTO_HTTP) {
printf("cnt != 1 && pm_results[0] != AlPROTO_HTTP\n");
goto end;
}
r = 1;
end:
if (alpd_tctx != NULL)
AppLayerProtoDetectDestroyCtxThread(alpd_tctx);
AppLayerProtoDetectDeSetup();
AppLayerProtoDetectUnittestCtxRestore();
return r;
}
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 MimeHandlerViewContainer::OnReady() {
if (!render_frame() || !is_embedded_)
return;
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
blink::WebAssociatedURLLoaderOptions options;
DCHECK(!loader_);
loader_.reset(frame->CreateAssociatedURLLoader(options));
blink::WebURLRequest request(original_url_);
request.SetRequestContext(blink::WebURLRequest::kRequestContextObject);
loader_->LoadAsynchronously(request, this);
}
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: cJSON *cJSON_DetachItemFromObject( cJSON *object, const char *string )
{
int i = 0;
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) ) {
++i;
c = c->next;
}
if ( c )
return cJSON_DetachItemFromArray( object, i );
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: gboolean BrowserWindowGtk::OnGtkAccelerator(GtkAccelGroup* accel_group,
GObject* acceleratable,
guint keyval,
GdkModifierType modifier,
void* user_data) {
int command_id = GPOINTER_TO_INT(user_data);
BrowserWindowGtk* browser_window =
GetBrowserWindowForNativeWindow(GTK_WINDOW(acceleratable));
DCHECK(browser_window != NULL);
return chrome::ExecuteCommand(browser_window->browser(), command_id);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int crypto_cbc_decrypt_inplace(struct blkcipher_desc *desc,
struct blkcipher_walk *walk,
struct crypto_cipher *tfm)
{
void (*fn)(struct crypto_tfm *, u8 *, const u8 *) =
crypto_cipher_alg(tfm)->cia_decrypt;
int bsize = crypto_cipher_blocksize(tfm);
unsigned int nbytes = walk->nbytes;
u8 *src = walk->src.virt.addr;
u8 last_iv[bsize];
/* Start of the last block. */
src += nbytes - (nbytes & (bsize - 1)) - bsize;
memcpy(last_iv, src, bsize);
for (;;) {
fn(crypto_cipher_tfm(tfm), src, src);
if ((nbytes -= bsize) < bsize)
break;
crypto_xor(src, src - bsize, bsize);
src -= bsize;
}
crypto_xor(src, walk->iv, bsize);
memcpy(walk->iv, last_iv, bsize);
return nbytes;
}
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: status_t StreamingProcessor::processRecordingFrame() {
ATRACE_CALL();
status_t res;
sp<Camera2Heap> recordingHeap;
size_t heapIdx = 0;
nsecs_t timestamp;
sp<Camera2Client> client = mClient.promote();
if (client == 0) {
BufferItem imgBuffer;
res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0);
if (res != OK) {
if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) {
ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)",
__FUNCTION__, mId, strerror(-res), res);
}
return res;
}
mRecordingConsumer->releaseBuffer(imgBuffer);
return OK;
}
{
/* acquire SharedParameters before mMutex so we don't dead lock
with Camera2Client code calling into StreamingProcessor */
SharedParameters::Lock l(client->getParameters());
Mutex::Autolock m(mMutex);
BufferItem imgBuffer;
res = mRecordingConsumer->acquireBuffer(&imgBuffer, 0);
if (res != OK) {
if (res != BufferItemConsumer::NO_BUFFER_AVAILABLE) {
ALOGE("%s: Camera %d: Can't acquire recording buffer: %s (%d)",
__FUNCTION__, mId, strerror(-res), res);
}
return res;
}
timestamp = imgBuffer.mTimestamp;
mRecordingFrameCount++;
ALOGVV("OnRecordingFrame: Frame %d", mRecordingFrameCount);
if (l.mParameters.state != Parameters::RECORD &&
l.mParameters.state != Parameters::VIDEO_SNAPSHOT) {
ALOGV("%s: Camera %d: Discarding recording image buffers "
"received after recording done", __FUNCTION__,
mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return INVALID_OPERATION;
}
if (mRecordingHeap == 0) {
size_t payloadSize = sizeof(VideoNativeMetadata);
ALOGV("%s: Camera %d: Creating recording heap with %zu buffers of "
"size %zu bytes", __FUNCTION__, mId,
mRecordingHeapCount, payloadSize);
mRecordingHeap = new Camera2Heap(payloadSize, mRecordingHeapCount,
"Camera2Client::RecordingHeap");
if (mRecordingHeap->mHeap->getSize() == 0) {
ALOGE("%s: Camera %d: Unable to allocate memory for recording",
__FUNCTION__, mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return NO_MEMORY;
}
for (size_t i = 0; i < mRecordingBuffers.size(); i++) {
if (mRecordingBuffers[i].mBuf !=
BufferItemConsumer::INVALID_BUFFER_SLOT) {
ALOGE("%s: Camera %d: Non-empty recording buffers list!",
__FUNCTION__, mId);
}
}
mRecordingBuffers.clear();
mRecordingBuffers.setCapacity(mRecordingHeapCount);
mRecordingBuffers.insertAt(0, mRecordingHeapCount);
mRecordingHeapHead = 0;
mRecordingHeapFree = mRecordingHeapCount;
}
if (mRecordingHeapFree == 0) {
ALOGE("%s: Camera %d: No free recording buffers, dropping frame",
__FUNCTION__, mId);
mRecordingConsumer->releaseBuffer(imgBuffer);
return NO_MEMORY;
}
heapIdx = mRecordingHeapHead;
mRecordingHeapHead = (mRecordingHeapHead + 1) % mRecordingHeapCount;
mRecordingHeapFree--;
ALOGVV("%s: Camera %d: Timestamp %lld",
__FUNCTION__, mId, timestamp);
ssize_t offset;
size_t size;
sp<IMemoryHeap> heap =
mRecordingHeap->mBuffers[heapIdx]->getMemory(&offset,
&size);
VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>(
(uint8_t*)heap->getBase() + offset);
payload->eType = kMetadataBufferTypeANWBuffer;
payload->pBuffer = imgBuffer.mGraphicBuffer->getNativeBuffer();
payload->nFenceFd = -1;
ALOGVV("%s: Camera %d: Sending out ANWBuffer %p",
__FUNCTION__, mId, payload->pBuffer);
mRecordingBuffers.replaceAt(imgBuffer, heapIdx);
recordingHeap = mRecordingHeap;
}
Camera2Client::SharedCameraCallbacks::Lock l(client->mSharedCameraCallbacks);
if (l.mRemoteCallback != 0) {
l.mRemoteCallback->dataCallbackTimestamp(timestamp,
CAMERA_MSG_VIDEO_FRAME,
recordingHeap->mBuffers[heapIdx]);
} else {
ALOGW("%s: Camera %d: Remote callback gone", __FUNCTION__, mId);
}
return OK;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int decode_attr_rdev(struct xdr_stream *xdr, uint32_t *bitmap, dev_t *rdev)
{
uint32_t major = 0, minor = 0;
__be32 *p;
int ret = 0;
*rdev = MKDEV(0,0);
if (unlikely(bitmap[1] & (FATTR4_WORD1_RAWDEV - 1U)))
return -EIO;
if (likely(bitmap[1] & FATTR4_WORD1_RAWDEV)) {
dev_t tmp;
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
major = be32_to_cpup(p++);
minor = be32_to_cpup(p);
tmp = MKDEV(major, minor);
if (MAJOR(tmp) == major && MINOR(tmp) == minor)
*rdev = tmp;
bitmap[1] &= ~ FATTR4_WORD1_RAWDEV;
ret = NFS_ATTR_FATTR_RDEV;
}
dprintk("%s: rdev=(0x%x:0x%x)\n", __func__, major, minor);
return ret;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
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: virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 16;
fwd_txfm_ref = fht16x16_ref;
}
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 dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
*p == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
CWE ID:
Target: 1
Example 2:
Code: void show_numa_stats(struct task_struct *p, struct seq_file *m)
{
int node;
unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
for_each_online_node(node) {
if (p->numa_faults) {
tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
}
if (p->numa_group) {
gsf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 0)],
gpf = p->numa_group->faults[task_faults_idx(NUMA_MEM, node, 1)];
}
print_numa_stats(m, node, tsf, tpf, gsf, gpf);
}
}
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: int tcp_v4_rcv(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
const struct iphdr *iph;
const struct tcphdr *th;
bool refcounted;
struct sock *sk;
int ret;
if (skb->pkt_type != PACKET_HOST)
goto discard_it;
/* Count it even if it's bad */
__TCP_INC_STATS(net, TCP_MIB_INSEGS);
if (!pskb_may_pull(skb, sizeof(struct tcphdr)))
goto discard_it;
th = (const struct tcphdr *)skb->data;
if (unlikely(th->doff < sizeof(struct tcphdr) / 4))
goto bad_packet;
if (!pskb_may_pull(skb, th->doff * 4))
goto discard_it;
/* An explanation is required here, I think.
* Packet length and doff are validated by header prediction,
* provided case of th->doff==0 is eliminated.
* So, we defer the checks. */
if (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo))
goto csum_error;
th = (const struct tcphdr *)skb->data;
iph = ip_hdr(skb);
/* This is tricky : We move IPCB at its correct location into TCP_SKB_CB()
* barrier() makes sure compiler wont play fool^Waliasing games.
*/
memmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb),
sizeof(struct inet_skb_parm));
barrier();
TCP_SKB_CB(skb)->seq = ntohl(th->seq);
TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +
skb->len - th->doff * 4);
TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);
TCP_SKB_CB(skb)->tcp_flags = tcp_flag_byte(th);
TCP_SKB_CB(skb)->tcp_tw_isn = 0;
TCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph);
TCP_SKB_CB(skb)->sacked = 0;
lookup:
sk = __inet_lookup_skb(&tcp_hashinfo, skb, __tcp_hdrlen(th), th->source,
th->dest, &refcounted);
if (!sk)
goto no_tcp_socket;
process:
if (sk->sk_state == TCP_TIME_WAIT)
goto do_time_wait;
if (sk->sk_state == TCP_NEW_SYN_RECV) {
struct request_sock *req = inet_reqsk(sk);
struct sock *nsk;
sk = req->rsk_listener;
if (unlikely(tcp_v4_inbound_md5_hash(sk, skb))) {
sk_drops_add(sk, skb);
reqsk_put(req);
goto discard_it;
}
if (unlikely(sk->sk_state != TCP_LISTEN)) {
inet_csk_reqsk_queue_drop_and_put(sk, req);
goto lookup;
}
/* We own a reference on the listener, increase it again
* as we might lose it too soon.
*/
sock_hold(sk);
refcounted = true;
nsk = tcp_check_req(sk, skb, req, false);
if (!nsk) {
reqsk_put(req);
goto discard_and_relse;
}
if (nsk == sk) {
reqsk_put(req);
} else if (tcp_child_process(sk, nsk, skb)) {
tcp_v4_send_reset(nsk, skb);
goto discard_and_relse;
} else {
sock_put(sk);
return 0;
}
}
if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) {
__NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
goto discard_and_relse;
}
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
goto discard_and_relse;
if (tcp_v4_inbound_md5_hash(sk, skb))
goto discard_and_relse;
nf_reset(skb);
if (sk_filter(sk, skb))
goto discard_and_relse;
skb->dev = NULL;
if (sk->sk_state == TCP_LISTEN) {
ret = tcp_v4_do_rcv(sk, skb);
goto put_and_return;
}
sk_incoming_cpu_update(sk);
bh_lock_sock_nested(sk);
tcp_segs_in(tcp_sk(sk), skb);
ret = 0;
if (!sock_owned_by_user(sk)) {
if (!tcp_prequeue(sk, skb))
ret = tcp_v4_do_rcv(sk, skb);
} else if (tcp_add_backlog(sk, skb)) {
goto discard_and_relse;
}
bh_unlock_sock(sk);
put_and_return:
if (refcounted)
sock_put(sk);
return ret;
no_tcp_socket:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
goto discard_it;
if (tcp_checksum_complete(skb)) {
csum_error:
__TCP_INC_STATS(net, TCP_MIB_CSUMERRORS);
bad_packet:
__TCP_INC_STATS(net, TCP_MIB_INERRS);
} else {
tcp_v4_send_reset(NULL, skb);
}
discard_it:
/* Discard frame. */
kfree_skb(skb);
return 0;
discard_and_relse:
sk_drops_add(sk, skb);
if (refcounted)
sock_put(sk);
goto discard_it;
do_time_wait:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
inet_twsk_put(inet_twsk(sk));
goto discard_it;
}
if (tcp_checksum_complete(skb)) {
inet_twsk_put(inet_twsk(sk));
goto csum_error;
}
switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) {
case TCP_TW_SYN: {
struct sock *sk2 = inet_lookup_listener(dev_net(skb->dev),
&tcp_hashinfo, skb,
__tcp_hdrlen(th),
iph->saddr, th->source,
iph->daddr, th->dest,
inet_iif(skb));
if (sk2) {
inet_twsk_deschedule_put(inet_twsk(sk));
sk = sk2;
refcounted = false;
goto process;
}
/* Fall through to ACK */
}
case TCP_TW_ACK:
tcp_v4_timewait_ack(sk, skb);
break;
case TCP_TW_RST:
tcp_v4_send_reset(sk, skb);
inet_twsk_deschedule_put(inet_twsk(sk));
goto discard_it;
case TCP_TW_SUCCESS:;
}
goto discard_it;
}
CWE ID: CWE-284
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud,
unsigned long addr, unsigned long end,
swp_entry_t entry, struct page *page)
{
pmd_t *pmd;
unsigned long next;
int ret;
pmd = pmd_offset(pud, addr);
do {
next = pmd_addr_end(addr, end);
if (unlikely(pmd_trans_huge(*pmd)))
continue;
if (pmd_none_or_clear_bad(pmd))
continue;
ret = unuse_pte_range(vma, pmd, addr, next, entry, page);
if (ret)
return ret;
} while (pmd++, addr = next, addr != end);
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void put_nfs_open_context(struct nfs_open_context *ctx)
{
__put_nfs_open_context(ctx, 0);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void Sp_match(js_State *J)
{
js_Regexp *re;
const char *text;
int len;
const char *a, *b, *c, *e;
Resub m;
text = checkstring(J, 0);
if (js_isregexp(J, 1))
js_copy(J, 1);
else if (js_isundefined(J, 1))
js_newregexp(J, "", 0);
else
js_newregexp(J, js_tostring(J, 1), 0);
re = js_toregexp(J, -1);
if (!(re->flags & JS_REGEXP_G)) {
js_RegExp_prototype_exec(J, re, text);
return;
}
re->last = 0;
js_newarray(J);
len = 0;
a = text;
e = text + strlen(text);
while (a <= e) {
if (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0))
break;
b = m.sub[0].sp;
c = m.sub[0].ep;
js_pushlstring(J, b, c - b);
js_setindex(J, -2, len++);
a = c;
if (c - b == 0)
++a;
}
if (len == 0) {
js_pop(J, 1);
js_pushnull(J);
}
}
CWE ID: CWE-400
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 store_xauthority(void) {
fs_build_mnt_dir();
char *src;
char *dest = RUN_XAUTHORITY_FILE;
FILE *fp = fopen(dest, "w");
if (fp) {
fprintf(fp, "\n");
SET_PERMS_STREAM(fp, getuid(), getgid(), 0600);
fclose(fp);
}
if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
struct stat s;
if (stat(src, &s) == 0) {
if (is_link(src)) {
fprintf(stderr, "Warning: invalid .Xauthority file\n");
return 0;
}
copy_file_as_user(src, dest, getuid(), getgid(), 0600);
fs_logger2("clone", dest);
return 1; // file copied
}
return 0;
}
CWE ID: CWE-269
Target: 1
Example 2:
Code: void WebGL2RenderingContextBase::uniform1fv(
const WebGLUniformLocation* location,
Vector<GLfloat>& v,
GLuint src_offset,
GLuint src_length) {
if (isContextLost() ||
!ValidateUniformParameters("uniform1fv", location, v.data(), v.size(), 1,
src_offset, src_length))
return;
ContextGL()->Uniform1fv(location->Location(),
src_length ? src_length : (v.size() - src_offset),
v.data() + src_offset);
}
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: bool MediaControlCastButtonElement::keepEventInNode(Event* event) {
return isUserInteractionEvent(event);
}
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: image_transform_png_set_@_add(image_transform *this,
PNG_CONST image_transform **that, char *name, size_t sizeof_name,
size_t *pos, png_byte colour_type, png_byte bit_depth)
{
this->next = *that;
*that = this;
*pos = safecat(name, sizeof_name, *pos, " +@");
return 1;
}
CWE ID:
Target: 1
Example 2:
Code: static int ip6_dst_lookup_tail(struct sock *sk,
struct dst_entry **dst, struct flowi6 *fl6)
{
struct net *net = sock_net(sk);
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
struct neighbour *n;
struct rt6_info *rt;
#endif
int err;
if (*dst == NULL)
*dst = ip6_route_output(net, sk, fl6);
if ((err = (*dst)->error))
goto out_err_release;
if (ipv6_addr_any(&fl6->saddr)) {
struct rt6_info *rt = (struct rt6_info *) *dst;
err = ip6_route_get_saddr(net, rt, &fl6->daddr,
sk ? inet6_sk(sk)->srcprefs : 0,
&fl6->saddr);
if (err)
goto out_err_release;
}
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
/*
* Here if the dst entry we've looked up
* has a neighbour entry that is in the INCOMPLETE
* state and the src address from the flow is
* marked as OPTIMISTIC, we release the found
* dst entry and replace it instead with the
* dst entry of the nexthop router
*/
rt = (struct rt6_info *) *dst;
rcu_read_lock_bh();
n = __ipv6_neigh_lookup_noref(rt->dst.dev, rt6_nexthop(rt, &fl6->daddr));
err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0;
rcu_read_unlock_bh();
if (err) {
struct inet6_ifaddr *ifp;
struct flowi6 fl_gw6;
int redirect;
ifp = ipv6_get_ifaddr(net, &fl6->saddr,
(*dst)->dev, 1);
redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC);
if (ifp)
in6_ifa_put(ifp);
if (redirect) {
/*
* We need to get the dst entry for the
* default router instead
*/
dst_release(*dst);
memcpy(&fl_gw6, fl6, sizeof(struct flowi6));
memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr));
*dst = ip6_route_output(net, sk, &fl_gw6);
if ((err = (*dst)->error))
goto out_err_release;
}
}
#endif
return 0;
out_err_release:
if (err == -ENETUNREACH)
IP6_INC_STATS_BH(net, NULL, IPSTATS_MIB_OUTNOROUTES);
dst_release(*dst);
*dst = NULL;
return err;
}
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: nfsd4_decode_rename(struct nfsd4_compoundargs *argp, struct nfsd4_rename *rename)
{
DECODE_HEAD;
READ_BUF(4);
rename->rn_snamelen = be32_to_cpup(p++);
READ_BUF(rename->rn_snamelen);
SAVEMEM(rename->rn_sname, rename->rn_snamelen);
READ_BUF(4);
rename->rn_tnamelen = be32_to_cpup(p++);
READ_BUF(rename->rn_tnamelen);
SAVEMEM(rename->rn_tname, rename->rn_tnamelen);
if ((status = check_filename(rename->rn_sname, rename->rn_snamelen)))
return status;
if ((status = check_filename(rename->rn_tname, rename->rn_tnamelen)))
return status;
DECODE_TAIL;
}
CWE ID: CWE-404
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: xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%') return;
switch(ctxt->instate) {
case XML_PARSER_CDATA_SECTION:
return;
case XML_PARSER_COMMENT:
return;
case XML_PARSER_START_TAG:
return;
case XML_PARSER_END_TAG:
return;
case XML_PARSER_EOF:
xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL);
return;
case XML_PARSER_PROLOG:
case XML_PARSER_START:
case XML_PARSER_MISC:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL);
return;
case XML_PARSER_ENTITY_DECL:
case XML_PARSER_CONTENT:
case XML_PARSER_ATTRIBUTE_VALUE:
case XML_PARSER_PI:
case XML_PARSER_SYSTEM_LITERAL:
case XML_PARSER_PUBLIC_LITERAL:
/* we just ignore it there */
return;
case XML_PARSER_EPILOG:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL);
return;
case XML_PARSER_ENTITY_VALUE:
/*
* NOTE: in the case of entity values, we don't do the
* substitution here since we need the literal
* entity value to be able to save the internal
* subset of the document.
* This will be handled by xmlStringDecodeEntities
*/
return;
case XML_PARSER_DTD:
/*
* [WFC: Well-Formedness Constraint: PEs in Internal Subset]
* In the internal DTD subset, parameter-entity references
* can occur only where markup declarations can occur, not
* within markup declarations.
* In that case this is handled in xmlParseMarkupDecl
*/
if ((ctxt->external == 0) && (ctxt->inputNr == 1))
return;
if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0)
return;
break;
case XML_PARSER_IGNORE:
return;
}
NEXT;
name = xmlParseName(ctxt);
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL);
} else {
if (RAW == ';') {
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) ||
(entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
* this is done independently.
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"PEReference: %s is not a parameter entity\n",
name);
}
}
} else {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void MediaRecorderHandler::Pause() {
DCHECK(main_render_thread_checker_.CalledOnValidThread());
DCHECK(recording_);
recording_ = false;
for (const auto& video_recorder : video_recorders_)
video_recorder->Pause();
for (const auto& audio_recorder : audio_recorders_)
audio_recorder->Pause();
webm_muxer_->Pause();
}
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: ikev2_ID_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
id_len = ntohs(id.h.len);
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
}
idtype_len =id_len - sizeof(struct ikev2_id);
dumpascii = 0;
dumphex = 0;
typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id);
switch(id.type) {
case ID_IPV4_ADDR:
ND_PRINT((ndo, " ipv4:"));
dumphex=1;
break;
case ID_FQDN:
ND_PRINT((ndo, " fqdn:"));
dumpascii=1;
break;
case ID_RFC822_ADDR:
ND_PRINT((ndo, " rfc822:"));
dumpascii=1;
break;
case ID_IPV6_ADDR:
ND_PRINT((ndo, " ipv6:"));
dumphex=1;
break;
case ID_DER_ASN1_DN:
ND_PRINT((ndo, " dn:"));
dumphex=1;
break;
case ID_DER_ASN1_GN:
ND_PRINT((ndo, " gn:"));
dumphex=1;
break;
case ID_KEY_ID:
ND_PRINT((ndo, " keyid:"));
dumphex=1;
break;
}
if(dumpascii) {
ND_TCHECK2(*typedata, idtype_len);
for(i=0; i<idtype_len; i++) {
if(ND_ISPRINT(typedata[i])) {
ND_PRINT((ndo, "%c", typedata[i]));
} else {
ND_PRINT((ndo, "."));
}
}
}
if(dumphex) {
if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len))
goto trunc;
}
return (const u_char *)ext + id_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
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: DownloadUrlParameters::DownloadUrlParameters(
const GURL& url,
int render_process_host_id,
int render_view_host_routing_id,
int render_frame_host_routing_id,
const net::NetworkTrafficAnnotationTag& traffic_annotation)
: content_initiated_(false),
use_if_range_(true),
method_("GET"),
post_id_(-1),
prefer_cache_(false),
referrer_policy_(
net::URLRequest::
CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
render_process_host_id_(render_process_host_id),
render_view_host_routing_id_(render_view_host_routing_id),
render_frame_host_routing_id_(render_frame_host_routing_id),
url_(url),
do_not_prompt_for_login_(false),
follow_cross_origin_redirects_(true),
fetch_error_body_(false),
transient_(false),
traffic_annotation_(traffic_annotation),
download_source_(DownloadSource::UNKNOWN) {}
CWE ID: CWE-284
Target: 1
Example 2:
Code: int acpi_os_map_generic_address(struct acpi_generic_address *gas)
{
u64 addr;
void __iomem *virt;
if (gas->space_id != ACPI_ADR_SPACE_SYSTEM_MEMORY)
return 0;
/* Handle possible alignment issues */
memcpy(&addr, &gas->address, sizeof(addr));
if (!addr || !gas->bit_width)
return -EINVAL;
virt = acpi_os_map_iomem(addr, gas->bit_width / 8);
if (!virt)
return -EIO;
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: static void construct_get_dest_keyring(struct key **_dest_keyring)
{
struct request_key_auth *rka;
const struct cred *cred = current_cred();
struct key *dest_keyring = *_dest_keyring, *authkey;
kenter("%p", dest_keyring);
/* find the appropriate keyring */
if (dest_keyring) {
/* the caller supplied one */
key_get(dest_keyring);
} else {
/* use a default keyring; falling through the cases until we
* find one that we actually have */
switch (cred->jit_keyring) {
case KEY_REQKEY_DEFL_DEFAULT:
case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
if (cred->request_key_auth) {
authkey = cred->request_key_auth;
down_read(&authkey->sem);
rka = authkey->payload.data[0];
if (!test_bit(KEY_FLAG_REVOKED,
&authkey->flags))
dest_keyring =
key_get(rka->dest_keyring);
up_read(&authkey->sem);
if (dest_keyring)
break;
}
case KEY_REQKEY_DEFL_THREAD_KEYRING:
dest_keyring = key_get(cred->thread_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_PROCESS_KEYRING:
dest_keyring = key_get(cred->process_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_SESSION_KEYRING:
rcu_read_lock();
dest_keyring = key_get(
rcu_dereference(cred->session_keyring));
rcu_read_unlock();
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
dest_keyring =
key_get(cred->user->session_keyring);
break;
case KEY_REQKEY_DEFL_USER_KEYRING:
dest_keyring = key_get(cred->user->uid_keyring);
break;
case KEY_REQKEY_DEFL_GROUP_KEYRING:
default:
BUG();
}
}
*_dest_keyring = dest_keyring;
kleave(" [dk %d]", key_serial(dest_keyring));
return;
}
CWE ID: CWE-862
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 ip_queue_xmit(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct inet_sock *inet = inet_sk(sk);
struct ip_options *opt = inet->opt;
struct rtable *rt;
struct iphdr *iph;
int res;
/* Skip all of this if the packet is already routed,
* f.e. by something like SCTP.
*/
rcu_read_lock();
rt = skb_rtable(skb);
if (rt != NULL)
goto packet_routed;
/* Make sure we can route this packet. */
rt = (struct rtable *)__sk_dst_check(sk, 0);
if (rt == NULL) {
__be32 daddr;
/* Use correct destination address if we have options. */
daddr = inet->inet_daddr;
if(opt && opt->srr)
daddr = opt->faddr;
/* If this fails, retransmit mechanism of transport layer will
* keep trying until route appears or the connection times
* itself out.
*/
rt = ip_route_output_ports(sock_net(sk), sk,
daddr, inet->inet_saddr,
inet->inet_dport,
inet->inet_sport,
sk->sk_protocol,
RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if);
if (IS_ERR(rt))
goto no_route;
sk_setup_caps(sk, &rt->dst);
}
skb_dst_set_noref(skb, &rt->dst);
packet_routed:
if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway)
goto no_route;
/* OK, we know where to send it, allocate and build IP header. */
skb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen : 0));
skb_reset_network_header(skb);
iph = ip_hdr(skb);
*((__be16 *)iph) = htons((4 << 12) | (5 << 8) | (inet->tos & 0xff));
if (ip_dont_fragment(sk, &rt->dst) && !skb->local_df)
iph->frag_off = htons(IP_DF);
else
iph->frag_off = 0;
iph->ttl = ip_select_ttl(inet, &rt->dst);
iph->protocol = sk->sk_protocol;
iph->saddr = rt->rt_src;
iph->daddr = rt->rt_dst;
/* Transport layer set skb->h.foo itself. */
if (opt && opt->optlen) {
iph->ihl += opt->optlen >> 2;
ip_options_build(skb, opt, inet->inet_daddr, rt, 0);
}
ip_select_ident_more(iph, &rt->dst, sk,
(skb_shinfo(skb)->gso_segs ?: 1) - 1);
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
res = ip_local_out(skb);
rcu_read_unlock();
return res;
no_route:
rcu_read_unlock();
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
return -EHOSTUNREACH;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: bool has_composition_text() const {
return tab_view()->has_composition_text_;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,
rpmpsm psm, char ** failedFile)
{
FD_t payload = rpmtePayload(te);
rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE);
rpmfs fs = rpmteGetFileStates(te);
rpmPlugins plugins = rpmtsPlugins(ts);
struct stat sb;
int saveerrno = errno;
int rc = 0;
int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0;
int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0;
int firsthardlink = -1;
int skip;
rpmFileAction action;
char *tid = NULL;
const char *suffix;
char *fpath = NULL;
if (fi == NULL) {
rc = RPMERR_BAD_MAGIC;
goto exit;
}
/* transaction id used for temporary path suffix while installing */
rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts));
/* Detect and create directories not explicitly in package. */
rc = fsmMkdirs(files, fs, plugins);
while (!rc) {
/* Read next payload header. */
rc = rpmfiNext(fi);
if (rc < 0) {
if (rc == RPMERR_ITER_END)
rc = 0;
break;
}
action = rpmfsGetAction(fs, rpmfiFX(fi));
skip = XFA_SKIPPING(action);
suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid;
if (action != FA_TOUCH) {
fpath = fsmFsPath(fi, suffix);
} else {
fpath = fsmFsPath(fi, "");
}
/* Remap file perms, owner, and group. */
rc = rpmfiStat(fi, 1, &sb);
fsmDebug(fpath, action, &sb);
/* Exit on error. */
if (rc)
break;
/* Run fsm file pre hook for all plugins */
rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath,
sb.st_mode, action);
if (rc) {
skip = 1;
} else {
setFileState(fs, rpmfiFX(fi));
}
if (!skip) {
int setmeta = 1;
/* Directories replacing something need early backup */
if (!suffix) {
rc = fsmBackup(fi, action);
}
/* Assume file does't exist when tmp suffix is in use */
if (!suffix) {
rc = fsmVerify(fpath, fi);
} else {
rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT;
}
if (S_ISREG(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmMkfile(fi, fpath, files, psm, nodigest,
&setmeta, &firsthardlink);
}
} else if (S_ISDIR(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
mode_t mode = sb.st_mode;
mode &= ~07777;
mode |= 00700;
rc = fsmMkdir(fpath, mode);
}
} else if (S_ISLNK(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmSymlink(rpmfiFLink(fi), fpath);
}
} else if (S_ISFIFO(sb.st_mode)) {
/* This mimics cpio S_ISSOCK() behavior but probably isn't right */
if (rc == RPMERR_ENOENT) {
rc = fsmMkfifo(fpath, 0000);
}
} else if (S_ISCHR(sb.st_mode) ||
S_ISBLK(sb.st_mode) ||
S_ISSOCK(sb.st_mode))
{
if (rc == RPMERR_ENOENT) {
rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev);
}
} else {
/* XXX Special case /dev/log, which shouldn't be packaged anyways */
if (!IS_DEV_LOG(fpath))
rc = RPMERR_UNKNOWN_FILETYPE;
}
/* Set permissions, timestamps etc for non-hardlink entries */
if (!rc && setmeta) {
rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps);
}
} else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) {
/* we skip the hard linked file containing the content */
/* write the content to the first used instead */
char *fn = rpmfilesFN(files, firsthardlink);
rc = expandRegular(fi, fn, psm, 0, nodigest, 0);
firsthardlink = -1;
free(fn);
}
if (rc) {
if (!skip) {
/* XXX only erase if temp fn w suffix is in use */
if (suffix && (action != FA_TOUCH)) {
(void) fsmRemove(fpath, sb.st_mode);
}
errno = saveerrno;
}
} else {
/* Notify on success. */
rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi));
if (!skip) {
/* Backup file if needed. Directories are handled earlier */
if (suffix)
rc = fsmBackup(fi, action);
if (!rc)
rc = fsmCommit(&fpath, fi, action, suffix);
}
}
if (rc)
*failedFile = xstrdup(fpath);
/* Run fsm file post hook for all plugins */
rpmpluginsCallFsmFilePost(plugins, fi, fpath,
sb.st_mode, action, rc);
fpath = _free(fpath);
}
rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ));
rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST));
exit:
/* No need to bother with close errors on read */
rpmfiArchiveClose(fi);
rpmfiFree(fi);
Fclose(payload);
free(tid);
free(fpath);
return rc;
}
CWE ID: CWE-59
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void frag_kfree_skb(struct netns_frags *nf, struct sk_buff *skb)
{
atomic_sub(skb->truesize, &nf->mem);
kfree_skb(skb);
}
CWE ID:
Target: 1
Example 2:
Code: static inline bool arch_syscall_match_sym_name(const char *sym, const char *name)
{
/*
* Only compare after the "sys" prefix. Archs that use
* syscall wrappers may have syscalls symbols aliases prefixed
* with ".SyS" or ".sys" instead of "sys", leading to an unwanted
* mismatch.
*/
return !strcmp(sym + 3, name + 3);
}
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: ofputil_pull_ofp15_buckets(struct ofpbuf *msg, size_t buckets_length,
enum ofp_version version, uint8_t group_type,
struct ovs_list *buckets)
{
struct ofp15_bucket *ob;
ovs_list_init(buckets);
while (buckets_length > 0) {
struct ofputil_bucket *bucket = NULL;
struct ofpbuf ofpacts;
enum ofperr err = OFPERR_OFPGMFC_BAD_BUCKET;
size_t ob_len, actions_len, properties_len;
ovs_be32 watch_port = ofputil_port_to_ofp11(OFPP_ANY);
ovs_be32 watch_group = htonl(OFPG_ANY);
ovs_be16 weight = htons(group_type == OFPGT11_SELECT ? 1 : 0);
ofpbuf_init(&ofpacts, 0);
ob = ofpbuf_try_pull(msg, sizeof *ob);
if (!ob) {
VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %"PRIuSIZE
" leftover bytes", buckets_length);
goto err;
}
ob_len = ntohs(ob->len);
actions_len = ntohs(ob->action_array_len);
if (ob_len < sizeof *ob) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
"%"PRIuSIZE" is not valid", ob_len);
goto err;
} else if (ob_len > buckets_length) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
"%"PRIuSIZE" exceeds remaining buckets data size %"
PRIuSIZE, ob_len, buckets_length);
goto err;
} else if (actions_len > ob_len - sizeof *ob) {
VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket actions "
"length %"PRIuSIZE" exceeds remaining bucket "
"data size %"PRIuSIZE, actions_len,
ob_len - sizeof *ob);
goto err;
}
buckets_length -= ob_len;
err = ofpacts_pull_openflow_actions(msg, actions_len, version,
NULL, NULL, &ofpacts);
if (err) {
goto err;
}
properties_len = ob_len - sizeof *ob - actions_len;
struct ofpbuf properties = ofpbuf_const_initializer(
ofpbuf_pull(msg, properties_len), properties_len);
while (properties.size > 0) {
struct ofpbuf payload;
uint64_t type;
err = ofpprop_pull(&properties, &payload, &type);
if (err) {
goto err;
}
switch (type) {
case OFPGBPT15_WEIGHT:
err = ofpprop_parse_be16(&payload, &weight);
break;
case OFPGBPT15_WATCH_PORT:
err = ofpprop_parse_be32(&payload, &watch_port);
break;
case OFPGBPT15_WATCH_GROUP:
err = ofpprop_parse_be32(&payload, &watch_group);
break;
default:
err = OFPPROP_UNKNOWN(false, "group bucket", type);
break;
}
if (err) {
goto err;
}
}
bucket = xzalloc(sizeof *bucket);
bucket->weight = ntohs(weight);
err = ofputil_port_from_ofp11(watch_port, &bucket->watch_port);
if (err) {
err = OFPERR_OFPGMFC_BAD_WATCH;
goto err;
}
bucket->watch_group = ntohl(watch_group);
bucket->bucket_id = ntohl(ob->bucket_id);
if (bucket->bucket_id > OFPG15_BUCKET_MAX) {
VLOG_WARN_RL(&bad_ofmsg_rl, "bucket id (%u) is out of range",
bucket->bucket_id);
err = OFPERR_OFPGMFC_BAD_BUCKET;
goto err;
}
bucket->ofpacts = ofpbuf_steal_data(&ofpacts);
bucket->ofpacts_len = ofpacts.size;
ovs_list_push_back(buckets, &bucket->list_node);
continue;
err:
free(bucket);
ofpbuf_uninit(&ofpacts);
ofputil_bucket_list_destroy(buckets);
return err;
}
if (ofputil_bucket_check_duplicate_id(buckets)) {
VLOG_WARN_RL(&bad_ofmsg_rl, "Duplicate bucket id");
ofputil_bucket_list_destroy(buckets);
return OFPERR_OFPGMFC_BAD_BUCKET;
}
return 0;
}
CWE ID: CWE-617
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PlatformSensor::GetLatestReading(SensorReading* result) {
if (!shared_buffer_reader_) {
const auto* buffer = static_cast<const device::SensorReadingSharedBuffer*>(
shared_buffer_mapping_.get());
shared_buffer_reader_ =
std::make_unique<SensorReadingSharedBufferReader>(buffer);
}
return shared_buffer_reader_->GetReading(result);
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: void S_AL_MusicProcess(ALuint b)
{
ALenum error;
int l;
ALuint format;
snd_stream_t *curstream;
S_AL_ClearError( qfalse );
if(intro_stream)
curstream = intro_stream;
else
curstream = mus_stream;
if(!curstream)
return;
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
if(l == 0)
{
S_CodecCloseStream(curstream);
if(intro_stream)
intro_stream = NULL;
else
mus_stream = S_CodecOpenStream(s_backgroundLoop);
curstream = mus_stream;
if(!curstream)
{
S_AL_StopBackgroundTrack();
return;
}
l = S_CodecReadStream(curstream, MUSIC_BUFFER_SIZE, decode_buffer);
}
format = S_AL_Format(curstream->info.width, curstream->info.channels);
if( l == 0 )
{
byte dummyData[ 2 ] = { 0 };
qalBufferData( b, AL_FORMAT_MONO16, (void *)dummyData, 2, 22050 );
}
else
qalBufferData(b, format, decode_buffer, l, curstream->info.rate);
if( ( error = qalGetError( ) ) != AL_NO_ERROR )
{
S_AL_StopBackgroundTrack( );
Com_Printf( S_COLOR_RED "ERROR: while buffering data for music stream - %s\n",
S_AL_ErrorMsg( error ) );
return;
}
}
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: SYSCALL_DEFINE1(setfsuid, uid_t, uid)
{
const struct cred *old;
struct cred *new;
uid_t old_fsuid;
kuid_t kuid;
old = current_cred();
old_fsuid = from_kuid_munged(old->user_ns, old->fsuid);
kuid = make_kuid(old->user_ns, uid);
if (!uid_valid(kuid))
return old_fsuid;
new = prepare_creds();
if (!new)
return old_fsuid;
if (uid_eq(kuid, old->uid) || uid_eq(kuid, old->euid) ||
uid_eq(kuid, old->suid) || uid_eq(kuid, old->fsuid) ||
nsown_capable(CAP_SETUID)) {
if (!uid_eq(kuid, old->fsuid)) {
new->fsuid = kuid;
if (security_task_fix_setuid(new, old, LSM_SETID_FS) == 0)
goto change_okay;
}
}
abort_creds(new);
return old_fsuid;
change_okay:
commit_creds(new);
return old_fsuid;
}
CWE ID: CWE-16
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: u32 h264bsdInit(storage_t *pStorage, u32 noOutputReordering)
{
/* Variables */
u32 size;
/* Code */
ASSERT(pStorage);
h264bsdInitStorage(pStorage);
/* allocate mbLayer to be next multiple of 64 to enable use of
* specific NEON optimized "memset" for clearing the structure */
size = (sizeof(macroblockLayer_t) + 63) & ~0x3F;
pStorage->mbLayer = (macroblockLayer_t*)H264SwDecMalloc(size);
if (!pStorage->mbLayer)
return HANTRO_NOK;
if (noOutputReordering)
pStorage->noReordering = HANTRO_TRUE;
return HANTRO_OK;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void __ip_do_redirect(struct rtable *rt, struct sk_buff *skb, struct flowi4 *fl4,
bool kill_route)
{
__be32 new_gw = icmp_hdr(skb)->un.gateway;
__be32 old_gw = ip_hdr(skb)->saddr;
struct net_device *dev = skb->dev;
struct in_device *in_dev;
struct fib_result res;
struct neighbour *n;
struct net *net;
switch (icmp_hdr(skb)->code & 7) {
case ICMP_REDIR_NET:
case ICMP_REDIR_NETTOS:
case ICMP_REDIR_HOST:
case ICMP_REDIR_HOSTTOS:
break;
default:
return;
}
if (rt->rt_gateway != old_gw)
return;
in_dev = __in_dev_get_rcu(dev);
if (!in_dev)
return;
net = dev_net(dev);
if (new_gw == old_gw || !IN_DEV_RX_REDIRECTS(in_dev) ||
ipv4_is_multicast(new_gw) || ipv4_is_lbcast(new_gw) ||
ipv4_is_zeronet(new_gw))
goto reject_redirect;
if (!IN_DEV_SHARED_MEDIA(in_dev)) {
if (!inet_addr_onlink(in_dev, new_gw, old_gw))
goto reject_redirect;
if (IN_DEV_SEC_REDIRECTS(in_dev) && ip_fib_check_default(new_gw, dev))
goto reject_redirect;
} else {
if (inet_addr_type(net, new_gw) != RTN_UNICAST)
goto reject_redirect;
}
n = __ipv4_neigh_lookup(rt->dst.dev, new_gw);
if (!n)
n = neigh_create(&arp_tbl, &new_gw, rt->dst.dev);
if (!IS_ERR(n)) {
if (!(n->nud_state & NUD_VALID)) {
neigh_event_send(n, NULL);
} else {
if (fib_lookup(net, fl4, &res, 0) == 0) {
struct fib_nh *nh = &FIB_RES_NH(res);
update_or_create_fnhe(nh, fl4->daddr, new_gw,
0, jiffies + ip_rt_gc_timeout);
}
if (kill_route)
rt->dst.obsolete = DST_OBSOLETE_KILL;
call_netevent_notifiers(NETEVENT_NEIGH_UPDATE, n);
}
neigh_release(n);
}
return;
reject_redirect:
#ifdef CONFIG_IP_ROUTE_VERBOSE
if (IN_DEV_LOG_MARTIANS(in_dev)) {
const struct iphdr *iph = (const struct iphdr *) skb->data;
__be32 daddr = iph->daddr;
__be32 saddr = iph->saddr;
net_info_ratelimited("Redirect from %pI4 on %s about %pI4 ignored\n"
" Advised path = %pI4 -> %pI4\n",
&old_gw, dev->name, &new_gw,
&saddr, &daddr);
}
#endif
;
}
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: rm_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) {
char * name = NULL;
int rtnVal = FALSE;
int rc;
bool found_cred;
CredentialWrapper * cred_wrapper = NULL;
char * owner = NULL;
const char * user;
ReliSock * socket = (ReliSock*)stream;
if (!socket->triedAuthentication()) {
CondorError errstack;
if( ! SecMan::authenticate_sock(socket, READ, &errstack) ) {
dprintf (D_ALWAYS, "Unable to authenticate, qutting\n");
goto EXIT;
}
}
socket->decode();
if (!socket->code(name)) {
dprintf (D_ALWAYS, "Error receiving credential name\n");
goto EXIT;
}
user = socket->getFullyQualifiedUser();
dprintf (D_ALWAYS, "Authenticated as %s\n", user);
if (strchr (name, ':')) {
owner = strdup (name);
char * pColon = strchr (owner, ':');
*pColon = '\0';
sprintf (name, (char*)(pColon+sizeof(char)));
if (strcmp (owner, user) != 0) {
dprintf (D_ALWAYS, "Requesting another user's (%s) credential %s\n", owner, name);
if (!isSuperUser (user)) {
dprintf (D_ALWAYS, "User %s is NOT super user, request DENIED\n", user);
goto EXIT;
} else {
dprintf (D_FULLDEBUG, "User %s is super user, request GRANTED\n", user);
}
}
} else {
owner = strdup (user);
}
dprintf (D_ALWAYS, "Attempting to delete cred %s for user %s\n", name, owner);
found_cred=false;
credentials.Rewind();
while (credentials.Next(cred_wrapper)) {
if (cred_wrapper->cred->GetType() == X509_CREDENTIAL_TYPE) {
if ((strcmp(cred_wrapper->cred->GetName(), name) == 0) &&
(strcmp(cred_wrapper->cred->GetOwner(), owner) == 0)) {
credentials.DeleteCurrent();
found_cred=true;
break; // found it
}
}
}
if (found_cred) {
priv_state priv = set_root_priv();
unlink (cred_wrapper->GetStorageName());
SaveCredentialList();
set_priv(priv);
delete cred_wrapper;
dprintf (D_ALWAYS, "Removed credential %s for owner %s\n", name, owner);
} else {
dprintf (D_ALWAYS, "Unable to remove credential %s:%s (not found)\n", owner, name);
}
free (owner);
socket->encode();
rc = (found_cred)?CREDD_SUCCESS:CREDD_CREDENTIAL_NOT_FOUND;
socket->code(rc);
rtnVal = TRUE;
EXIT:
if (name != NULL) {
free (name);
}
return rtnVal;
}
CWE ID: CWE-134
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 dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh,
u32 seq, struct nlattr **tb, struct sk_buff *skb)
{
u8 perm_addr[MAX_ADDR_LEN];
if (!netdev->dcbnl_ops->getpermhwaddr)
return -EOPNOTSUPP;
netdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr);
return nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: dissect_pch_channel_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
int offset, struct fp_info *p_fp_info, void *data)
{
gboolean is_control_frame;
guint16 pch_cfn;
gboolean paging_indication;
guint16 header_crc = 0;
proto_item * header_crc_pi = NULL;
/* Header CRC */
header_crc = tvb_get_bits8(tvb, 0, 7);
header_crc_pi = proto_tree_add_item(tree, hf_fp_header_crc, tvb, offset, 1, ENC_BIG_ENDIAN);
/* Frame Type */
is_control_frame = tvb_get_guint8(tvb, offset) & 0x01;
proto_tree_add_item(tree, hf_fp_ft, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
col_append_str(pinfo->cinfo, COL_INFO, is_control_frame ? " [Control] " : " [Data] ");
if (is_control_frame) {
dissect_common_control(tvb, pinfo, tree, offset, p_fp_info);
/* For control frame the header CRC is actually frame CRC covering all
* bytes except the first */
if (preferences_header_checksum) {
verify_control_frame_crc(tvb, pinfo, header_crc_pi, header_crc);
}
}
else {
guint header_length = 0;
/* DATA */
/* 12-bit CFN value */
proto_tree_add_item(tree, hf_fp_pch_cfn, tvb, offset, 2, ENC_BIG_ENDIAN);
pch_cfn = (tvb_get_ntohs(tvb, offset) & 0xfff0) >> 4;
offset++;
col_append_fstr(pinfo->cinfo, COL_INFO, "CFN=%04u ", pch_cfn);
/* Paging indication */
proto_tree_add_item(tree, hf_fp_pch_pi, tvb, offset, 1, ENC_BIG_ENDIAN);
paging_indication = tvb_get_guint8(tvb, offset) & 0x01;
offset++;
/* 5-bit TFI */
proto_tree_add_item(tree, hf_fp_pch_tfi, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
header_length = offset;
/* Optional paging indications */
if (paging_indication) {
proto_item *ti;
ti = proto_tree_add_item(tree, hf_fp_paging_indication_bitmap, tvb,
offset,
(p_fp_info->paging_indications+7) / 8,
ENC_NA);
proto_item_append_text(ti, " (%u bits)", p_fp_info->paging_indications);
offset += ((p_fp_info->paging_indications+7) / 8);
}
/* TB data */
offset = dissect_tb_data(tvb, pinfo, tree, offset, p_fp_info, &mac_fdd_pch_handle, data);
if (preferences_header_checksum) {
verify_header_crc(tvb, pinfo, header_crc_pi, header_crc, header_length);
}
/* Spare Extension and Payload CRC */
dissect_spare_extension_and_crc(tvb, pinfo, tree, 1, offset, header_length);
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashColorMode srcMode;
SplashImageSource src;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = maskColors;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
break;
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
src = maskColors ? &alphaImageSrc : &imageSrc;
splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse,
width, height, mat);
if (inlineImg) {
while (imgData.y < height) {
imgData.imgStr->getLine();
++imgData.y;
}
}
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void rng_backend_request_entropy(RngBackend *s, size_t size,
EntropyReceiveFunc *receive_entropy,
void *opaque)
{
RngBackendClass *k = RNG_BACKEND_GET_CLASS(s);
if (k->request_entropy) {
k->request_entropy(s, size, receive_entropy, opaque);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: eval_acl(uschar ** sub, int nsub, uschar ** user_msgp)
{
int i;
uschar *tmp;
int sav_narg = acl_narg;
int ret;
extern int acl_where;
if(--nsub > sizeof(acl_arg)/sizeof(*acl_arg)) nsub = sizeof(acl_arg)/sizeof(*acl_arg);
for (i = 0; i < nsub && sub[i+1]; i++)
{
tmp = acl_arg[i];
acl_arg[i] = sub[i+1]; /* place callers args in the globals */
sub[i+1] = tmp; /* stash the old args using our caller's storage */
}
acl_narg = i;
while (i < nsub)
{
sub[i+1] = acl_arg[i];
acl_arg[i++] = NULL;
}
DEBUG(D_expand)
debug_printf("expanding: acl: %s arg: %s%s\n",
sub[0],
acl_narg>0 ? acl_arg[0] : US"<none>",
acl_narg>1 ? " +more" : "");
ret = acl_eval(acl_where, sub[0], user_msgp, &tmp);
for (i = 0; i < nsub; i++)
acl_arg[i] = sub[i+1]; /* restore old args */
acl_narg = sav_narg;
return ret;
}
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 HarfBuzzShaper::setExpansion(float padding)
{
m_expansion = padding;
if (!m_expansion)
return;
bool isAfterExpansion = m_isAfterExpansion;
m_expansionOpportunityCount = Character::expansionOpportunityCount(m_normalizedBuffer.get(), m_normalizedBufferLength, m_run.direction(), isAfterExpansion, m_run.textJustify());
if (isAfterExpansion && !m_run.allowsTrailingExpansion()) {
ASSERT(m_expansionOpportunityCount > 0);
--m_expansionOpportunityCount;
}
if (m_expansionOpportunityCount)
m_expansionPerOpportunity = m_expansion / m_expansionOpportunityCount;
else
m_expansionPerOpportunity = 0;
}
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 PlatformSensorProviderLinux::CreateSensorAndNotify(
mojom::SensorType type,
SensorInfoLinux* sensor_device) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
scoped_refptr<PlatformSensorLinux> sensor;
mojo::ScopedSharedBufferMapping mapping = MapSharedBufferForType(type);
if (sensor_device && mapping && StartPollingThread()) {
sensor =
new PlatformSensorLinux(type, std::move(mapping), this, sensor_device,
polling_thread_->task_runner());
}
NotifySensorCreated(type, sensor);
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: void Document::ParseDNSPrefetchControlHeader(
const String& dns_prefetch_control) {
if (DeprecatedEqualIgnoringCase(dns_prefetch_control, "on") &&
!have_explicitly_disabled_dns_prefetch_) {
is_dns_prefetch_enabled_ = true;
return;
}
is_dns_prefetch_enabled_ = false;
have_explicitly_disabled_dns_prefetch_ = true;
}
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: php_apache_sapi_header_handler(sapi_header_struct *sapi_header, sapi_header_op_enum op, sapi_headers_struct *sapi_headers TSRMLS_DC)
{
php_struct *ctx;
char *val, *ptr;
ctx = SG(server_context);
switch (op) {
case SAPI_HEADER_DELETE:
apr_table_unset(ctx->r->headers_out, sapi_header->header);
return 0;
case SAPI_HEADER_DELETE_ALL:
apr_table_clear(ctx->r->headers_out);
return 0;
case SAPI_HEADER_ADD:
case SAPI_HEADER_REPLACE:
val = strchr(sapi_header->header, ':');
if (!val) {
return 0;
}
ptr = val;
*val = '\0';
do {
val++;
} while (*val == ' ');
if (!strcasecmp(sapi_header->header, "content-type")) {
if (ctx->content_type) {
efree(ctx->content_type);
}
ctx->content_type = estrdup(val);
} else if (!strcasecmp(sapi_header->header, "content-length")) {
apr_off_t clen = 0;
if (APR_SUCCESS != apr_strtoff(&clen, val, (char **) NULL, 10)) {
/* We'll fall back to strtol, since that's what we used to
* do anyway. */
clen = (apr_off_t) strtol(val, (char **) NULL, 10);
}
ap_set_content_length(ctx->r, clen);
} else if (op == SAPI_HEADER_REPLACE) {
apr_table_set(ctx->r->headers_out, sapi_header->header, val);
} else {
apr_table_add(ctx->r->headers_out, sapi_header->header, val);
}
*ptr = ':';
return SAPI_HEADER_ADD;
default:
return 0;
}
}
CWE ID: CWE-79
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: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain)
{
int r;
size_t len = 0;
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
LOG_FUNC_CALLED(card->ctx);
r = sc_check_sw(card, sm->sw1, sm->sw2);
if (r == SC_SUCCESS) {
if (exdata->sm) {
if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len))
return SC_ERROR_CARD_CMD_FAILED;
}
else {
memcpy(plain->resp, sm->resp, sm->resplen);
len = sm->resplen;
}
}
plain->resplen = len;
plain->sw1 = sm->sw1;
plain->sw2 = sm->sw2;
sc_log(card->ctx,
"unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X",
plain->resplen, plain->sw1, plain->sw2);
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: ftrace_notrace_open(struct inode *inode, struct file *file)
{
return ftrace_regex_open(&global_ops, FTRACE_ITER_NOTRACE,
inode, file);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool IsNewRemotePlaybackPipelineEnabled() {
return base::FeatureList::IsEnabled(kNewRemotePlaybackPipeline);
}
CWE ID: CWE-732
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: sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo)
{
Sg_request *srp;
int val;
unsigned int ms;
val = 0;
list_for_each_entry(srp, &sfp->rq_list, entry) {
if (val > SG_MAX_QUEUE)
break;
memset(&rinfo[val], 0, SZ_SG_REQ_INFO);
rinfo[val].req_state = srp->done + 1;
rinfo[val].problem =
srp->header.masked_status &
srp->header.host_status &
srp->header.driver_status;
if (srp->done)
rinfo[val].duration =
srp->header.duration;
else {
ms = jiffies_to_msecs(jiffies);
rinfo[val].duration =
(ms > srp->header.duration) ?
(ms - srp->header.duration) : 0;
}
rinfo[val].orphan = srp->orphan;
rinfo[val].sg_io_owned = srp->sg_io_owned;
rinfo[val].pack_id = srp->header.pack_id;
rinfo[val].usr_ptr = srp->header.usr_ptr;
val++;
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static Pgno btreePagecount(BtShared *pBt){
return pBt->nPage;
}
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 HB_Error Load_MarkLigPos( HB_GPOS_SubTable* st,
HB_Stream stream )
{
HB_Error error;
HB_MarkLigPos* mlp = &st->marklig;
HB_UInt cur_offset, new_offset, base_offset;
base_offset = FILE_Pos();
if ( ACCESS_Frame( 4L ) )
return error;
mlp->PosFormat = GET_UShort();
new_offset = GET_UShort() + base_offset;
FORGET_Frame();
cur_offset = FILE_Pos();
if ( FILE_Seek( new_offset ) ||
( error = _HB_OPEN_Load_Coverage( &mlp->MarkCoverage, stream ) ) != HB_Err_Ok )
return error;
(void)FILE_Seek( cur_offset );
if ( ACCESS_Frame( 2L ) )
goto Fail3;
new_offset = GET_UShort() + base_offset;
FORGET_Frame();
cur_offset = FILE_Pos();
if ( FILE_Seek( new_offset ) ||
( error = _HB_OPEN_Load_Coverage( &mlp->LigatureCoverage,
stream ) ) != HB_Err_Ok )
goto Fail3;
(void)FILE_Seek( cur_offset );
if ( ACCESS_Frame( 4L ) )
goto Fail2;
mlp->ClassCount = GET_UShort();
new_offset = GET_UShort() + base_offset;
FORGET_Frame();
cur_offset = FILE_Pos();
if ( FILE_Seek( new_offset ) ||
( error = Load_MarkArray( &mlp->MarkArray, stream ) ) != HB_Err_Ok )
goto Fail2;
(void)FILE_Seek( cur_offset );
if ( ACCESS_Frame( 2L ) )
goto Fail1;
new_offset = GET_UShort() + base_offset;
FORGET_Frame();
cur_offset = FILE_Pos();
if ( FILE_Seek( new_offset ) ||
( error = Load_LigatureArray( &mlp->LigatureArray, mlp->ClassCount,
stream ) ) != HB_Err_Ok )
goto Fail1;
return HB_Err_Ok;
Fail1:
Free_MarkArray( &mlp->MarkArray );
Fail2:
_HB_OPEN_Free_Coverage( &mlp->LigatureCoverage );
Fail3:
_HB_OPEN_Free_Coverage( &mlp->MarkCoverage );
return error;
}
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 struct dst_entry *ip6_sk_dst_check(struct sock *sk,
struct dst_entry *dst,
const struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct rt6_info *rt = (struct rt6_info *)dst;
if (!dst)
goto out;
/* Yes, checking route validity in not connected
* case is not very simple. Take into account,
* that we do not support routing by source, TOS,
* and MSG_DONTROUTE --ANK (980726)
*
* 1. ip6_rt_check(): If route was host route,
* check that cached destination is current.
* If it is network route, we still may
* check its validity using saved pointer
* to the last used address: daddr_cache.
* We do not want to save whole address now,
* (because main consumer of this service
* is tcp, which has not this problem),
* so that the last trick works only on connected
* sockets.
* 2. oif also should be the same.
*/
if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
#ifdef CONFIG_IPV6_SUBTREES
ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
#endif
(fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) {
dst_release(dst);
dst = NULL;
}
out:
return dst;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int decode_delegation(struct xdr_stream *xdr, struct nfs_openres *res)
{
__be32 *p;
uint32_t delegation_type;
int status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
delegation_type = be32_to_cpup(p);
if (delegation_type == NFS4_OPEN_DELEGATE_NONE) {
res->delegation_type = 0;
return 0;
}
status = decode_stateid(xdr, &res->delegation);
if (unlikely(status))
return status;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
res->do_recall = be32_to_cpup(p);
switch (delegation_type) {
case NFS4_OPEN_DELEGATE_READ:
res->delegation_type = FMODE_READ;
break;
case NFS4_OPEN_DELEGATE_WRITE:
res->delegation_type = FMODE_WRITE|FMODE_READ;
if (decode_space_limit(xdr, &res->maxsize) < 0)
return -EIO;
}
return decode_ace(xdr, NULL, res->server->nfs_client);
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
}
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: GF_Err saio_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleAuxiliaryInfoOffsetBox", trace);
fprintf(trace, "entry_count=\"%d\"", ptr->entry_count);
if (ptr->flags & 1) {
if (isalnum(ptr->aux_info_type>>24)) {
fprintf(trace, " aux_info_type=\"%s\" aux_info_type_parameter=\"%d\"", gf_4cc_to_str(ptr->aux_info_type), ptr->aux_info_type_parameter);
} else {
fprintf(trace, " aux_info_type=\"%d\" aux_info_type_parameter=\"%d\"", ptr->aux_info_type, ptr->aux_info_type_parameter);
}
}
fprintf(trace, ">\n");
if (ptr->version==0) {
for (i=0; i<ptr->entry_count; i++) {
fprintf(trace, "<SAIChunkOffset offset=\"%d\"/>\n", ptr->offsets[i]);
}
} else {
for (i=0; i<ptr->entry_count; i++) {
fprintf(trace, "<SAIChunkOffset offset=\""LLD"\"/>\n", ptr->offsets_large[i]);
}
}
if (!ptr->size) {
fprintf(trace, "<SAIChunkOffset offset=\"\"/>\n");
}
gf_isom_box_dump_done("SampleAuxiliaryInfoOffsetBox", a, trace);
return GF_OK;
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct sock *sk = sock->sk;
struct tcp_splice_state tss = {
.pipe = pipe,
.len = len,
.flags = flags,
};
long timeo;
ssize_t spliced;
int ret;
sock_rps_record_flow(sk);
/*
* We can't seek on a socket input
*/
if (unlikely(*ppos))
return -ESPIPE;
ret = spliced = 0;
lock_sock(sk);
timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
while (tss.len) {
ret = __tcp_splice_read(sk, &tss);
if (ret < 0)
break;
else if (!ret) {
if (spliced)
break;
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
ret = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_state == TCP_CLOSE) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
if (!sock_flag(sk, SOCK_DONE))
ret = -ENOTCONN;
break;
}
if (!timeo) {
ret = -EAGAIN;
break;
}
sk_wait_data(sk, &timeo, NULL);
if (signal_pending(current)) {
ret = sock_intr_errno(timeo);
break;
}
continue;
}
tss.len -= ret;
spliced += ret;
if (!timeo)
break;
release_sock(sk);
lock_sock(sk);
if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current))
break;
}
release_sock(sk);
if (spliced)
return spliced;
return ret;
}
CWE ID: CWE-835
Target: 1
Example 2:
Code: static void tracked_request_end(BdrvTrackedRequest *req)
{
if (req->serialising) {
req->bs->serialising_in_flight--;
}
QLIST_REMOVE(req, list);
qemu_co_queue_restart_all(&req->wait_queue);
}
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 OomInterventionImpl::StartDetection(
mojom::blink::OomInterventionHostPtr host,
mojom::blink::DetectionArgsPtr detection_args,
bool renderer_pause_enabled,
bool navigate_ads_enabled) {
host_ = std::move(host);
if (CrashMemoryMetricsReporterImpl::Instance().ResetFileDiscriptors())
return;
detection_args_ = std::move(detection_args);
renderer_pause_enabled_ = renderer_pause_enabled;
navigate_ads_enabled_ = navigate_ads_enabled;
timer_.Start(TimeDelta(), TimeDelta::FromSeconds(1), FROM_HERE);
}
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 ServiceWorkerContainer::registerServiceWorkerImpl(ExecutionContext* executionContext, const KURL& rawScriptURL, const KURL& scope, PassOwnPtr<RegistrationCallbacks> callbacks)
{
if (!m_provider) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeState, "Failed to register a ServiceWorker: The document is in an invalid state."));
return;
}
RefPtr<SecurityOrigin> documentOrigin = executionContext->getSecurityOrigin();
String errorMessage;
if (!executionContext->isSecureContext(errorMessage)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, errorMessage));
return;
}
KURL pageURL = KURL(KURL(), documentOrigin->toString());
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(pageURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the current origin ('" + documentOrigin->toString() + "') is not supported.")));
return;
}
KURL scriptURL = rawScriptURL;
scriptURL.removeFragmentIdentifier();
if (!documentOrigin->canRequest(scriptURL)) {
RefPtr<SecurityOrigin> scriptOrigin = SecurityOrigin::create(scriptURL);
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scriptURL ('" + scriptOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "').")));
return;
}
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(scriptURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the script ('" + scriptURL.getString() + "') is not supported.")));
return;
}
KURL patternURL = scope;
patternURL.removeFragmentIdentifier();
if (!documentOrigin->canRequest(patternURL)) {
RefPtr<SecurityOrigin> patternOrigin = SecurityOrigin::create(patternURL);
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scope ('" + patternOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "').")));
return;
}
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(patternURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the scope ('" + patternURL.getString() + "') is not supported.")));
return;
}
WebString webErrorMessage;
if (!m_provider->validateScopeAndScriptURL(patternURL, scriptURL, &webErrorMessage)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeType, WebString::fromUTF8("Failed to register a ServiceWorker: " + webErrorMessage.utf8())));
return;
}
m_provider->registerServiceWorker(patternURL, scriptURL, callbacks.leakPtr());
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: void V8TestObject::DoubleOrStringAttributeAttributeSetterCallback(
const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_doubleOrStringAttribute_Setter");
v8::Local<v8::Value> v8_value = info[0];
test_object_v8_internal::DoubleOrStringAttributeAttributeSetter(v8_value, info);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void QQuickWebViewPrivate::_q_onOpenPanelFinished(int result)
{
if (result == QDialog::Rejected)
WKOpenPanelResultListenerCancel(openPanelResultListener);
fileDialog->deleteLater();
fileDialog = 0;
}
CWE ID: CWE-189
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, many);
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: bool omx_vdec::allocate_input_done(void)
{
bool bRet = false;
unsigned i=0;
if (m_inp_mem_ptr == NULL) {
return bRet;
}
if (m_inp_mem_ptr ) {
for (; i<drv_ctx.ip_buf.actualcount; i++) {
if (BITMASK_ABSENT(&m_inp_bm_count,i)) {
break;
}
}
}
if (i == drv_ctx.ip_buf.actualcount) {
bRet = true;
DEBUG_PRINT_HIGH("Allocate done for all i/p buffers");
}
if (i==drv_ctx.ip_buf.actualcount && m_inp_bEnabled) {
m_inp_bPopulated = OMX_TRUE;
}
return bRet;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) {
if (!(gpu_enabled_ &&
GpuDataManagerImpl::GetInstance()->ShouldUseSoftwareRendering()) &&
!hardware_gpu_enabled_) {
SendOutstandingReplies();
return false;
}
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
CommandLine::StringType gpu_launcher =
browser_command_line.GetSwitchValueNative(switches::kGpuLauncher);
#if defined(OS_LINUX)
int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF :
ChildProcessHost::CHILD_NORMAL;
#else
int child_flags = ChildProcessHost::CHILD_NORMAL;
#endif
FilePath exe_path = ChildProcessHost::GetChildPath(child_flags);
if (exe_path.empty())
return false;
CommandLine* cmd_line = new CommandLine(exe_path);
cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess);
cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id);
if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED)
cmd_line->AppendSwitch(switches::kDisableGpuSandbox);
static const char* const kSwitchNames[] = {
switches::kDisableBreakpad,
switches::kDisableGLMultisampling,
switches::kDisableGpuSandbox,
switches::kReduceGpuSandbox,
switches::kDisableSeccompFilterSandbox,
switches::kDisableGpuSwitching,
switches::kDisableGpuVsync,
switches::kDisableGpuWatchdog,
switches::kDisableImageTransportSurface,
switches::kDisableLogging,
switches::kEnableGPUServiceLogging,
switches::kEnableLogging,
#if defined(OS_MACOSX)
switches::kEnableSandboxLogging,
#endif
#if defined(OS_CHROMEOS)
switches::kEnableVaapi,
#endif
switches::kGpuNoContextLost,
switches::kGpuStartupDialog,
switches::kLoggingLevel,
switches::kNoSandbox,
switches::kTestGLLib,
switches::kTraceStartup,
switches::kV,
switches::kVModule,
};
cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
arraysize(kSwitchNames));
cmd_line->CopySwitchesFrom(
browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches);
content::GetContentClient()->browser()->AppendExtraCommandLineSwitches(
cmd_line, process_->GetData().id);
GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line);
if (cmd_line->HasSwitch(switches::kUseGL))
software_rendering_ =
(cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader");
UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessSoftwareRendering", software_rendering_);
if (!gpu_launcher.empty())
cmd_line->PrependWrapper(gpu_launcher);
process_->Launch(
#if defined(OS_WIN)
FilePath(),
#elif defined(OS_POSIX)
false, // Never use the zygote (GPU plugin can't be sandboxed).
base::EnvironmentVector(),
#endif
cmd_line);
process_launched_ = true;
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX);
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: long long BlockGroup::GetNextTimeCode() const
{
return m_next;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: alen_array_element_start(void *state, bool isnull)
{
AlenState *_state = (AlenState *) state;
/* just count up all the level 1 elements */
if (_state->lex->lex_level == 1)
_state->count++;
}
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 encode_create(struct xdr_stream *xdr, const struct nfs4_create_arg *create)
{
__be32 *p;
RESERVE_SPACE(8);
WRITE32(OP_CREATE);
WRITE32(create->ftype);
switch (create->ftype) {
case NF4LNK:
RESERVE_SPACE(4);
WRITE32(create->u.symlink.len);
xdr_write_pages(xdr, create->u.symlink.pages, 0, create->u.symlink.len);
break;
case NF4BLK: case NF4CHR:
RESERVE_SPACE(8);
WRITE32(create->u.device.specdata1);
WRITE32(create->u.device.specdata2);
break;
default:
break;
}
RESERVE_SPACE(4 + create->name->len);
WRITE32(create->name->len);
WRITEMEM(create->name->name, create->name->len);
return encode_attrs(xdr, create->attrs, create->server);
}
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: XSLStyleSheet::XSLStyleSheet(XSLImportRule* parentRule, const String& originalURL, const KURL& finalURL)
: m_ownerNode(0)
, m_originalURL(originalURL)
, m_finalURL(finalURL)
, m_isDisabled(false)
, m_embedded(false)
, m_processed(false) // Child sheets get marked as processed when the libxslt engine has finally seen them.
, m_stylesheetDoc(0)
, m_stylesheetDocTaken(false)
, m_parentStyleSheet(parentRule ? parentRule->parentStyleSheet() : 0)
{
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: poppler_page_get_size (PopplerPage *page,
double *width,
double *height)
{
double page_width, page_height;
int rotate;
g_return_if_fail (POPPLER_IS_PAGE (page));
rotate = page->page->getRotate ();
if (rotate == 90 || rotate == 270) {
page_height = page->page->getCropWidth ();
page_width = page->page->getCropHeight ();
} else {
page_width = page->page->getCropWidth ();
page_height = page->page->getCropHeight ();
}
if (width != NULL)
*width = page_width;
if (height != NULL)
*height = page_height;
}
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 keyring_search_iterator(const void *object, void *iterator_data)
{
struct keyring_search_context *ctx = iterator_data;
const struct key *key = keyring_ptr_to_key(object);
unsigned long kflags = key->flags;
kenter("{%d}", key->serial);
/* ignore keys not of this type */
if (key->type != ctx->index_key.type) {
kleave(" = 0 [!type]");
return 0;
}
/* skip invalidated, revoked and expired keys */
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
if (kflags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED))) {
ctx->result = ERR_PTR(-EKEYREVOKED);
kleave(" = %d [invrev]", ctx->skipped_ret);
goto skipped;
}
if (key->expiry && ctx->now.tv_sec >= key->expiry) {
if (!(ctx->flags & KEYRING_SEARCH_SKIP_EXPIRED))
ctx->result = ERR_PTR(-EKEYEXPIRED);
kleave(" = %d [expire]", ctx->skipped_ret);
goto skipped;
}
}
/* keys that don't match */
if (!ctx->match_data.cmp(key, &ctx->match_data)) {
kleave(" = 0 [!match]");
return 0;
}
/* key must have search permissions */
if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
key_task_permission(make_key_ref(key, ctx->possessed),
ctx->cred, KEY_NEED_SEARCH) < 0) {
ctx->result = ERR_PTR(-EACCES);
kleave(" = %d [!perm]", ctx->skipped_ret);
goto skipped;
}
if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) {
/* we set a different error code if we pass a negative key */
if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
smp_rmb();
ctx->result = ERR_PTR(key->type_data.reject_error);
kleave(" = %d [neg]", ctx->skipped_ret);
goto skipped;
}
}
/* Found */
ctx->result = make_key_ref(key, ctx->possessed);
kleave(" = 1 [found]");
return 1;
skipped:
return ctx->skipped_ret;
}
CWE ID: CWE-119
Output:
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.