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: ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
{
struct session_state *state = ssh->state;
struct sshbuf *b;
int r;
if ((b = sshbuf_new()) == NULL)
return SSH_ERR_ALLOC_FAIL;
if (state->compression_in_started) {
if ((r = sshbuf_put_string(b, &state->compression_in_stream,
sizeof(state->compression_in_stream))) != 0)
goto out;
} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
goto out;
if (state->compression_out_started) {
if ((r = sshbuf_put_string(b, &state->compression_out_stream,
sizeof(state->compression_out_stream))) != 0)
goto out;
} else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
goto out;
r = sshbuf_put_stringb(m, b);
out:
sshbuf_free(b);
return r;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool TabsCaptureVisibleTabFunction::HasPermission() {
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: int AskAllowCount() { return mock_permission_prompt_factory_->show_count(); }
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: MediaStreamDispatcherHost::~MediaStreamDispatcherHost() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
bindings_.CloseAllBindings();
CancelAllRequests();
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: bool doReadUintHelper(T* value)
{
*value = 0;
uint8_t currentByte;
int shift = 0;
do {
if (m_position >= m_length)
return false;
currentByte = m_buffer[m_position++];
*value |= ((currentByte & varIntMask) << shift);
shift += varIntShift;
} while (currentByte & (1 << varIntShift));
return true;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: InspectorClientImpl::~InspectorClientImpl()
{
}
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: TabContents* TabStripModel::DetachTabContentsAt(int index) {
if (contents_data_.empty())
return NULL;
DCHECK(ContainsIndex(index));
TabContents* removed_contents = GetTabContentsAtImpl(index);
bool was_selected = IsTabSelected(index);
int next_selected_index = order_controller_->DetermineNewSelectedIndex(index);
delete contents_data_[index];
contents_data_.erase(contents_data_.begin() + index);
ForgetOpenersAndGroupsReferencing(removed_contents->web_contents());
if (empty())
closing_all_ = true;
FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
TabDetachedAt(removed_contents, index));
if (empty()) {
selection_model_.Clear();
FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty());
} else {
int old_active = active_index();
selection_model_.DecrementFrom(index);
TabStripSelectionModel old_model;
old_model.Copy(selection_model_);
if (index == old_active) {
NotifyIfTabDeactivated(removed_contents);
if (!selection_model_.empty()) {
selection_model_.set_active(selection_model_.selected_indices()[0]);
selection_model_.set_anchor(selection_model_.active());
} else {
selection_model_.SetSelectedIndex(next_selected_index);
}
NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT);
}
if (was_selected) {
FOR_EACH_OBSERVER(TabStripModelObserver, observers_,
TabSelectionChanged(this, old_model));
}
}
return removed_contents;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void show_special(struct audit_context *context, int *call_panic)
{
struct audit_buffer *ab;
int i;
ab = audit_log_start(context, GFP_KERNEL, context->type);
if (!ab)
return;
switch (context->type) {
case AUDIT_SOCKETCALL: {
int nargs = context->socketcall.nargs;
audit_log_format(ab, "nargs=%d", nargs);
for (i = 0; i < nargs; i++)
audit_log_format(ab, " a%d=%lx", i,
context->socketcall.args[i]);
break; }
case AUDIT_IPC: {
u32 osid = context->ipc.osid;
audit_log_format(ab, "ouid=%u ogid=%u mode=%#ho",
from_kuid(&init_user_ns, context->ipc.uid),
from_kgid(&init_user_ns, context->ipc.gid),
context->ipc.mode);
if (osid) {
char *ctx = NULL;
u32 len;
if (security_secid_to_secctx(osid, &ctx, &len)) {
audit_log_format(ab, " osid=%u", osid);
*call_panic = 1;
} else {
audit_log_format(ab, " obj=%s", ctx);
security_release_secctx(ctx, len);
}
}
if (context->ipc.has_perm) {
audit_log_end(ab);
ab = audit_log_start(context, GFP_KERNEL,
AUDIT_IPC_SET_PERM);
if (unlikely(!ab))
return;
audit_log_format(ab,
"qbytes=%lx ouid=%u ogid=%u mode=%#ho",
context->ipc.qbytes,
context->ipc.perm_uid,
context->ipc.perm_gid,
context->ipc.perm_mode);
}
break; }
case AUDIT_MQ_OPEN: {
audit_log_format(ab,
"oflag=0x%x mode=%#ho mq_flags=0x%lx mq_maxmsg=%ld "
"mq_msgsize=%ld mq_curmsgs=%ld",
context->mq_open.oflag, context->mq_open.mode,
context->mq_open.attr.mq_flags,
context->mq_open.attr.mq_maxmsg,
context->mq_open.attr.mq_msgsize,
context->mq_open.attr.mq_curmsgs);
break; }
case AUDIT_MQ_SENDRECV: {
audit_log_format(ab,
"mqdes=%d msg_len=%zd msg_prio=%u "
"abs_timeout_sec=%ld abs_timeout_nsec=%ld",
context->mq_sendrecv.mqdes,
context->mq_sendrecv.msg_len,
context->mq_sendrecv.msg_prio,
context->mq_sendrecv.abs_timeout.tv_sec,
context->mq_sendrecv.abs_timeout.tv_nsec);
break; }
case AUDIT_MQ_NOTIFY: {
audit_log_format(ab, "mqdes=%d sigev_signo=%d",
context->mq_notify.mqdes,
context->mq_notify.sigev_signo);
break; }
case AUDIT_MQ_GETSETATTR: {
struct mq_attr *attr = &context->mq_getsetattr.mqstat;
audit_log_format(ab,
"mqdes=%d mq_flags=0x%lx mq_maxmsg=%ld mq_msgsize=%ld "
"mq_curmsgs=%ld ",
context->mq_getsetattr.mqdes,
attr->mq_flags, attr->mq_maxmsg,
attr->mq_msgsize, attr->mq_curmsgs);
break; }
case AUDIT_CAPSET: {
audit_log_format(ab, "pid=%d", context->capset.pid);
audit_log_cap(ab, "cap_pi", &context->capset.cap.inheritable);
audit_log_cap(ab, "cap_pp", &context->capset.cap.permitted);
audit_log_cap(ab, "cap_pe", &context->capset.cap.effective);
break; }
case AUDIT_MMAP: {
audit_log_format(ab, "fd=%d flags=0x%x", context->mmap.fd,
context->mmap.flags);
break; }
case AUDIT_EXECVE: {
audit_log_execve_info(context, &ab);
break; }
}
audit_log_end(ab);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool SendKeyEvent(const std::string type,
int key_value,
int key_code,
std::string key_name,
int modifiers,
aura::WindowTreeHost* host) {
ui::EventType event_type = ui::ET_UNKNOWN;
if (type == kKeyDown)
event_type = ui::ET_KEY_PRESSED;
else if (type == kKeyUp)
event_type = ui::ET_KEY_RELEASED;
if (event_type == ui::ET_UNKNOWN)
return false;
ui::KeyboardCode code = static_cast<ui::KeyboardCode>(key_code);
if (code == ui::VKEY_UNKNOWN) {
if (event_type == ui::ET_KEY_RELEASED) {
ui::InputMethod* input_method = host->window()->GetProperty(
aura::client::kRootWindowInputMethodKey);
if (!input_method)
return false;
ui::TextInputClient* tic = input_method->GetTextInputClient();
SendProcessKeyEvent(ui::ET_KEY_PRESSED, host);
tic->InsertChar(static_cast<uint16>(key_value), ui::EF_NONE);
SendProcessKeyEvent(ui::ET_KEY_RELEASED, host);
}
} else {
if (event_type == ui::ET_KEY_RELEASED) {
static int keys_seen = 0;
if (code == ui::VKEY_BACK) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"VirtualKeyboard.KeystrokesBetweenBackspaces",
keys_seen, 1, 1000, 50);
keys_seen = 0;
} else {
++keys_seen;
}
}
ui::DomCode dom_code = ui::DomCode::NONE;
if (!key_name.empty())
dom_code = ui::KeycodeConverter::CodeStringToDomCode(key_name.c_str());
if (dom_code == ui::DomCode::NONE)
dom_code = ui::UsLayoutKeyboardCodeToDomCode(code);
CHECK(dom_code != ui::DomCode::NONE);
ui::KeyEvent event(
event_type,
code,
dom_code,
modifiers);
ui::EventDispatchDetails details =
host->event_processor()->OnEventFromSource(&event);
CHECK(!details.dispatcher_destroyed);
}
return true;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: double AffineTransform::xScale() const
{
return sqrt(m_transform[0] * m_transform[0] + m_transform[1] * m_transform[1]);
}
CWE ID:
Target: 1
Example 2:
Code: static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
struct inode *inode, u64 file_pos,
u64 disk_bytenr, u64 disk_num_bytes,
u64 num_bytes, u64 ram_bytes,
u8 compression, u8 encryption,
u16 other_encoding, int extent_type)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_file_extent_item *fi;
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_key ins;
int ret;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->leave_spinning = 1;
/*
* we may be replacing one extent in the tree with another.
* The new extent is pinned in the extent map, and we don't want
* to drop it from the cache until it is completely in the btree.
*
* So, tell btrfs_drop_extents to leave this extent in the cache.
* the caller is expected to unpin it and allow it to be merged
* with the others.
*/
ret = btrfs_drop_extents(trans, root, inode, file_pos,
file_pos + num_bytes, 0);
if (ret)
goto out;
ins.objectid = btrfs_ino(inode);
ins.offset = file_pos;
ins.type = BTRFS_EXTENT_DATA_KEY;
ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
if (ret)
goto out;
leaf = path->nodes[0];
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, fi, trans->transid);
btrfs_set_file_extent_type(leaf, fi, extent_type);
btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
btrfs_set_file_extent_offset(leaf, fi, 0);
btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
btrfs_set_file_extent_compression(leaf, fi, compression);
btrfs_set_file_extent_encryption(leaf, fi, encryption);
btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
btrfs_mark_buffer_dirty(leaf);
btrfs_release_path(path);
inode_add_bytes(inode, num_bytes);
ins.objectid = disk_bytenr;
ins.offset = disk_num_bytes;
ins.type = BTRFS_EXTENT_ITEM_KEY;
ret = btrfs_alloc_reserved_file_extent(trans, root,
root->root_key.objectid,
btrfs_ino(inode), file_pos, &ins);
out:
btrfs_free_path(path);
return ret;
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenameFile(const DownloadId& id,
const FilePath& new_path,
const FilePath& unique_path,
net::Error rename_error,
RenameFileState state,
RenameFileOverwrite should_overwrite) {
MockDownloadFile* file = download_file_factory_->GetExistingFile(id);
ASSERT_TRUE(file != NULL);
EXPECT_CALL(*file, Rename(unique_path))
.Times(1)
.WillOnce(Return(rename_error));
if (rename_error != net::OK) {
EXPECT_CALL(*file, BytesSoFar())
.Times(AtLeast(1))
.WillRepeatedly(Return(byte_count_[id]));
EXPECT_CALL(*file, GetHashState())
.Times(AtLeast(1));
EXPECT_CALL(*file, GetDownloadManager())
.Times(AtLeast(1));
} else if (state == COMPLETE) {
#if defined(OS_MACOSX)
EXPECT_CALL(*file, AnnotateWithSourceInformation());
#endif
}
if (state == IN_PROGRESS) {
download_file_manager_->RenameInProgressDownloadFile(
id, new_path, (should_overwrite == OVERWRITE),
base::Bind(&TestDownloadManager::OnDownloadRenamed,
download_manager_, id.local()));
} else { // state == COMPLETE
download_file_manager_->RenameCompletingDownloadFile(
id, new_path, (should_overwrite == OVERWRITE),
base::Bind(&TestDownloadManager::OnDownloadRenamed,
download_manager_, id.local()));
}
if (rename_error != net::OK) {
EXPECT_CALL(*download_manager_,
OnDownloadInterrupted(
id.local(),
byte_count_[id],
"",
content::ConvertNetErrorToInterruptReason(
rename_error,
content::DOWNLOAD_INTERRUPT_FROM_DISK)));
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), FilePath()));
ProcessAllPendingMessages();
++error_count_[id];
} else {
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), unique_path));
ProcessAllPendingMessages();
}
}
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: krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data,
krb5_kvno mkvno) {
struct berval **ret = NULL;
int currkvno;
int num_versions = 1;
int i, j, last;
krb5_error_code err = 0;
krb5_key_data *key_data;
if (n_key_data <= 0)
return NULL;
/* Make a shallow copy of the key data so we can alter it. */
key_data = k5calloc(n_key_data, sizeof(*key_data), &err);
if (key_data_in == NULL)
goto cleanup;
memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data));
/* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt
* field. For compatibility, always encode a salt field. */
for (i = 0; i < n_key_data; i++) {
if (key_data[i].key_data_ver == 1) {
key_data[i].key_data_ver = 2;
key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL;
key_data[i].key_data_length[1] = 0;
key_data[i].key_data_contents[1] = NULL;
}
}
/* Find the number of key versions */
for (i = 0; i < n_key_data - 1; i++)
if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno)
num_versions++;
ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *));
if (ret == NULL) {
err = ENOMEM;
goto cleanup;
}
for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) {
krb5_data *code;
if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) {
ret[j] = k5alloc(sizeof(struct berval), &err);
if (ret[j] == NULL)
goto cleanup;
err = asn1_encode_sequence_of_keys(key_data + last,
(krb5_int16)i - last + 1,
mkvno, &code);
if (err)
goto cleanup;
/*CHECK_NULL(ret[j]); */
ret[j]->bv_len = code->length;
ret[j]->bv_val = code->data;
free(code);
j++;
last = i + 1;
if (i < n_key_data - 1)
currkvno = key_data[i + 1].key_data_kvno;
}
}
ret[num_versions] = NULL;
cleanup:
free(key_data);
if (err != 0) {
if (ret != NULL) {
for (i = 0; i <= num_versions; i++)
if (ret[i] != NULL)
free (ret[i]);
free (ret);
ret = NULL;
}
}
return ret;
}
CWE ID:
Target: 1
Example 2:
Code: static void dynamicPutchar(struct gdIOCtx *ctx, int a)
{
unsigned char b;
dpIOCtxPtr dctx;
b = a;
dctx = (dpIOCtxPtr) ctx;
appendDynamic(dctx->dp, &b, 1);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void free_huge_page(struct page *page)
{
/*
* Can't pass hstate in here because it is called from the
* compound page destructor.
*/
struct hstate *h = page_hstate(page);
int nid = page_to_nid(page);
struct hugepage_subpool *spool =
(struct hugepage_subpool *)page_private(page);
bool restore_reserve;
set_page_private(page, 0);
page->mapping = NULL;
VM_BUG_ON_PAGE(page_count(page), page);
VM_BUG_ON_PAGE(page_mapcount(page), page);
restore_reserve = PagePrivate(page);
ClearPagePrivate(page);
/*
* A return code of zero implies that the subpool will be under its
* minimum size if the reservation is not restored after page is free.
* Therefore, force restore_reserve operation.
*/
if (hugepage_subpool_put_pages(spool, 1) == 0)
restore_reserve = true;
spin_lock(&hugetlb_lock);
clear_page_huge_active(page);
hugetlb_cgroup_uncharge_page(hstate_index(h),
pages_per_huge_page(h), page);
if (restore_reserve)
h->resv_huge_pages++;
if (h->surplus_huge_pages_node[nid]) {
/* remove the page from active list */
list_del(&page->lru);
update_and_free_page(h, page);
h->surplus_huge_pages--;
h->surplus_huge_pages_node[nid]--;
} else {
arch_clear_hugepage_flags(page);
enqueue_huge_page(h, page);
}
spin_unlock(&hugetlb_lock);
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int rd_build_device_space(struct rd_dev *rd_dev)
{
u32 i = 0, j, page_offset = 0, sg_per_table, sg_tables, total_sg_needed;
u32 max_sg_per_table = (RD_MAX_ALLOCATION_SIZE /
sizeof(struct scatterlist));
struct rd_dev_sg_table *sg_table;
struct page *pg;
struct scatterlist *sg;
if (rd_dev->rd_page_count <= 0) {
pr_err("Illegal page count: %u for Ramdisk device\n",
rd_dev->rd_page_count);
return -EINVAL;
}
/* Don't need backing pages for NULLIO */
if (rd_dev->rd_flags & RDF_NULLIO)
return 0;
total_sg_needed = rd_dev->rd_page_count;
sg_tables = (total_sg_needed / max_sg_per_table) + 1;
sg_table = kzalloc(sg_tables * sizeof(struct rd_dev_sg_table), GFP_KERNEL);
if (!sg_table) {
pr_err("Unable to allocate memory for Ramdisk"
" scatterlist tables\n");
return -ENOMEM;
}
rd_dev->sg_table_array = sg_table;
rd_dev->sg_table_count = sg_tables;
while (total_sg_needed) {
sg_per_table = (total_sg_needed > max_sg_per_table) ?
max_sg_per_table : total_sg_needed;
sg = kzalloc(sg_per_table * sizeof(struct scatterlist),
GFP_KERNEL);
if (!sg) {
pr_err("Unable to allocate scatterlist array"
" for struct rd_dev\n");
return -ENOMEM;
}
sg_init_table(sg, sg_per_table);
sg_table[i].sg_table = sg;
sg_table[i].rd_sg_count = sg_per_table;
sg_table[i].page_start_offset = page_offset;
sg_table[i++].page_end_offset = (page_offset + sg_per_table)
- 1;
for (j = 0; j < sg_per_table; j++) {
pg = alloc_pages(GFP_KERNEL, 0);
if (!pg) {
pr_err("Unable to allocate scatterlist"
" pages for struct rd_dev_sg_table\n");
return -ENOMEM;
}
sg_assign_page(&sg[j], pg);
sg[j].length = PAGE_SIZE;
}
page_offset += sg_per_table;
total_sg_needed -= sg_per_table;
}
pr_debug("CORE_RD[%u] - Built Ramdisk Device ID: %u space of"
" %u pages in %u tables\n", rd_dev->rd_host->rd_host_id,
rd_dev->rd_dev_id, rd_dev->rd_page_count,
rd_dev->sg_table_count);
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
{
struct vmcs12 *vmcs12;
struct vcpu_vmx *vmx = to_vmx(vcpu);
u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
u32 exit_qual;
int ret;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
goto out;
vmcs12 = get_vmcs12(vcpu);
if (enable_shadow_vmcs)
copy_shadow_to_vmcs12(vmx);
/*
* The nested entry process starts with enforcing various prerequisites
* on vmcs12 as required by the Intel SDM, and act appropriately when
* they fail: As the SDM explains, some conditions should cause the
* instruction to fail, while others will cause the instruction to seem
* to succeed, but return an EXIT_REASON_INVALID_STATE.
* To speed up the normal (success) code path, we should avoid checking
* for misconfigurations which will anyway be caught by the processor
* when using the merged vmcs02.
*/
if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
nested_vmx_failValid(vcpu,
VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
goto out;
}
if (vmcs12->launch_state == launch) {
nested_vmx_failValid(vcpu,
launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
: VMXERR_VMRESUME_NONLAUNCHED_VMCS);
goto out;
}
ret = check_vmentry_prereqs(vcpu, vmcs12);
if (ret) {
nested_vmx_failValid(vcpu, ret);
goto out;
}
/*
* After this point, the trap flag no longer triggers a singlestep trap
* on the vm entry instructions; don't call kvm_skip_emulated_instruction.
* This is not 100% correct; for performance reasons, we delegate most
* of the checks on host state to the processor. If those fail,
* the singlestep trap is missed.
*/
skip_emulated_instruction(vcpu);
ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
if (ret) {
nested_vmx_entry_failure(vcpu, vmcs12,
EXIT_REASON_INVALID_STATE, exit_qual);
return 1;
}
/*
* We're finally done with prerequisite checking, and can start with
* the nested entry.
*/
ret = enter_vmx_non_root_mode(vcpu, true);
if (ret)
return ret;
if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
return kvm_vcpu_halt(vcpu);
vmx->nested.nested_run_pending = 1;
return 1;
out:
return kvm_skip_emulated_instruction(vcpu);
}
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: xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode,
xmlNodePtr inst, xsltStylePreCompPtr comp ATTRIBUTE_UNUSED)
{
xmlNodePtr cur;
if ((ctxt == NULL) || (contextNode == NULL) || (inst == NULL))
return;
/*
* TODO: Content model checks should be done only at compilation
* time.
*/
cur = inst->children;
if (cur == NULL) {
xsltTransformError(ctxt, NULL, inst,
"xsl:choose: The instruction has no content.\n");
return;
}
#ifdef XSLT_REFACTORED
/*
* We don't check the content model during transformation.
*/
#else
if ((! IS_XSLT_ELEM(cur)) || (! IS_XSLT_NAME(cur, "when"))) {
xsltTransformError(ctxt, NULL, inst,
"xsl:choose: xsl:when expected first\n");
return;
}
#endif
{
int testRes = 0, res = 0;
xmlXPathContextPtr xpctxt = ctxt->xpathCtxt;
xmlDocPtr oldXPContextDoc = xpctxt->doc;
int oldXPProximityPosition = xpctxt->proximityPosition;
int oldXPContextSize = xpctxt->contextSize;
xmlNsPtr *oldXPNamespaces = xpctxt->namespaces;
int oldXPNsNr = xpctxt->nsNr;
#ifdef XSLT_REFACTORED
xsltStyleItemWhenPtr wcomp = NULL;
#else
xsltStylePreCompPtr wcomp = NULL;
#endif
/*
* Process xsl:when ---------------------------------------------------
*/
while (IS_XSLT_ELEM(cur) && IS_XSLT_NAME(cur, "when")) {
wcomp = cur->psvi;
if ((wcomp == NULL) || (wcomp->test == NULL) ||
(wcomp->comp == NULL))
{
xsltTransformError(ctxt, NULL, cur,
"Internal error in xsltChoose(): "
"The XSLT 'when' instruction was not compiled.\n");
goto error;
}
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE) {
/*
* TODO: Isn't comp->templ always NULL for xsl:choose?
*/
xslHandleDebugger(cur, contextNode, NULL, ctxt);
}
#endif
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test %s\n", wcomp->test));
#endif
xpctxt->node = contextNode;
xpctxt->doc = oldXPContextDoc;
xpctxt->proximityPosition = oldXPProximityPosition;
xpctxt->contextSize = oldXPContextSize;
#ifdef XSLT_REFACTORED
if (wcomp->inScopeNs != NULL) {
xpctxt->namespaces = wcomp->inScopeNs->list;
xpctxt->nsNr = wcomp->inScopeNs->xpathNumber;
} else {
xpctxt->namespaces = NULL;
xpctxt->nsNr = 0;
}
#else
xpctxt->namespaces = wcomp->nsList;
xpctxt->nsNr = wcomp->nsNr;
#endif
#ifdef XSLT_FAST_IF
res = xmlXPathCompiledEvalToBoolean(wcomp->comp, xpctxt);
if (res == -1) {
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
testRes = (res == 1) ? 1 : 0;
#else /* XSLT_FAST_IF */
res = xmlXPathCompiledEval(wcomp->comp, xpctxt);
if (res != NULL) {
if (res->type != XPATH_BOOLEAN)
res = xmlXPathConvertBoolean(res);
if (res->type == XPATH_BOOLEAN)
testRes = res->boolval;
else {
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test didn't evaluate to a boolean\n"));
#endif
goto error;
}
xmlXPathFreeObject(res);
res = NULL;
} else {
ctxt->state = XSLT_STATE_STOPPED;
goto error;
}
#endif /* else of XSLT_FAST_IF */
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"xsltChoose: test evaluate to %d\n", testRes));
#endif
if (testRes)
goto test_is_true;
cur = cur->next;
}
/*
* Process xsl:otherwise ----------------------------------------------
*/
if (IS_XSLT_ELEM(cur) && IS_XSLT_NAME(cur, "otherwise")) {
#ifdef WITH_DEBUGGER
if (xslDebugStatus != XSLT_DEBUG_NONE)
xslHandleDebugger(cur, contextNode, NULL, ctxt);
#endif
#ifdef WITH_XSLT_DEBUG_PROCESS
XSLT_TRACE(ctxt,XSLT_TRACE_CHOOSE,xsltGenericDebug(xsltGenericDebugContext,
"evaluating xsl:otherwise\n"));
#endif
goto test_is_true;
}
xpctxt->node = contextNode;
xpctxt->doc = oldXPContextDoc;
xpctxt->proximityPosition = oldXPProximityPosition;
xpctxt->contextSize = oldXPContextSize;
xpctxt->namespaces = oldXPNamespaces;
xpctxt->nsNr = oldXPNsNr;
goto exit;
test_is_true:
xpctxt->node = contextNode;
xpctxt->doc = oldXPContextDoc;
xpctxt->proximityPosition = oldXPProximityPosition;
xpctxt->contextSize = oldXPContextSize;
xpctxt->namespaces = oldXPNamespaces;
xpctxt->nsNr = oldXPNsNr;
goto process_sequence;
}
process_sequence:
/*
* Instantiate the sequence constructor.
*/
xsltApplySequenceConstructor(ctxt, ctxt->node, cur->children,
NULL);
exit:
error:
return;
}
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 svc_rdma_wc_write(struct ib_cq *cq, struct ib_wc *wc)
{
struct ib_cqe *cqe = wc->wr_cqe;
struct svc_rdma_op_ctxt *ctxt;
svc_rdma_send_wc_common_put(cq, wc, "write");
ctxt = container_of(cqe, struct svc_rdma_op_ctxt, cqe);
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 0);
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: void WebContentsImpl::CreateNewWidget(int32_t render_process_id,
int32_t route_id,
blink::WebPopupType popup_type) {
CreateNewWidget(render_process_id, route_id, false, popup_type);
}
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 DownloadItemImpl::UpdateProgress(int64 bytes_so_far,
int64 bytes_per_sec,
const std::string& hash_state) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!IsInProgress()) {
NOTREACHED();
return;
}
bytes_per_sec_ = bytes_per_sec;
UpdateProgress(bytes_so_far, hash_state);
UpdateObservers();
}
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: do_setup_env(Session *s, const char *shell)
{
struct ssh *ssh = active_state; /* XXX */
char buf[256];
u_int i, envsize;
char **env, *laddr;
struct passwd *pw = s->pw;
#if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
char *path = NULL;
#endif
/* Initialize the environment. */
envsize = 100;
env = xcalloc(envsize, sizeof(char *));
env[0] = NULL;
#ifdef HAVE_CYGWIN
/*
* The Windows environment contains some setting which are
* important for a running system. They must not be dropped.
*/
{
char **p;
p = fetch_windows_environment();
copy_environment(p, &env, &envsize);
free_windows_environment(p);
}
#endif
#ifdef GSSAPI
/* Allow any GSSAPI methods that we've used to alter
* the childs environment as they see fit
*/
ssh_gssapi_do_child(&env, &envsize);
#endif
if (!options.use_login) {
/* Set basic environment. */
for (i = 0; i < s->num_env; i++)
child_set_env(&env, &envsize, s->env[i].name,
s->env[i].val);
child_set_env(&env, &envsize, "USER", pw->pw_name);
child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
#ifdef _AIX
child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
#endif
child_set_env(&env, &envsize, "HOME", pw->pw_dir);
#ifdef HAVE_LOGIN_CAP
if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
else
child_set_env(&env, &envsize, "PATH", getenv("PATH"));
#else /* HAVE_LOGIN_CAP */
# ifndef HAVE_CYGWIN
/*
* There's no standard path on Windows. The path contains
* important components pointing to the system directories,
* needed for loading shared libraries. So the path better
* remains intact here.
*/
# ifdef HAVE_ETC_DEFAULT_LOGIN
read_etc_default_login(&env, &envsize, pw->pw_uid);
path = child_get_env(env, "PATH");
# endif /* HAVE_ETC_DEFAULT_LOGIN */
if (path == NULL || *path == '\0') {
child_set_env(&env, &envsize, "PATH",
s->pw->pw_uid == 0 ?
SUPERUSER_PATH : _PATH_STDPATH);
}
# endif /* HAVE_CYGWIN */
#endif /* HAVE_LOGIN_CAP */
snprintf(buf, sizeof buf, "%.200s/%.50s",
_PATH_MAILDIR, pw->pw_name);
child_set_env(&env, &envsize, "MAIL", buf);
/* Normal systems set SHELL by default. */
child_set_env(&env, &envsize, "SHELL", shell);
}
if (getenv("TZ"))
child_set_env(&env, &envsize, "TZ", getenv("TZ"));
/* Set custom environment options from RSA authentication. */
if (!options.use_login) {
while (custom_environment) {
struct envstring *ce = custom_environment;
char *str = ce->s;
for (i = 0; str[i] != '=' && str[i]; i++)
;
if (str[i] == '=') {
str[i] = 0;
child_set_env(&env, &envsize, str, str + i + 1);
}
custom_environment = ce->next;
free(ce->s);
free(ce);
}
}
/* SSH_CLIENT deprecated */
snprintf(buf, sizeof buf, "%.50s %d %d",
ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
ssh_local_port(ssh));
child_set_env(&env, &envsize, "SSH_CLIENT", buf);
laddr = get_local_ipaddr(packet_get_connection_in());
snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
laddr, ssh_local_port(ssh));
free(laddr);
child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
if (s->ttyfd != -1)
child_set_env(&env, &envsize, "SSH_TTY", s->tty);
if (s->term)
child_set_env(&env, &envsize, "TERM", s->term);
if (s->display)
child_set_env(&env, &envsize, "DISPLAY", s->display);
if (original_command)
child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
original_command);
#ifdef _UNICOS
if (cray_tmpdir[0] != '\0')
child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
#endif /* _UNICOS */
/*
* Since we clear KRB5CCNAME at startup, if it's set now then it
* must have been set by a native authentication method (eg AIX or
* SIA), so copy it to the child.
*/
{
char *cp;
if ((cp = getenv("KRB5CCNAME")) != NULL)
child_set_env(&env, &envsize, "KRB5CCNAME", cp);
}
#ifdef _AIX
{
char *cp;
if ((cp = getenv("AUTHSTATE")) != NULL)
child_set_env(&env, &envsize, "AUTHSTATE", cp);
read_environment_file(&env, &envsize, "/etc/environment");
}
#endif
#ifdef KRB5
if (s->authctxt->krb5_ccname)
child_set_env(&env, &envsize, "KRB5CCNAME",
s->authctxt->krb5_ccname);
#endif
#ifdef USE_PAM
/*
* Pull in any environment variables that may have
* been set by PAM.
*/
if (options.use_pam) {
char **p;
p = fetch_pam_child_environment();
copy_environment(p, &env, &envsize);
free_pam_environment(p);
p = fetch_pam_environment();
copy_environment(p, &env, &envsize);
free_pam_environment(p);
}
#endif /* USE_PAM */
if (auth_sock_name != NULL)
child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
auth_sock_name);
/* read $HOME/.ssh/environment. */
if (options.permit_user_env && !options.use_login) {
snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
read_environment_file(&env, &envsize, buf);
}
if (debug_flag) {
/* dump the environment */
fprintf(stderr, "Environment:\n");
for (i = 0; env[i]; i++)
fprintf(stderr, " %.200s\n", env[i]);
}
return env;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: GURL GlobalConfirmInfoBar::DelegateProxy::GetLinkURL() const {
return global_info_bar_ ? global_info_bar_->delegate_->GetLinkURL()
: GURL();
}
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: kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
{
struct ssh *ssh = ctxt;
struct kex *kex = ssh->kex;
const u_char *ptr;
u_int i;
size_t dlen;
int r;
debug("SSH2_MSG_KEXINIT received");
if (kex == NULL)
return SSH_ERR_INVALID_ARGUMENT;
ptr = sshpkt_ptr(ssh, &dlen);
if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
return r;
/* discard packet */
for (i = 0; i < KEX_COOKIE_LEN; i++)
if ((r = sshpkt_get_u8(ssh, NULL)) != 0)
return r;
for (i = 0; i < PROPOSAL_MAX; i++)
if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0)
return r;
/*
* XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
* KEX method has the server move first, but a server might be using
* a custom method or one that we otherwise don't support. We should
* be prepared to remember first_kex_follows here so we can eat a
* packet later.
* XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
* for cases where the server *doesn't* go first. I guess we should
* ignore it when it is set for these cases, which is what we do now.
*/
if ((r = sshpkt_get_u8(ssh, NULL)) != 0 || /* first_kex_follows */
(r = sshpkt_get_u32(ssh, NULL)) != 0 || /* reserved */
(r = sshpkt_get_end(ssh)) != 0)
return r;
if (!(kex->flags & KEX_INIT_SENT))
if ((r = kex_send_kexinit(ssh)) != 0)
return r;
if ((r = kex_choose_conf(ssh)) != 0)
return r;
if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
return (kex->kex[kex->kex_type])(ssh);
return SSH_ERR_INTERNAL_ERROR;
}
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 AppCacheGroup::RemoveCache(AppCache* cache) {
DCHECK(cache->associated_hosts().empty());
if (cache == newest_complete_cache_) {
CancelUpdate();
AppCache* tmp_cache = newest_complete_cache_;
newest_complete_cache_ = nullptr;
tmp_cache->set_owning_group(nullptr); // may cause this group to be deleted
} else {
scoped_refptr<AppCacheGroup> protect(this);
Caches::iterator it =
std::find(old_caches_.begin(), old_caches_.end(), cache);
if (it != old_caches_.end()) {
AppCache* tmp_cache = *it;
old_caches_.erase(it);
tmp_cache->set_owning_group(nullptr); // may cause group to be released
}
if (!is_obsolete() && old_caches_.empty() &&
!newly_deletable_response_ids_.empty()) {
storage_->DeleteResponses(manifest_url_, newly_deletable_response_ids_);
newly_deletable_response_ids_.clear();
}
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif)
{
static const char module[]="OJPEGReadHeaderInfoSecTablesQTable";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
uint8 n;
uint32 oa;
uint8* ob;
uint32 p;
if (sp->qtable_offset[0]==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
return(0);
}
sp->in_buffer_file_pos_log=0;
for (m=0; m<sp->samples_per_pixel; m++)
{
if ((sp->qtable_offset[m]!=0) && ((m==0) || (sp->qtable_offset[m]!=sp->qtable_offset[m-1])))
{
for (n=0; n<m-1; n++)
{
if (sp->qtable_offset[m]==sp->qtable_offset[n])
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegQTables tag value");
return(0);
}
}
oa=sizeof(uint32)+69;
ob=_TIFFmalloc(oa);
if (ob==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
*(uint32*)ob=oa;
ob[sizeof(uint32)]=255;
ob[sizeof(uint32)+1]=JPEG_MARKER_DQT;
ob[sizeof(uint32)+2]=0;
ob[sizeof(uint32)+3]=67;
ob[sizeof(uint32)+4]=m;
TIFFSeekFile(tif,sp->qtable_offset[m],SEEK_SET);
p=(uint32)TIFFReadFile(tif,&ob[sizeof(uint32)+5],64);
if (p!=64)
return(0);
sp->qtable[m]=ob;
sp->sof_tq[m]=m;
}
else
sp->sof_tq[m]=sp->sof_tq[m-1];
}
return(1);
}
CWE ID: CWE-369
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MediaElementAudioSourceHandler::OnCurrentSrcChanged(
const KURL& current_src) {
DCHECK(IsMainThread());
Locker<MediaElementAudioSourceHandler> locker(*this);
passes_current_src_cors_access_check_ =
PassesCurrentSrcCORSAccessCheck(current_src);
maybe_print_cors_message_ = !passes_current_src_cors_access_check_;
current_src_string_ = current_src.GetString();
}
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 struct vm_area_struct *vma_to_resize(unsigned long addr,
unsigned long old_len, unsigned long new_len, unsigned long *p)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = find_vma(mm, addr);
if (!vma || vma->vm_start > addr)
goto Efault;
if (is_vm_hugetlb_page(vma))
goto Einval;
/* We can't remap across vm area boundaries */
if (old_len > vma->vm_end - addr)
goto Efault;
if (vma->vm_flags & (VM_DONTEXPAND | VM_PFNMAP)) {
if (new_len > old_len)
goto Efault;
}
if (vma->vm_flags & VM_LOCKED) {
unsigned long locked, lock_limit;
locked = mm->locked_vm << PAGE_SHIFT;
lock_limit = rlimit(RLIMIT_MEMLOCK);
locked += new_len - old_len;
if (locked > lock_limit && !capable(CAP_IPC_LOCK))
goto Eagain;
}
if (!may_expand_vm(mm, (new_len - old_len) >> PAGE_SHIFT))
goto Enomem;
if (vma->vm_flags & VM_ACCOUNT) {
unsigned long charged = (new_len - old_len) >> PAGE_SHIFT;
if (security_vm_enough_memory(charged))
goto Efault;
*p = charged;
}
return vma;
Efault: /* very odd choice for most of the cases, but... */
return ERR_PTR(-EFAULT);
Einval:
return ERR_PTR(-EINVAL);
Enomem:
return ERR_PTR(-ENOMEM);
Eagain:
return ERR_PTR(-EAGAIN);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static int checkMutexNotheld(sqlite3_mutex *p){
return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
}
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: bool NaClProcessHost::StartNaClExecution() {
NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
nacl::NaClStartParams params;
params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled();
params.validation_cache_key = nacl_browser->GetValidationCacheKey();
params.version = chrome::VersionInfo().CreateVersionString();
params.enable_exception_handling = enable_exception_handling_;
params.enable_debug_stub =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaClDebug);
params.enable_ipc_proxy = enable_ipc_proxy_;
base::PlatformFile irt_file = nacl_browser->IrtFile();
CHECK_NE(irt_file, base::kInvalidPlatformFileValue);
const ChildProcessData& data = process_->GetData();
for (size_t i = 0; i < internal_->sockets_for_sel_ldr.size(); i++) {
if (!ShareHandleToSelLdr(data.handle,
internal_->sockets_for_sel_ldr[i], true,
¶ms.handles)) {
return false;
}
}
if (!ShareHandleToSelLdr(data.handle, irt_file, false, ¶ms.handles))
return false;
#if defined(OS_MACOSX)
base::SharedMemory memory_buffer;
base::SharedMemoryCreateOptions options;
options.size = 1;
options.executable = true;
if (!memory_buffer.Create(options)) {
DLOG(ERROR) << "Failed to allocate memory buffer";
return false;
}
nacl::FileDescriptor memory_fd;
memory_fd.fd = dup(memory_buffer.handle().fd);
if (memory_fd.fd < 0) {
DLOG(ERROR) << "Failed to dup() a file descriptor";
return false;
}
memory_fd.auto_close = true;
params.handles.push_back(memory_fd);
#endif
process_->Send(new NaClProcessMsg_Start(params));
internal_->sockets_for_sel_ldr.clear();
return true;
}
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: static int crypto_pcomp_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_comp rpcomp;
snprintf(rpcomp.type, CRYPTO_MAX_ALG_NAME, "%s", "pcomp");
if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,
sizeof(struct crypto_report_comp), &rpcomp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: ofputil_decode_tlv_table_mod(const struct ofp_header *oh,
struct ofputil_tlv_table_mod *ttm)
{
struct ofpbuf msg = ofpbuf_const_initializer(oh, ntohs(oh->length));
ofpraw_pull_assert(&msg);
struct nx_tlv_table_mod *nx_ttm = ofpbuf_pull(&msg, sizeof *nx_ttm);
ttm->command = ntohs(nx_ttm->command);
if (ttm->command > NXTTMC_CLEAR) {
VLOG_WARN_RL(&bad_ofmsg_rl,
"tlv table mod command (%u) is out of range",
ttm->command);
return OFPERR_NXTTMFC_BAD_COMMAND;
}
return decode_tlv_table_mappings(&msg, TUN_METADATA_NUM_OPTS,
&ttm->mappings);
}
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: static inline unsigned long round_hint_to_min(unsigned long hint)
{
hint &= PAGE_MASK;
if (((void *)hint != NULL) &&
(hint < mmap_min_addr))
return PAGE_ALIGN(mmap_min_addr);
return hint;
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop)
{
if(!src.HasSampleData()) return;
dest.FreeSample();
dest = src;
dest.nLength = len;
dest.pSample = nullptr;
if(!dest.AllocateSample())
{
return;
}
if(len != src.nLength)
MemsetZero(dest.cues);
std::memcpy(dest.pSample8, src.pSample8 + start, len);
dest.uFlags.set(CHN_LOOP, loop);
if(loop)
{
dest.nLoopStart = 0;
dest.nLoopEnd = len;
} else
{
dest.nLoopStart = 0;
dest.nLoopEnd = 0;
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void WebMediaPlayerImpl::DoLoad(LoadType load_type,
const blink::WebURL& url,
CORSMode cors_mode) {
TRACE_EVENT1("media", "WebMediaPlayerImpl::DoLoad", "id", media_log_->id());
DVLOG(1) << __func__;
DCHECK(main_task_runner_->BelongsToCurrentThread());
GURL gurl(url);
ReportMetrics(load_type, gurl, *frame_, media_log_.get());
if (load_type == kLoadTypeURL) {
if (preload_ == MultibufferDataSource::METADATA) {
UMA_HISTOGRAM_BOOLEAN("Media.SRC.PreloadMetaDataHasPoster", has_poster_);
} else if (preload_ == MultibufferDataSource::AUTO) {
UMA_HISTOGRAM_BOOLEAN("Media.SRC.PreloadAutoHasPoster", has_poster_);
}
}
static base::debug::CrashKeyString* subresource_url =
base::debug::AllocateCrashKeyString("subresource_url",
base::debug::CrashKeySize::Size256);
base::debug::SetCrashKeyString(subresource_url, gurl.spec());
loaded_url_ = gurl;
load_type_ = load_type;
SetNetworkState(WebMediaPlayer::kNetworkStateLoading);
SetReadyState(WebMediaPlayer::kReadyStateHaveNothing);
media_log_->AddEvent(media_log_->CreateLoadEvent(url.GetString().Utf8()));
load_start_time_ = base::TimeTicks::Now();
media_metrics_provider_->Initialize(load_type == kLoadTypeMediaSource,
load_type == kLoadTypeURL
? GetMediaURLScheme(loaded_url_)
: mojom::MediaURLScheme::kUnknown);
if (load_type == kLoadTypeMediaSource) {
StartPipeline();
} else {
data_source_.reset(new MultibufferDataSource(
main_task_runner_,
url_index_->GetByUrl(url, static_cast<UrlData::CORSMode>(cors_mode)),
media_log_.get(), &buffered_data_source_host_,
base::Bind(&WebMediaPlayerImpl::NotifyDownloading, AsWeakPtr())));
data_source_->SetPreload(preload_);
data_source_->SetIsClientAudioElement(client_->IsAudioElement());
data_source_->Initialize(
base::Bind(&WebMediaPlayerImpl::DataSourceInitialized, AsWeakPtr()));
}
#if defined(OS_ANDROID) // WMPI_CAST
cast_impl_.Initialize(url, frame_, delegate_id_);
#endif
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: retry_deferred_block(struct nlm_block *block)
{
if (!(block->b_flags & B_GOT_CALLBACK))
block->b_flags |= B_TIMED_OUT;
nlmsvc_insert_block(block, NLM_TIMEOUT);
dprintk("revisit block %p flags %d\n", block, block->b_flags);
if (block->b_deferred_req) {
block->b_deferred_req->revisit(block->b_deferred_req, 0);
block->b_deferred_req = NULL;
}
}
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: static inline signed short ReadPropertySignedShort(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: bool TabStripGtk::IsTabDetached(const TabGtk* tab) const {
if (drag_controller_.get())
return drag_controller_->IsTabDetached(tab);
return false;
}
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 BluetoothOptionsHandler::GenerateFakeDiscoveredDevice(
const std::string& name,
const std::string& address,
const std::string& icon,
bool paired,
bool connected) {
DictionaryValue device;
device.SetString("name", name);
device.SetString("address", address);
device.SetString("icon", icon);
device.SetBoolean("paired", paired);
device.SetBoolean("connected", connected);
web_ui_->CallJavascriptFunction(
"options.SystemOptions.addBluetoothDevice", device);
}
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 ip6_mroute_setsockopt(struct sock *sk, int optname, char __user *optval, unsigned int optlen)
{
int ret, parent = 0;
struct mif6ctl vif;
struct mf6cctl mfc;
mifi_t mifi;
struct net *net = sock_net(sk);
struct mr6_table *mrt;
mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
if (!mrt)
return -ENOENT;
if (optname != MRT6_INIT) {
if (sk != mrt->mroute6_sk && !ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EACCES;
}
switch (optname) {
case MRT6_INIT:
if (sk->sk_type != SOCK_RAW ||
inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
if (optlen < sizeof(int))
return -EINVAL;
return ip6mr_sk_init(mrt, sk);
case MRT6_DONE:
return ip6mr_sk_done(sk);
case MRT6_ADD_MIF:
if (optlen < sizeof(vif))
return -EINVAL;
if (copy_from_user(&vif, optval, sizeof(vif)))
return -EFAULT;
if (vif.mif6c_mifi >= MAXMIFS)
return -ENFILE;
rtnl_lock();
ret = mif6_add(net, mrt, &vif, sk == mrt->mroute6_sk);
rtnl_unlock();
return ret;
case MRT6_DEL_MIF:
if (optlen < sizeof(mifi_t))
return -EINVAL;
if (copy_from_user(&mifi, optval, sizeof(mifi_t)))
return -EFAULT;
rtnl_lock();
ret = mif6_delete(mrt, mifi, NULL);
rtnl_unlock();
return ret;
/*
* Manipulate the forwarding caches. These live
* in a sort of kernel/user symbiosis.
*/
case MRT6_ADD_MFC:
case MRT6_DEL_MFC:
parent = -1;
case MRT6_ADD_MFC_PROXY:
case MRT6_DEL_MFC_PROXY:
if (optlen < sizeof(mfc))
return -EINVAL;
if (copy_from_user(&mfc, optval, sizeof(mfc)))
return -EFAULT;
if (parent == 0)
parent = mfc.mf6cc_parent;
rtnl_lock();
if (optname == MRT6_DEL_MFC || optname == MRT6_DEL_MFC_PROXY)
ret = ip6mr_mfc_delete(mrt, &mfc, parent);
else
ret = ip6mr_mfc_add(net, mrt, &mfc,
sk == mrt->mroute6_sk, parent);
rtnl_unlock();
return ret;
/*
* Control PIM assert (to activate pim will activate assert)
*/
case MRT6_ASSERT:
{
int v;
if (optlen != sizeof(v))
return -EINVAL;
if (get_user(v, (int __user *)optval))
return -EFAULT;
mrt->mroute_do_assert = v;
return 0;
}
#ifdef CONFIG_IPV6_PIMSM_V2
case MRT6_PIM:
{
int v;
if (optlen != sizeof(v))
return -EINVAL;
if (get_user(v, (int __user *)optval))
return -EFAULT;
v = !!v;
rtnl_lock();
ret = 0;
if (v != mrt->mroute_do_pim) {
mrt->mroute_do_pim = v;
mrt->mroute_do_assert = v;
}
rtnl_unlock();
return ret;
}
#endif
#ifdef CONFIG_IPV6_MROUTE_MULTIPLE_TABLES
case MRT6_TABLE:
{
u32 v;
if (optlen != sizeof(u32))
return -EINVAL;
if (get_user(v, (u32 __user *)optval))
return -EFAULT;
/* "pim6reg%u" should not exceed 16 bytes (IFNAMSIZ) */
if (v != RT_TABLE_DEFAULT && v >= 100000000)
return -EINVAL;
if (sk == mrt->mroute6_sk)
return -EBUSY;
rtnl_lock();
ret = 0;
if (!ip6mr_new_table(net, v))
ret = -ENOMEM;
raw6_sk(sk)->ip6mr_table = v;
rtnl_unlock();
return ret;
}
#endif
/*
* Spurious command, or MRT6_VERSION which you cannot
* set.
*/
default:
return -ENOPROTOOPT;
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool Document::ShouldComplete() {
return parsing_state_ == kFinishedParsing && HaveImportsLoaded() &&
!fetcher_->BlockingRequestCount() && !IsDelayingLoadEvent() &&
load_event_progress_ != kLoadEventInProgress &&
AllDescendantsAreComplete(frame_);
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void HTMLDocument::removeItemFromMap(HashCountedSet<StringImpl*>& map, const AtomicString& name)
{
if (name.isEmpty())
return;
map.remove(name.impl());
if (Frame* f = frame())
f->script()->namedItemRemoved(this, name);
}
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: BrightnessLibrary* CrosLibrary::GetBrightnessLibrary() {
return brightness_lib_.GetDefaultImpl(use_stub_impl_);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void DiskCacheBackendTest::BackendInvalidEntry() {
InitCache();
std::string key("Some key");
disk_cache::Entry* entry;
ASSERT_THAT(CreateEntry(key, &entry), IsOk());
const int kSize = 50;
scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(kSize));
memset(buffer->data(), 0, kSize);
base::strlcpy(buffer->data(), "And the data to save", kSize);
EXPECT_EQ(kSize, WriteData(entry, 0, 0, buffer.get(), kSize, false));
SimulateCrash();
EXPECT_NE(net::OK, OpenEntry(key, &entry));
EXPECT_EQ(0, cache_->GetEntryCount());
}
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 asymmetric_key_match_preparse(struct key_match_data *match_data)
{
match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE;
return 0;
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void impeg2d_flush_ext_and_user_data(dec_state_t *ps_dec)
{
UWORD32 u4_start_code;
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while(u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX)
{
impeg2d_bit_stream_flush(ps_stream,8);
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static int cieavalidate(i_ctx_t *i_ctx_p, ref *space, float *values, int num_comps)
{
os_ptr op = osp;
if (num_comps < 1)
return_error(gs_error_stackunderflow);
if (!r_has_type(op, t_integer) && !r_has_type(op, t_real))
return_error(gs_error_typecheck);
return 0;
}
CWE ID: CWE-704
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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_DEFINE3(osf_sysinfo, int, command, char __user *, buf, long, count)
{
const char *sysinfo_table[] = {
utsname()->sysname,
utsname()->nodename,
utsname()->release,
utsname()->version,
utsname()->machine,
"alpha", /* instruction set architecture */
"dummy", /* hardware serial number */
"dummy", /* hardware manufacturer */
"dummy", /* secure RPC domain */
};
unsigned long offset;
const char *res;
long len, err = -EINVAL;
offset = command-1;
if (offset >= ARRAY_SIZE(sysinfo_table)) {
/* Digital UNIX has a few unpublished interfaces here */
printk("sysinfo(%d)", command);
goto out;
}
down_read(&uts_sem);
res = sysinfo_table[offset];
len = strlen(res)+1;
if (len > count)
len = count;
if (copy_to_user(buf, res, len))
err = -EFAULT;
else
err = 0;
up_read(&uts_sem);
out:
return err;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static v8::Handle<v8::Value> setValueAndClosePopupCallback(const v8::Arguments& args)
{
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
DOMWindow* imp = V8DOMWindow::toNative(args.Data()->ToObject());
EXCEPTION_BLOCK(int, intValue, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, stringValue, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
DOMWindowPagePopup::setValueAndClosePopup(imp, intValue, stringValue);
return v8::Undefined();
}
CWE ID:
Target: 1
Example 2:
Code: V0CustomElementRegistrationContext* DocumentInit::RegistrationContext(
Document* document) const {
if (!document->IsHTMLDocument() && !document->IsXHTMLDocument())
return nullptr;
if (create_new_registration_context_)
return V0CustomElementRegistrationContext::Create();
return registration_context_.Get();
}
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 ByteAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.Holder();
TestObject* impl = V8TestObject::ToImpl(holder);
V8SetReturnValueInt(info, impl->byteAttribute());
}
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 ChromeContentRendererClient::RenderThreadStarted() {
chrome_observer_.reset(new ChromeRenderProcessObserver());
extension_dispatcher_.reset(new ExtensionDispatcher());
histogram_snapshots_.reset(new RendererHistogramSnapshots());
net_predictor_.reset(new RendererNetPredictor());
spellcheck_.reset(new SpellCheck());
visited_link_slave_.reset(new VisitedLinkSlave());
phishing_classifier_.reset(safe_browsing::PhishingClassifierFilter::Create());
RenderThread* thread = RenderThread::current();
thread->AddFilter(new DevToolsAgentFilter());
thread->AddObserver(chrome_observer_.get());
thread->AddObserver(extension_dispatcher_.get());
thread->AddObserver(histogram_snapshots_.get());
thread->AddObserver(phishing_classifier_.get());
thread->AddObserver(spellcheck_.get());
thread->AddObserver(visited_link_slave_.get());
thread->RegisterExtension(extensions_v8::ExternalExtension::Get());
thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get());
thread->RegisterExtension(extensions_v8::SearchBoxExtension::Get());
v8::Extension* search_extension = extensions_v8::SearchExtension::Get();
if (search_extension)
thread->RegisterExtension(search_extension);
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
thread->RegisterExtension(DomAutomationV8Extension::Get());
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableIPCFuzzing)) {
thread->channel()->set_outgoing_message_filter(LoadExternalIPCFuzzer());
}
WebString chrome_ui_scheme(ASCIIToUTF16(chrome::kChromeUIScheme));
WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(chrome_ui_scheme);
WebString extension_scheme(ASCIIToUTF16(chrome::kExtensionScheme));
WebSecurityPolicy::registerURLSchemeAsSecure(extension_scheme);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: Eina_Bool ewk_frame_contents_alternate_set(Evas_Object* ewkFrame, const char* contents, size_t contentsSize, const char* mimeType, const char* encoding, const char* baseUri, const char* unreachableUri)
{
EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData, false);
EINA_SAFETY_ON_NULL_RETURN_VAL(smartData->frame, false);
EINA_SAFETY_ON_NULL_RETURN_VAL(contents, false);
EINA_SAFETY_ON_NULL_RETURN_VAL(unreachableUri, false);
return _ewk_frame_contents_set_internal
(smartData, contents, contentsSize, mimeType, encoding, baseUri,
unreachableUri);
}
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: cid_parse_font_matrix( CID_Face face,
CID_Parser* parser )
{
CID_FaceDict dict;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts )
{
FT_Matrix* matrix;
FT_Vector* offset;
dict = face->cid.font_dicts + parser->num_dict;
matrix = &dict->font_matrix;
offset = &dict->font_offset;
(void)cid_parser_to_fixed_array( parser, 6, temp, 3 );
temp_scale = FT_ABS( temp[3] );
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
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: SPL_METHOD(SplObjectStorage, unserialize)
{
spl_SplObjectStorage *intern = Z_SPLOBJSTORAGE_P(getThis());
char *buf;
size_t buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
zval entry, inf;
zval *pcount, *pmembers;
spl_SplObjectStorageElement *element;
zend_long count;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
return;
}
/* storage */
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (*p!= 'x' || *++p != ':') {
goto outexcept;
}
++p;
pcount = var_tmp_var(&var_hash);
if (!php_var_unserialize(pcount, &p, s + buf_len, &var_hash) || Z_TYPE_P(pcount) != IS_LONG) {
goto outexcept;
}
--p; /* for ';' */
count = Z_LVAL_P(pcount);
while (count-- > 0) {
spl_SplObjectStorageElement *pelement;
zend_string *hash;
if (*p != ';') {
goto outexcept;
}
++p;
if(*p != 'O' && *p != 'C' && *p != 'r') {
goto outexcept;
}
/* store reference to allow cross-references between different elements */
if (!php_var_unserialize(&entry, &p, s + buf_len, &var_hash)) {
goto outexcept;
}
if (Z_TYPE(entry) != IS_OBJECT) {
zval_ptr_dtor(&entry);
goto outexcept;
}
if (*p == ',') { /* new version has inf */
++p;
if (!php_var_unserialize(&inf, &p, s + buf_len, &var_hash)) {
zval_ptr_dtor(&entry);
goto outexcept;
}
} else {
ZVAL_UNDEF(&inf);
}
hash = spl_object_storage_get_hash(intern, getThis(), &entry);
if (!hash) {
zval_ptr_dtor(&entry);
zval_ptr_dtor(&inf);
goto outexcept;
}
pelement = spl_object_storage_get(intern, hash);
spl_object_storage_free_hash(intern, hash);
if (pelement) {
if (!Z_ISUNDEF(pelement->inf)) {
var_push_dtor(&var_hash, &pelement->inf);
}
if (!Z_ISUNDEF(pelement->obj)) {
var_push_dtor(&var_hash, &pelement->obj);
}
}
element = spl_object_storage_attach(intern, getThis(), &entry, Z_ISUNDEF(inf)?NULL:&inf);
var_replace(&var_hash, &entry, &element->obj);
var_replace(&var_hash, &inf, &element->inf);
zval_ptr_dtor(&entry);
ZVAL_UNDEF(&entry);
zval_ptr_dtor(&inf);
ZVAL_UNDEF(&inf);
}
if (*p != ';') {
goto outexcept;
}
++p;
/* members */
if (*p!= 'm' || *++p != ':') {
goto outexcept;
}
++p;
pmembers = var_tmp_var(&var_hash);
if (!php_var_unserialize(pmembers, &p, s + buf_len, &var_hash) || Z_TYPE_P(pmembers) != IS_ARRAY) {
goto outexcept;
}
/* copy members */
object_properties_load(&intern->std, Z_ARRVAL_P(pmembers));
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
outexcept:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Error at offset %pd of %d bytes", (zend_long)((char*)p - buf), buf_len);
return;
} /* }}} */
ZEND_BEGIN_ARG_INFO(arginfo_Object, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_ARG_INFO(0, inf)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0)
ZEND_ARG_INFO(0, serialized)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0)
ZEND_ARG_INFO(0, info)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO();
ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1)
ZEND_ARG_INFO(0, object)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry spl_funcs_SplObjectStorage[] = {
SPL_ME(SplObjectStorage, attach, arginfo_attach, 0)
SPL_ME(SplObjectStorage, detach, arginfo_Object, 0)
SPL_ME(SplObjectStorage, contains, arginfo_Object, 0)
SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0)
SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0)
SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0)
SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0)
/* Countable */
SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0)
/* Iterator */
SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0)
SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0)
/* Serializable */
SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0)
SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0)
/* ArrayAccess */
SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0)
SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0)
SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0)
SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0)
{NULL, NULL, NULL}
};
typedef enum {
MIT_NEED_ANY = 0,
MIT_NEED_ALL = 1,
MIT_KEYS_NUMERIC = 0,
MIT_KEYS_ASSOC = 2
} MultipleIteratorFlags;
#define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1
#define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2
/* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC])
CWE ID: CWE-119
Target: 1
Example 2:
Code: cmsBool Type_ColorantTable_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr;
int i, nColors;
nColors = cmsNamedColorCount(NamedColorList);
if (!_cmsWriteUInt32Number(io, nColors)) return FALSE;
for (i=0; i < nColors; i++) {
char root[33];
cmsUInt16Number PCS[3];
if (!cmsNamedColorInfo(NamedColorList, i, root, NULL, NULL, PCS, NULL)) return 0;
root[32] = 0;
if (!io ->Write(io, 32, root)) return FALSE;
if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE;
}
return TRUE;
cmsUNUSED_PARAMETER(nItems);
cmsUNUSED_PARAMETER(self);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void implementedAsVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
imp->implementedAsMethodName();
}
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 rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len)
{
unsigned char l, n = 0;
char callsign[11];
do {
switch (*p & 0xC0) {
case 0x00:
p += 2;
n += 2;
len -= 2;
break;
case 0x40:
p += 3;
n += 3;
len -= 3;
break;
case 0x80:
p += 4;
n += 4;
len -= 4;
break;
case 0xC0:
l = p[1];
if (*p == FAC_CCITT_DEST_NSAP) {
memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN);
memcpy(callsign, p + 12, l - 10);
callsign[l - 10] = '\0';
asc2ax(&facilities->source_call, callsign);
}
if (*p == FAC_CCITT_SRC_NSAP) {
memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN);
memcpy(callsign, p + 12, l - 10);
callsign[l - 10] = '\0';
asc2ax(&facilities->dest_call, callsign);
}
p += l + 2;
n += l + 2;
len -= l + 2;
break;
}
} while (*p != 0x00 && len > 0);
return n;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static struct pending_req *alloc_req(struct xen_blkif *blkif)
{
struct pending_req *req = NULL;
unsigned long flags;
spin_lock_irqsave(&blkif->pending_free_lock, flags);
if (!list_empty(&blkif->pending_free)) {
req = list_entry(blkif->pending_free.next, struct pending_req,
free_list);
list_del(&req->free_list);
}
spin_unlock_irqrestore(&blkif->pending_free_lock, flags);
return req;
}
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 mem_read(jas_stream_obj_t *obj, char *buf, int cnt)
{
int n;
assert(cnt >= 0);
assert(buf);
JAS_DBGLOG(100, ("mem_read(%p, %p, %d)\n", obj, buf, cnt));
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
n = m->len_ - m->pos_;
cnt = JAS_MIN(n, cnt);
memcpy(buf, &m->buf_[m->pos_], cnt);
m->pos_ += cnt;
return cnt;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode,
char __user *buf, size_t len, bool compat)
{
struct file *file = req->ki_filp;
ssize_t ret;
unsigned long nr_segs;
int rw;
fmode_t mode;
aio_rw_op *rw_op;
rw_iter_op *iter_op;
struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
struct iov_iter iter;
switch (opcode) {
case IOCB_CMD_PREAD:
case IOCB_CMD_PREADV:
mode = FMODE_READ;
rw = READ;
rw_op = file->f_op->aio_read;
iter_op = file->f_op->read_iter;
goto rw_common;
case IOCB_CMD_PWRITE:
case IOCB_CMD_PWRITEV:
mode = FMODE_WRITE;
rw = WRITE;
rw_op = file->f_op->aio_write;
iter_op = file->f_op->write_iter;
goto rw_common;
rw_common:
if (unlikely(!(file->f_mode & mode)))
return -EBADF;
if (!rw_op && !iter_op)
return -EINVAL;
if (opcode == IOCB_CMD_PREADV || opcode == IOCB_CMD_PWRITEV)
ret = aio_setup_vectored_rw(req, rw, buf, &nr_segs,
&len, &iovec, compat);
else
ret = aio_setup_single_vector(req, rw, buf, &nr_segs,
len, iovec);
if (!ret)
ret = rw_verify_area(rw, file, &req->ki_pos, len);
if (ret < 0) {
if (iovec != inline_vecs)
kfree(iovec);
return ret;
}
len = ret;
/* XXX: move/kill - rw_verify_area()? */
/* This matches the pread()/pwrite() logic */
if (req->ki_pos < 0) {
ret = -EINVAL;
break;
}
if (rw == WRITE)
file_start_write(file);
if (iter_op) {
iov_iter_init(&iter, rw, iovec, nr_segs, len);
ret = iter_op(req, &iter);
} else {
ret = rw_op(req, iovec, nr_segs, req->ki_pos);
}
if (rw == WRITE)
file_end_write(file);
break;
case IOCB_CMD_FDSYNC:
if (!file->f_op->aio_fsync)
return -EINVAL;
ret = file->f_op->aio_fsync(req, 1);
break;
case IOCB_CMD_FSYNC:
if (!file->f_op->aio_fsync)
return -EINVAL;
ret = file->f_op->aio_fsync(req, 0);
break;
default:
pr_debug("EINVAL: no operation provided\n");
return -EINVAL;
}
if (iovec != inline_vecs)
kfree(iovec);
if (ret != -EIOCBQUEUED) {
/*
* There's no easy way to restart the syscall since other AIO's
* may be already running. Just fail this IO with EINTR.
*/
if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
ret == -ERESTARTNOHAND ||
ret == -ERESTART_RESTARTBLOCK))
ret = -EINTR;
aio_complete(req, ret, 0);
}
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: void RenderThreadImpl::OnTrimMemoryImmediately() {
if (blink::MainThreadIsolate()) {
blink::MainThreadIsolate()->MemoryPressureNotification(
v8::MemoryPressureLevel::kCritical);
blink::MemoryPressureNotificationToWorkerThreadIsolates(
v8::MemoryPressureLevel::kCritical);
}
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void xsltDebugSetDefaultTrace(xsltDebugTraceCodes val) {
xsltDefaultTrace = 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: long ssl3_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
{
CERT *cert;
cert = ctx->cert;
switch (cmd) {
#ifndef OPENSSL_NO_RSA
case SSL_CTRL_NEED_TMP_RSA:
if ((cert->rsa_tmp == NULL) &&
((cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) ||
(EVP_PKEY_size(cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) >
(512 / 8)))
)
return (1);
else
return (0);
/* break; */
case SSL_CTRL_SET_TMP_RSA:
{
RSA *rsa;
int i;
rsa = (RSA *)parg;
i = 1;
if (rsa == NULL)
i = 0;
else {
if ((rsa = RSAPrivateKey_dup(rsa)) == NULL)
i = 0;
}
if (!i) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_RSA_LIB);
return (0);
} else {
if (cert->rsa_tmp != NULL)
RSA_free(cert->rsa_tmp);
cert->rsa_tmp = rsa;
return (1);
}
}
/* break; */
case SSL_CTRL_SET_TMP_RSA_CB:
{
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
return (0);
}
break;
#endif
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB);
return 0;
}
if (!(ctx->options & SSL_OP_SINGLE_DH_USE)) {
if (!DH_generate_key(new)) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB);
DH_free(new);
return 0;
}
}
if (cert->dh_tmp != NULL)
DH_free(cert->dh_tmp);
cert->dh_tmp = new;
if ((new = DHparams_dup(dh)) == NULL) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB);
return 0;
}
if (!(ctx->options & SSL_OP_SINGLE_DH_USE)) {
if (!DH_generate_key(new)) {
SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB);
DH_free(new);
return 0;
}
}
if (cert->dh_tmp != NULL)
DH_free(cert->dh_tmp);
cert->dh_tmp = new;
return 1;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void vmx_post_block(struct kvm_vcpu *vcpu)
{
struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
struct pi_desc old, new;
unsigned int dest;
unsigned long flags;
if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP))
return;
do {
old.control = new.control = pi_desc->control;
dest = cpu_physical_id(vcpu->cpu);
if (x2apic_enabled())
new.ndst = dest;
else
new.ndst = (dest << 8) & 0xFF00;
/* Allow posting non-urgent interrupts */
new.sn = 0;
/* set 'NV' to 'notification vector' */
new.nv = POSTED_INTR_VECTOR;
} while (cmpxchg(&pi_desc->control, old.control,
new.control) != old.control);
if(vcpu->pre_pcpu != -1) {
spin_lock_irqsave(
&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
list_del(&vcpu->blocked_vcpu_list);
spin_unlock_irqrestore(
&per_cpu(blocked_vcpu_on_cpu_lock,
vcpu->pre_pcpu), flags);
vcpu->pre_pcpu = -1;
}
}
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: person_set_speed(person_t* person, double x_speed, double y_speed)
{
person->speed_x = x_speed;
person->speed_y = y_speed;
}
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 SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImeConfig: IBus connection is not alive";
return false;
}
bool is_preload_engines = false;
std::vector<std::string> string_list;
if ((value.type == ImeConfigValue::kValueTypeStringList) &&
(section == kGeneralSectionName) &&
(config_name == kPreloadEnginesConfigName)) {
FilterInputMethods(value.string_list_value, &string_list);
is_preload_engines = true;
} else {
string_list = value.string_list_value;
}
GVariant* variant = NULL;
switch (value.type) {
case ImeConfigValue::kValueTypeString:
variant = g_variant_new_string(value.string_value.c_str());
break;
case ImeConfigValue::kValueTypeInt:
variant = g_variant_new_int32(value.int_value);
break;
case ImeConfigValue::kValueTypeBool:
variant = g_variant_new_boolean(value.bool_value);
break;
case ImeConfigValue::kValueTypeStringList:
GVariantBuilder variant_builder;
g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as"));
const size_t size = string_list.size(); // don't use string_list_value.
for (size_t i = 0; i < size; ++i) {
g_variant_builder_add(&variant_builder, "s", string_list[i].c_str());
}
variant = g_variant_builder_end(&variant_builder);
break;
}
if (!variant) {
LOG(ERROR) << "SetImeConfig: variant is NULL";
return false;
}
DCHECK(g_variant_is_floating(variant));
ibus_config_set_value_async(ibus_config_,
section.c_str(),
config_name.c_str(),
variant,
-1, // use the default ibus timeout
NULL, // cancellable
SetImeConfigCallback,
g_object_ref(ibus_config_));
if (is_preload_engines) {
DLOG(INFO) << "SetImeConfig: " << section << "/" << config_name
<< ": " << value.ToString();
}
return true;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void staticReadOnlyLongAttrAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectV8Internal::staticReadOnlyLongAttrAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SYSCALL_DEFINE4(osf_wait4, pid_t, pid, int __user *, ustatus, int, options,
struct rusage32 __user *, ur)
{
struct rusage r;
long ret, err;
mm_segment_t old_fs;
if (!ur)
return sys_wait4(pid, ustatus, options, NULL);
old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_wait4(pid, ustatus, options, (struct rusage __user *) &r);
set_fs (old_fs);
if (!access_ok(VERIFY_WRITE, ur, sizeof(*ur)))
return -EFAULT;
err = 0;
err |= __put_user(r.ru_utime.tv_sec, &ur->ru_utime.tv_sec);
err |= __put_user(r.ru_utime.tv_usec, &ur->ru_utime.tv_usec);
err |= __put_user(r.ru_stime.tv_sec, &ur->ru_stime.tv_sec);
err |= __put_user(r.ru_stime.tv_usec, &ur->ru_stime.tv_usec);
err |= __put_user(r.ru_maxrss, &ur->ru_maxrss);
err |= __put_user(r.ru_ixrss, &ur->ru_ixrss);
err |= __put_user(r.ru_idrss, &ur->ru_idrss);
err |= __put_user(r.ru_isrss, &ur->ru_isrss);
err |= __put_user(r.ru_minflt, &ur->ru_minflt);
err |= __put_user(r.ru_majflt, &ur->ru_majflt);
err |= __put_user(r.ru_nswap, &ur->ru_nswap);
err |= __put_user(r.ru_inblock, &ur->ru_inblock);
err |= __put_user(r.ru_oublock, &ur->ru_oublock);
err |= __put_user(r.ru_msgsnd, &ur->ru_msgsnd);
err |= __put_user(r.ru_msgrcv, &ur->ru_msgrcv);
err |= __put_user(r.ru_nsignals, &ur->ru_nsignals);
err |= __put_user(r.ru_nvcsw, &ur->ru_nvcsw);
err |= __put_user(r.ru_nivcsw, &ur->ru_nivcsw);
return err ? err : ret;
}
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 SetBuildInfoAnnotations(std::map<std::string, std::string>* annotations) {
base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
(*annotations)["android_build_id"] = info->android_build_id();
(*annotations)["android_build_fp"] = info->android_build_fp();
(*annotations)["device"] = info->device();
(*annotations)["model"] = info->model();
(*annotations)["brand"] = info->brand();
(*annotations)["board"] = info->board();
(*annotations)["installer_package_name"] = info->installer_package_name();
(*annotations)["abi_name"] = info->abi_name();
(*annotations)["custom_themes"] = info->custom_themes();
(*annotations)["resources_verison"] = info->resources_version();
(*annotations)["gms_core_version"] = info->gms_version_code();
if (info->firebase_app_id()[0] != '\0') {
(*annotations)["package"] = std::string(info->firebase_app_id()) + " v" +
info->package_version_code() + " (" +
info->package_version_name() + ")";
}
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static struct sk_buff *batadv_frag_create(struct sk_buff *skb,
struct batadv_frag_packet *frag_head,
unsigned int mtu)
{
struct sk_buff *skb_fragment;
unsigned header_size = sizeof(*frag_head);
unsigned fragment_size = mtu - header_size;
skb_fragment = netdev_alloc_skb(NULL, mtu + ETH_HLEN);
if (!skb_fragment)
goto err;
skb->priority = TC_PRIO_CONTROL;
/* Eat the last mtu-bytes of the skb */
skb_reserve(skb_fragment, header_size + ETH_HLEN);
skb_split(skb, skb_fragment, skb->len - fragment_size);
/* Add the header */
skb_push(skb_fragment, header_size);
memcpy(skb_fragment->data, frag_head, header_size);
err:
return skb_fragment;
}
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 RenderViewImpl::didCommitProvisionalLoad(WebFrame* frame,
bool is_new_navigation) {
DocumentState* document_state =
DocumentState::FromDataSource(frame->dataSource());
NavigationState* navigation_state = document_state->navigation_state();
if (document_state->commit_load_time().is_null())
document_state->set_commit_load_time(Time::Now());
if (is_new_navigation) {
UpdateSessionHistory(frame);
page_id_ = next_page_id_++;
if (GetLoadingUrl(frame) != GURL("about:swappedout")) {
history_list_offset_++;
if (history_list_offset_ >= content::kMaxSessionHistoryEntries)
history_list_offset_ = content::kMaxSessionHistoryEntries - 1;
history_list_length_ = history_list_offset_ + 1;
history_page_ids_.resize(history_list_length_, -1);
history_page_ids_[history_list_offset_] = page_id_;
}
} else {
if (navigation_state->pending_page_id() != -1 &&
navigation_state->pending_page_id() != page_id_ &&
!navigation_state->request_committed()) {
UpdateSessionHistory(frame);
page_id_ = navigation_state->pending_page_id();
history_list_offset_ = navigation_state->pending_history_list_offset();
DCHECK(history_list_length_ <= 0 ||
history_list_offset_ < 0 ||
history_list_offset_ >= history_list_length_ ||
history_page_ids_[history_list_offset_] == page_id_);
}
}
FOR_EACH_OBSERVER(RenderViewObserver, observers_,
DidCommitProvisionalLoad(frame, is_new_navigation));
navigation_state->set_request_committed(true);
UpdateURL(frame);
completed_client_redirect_src_ = Referrer();
UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
}
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: bool IsTraceEventArgsWhitelisted(const char* category_group_name,
const char* event_name) {
if (base::MatchPattern(category_group_name, "toplevel") &&
base::MatchPattern(event_name, "*")) {
return true;
}
return false;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: AutocompleteProvider::ACProviderListener::~ACProviderListener() {
}
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: status_t BnSoundTriggerHwService::onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
switch(code) {
case LIST_MODULES: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
unsigned int numModulesReq = data.readInt32();
unsigned int numModules = numModulesReq;
struct sound_trigger_module_descriptor *modules =
(struct sound_trigger_module_descriptor *)calloc(numModulesReq,
sizeof(struct sound_trigger_module_descriptor));
status_t status = listModules(modules, &numModules);
reply->writeInt32(status);
reply->writeInt32(numModules);
ALOGV("LIST_MODULES status %d got numModules %d", status, numModules);
if (status == NO_ERROR) {
if (numModulesReq > numModules) {
numModulesReq = numModules;
}
reply->write(modules,
numModulesReq * sizeof(struct sound_trigger_module_descriptor));
}
free(modules);
return NO_ERROR;
}
case ATTACH: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
sound_trigger_module_handle_t handle;
data.read(&handle, sizeof(sound_trigger_module_handle_t));
sp<ISoundTriggerClient> client =
interface_cast<ISoundTriggerClient>(data.readStrongBinder());
sp<ISoundTrigger> module;
status_t status = attach(handle, client, module);
reply->writeInt32(status);
if (module != 0) {
reply->writeInt32(1);
reply->writeStrongBinder(IInterface::asBinder(module));
} else {
reply->writeInt32(0);
}
return NO_ERROR;
} break;
case SET_CAPTURE_STATE: {
CHECK_INTERFACE(ISoundTriggerHwService, data, reply);
reply->writeInt32(setCaptureState((bool)data.readInt32()));
return NO_ERROR;
} break;
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool BluetoothDeviceChromeOS::ExpectingPasskey() const {
return !passkey_callback_.is_null();
}
CWE ID:
Target: 1
Example 2:
Code: void CWebServer::Cmd_GetSceneActivations(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string idx = request::findValue(&req, "idx");
if (idx.empty())
return;
root["status"] = "OK";
root["title"] = "GetSceneActivations";
std::vector<std::vector<std::string> > result, result2;
result = m_sql.safe_query("SELECT Activators, SceneType FROM Scenes WHERE (ID==%q)", idx.c_str());
if (result.empty())
return;
int ii = 0;
std::string Activators = result[0][0];
int SceneType = atoi(result[0][1].c_str());
if (!Activators.empty())
{
std::vector<std::string> arrayActivators;
StringSplit(Activators, ";", arrayActivators);
for (const auto & ittAct : arrayActivators)
{
std::string sCodeCmd = ittAct;
std::vector<std::string> arrayCode;
StringSplit(sCodeCmd, ":", arrayCode);
std::string sID = arrayCode[0];
int sCode = 0;
if (arrayCode.size() == 2)
{
sCode = atoi(arrayCode[1].c_str());
}
result2 = m_sql.safe_query("SELECT Name, [Type], SubType, SwitchType FROM DeviceStatus WHERE (ID==%q)", sID.c_str());
if (!result2.empty())
{
std::vector<std::string> sd = result2[0];
std::string lstatus = "-";
if ((SceneType == 0) && (arrayCode.size() == 2))
{
unsigned char devType = (unsigned char)atoi(sd[1].c_str());
unsigned char subType = (unsigned char)atoi(sd[2].c_str());
_eSwitchType switchtype = (_eSwitchType)atoi(sd[3].c_str());
int nValue = sCode;
std::string sValue = "";
int llevel = 0;
bool bHaveDimmer = false;
bool bHaveGroupCmd = false;
int maxDimLevel = 0;
GetLightStatus(devType, subType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd);
}
uint64_t dID = std::strtoull(sID.c_str(), nullptr, 10);
root["result"][ii]["idx"] = dID;
root["result"][ii]["name"] = sd[0];
root["result"][ii]["code"] = sCode;
root["result"][ii]["codestr"] = lstatus;
ii++;
}
}
}
}
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: SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen)
{
struct socket *sock;
struct sockaddr_storage address;
int err, fput_needed;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (sock) {
err = move_addr_to_kernel(umyaddr, addrlen, (struct sockaddr *)&address);
if (err >= 0) {
err = security_socket_bind(sock,
(struct sockaddr *)&address,
addrlen);
if (!err)
err = sock->ops->bind(sock,
(struct sockaddr *)
&address, addrlen);
}
fput_light(sock->file, fput_needed);
}
return err;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void scsi_dma_restart_bh(void *opaque)
{
SCSIDiskState *s = opaque;
SCSIRequest *req;
SCSIDiskReq *r;
qemu_bh_delete(s->bh);
s->bh = NULL;
QTAILQ_FOREACH(req, &s->qdev.requests, next) {
r = DO_UPCAST(SCSIDiskReq, req, req);
if (r->status & SCSI_REQ_STATUS_RETRY) {
int status = r->status;
int ret;
r->status &=
~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK);
switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) {
case SCSI_REQ_STATUS_RETRY_READ:
scsi_read_data(&r->req);
break;
case SCSI_REQ_STATUS_RETRY_WRITE:
scsi_write_data(&r->req);
break;
case SCSI_REQ_STATUS_RETRY_FLUSH:
ret = scsi_disk_emulate_command(r, r->iov.iov_base);
if (ret == 0) {
scsi_req_complete(&r->req, GOOD);
}
}
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int channel_exec (lua_State *L, int status, lua_KContext ctx) {
int rc;
LIBSSH2_CHANNEL **channel = (LIBSSH2_CHANNEL **) lua_touserdata(L, 2);
const char *cmd = luaL_checkstring(L, 3);
while ((rc = libssh2_channel_exec(*channel, cmd)) == LIBSSH2_ERROR_EAGAIN) {
luaL_getmetafield(L, 1, "filter");
lua_pushvalue(L, 1);
lua_callk(L, 1, 0, 0, channel_exec);
}
if (rc != 0)
return luaL_error(L, "Error executing command");
return 0;
}
CWE ID: CWE-415
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ext4_xattr_block_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext4_xattr_entry *entry;
size_t size;
int error;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
error = -ENODATA;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(inode, bh)) {
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
ext4_xattr_cache_insert(ext4_mb_cache, bh);
entry = BFIRST(bh);
error = ext4_xattr_find_entry(&entry, name_index, name, bh->b_size, 1);
if (error == -EFSCORRUPTED)
goto bad_block;
if (error)
goto cleanup;
size = le32_to_cpu(entry->e_value_size);
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
size);
}
error = size;
cleanup:
brelse(bh);
return error;
}
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: CompositedLayerRasterInvalidatorTest& Properties(
const TransformPaintPropertyNode* t,
const ClipPaintPropertyNode* c = ClipPaintPropertyNode::Root(),
const EffectPaintPropertyNode* e = EffectPaintPropertyNode::Root()) {
auto& state = data_.chunks.back().properties;
state.SetTransform(t);
state.SetClip(c);
state.SetEffect(e);
return *this;
}
CWE ID:
Target: 1
Example 2:
Code: static void queue_add(struct queue *head, struct queue *q)
{
struct queue *pos = head->q_prev;
q->q_prev = pos;
q->q_next = pos->q_next;
q->q_next->q_prev = q;
pos->q_next = q;
}
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 hub_port_debounce(struct usb_hub *hub, int port1, bool must_be_connected)
{
int ret;
u16 portchange, portstatus;
unsigned connection = 0xffff;
int total_time, stable_time = 0;
struct usb_port *port_dev = hub->ports[port1 - 1];
for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
ret = hub_port_status(hub, port1, &portstatus, &portchange);
if (ret < 0)
return ret;
if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
(portstatus & USB_PORT_STAT_CONNECTION) == connection) {
if (!must_be_connected ||
(connection == USB_PORT_STAT_CONNECTION))
stable_time += HUB_DEBOUNCE_STEP;
if (stable_time >= HUB_DEBOUNCE_STABLE)
break;
} else {
stable_time = 0;
connection = portstatus & USB_PORT_STAT_CONNECTION;
}
if (portchange & USB_PORT_STAT_C_CONNECTION) {
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION);
}
if (total_time >= HUB_DEBOUNCE_TIMEOUT)
break;
msleep(HUB_DEBOUNCE_STEP);
}
dev_dbg(&port_dev->dev, "debounce total %dms stable %dms status 0x%x\n",
total_time, stable_time, portstatus);
if (stable_time < HUB_DEBOUNCE_STABLE)
return -ETIMEDOUT;
return portstatus;
}
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: OMX_ERRORTYPE omx_vdec::free_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_U32 port,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned int nPortIndex;
(void) hComp;
DEBUG_PRINT_LOW("In for decoder free_buffer");
if (m_state == OMX_StateIdle &&
(BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) {
DEBUG_PRINT_LOW(" free buffer while Component in Loading pending");
} else if ((m_inp_bEnabled == OMX_FALSE && port == OMX_CORE_INPUT_PORT_INDEX)||
(m_out_bEnabled == OMX_FALSE && port == OMX_CORE_OUTPUT_PORT_INDEX)) {
DEBUG_PRINT_LOW("Free Buffer while port %u disabled", (unsigned int)port);
} else if ((port == OMX_CORE_INPUT_PORT_INDEX &&
BITMASK_PRESENT(&m_flags, OMX_COMPONENT_INPUT_ENABLE_PENDING)) ||
(port == OMX_CORE_OUTPUT_PORT_INDEX &&
BITMASK_PRESENT(&m_flags, OMX_COMPONENT_OUTPUT_ENABLE_PENDING))) {
DEBUG_PRINT_LOW("Free Buffer while port %u enable pending", (unsigned int)port);
} else if (m_state == OMX_StateExecuting || m_state == OMX_StatePause) {
DEBUG_PRINT_ERROR("Invalid state to free buffer,ports need to be disabled");
post_event(OMX_EventError,
OMX_ErrorPortUnpopulated,
OMX_COMPONENT_GENERATE_EVENT);
return OMX_ErrorIncorrectStateOperation;
} else if (m_state != OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Invalid state to free buffer,port lost Buffers");
post_event(OMX_EventError,
OMX_ErrorPortUnpopulated,
OMX_COMPONENT_GENERATE_EVENT);
}
if (port == OMX_CORE_INPUT_PORT_INDEX) {
/*Check if arbitrary bytes*/
if (!arbitrary_bytes && !input_use_buffer)
nPortIndex = buffer - m_inp_mem_ptr;
else
nPortIndex = buffer - m_inp_heap_ptr;
DEBUG_PRINT_LOW("free_buffer on i/p port - Port idx %d", nPortIndex);
if (nPortIndex < drv_ctx.ip_buf.actualcount) {
BITMASK_CLEAR(&m_inp_bm_count,nPortIndex);
BITMASK_CLEAR(&m_heap_inp_bm_count,nPortIndex);
if (input_use_buffer == true) {
DEBUG_PRINT_LOW("Free pmem Buffer index %d",nPortIndex);
if (m_phdr_pmem_ptr)
free_input_buffer(m_phdr_pmem_ptr[nPortIndex]);
} else {
if (arbitrary_bytes) {
if (m_phdr_pmem_ptr)
free_input_buffer(nPortIndex,m_phdr_pmem_ptr[nPortIndex]);
else
free_input_buffer(nPortIndex,NULL);
} else
free_input_buffer(buffer);
}
m_inp_bPopulated = OMX_FALSE;
if(release_input_done())
release_buffers(this, VDEC_BUFFER_TYPE_INPUT);
/*Free the Buffer Header*/
if (release_input_done()) {
DEBUG_PRINT_HIGH("ALL input buffers are freed/released");
free_input_buffer_header();
}
} else {
DEBUG_PRINT_ERROR("Error: free_buffer ,Port Index Invalid");
eRet = OMX_ErrorBadPortIndex;
}
if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING)
&& release_input_done()) {
DEBUG_PRINT_LOW("MOVING TO DISABLED STATE");
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING);
post_event(OMX_CommandPortDisable,
OMX_CORE_INPUT_PORT_INDEX,
OMX_COMPONENT_GENERATE_EVENT);
}
} else if (port == OMX_CORE_OUTPUT_PORT_INDEX) {
nPortIndex = buffer - client_buffers.get_il_buf_hdr();
if (nPortIndex < drv_ctx.op_buf.actualcount) {
DEBUG_PRINT_LOW("free_buffer on o/p port - Port idx %d", nPortIndex);
BITMASK_CLEAR(&m_out_bm_count,nPortIndex);
m_out_bPopulated = OMX_FALSE;
client_buffers.free_output_buffer (buffer);
if(release_output_done()) {
release_buffers(this, VDEC_BUFFER_TYPE_OUTPUT);
}
if (release_output_done()) {
free_output_buffer_header();
}
} else {
DEBUG_PRINT_ERROR("Error: free_buffer , Port Index Invalid");
eRet = OMX_ErrorBadPortIndex;
}
if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING)
&& release_output_done()) {
DEBUG_PRINT_LOW("FreeBuffer : If any Disable event pending,post it");
DEBUG_PRINT_LOW("MOVING TO DISABLED STATE");
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING);
#ifdef _ANDROID_ICS_
if (m_enable_android_native_buffers) {
DEBUG_PRINT_LOW("FreeBuffer - outport disabled: reset native buffers");
memset(&native_buffer, 0 ,(sizeof(struct nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS));
}
#endif
post_event(OMX_CommandPortDisable,
OMX_CORE_OUTPUT_PORT_INDEX,
OMX_COMPONENT_GENERATE_EVENT);
}
} else {
eRet = OMX_ErrorBadPortIndex;
}
if ((eRet == OMX_ErrorNone) &&
(BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) {
if (release_done()) {
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_LOADING_PENDING);
post_event(OMX_CommandStateSet, OMX_StateLoaded,
OMX_COMPONENT_GENERATE_EVENT);
}
}
return eRet;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int l2cap_sock_accept(struct socket *sock, struct socket *newsock, int flags)
{
DECLARE_WAITQUEUE(wait, current);
struct sock *sk = sock->sk, *nsk;
long timeo;
int err = 0;
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
BT_DBG("sk %p timeo %ld", sk, timeo);
/* Wait for an incoming connection. (wake-one). */
add_wait_queue_exclusive(sk_sleep(sk), &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (sk->sk_state != BT_LISTEN) {
err = -EBADFD;
break;
}
nsk = bt_accept_dequeue(sk, newsock);
if (nsk)
break;
if (!timeo) {
err = -EAGAIN;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock_nested(sk, SINGLE_DEPTH_NESTING);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
if (err)
goto done;
newsock->state = SS_CONNECTED;
BT_DBG("new socket %p", nsk);
done:
release_sock(sk);
return err;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MockPrinter::UpdateSettings(int cookie,
PrintMsg_PrintPages_Params* params,
const std::vector<int>& pages) {
EXPECT_EQ(document_cookie_, cookie);
params->Reset();
params->pages = pages;
SetPrintParams(&(params->params));
printer_status_ = PRINTER_PRINTING;
}
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: virtual void SetUp() {
const tuple<int, int, SubpelVarianceFunctionType>& params =
this->GetParam();
log2width_ = get<0>(params);
width_ = 1 << log2width_;
log2height_ = get<1>(params);
height_ = 1 << log2height_;
subpel_variance_ = get<2>(params);
rnd(ACMRandom::DeterministicSeed());
block_size_ = width_ * height_;
src_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_));
sec_ = reinterpret_cast<uint8_t *>(vpx_memalign(16, block_size_));
ref_ = new uint8_t[block_size_ + width_ + height_ + 1];
ASSERT_TRUE(src_ != NULL);
ASSERT_TRUE(sec_ != NULL);
ASSERT_TRUE(ref_ != NULL);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void writeVector(Parcel &data, Vector<uint8_t> const &vector) const {
data.writeInt32(vector.size());
data.write(vector.array(), vector.size());
}
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 SplashOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref,
Stream *str, int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr,
int maskWidth, int maskHeight,
GfxImageColorMap *maskColorMap) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashOutImageData imgMaskData;
SplashColorMode srcMode;
SplashBitmap *maskBitmap;
Splash *maskSplash;
SplashColor maskColor;
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];
imgMaskData.imgStr = new ImageStream(maskStr, maskWidth,
maskColorMap->getNumPixelComps(),
maskColorMap->getBits());
imgMaskData.imgStr->reset();
imgMaskData.colorMap = maskColorMap;
imgMaskData.maskColors = NULL;
imgMaskData.colorMode = splashModeMono8;
imgMaskData.width = maskWidth;
imgMaskData.height = maskHeight;
imgMaskData.y = 0;
n = 1 << maskColorMap->getBits();
imgMaskData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
maskColorMap->getGray(&pix, &gray);
imgMaskData.lookup[i] = colToByte(gray);
}
maskBitmap = new SplashBitmap(bitmap->getWidth(), bitmap->getHeight(),
1, splashModeMono8, gFalse);
maskSplash = new Splash(maskBitmap, vectorAntialias);
maskColor[0] = 0;
maskSplash->clear(maskColor);
maskSplash->drawImage(&imageSrc, &imgMaskData, splashModeMono8, gFalse,
maskWidth, maskHeight, mat);
delete imgMaskData.imgStr;
maskStr->close();
gfree(imgMaskData.lookup);
delete maskSplash;
splash->setSoftMask(maskBitmap);
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = NULL;
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)gmalloc(3 * n);
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)gmalloc(4 * n);
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)gmalloc(4 * n);
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
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
splash->drawImage(&imageSrc, &imgData, srcMode, gFalse, width, height, mat);
splash->setSoftMask(NULL);
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: modifier_color_encoding_is_set(PNG_CONST png_modifier *pm)
{
return pm->current_gamma != 0;
}
CWE ID:
Target: 1
Example 2:
Code: void OmniboxViewWin::SetWindowTextAndCaretPos(const string16& text,
size_t caret_pos) {
SetWindowText(text.c_str());
PlaceCaretAt(caret_pos);
}
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 power_pmu_add(struct perf_event *event, int ef_flags)
{
struct cpu_hw_events *cpuhw;
unsigned long flags;
int n0;
int ret = -EAGAIN;
local_irq_save(flags);
perf_pmu_disable(event->pmu);
/*
* Add the event to the list (if there is room)
* and check whether the total set is still feasible.
*/
cpuhw = &__get_cpu_var(cpu_hw_events);
n0 = cpuhw->n_events;
if (n0 >= ppmu->n_counter)
goto out;
cpuhw->event[n0] = event;
cpuhw->events[n0] = event->hw.config;
cpuhw->flags[n0] = event->hw.event_base;
if (!(ef_flags & PERF_EF_START))
event->hw.state = PERF_HES_STOPPED | PERF_HES_UPTODATE;
/*
* If group events scheduling transaction was started,
* skip the schedulability test here, it will be peformed
* at commit time(->commit_txn) as a whole
*/
if (cpuhw->group_flag & PERF_EVENT_TXN)
goto nocheck;
if (check_excludes(cpuhw->event, cpuhw->flags, n0, 1))
goto out;
if (power_check_constraints(cpuhw, cpuhw->events, cpuhw->flags, n0 + 1))
goto out;
event->hw.config = cpuhw->events[n0];
nocheck:
++cpuhw->n_events;
++cpuhw->n_added;
ret = 0;
out:
perf_pmu_enable(event->pmu);
local_irq_restore(flags);
return ret;
}
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: PowerLibrary* CrosLibrary::GetPowerLibrary() {
return power_lib_.GetDefaultImpl(use_stub_impl_);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: bool jsvIsFloat(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)==JSV_FLOAT; }
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MediaControlFullscreenButtonElement::defaultEventHandler(Event* event) {
if (event->type() == EventTypeNames::click) {
if (mediaElement().isFullscreen()) {
Platform::current()->recordAction(
UserMetricsAction("Media.Controls.ExitFullscreen"));
mediaControls().exitFullscreen();
} else {
Platform::current()->recordAction(
UserMetricsAction("Media.Controls.EnterFullscreen"));
mediaControls().enterFullscreen();
}
event->setDefaultHandled();
}
MediaControlInputElement::defaultEventHandler(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: atm_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int length = h->len;
uint32_t llchdr;
u_int hdrlen = 0;
if (caplen < 1 || length < 1) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
/* Cisco Style NLPID ? */
if (*p == LLC_UI) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "CNLPID "));
isoclns_print(ndo, p + 1, length - 1, caplen - 1);
return hdrlen;
}
/*
* Must have at least a DSAP, an SSAP, and the first byte of the
* control field.
*/
if (caplen < 3 || length < 3) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
/*
* Extract the presumed LLC header into a variable, for quick
* testing.
* Then check for a header that's neither a header for a SNAP
* packet nor an RFC 2684 routed NLPID-formatted PDU nor
* an 802.2-but-no-SNAP IP packet.
*/
llchdr = EXTRACT_24BITS(p);
if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) &&
llchdr != LLC_UI_HDR(LLCSAP_ISONS) &&
llchdr != LLC_UI_HDR(LLCSAP_IP)) {
/*
* XXX - assume 802.6 MAC header from Fore driver.
*
* Unfortunately, the above list doesn't check for
* all known SAPs, doesn't check for headers where
* the source and destination SAP aren't the same,
* and doesn't check for non-UI frames. It also
* runs the risk of an 802.6 MAC header that happens
* to begin with one of those values being
* incorrectly treated as an 802.2 header.
*
* So is that Fore driver still around? And, if so,
* is it still putting 802.6 MAC headers on ATM
* packets? If so, could it be changed to use a
* new DLT_IEEE802_6 value if we added it?
*/
if (caplen < 20 || length < 20) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%08x%08x %08x%08x ",
EXTRACT_32BITS(p),
EXTRACT_32BITS(p+4),
EXTRACT_32BITS(p+8),
EXTRACT_32BITS(p+12)));
p += 20;
length -= 20;
caplen -= 20;
hdrlen += 20;
}
hdrlen += atm_llc_print(ndo, p, length, caplen);
return (hdrlen);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: crm_ipc_name(crm_ipc_t * client)
{
CRM_ASSERT(client != NULL);
return client->name;
}
CWE ID: CWE-285
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nl80211_get_ifidx(struct netlink_callback *cb)
{
int res;
res = nlmsg_parse(cb->nlh, GENL_HDRLEN + nl80211_fam.hdrsize,
nl80211_fam.attrbuf, nl80211_fam.maxattr,
nl80211_policy);
if (res)
return res;
if (!nl80211_fam.attrbuf[NL80211_ATTR_IFINDEX])
return -EINVAL;
res = nla_get_u32(nl80211_fam.attrbuf[NL80211_ATTR_IFINDEX]);
if (!res)
return -EINVAL;
return res;
}
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: matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void ShellSurface::Move() {
TRACE_EVENT0("exo", "ShellSurface::Move");
if (widget_ && !widget_->movement_disabled())
AttemptToStartDrag(HTCAPTION);
}
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 edge_release(struct usb_serial *serial)
{
kfree(usb_get_serial_data(serial));
}
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 void __init netlink_add_usersock_entry(void)
{
struct listeners *listeners;
int groups = 32;
listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
if (!listeners)
panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
netlink_table_grab();
nl_table[NETLINK_USERSOCK].groups = groups;
rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
nl_table[NETLINK_USERSOCK].registered = 1;
netlink_table_ungrab();
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: void Splash::scaleImageYuXuBilinear(SplashImageSource src, void *srcData,
SplashColorMode srcMode, int nComps,
GBool srcAlpha, int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest) {
Guchar *srcBuf, *lineBuf1, *lineBuf2, *alphaSrcBuf, *alphaLineBuf1, *alphaLineBuf2;
Guint pix[splashMaxColorComps];
Guchar *destPtr0, *destPtr, *destAlphaPtr0, *destAlphaPtr;
int i;
srcBuf = (Guchar *)gmallocn(srcWidth+1, nComps); // + 1 pixel of padding
lineBuf1 = (Guchar *)gmallocn(scaledWidth, nComps);
lineBuf2 = (Guchar *)gmallocn(scaledWidth, nComps);
if (srcAlpha) {
alphaSrcBuf = (Guchar *)gmalloc(srcWidth+1); // + 1 pixel of padding
alphaLineBuf1 = (Guchar *)gmalloc(scaledWidth);
alphaLineBuf2 = (Guchar *)gmalloc(scaledWidth);
} else {
alphaSrcBuf = NULL;
alphaLineBuf1 = NULL;
alphaLineBuf2 = NULL;
}
double ySrc = 0.0;
double yStep = (double)srcHeight/scaledHeight;
double yFrac, yInt;
int currentSrcRow = -1;
(*src)(srcData, srcBuf, alphaSrcBuf);
expandRow(srcBuf, lineBuf2, srcWidth, scaledWidth, nComps);
if (srcAlpha)
expandRow(alphaSrcBuf, alphaLineBuf2, srcWidth, scaledWidth, 1);
destPtr0 = dest->data;
destAlphaPtr0 = dest->alpha;
for (int y = 0; y < scaledHeight; y++) {
yFrac = modf(ySrc, &yInt);
if ((int)yInt > currentSrcRow) {
currentSrcRow++;
memcpy(lineBuf1, lineBuf2, scaledWidth * nComps);
if (srcAlpha)
memcpy(alphaLineBuf1, alphaLineBuf2, scaledWidth);
if (currentSrcRow < srcHeight) {
(*src)(srcData, srcBuf, alphaSrcBuf);
expandRow(srcBuf, lineBuf2, srcWidth, scaledWidth, nComps);
if (srcAlpha)
expandRow(alphaSrcBuf, alphaLineBuf2, srcWidth, scaledWidth, 1);
}
}
for (int x = 0; x < scaledWidth; ++x) {
for (i = 0; i < nComps; ++i) {
pix[i] = lineBuf1[x*nComps + i]*(1.0 - yFrac) + lineBuf2[x*nComps + i]*yFrac;
}
destPtr = destPtr0 + (y * scaledWidth + x) * nComps;
switch (srcMode) {
case splashModeMono1: // mono1 is not allowed
break;
case splashModeMono8:
*destPtr++ = (Guchar)pix[0];
break;
case splashModeRGB8:
*destPtr++ = (Guchar)pix[0];
*destPtr++ = (Guchar)pix[1];
*destPtr++ = (Guchar)pix[2];
break;
case splashModeXBGR8:
*destPtr++ = (Guchar)pix[2];
*destPtr++ = (Guchar)pix[1];
*destPtr++ = (Guchar)pix[0];
*destPtr++ = (Guchar)255;
break;
case splashModeBGR8:
*destPtr++ = (Guchar)pix[2];
*destPtr++ = (Guchar)pix[1];
*destPtr++ = (Guchar)pix[0];
break;
#if SPLASH_CMYK
case splashModeCMYK8:
*destPtr++ = (Guchar)pix[0];
*destPtr++ = (Guchar)pix[1];
*destPtr++ = (Guchar)pix[2];
*destPtr++ = (Guchar)pix[3];
break;
case splashModeDeviceN8:
for (int cp = 0; cp < SPOT_NCOMPS+4; cp++)
*destPtr++ = (Guchar)pix[cp];
break;
#endif
}
if (srcAlpha) {
destAlphaPtr = destAlphaPtr0 + y*scaledWidth + x;
*destAlphaPtr = alphaLineBuf1[x]*(1.0 - yFrac) + alphaLineBuf2[x]*yFrac;
}
}
ySrc += yStep;
}
gfree(alphaSrcBuf);
gfree(alphaLineBuf1);
gfree(alphaLineBuf2);
gfree(srcBuf);
gfree(lineBuf1);
gfree(lineBuf2);
}
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 GLES2DecoderImpl::DeleteBuffersHelper(GLsizei n,
const volatile GLuint* client_ids) {
for (GLsizei ii = 0; ii < n; ++ii) {
GLuint client_id = client_ids[ii];
Buffer* buffer = GetBuffer(client_id);
if (buffer && !buffer->IsDeleted()) {
if (buffer->GetMappedRange()) {
GLenum target = buffer->initial_target();
Buffer* currently_bound =
buffer_manager()->GetBufferInfoForTarget(&state_, target);
if (currently_bound != buffer) {
api()->glBindBufferFn(target, buffer->service_id());
}
UnmapBufferHelper(buffer, target);
if (currently_bound != buffer) {
api()->glBindBufferFn(
target, currently_bound ? currently_bound->service_id() : 0);
}
}
state_.RemoveBoundBuffer(buffer);
buffer_manager()->RemoveBuffer(client_id);
}
}
}
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: bool ChildProcessSecurityPolicyImpl::CanCommitURL(int child_id,
const GURL& url) {
if (!url.is_valid())
return false; // Can't commit invalid URLs.
const std::string& scheme = url.scheme();
if (IsPseudoScheme(scheme))
return url == url::kAboutBlankURL || url == kAboutSrcDocURL;
if (url.SchemeIsBlob() || url.SchemeIsFileSystem()) {
if (IsMalformedBlobUrl(url))
return false;
url::Origin origin = url::Origin::Create(url);
return origin.unique() || CanCommitURL(child_id, GURL(origin.Serialize()));
}
{
base::AutoLock lock(lock_);
if (base::ContainsKey(schemes_okay_to_commit_in_any_process_, scheme))
return true;
SecurityStateMap::iterator state = security_state_.find(child_id);
if (state == security_state_.end())
return false;
return state->second->CanCommitURL(url);
}
}
CWE ID:
Target: 1
Example 2:
Code: static int atl2_set_eeprom(struct net_device *netdev,
struct ethtool_eeprom *eeprom, u8 *bytes)
{
struct atl2_adapter *adapter = netdev_priv(netdev);
struct atl2_hw *hw = &adapter->hw;
u32 *eeprom_buff;
u32 *ptr;
int max_len, first_dword, last_dword, ret_val = 0;
int i;
if (eeprom->len == 0)
return -EOPNOTSUPP;
if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16)))
return -EFAULT;
max_len = 512;
first_dword = eeprom->offset >> 2;
last_dword = (eeprom->offset + eeprom->len - 1) >> 2;
eeprom_buff = kmalloc(max_len, GFP_KERNEL);
if (!eeprom_buff)
return -ENOMEM;
ptr = eeprom_buff;
if (eeprom->offset & 3) {
/* need read/modify/write of first changed EEPROM word */
/* only the second byte of the word is being modified */
if (!atl2_read_eeprom(hw, first_dword*4, &(eeprom_buff[0]))) {
ret_val = -EIO;
goto out;
}
ptr++;
}
if (((eeprom->offset + eeprom->len) & 3)) {
/*
* need read/modify/write of last changed EEPROM word
* only the first byte of the word is being modified
*/
if (!atl2_read_eeprom(hw, last_dword * 4,
&(eeprom_buff[last_dword - first_dword]))) {
ret_val = -EIO;
goto out;
}
}
/* Device's eeprom is always little-endian, word addressable */
memcpy(ptr, bytes, eeprom->len);
for (i = 0; i < last_dword - first_dword + 1; i++) {
if (!atl2_write_eeprom(hw, ((first_dword+i)*4), eeprom_buff[i])) {
ret_val = -EIO;
goto out;
}
}
out:
kfree(eeprom_buff);
return ret_val;
}
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 BluetoothDeviceChromeOS::RequestPasskey(
const dbus::ObjectPath& device_path,
const PasskeyCallback& callback) {
DCHECK(agent_.get());
DCHECK(device_path == object_path_);
VLOG(1) << object_path_.value() << ": RequestPasskey";
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_REQUEST_PASSKEY,
UMA_PAIRING_METHOD_COUNT);
DCHECK(pairing_delegate_);
DCHECK(passkey_callback_.is_null());
passkey_callback_ = callback;
pairing_delegate_->RequestPasskey(this);
pairing_delegate_used_ = 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: AppControllerImpl::~AppControllerImpl() {
if (apps::AppServiceProxy::Get(profile_))
app_service_proxy_->AppRegistryCache().RemoveObserver(this);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: int accelerator_pressed_count() const {
return accelerator_pressed_count_;
}
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 LayerWebKitThread::addSublayer(PassRefPtr<LayerWebKitThread> sublayer)
{
insert(m_sublayers, sublayer, m_sublayers.size());
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FileSystemOperation::GetUsageAndQuotaThenRunTask(
const GURL& origin, FileSystemType type,
const base::Closure& task,
const base::Closure& error_callback) {
quota::QuotaManagerProxy* quota_manager_proxy =
file_system_context()->quota_manager_proxy();
if (!quota_manager_proxy ||
!file_system_context()->GetQuotaUtil(type)) {
operation_context_.set_allowed_bytes_growth(kint64max);
task.Run();
return;
}
TaskParamsForDidGetQuota params;
params.origin = origin;
params.type = type;
params.task = task;
params.error_callback = error_callback;
DCHECK(quota_manager_proxy);
DCHECK(quota_manager_proxy->quota_manager());
quota_manager_proxy->quota_manager()->GetUsageAndQuota(
origin,
FileSystemTypeToQuotaStorageType(type),
base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask,
base::Unretained(this), params));
}
CWE ID:
Target: 1
Example 2:
Code: bool Framebuffer::HasUnclearedAttachment(
GLenum attachment) const {
AttachmentMap::const_iterator it =
attachments_.find(attachment);
if (it != attachments_.end()) {
const Attachment* attachment = it->second.get();
return !attachment->cleared();
}
return false;
}
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: get_uncompressed_data(struct archive_read *a, const void **buff, size_t size,
size_t minimum)
{
struct _7zip *zip = (struct _7zip *)a->format->data;
ssize_t bytes_avail;
if (zip->codec == _7Z_COPY && zip->codec2 == (unsigned long)-1) {
/* Copy mode. */
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
*buff = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated 7-Zip file data");
return (ARCHIVE_FATAL);
}
if ((size_t)bytes_avail >
zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
if ((size_t)bytes_avail > size)
bytes_avail = (ssize_t)size;
zip->pack_stream_bytes_unconsumed = bytes_avail;
} else if (zip->uncompressed_buffer_pointer == NULL) {
/* Decompression has failed. */
archive_set_error(&(a->archive),
ARCHIVE_ERRNO_MISC, "Damaged 7-Zip archive");
return (ARCHIVE_FATAL);
} else {
/* Packed mode. */
if (minimum > zip->uncompressed_buffer_bytes_remaining) {
/*
* If remaining uncompressed data size is less than
* the minimum size, fill the buffer up to the
* minimum size.
*/
if (extract_pack_stream(a, minimum) < 0)
return (ARCHIVE_FATAL);
}
if (size > zip->uncompressed_buffer_bytes_remaining)
bytes_avail = (ssize_t)
zip->uncompressed_buffer_bytes_remaining;
else
bytes_avail = (ssize_t)size;
*buff = zip->uncompressed_buffer_pointer;
zip->uncompressed_buffer_pointer += bytes_avail;
}
zip->uncompressed_buffer_bytes_remaining -= bytes_avail;
return (bytes_avail);
}
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: xmlParseNmtoken(xmlParserCtxtPtr ctxt) {
xmlChar buf[XML_MAX_NAMELEN + 5];
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNmToken++;
#endif
GROW;
c = CUR_CHAR(l);
while (xmlIsNameChar(ctxt, c)) {
if (count++ > 100) {
count = 0;
GROW;
}
COPY_BUF(l,buf,len,c);
NEXTL(l);
c = CUR_CHAR(l);
if (len >= XML_MAX_NAMELEN) {
/*
* Okay someone managed to make a huge token, so he's ready to pay
* for the processing speed.
*/
xmlChar *buffer;
int max = len * 2;
buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
if (buffer == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
memcpy(buffer, buf, len);
while (xmlIsNameChar(ctxt, c)) {
if (count++ > 100) {
count = 0;
GROW;
}
if (len + 10 > max) {
xmlChar *tmp;
max *= 2;
tmp = (xmlChar *) xmlRealloc(buffer,
max * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buffer);
return(NULL);
}
buffer = tmp;
}
COPY_BUF(l,buffer,len,c);
NEXTL(l);
c = CUR_CHAR(l);
}
buffer[len] = 0;
return(buffer);
}
}
if (len == 0)
return(NULL);
return(xmlStrndup(buf, len));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: person_has_moved(const person_t* person)
{
return person->mv_x != 0 || person->mv_y != 0;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int main(int argc, char *argv[] ) {
int i, fails_count=0;
CU_pSuite cryptoUtilsTestSuite, parserTestSuite;
CU_pSuite *suites[] = {
&cryptoUtilsTestSuite,
&parserTestSuite,
NULL
};
if (argc>1) {
if (argv[1][0] == '-') {
if (strcmp(argv[1], "-verbose") == 0) {
verbose = 1;
} else {
printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]);
return 1;
}
} else {
printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]);
return 1;
}
}
#ifdef HAVE_LIBXML2
xmlInitParser();
#endif
/* initialize the CUnit test registry */
if (CUE_SUCCESS != CU_initialize_registry()) {
return CU_get_error();
}
/* Add the cryptoUtils suite to the registry */
cryptoUtilsTestSuite = CU_add_suite("Bzrtp Crypto Utils", NULL, NULL);
CU_add_test(cryptoUtilsTestSuite, "zrtpKDF", test_zrtpKDF);
CU_add_test(cryptoUtilsTestSuite, "CRC32", test_CRC32);
CU_add_test(cryptoUtilsTestSuite, "algo agreement", test_algoAgreement);
CU_add_test(cryptoUtilsTestSuite, "context algo setter and getter", test_algoSetterGetter);
CU_add_test(cryptoUtilsTestSuite, "adding mandatory crypto algorithms if needed", test_addMandatoryCryptoTypesIfNeeded);
/* Add the parser suite to the registry */
parserTestSuite = CU_add_suite("Bzrtp ZRTP Packet Parser", NULL, NULL);
CU_add_test(parserTestSuite, "Parse", test_parser);
CU_add_test(parserTestSuite, "Parse Exchange", test_parserComplete);
CU_add_test(parserTestSuite, "State machine", test_stateMachine);
/* Run all suites */
for(i=0; suites[i]; i++){
CU_basic_run_suite(*suites[i]);
fails_count += CU_get_number_of_tests_failed();
}
/* cleanup the CUnit registry */
CU_cleanup_registry();
#ifdef HAVE_LIBXML2
/* cleanup libxml2 */
xmlCleanupParser();
#endif
return (fails_count == 0 ? 0 : 1);
}
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintPreviewDataService::GetDataEntry(
const std::string& preview_ui_addr_str,
int index,
scoped_refptr<base::RefCountedBytes>* data_bytes) {
*data_bytes = NULL;
PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str);
if (it != data_store_map_.end())
it->second->GetPreviewDataForIndex(index, data_bytes);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void zend_unclean_zval_ptr_dtor(zval *zv) /* {{{ */
{
if (Z_TYPE_P(zv) == IS_INDIRECT) {
zv = Z_INDIRECT_P(zv);
}
i_zval_ptr_dtor(zv ZEND_FILE_LINE_CC);
}
/* }}} */
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MojoResult Core::CancelWatch(MojoHandle watcher_handle, uintptr_t context) {
RequestContext request_context;
scoped_refptr<Dispatcher> watcher = GetDispatcher(watcher_handle);
if (!watcher || watcher->GetType() != Dispatcher::Type::WATCHER)
return MOJO_RESULT_INVALID_ARGUMENT;
return watcher->CancelWatch(context);
}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void NavigatorImpl::DidFailProvisionalLoadWithError(
RenderFrameHostImpl* render_frame_host,
const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
<< ", error_code: " << params.error_code
<< ", error_description: " << params.error_description
<< ", showing_repost_interstitial: " <<
params.showing_repost_interstitial
<< ", frame_id: " << render_frame_host->GetRoutingID();
GURL validated_url(params.url);
RenderProcessHost* render_process_host = render_frame_host->GetProcess();
render_process_host->FilterURL(false, &validated_url);
if (net::ERR_ABORTED == params.error_code) {
FrameTreeNode* root =
render_frame_host->frame_tree_node()->frame_tree()->root();
if (root->render_manager()->interstitial_page() != NULL) {
LOG(WARNING) << "Discarding message during interstitial.";
return;
}
}
int expected_pending_entry_id =
render_frame_host->navigation_handle()
? render_frame_host->navigation_handle()->pending_nav_entry_id()
: 0;
DiscardPendingEntryIfNeeded(expected_pending_entry_id);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static RenderObject* nearestCommonHoverAncestor(RenderObject* obj1, RenderObject* obj2)
{
if (!obj1 || !obj2)
return 0;
for (RenderObject* currObj1 = obj1; currObj1; currObj1 = currObj1->hoverAncestor()) {
for (RenderObject* currObj2 = obj2; currObj2; currObj2 = currObj2->hoverAncestor()) {
if (currObj1 == currObj2)
return currObj1;
}
}
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int wrmsr_interception(struct vcpu_svm *svm)
{
struct msr_data msr;
u32 ecx = svm->vcpu.arch.regs[VCPU_REGS_RCX];
u64 data = (svm->vcpu.arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(svm->vcpu.arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
if (svm_set_msr(&svm->vcpu, &msr)) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(&svm->vcpu, 0);
} else {
trace_kvm_msr_write(ecx, data);
skip_emulated_instruction(&svm->vcpu);
}
return 1;
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadMACImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
x;
register unsigned char
*p;
size_t
length;
ssize_t
offset,
y;
unsigned char
count,
bit,
byte,
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MAC X image.
*/
length=ReadBlobLSBShort(image);
if ((length & 0xff) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
for (x=0; x < (ssize_t) 638; x++)
if (ReadBlobByte(image) == EOF)
ThrowReaderException(CorruptImageError,"CorruptImage");
image->columns=576;
image->rows=720;
image->depth=1;
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert MAC raster image to pixel packets.
*/
length=(image->columns+7)/8;
pixels=(unsigned char *) AcquireQuantumMemory(length+1,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=pixels;
offset=0;
for (y=0; y < (ssize_t) image->rows; )
{
count=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
break;
if ((count <= 0) || (count >= 128))
{
byte=(unsigned char) (~ReadBlobByte(image));
count=(~count)+2;
while (count != 0)
{
*p++=byte;
offset++;
count--;
if (offset >= (ssize_t) length)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=pixels;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(*p++);
SetPixelIndex(indexes+x,((byte & 0x80) != 0 ? 0x01 : 0x00));
bit++;
byte<<=1;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=0;
p=pixels;
y++;
}
}
continue;
}
count++;
while (count != 0)
{
byte=(unsigned char) (~ReadBlobByte(image));
*p++=byte;
offset++;
count--;
if (offset >= (ssize_t) length)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=pixels;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(*p++);
SetPixelIndex(indexes+x,((byte & 0x80) != 0 ? 0x01 : 0x00));
bit++;
byte<<=1;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
offset=0;
p=pixels;
y++;
}
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) SyncImage(image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: TT_Save_Context( TT_ExecContext exec,
TT_Size size )
{
FT_Int i;
/* XXXX: Will probably disappear soon with all the code range */
/* management, which is now rather obsolete. */
/* */
size->num_function_defs = exec->numFDefs;
size->num_instruction_defs = exec->numIDefs;
size->max_func = exec->maxFunc;
size->max_ins = exec->maxIns;
for ( i = 0; i < TT_MAX_CODE_RANGES; i++ )
size->codeRangeTable[i] = exec->codeRangeTable[i];
return TT_Err_Ok;
}
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: BrowserContextImpl::~BrowserContextImpl() {
CHECK(!otr_context_);
}
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: find_extend_vma(struct mm_struct *mm, unsigned long addr)
{
struct vm_area_struct *vma, *prev;
addr &= PAGE_MASK;
vma = find_vma_prev(mm, addr, &prev);
if (vma && (vma->vm_start <= addr))
return vma;
if (!prev || expand_stack(prev, addr))
return NULL;
if (prev->vm_flags & VM_LOCKED)
populate_vma_page_range(prev, addr, prev->vm_end, NULL);
return prev;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output)
{
tsize_t written = 0;
char* info;
char buffer[512];
if(t2p->pdf_datetime[0] == '\0')
t2p_pdf_tifftime(t2p, input);
if (strlen(t2p->pdf_datetime) > 0) {
written += t2pWriteFile(output, (tdata_t) "<< \n/CreationDate ", 18);
written += t2p_write_pdf_string(t2p->pdf_datetime, output);
written += t2pWriteFile(output, (tdata_t) "\n/ModDate ", 10);
written += t2p_write_pdf_string(t2p->pdf_datetime, output);
}
written += t2pWriteFile(output, (tdata_t) "\n/Producer ", 11);
snprintf(buffer, sizeof(buffer), "libtiff / tiff2pdf - %d", TIFFLIB_VERSION);
written += t2p_write_pdf_string(buffer, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
if (t2p->pdf_creator[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Creator ", 9);
written += t2p_write_pdf_string(t2p->pdf_creator, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
} else {
if (TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0 && info) {
if(strlen(info) >= sizeof(t2p->pdf_creator))
info[sizeof(t2p->pdf_creator) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) "/Creator ", 9);
written += t2p_write_pdf_string(info, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
if (t2p->pdf_author[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(t2p->pdf_author, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
} else {
if ((TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0
|| TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0)
&& info) {
if (strlen(info) >= sizeof(t2p->pdf_author))
info[sizeof(t2p->pdf_author) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(info, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
if (t2p->pdf_title[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Title ", 7);
written += t2p_write_pdf_string(t2p->pdf_title, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
} else {
if (TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){
if(strlen(info) > 511) {
info[512] = '\0';
}
written += t2pWriteFile(output, (tdata_t) "/Title ", 7);
written += t2p_write_pdf_string(info, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
if (t2p->pdf_subject[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Subject ", 9);
written += t2p_write_pdf_string(t2p->pdf_subject, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
} else {
if (TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0 && info) {
if (strlen(info) >= sizeof(t2p->pdf_subject))
info[sizeof(t2p->pdf_subject) - 1] = '\0';
written += t2pWriteFile(output, (tdata_t) "/Subject ", 9);
written += t2p_write_pdf_string(info, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
}
if (t2p->pdf_keywords[0] != '\0') {
written += t2pWriteFile(output, (tdata_t) "/Keywords ", 10);
written += t2p_write_pdf_string(t2p->pdf_keywords, output);
written += t2pWriteFile(output, (tdata_t) "\n", 1);
}
written += t2pWriteFile(output, (tdata_t) ">> \n", 4);
return(written);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderViewHostImpl::OnDidStartLoading() {
delegate_->DidStartLoading(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: mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void WebContentsImpl::MediaStoppedPlaying(
const WebContentsObserver::MediaPlayerInfo& media_info,
const WebContentsObserver::MediaPlayerId& id) {
if (media_info.has_video)
currently_playing_video_count_--;
for (auto& observer : observers_)
observer.MediaStoppedPlaying(media_info, 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: void SynchronousCompositorImpl::Invalidate() {
DCHECK(CalledOnValidThread());
if (registered_with_client_)
compositor_client_->PostInvalidate();
}
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: pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri)
{
int i;
uint32_t txr_len_log2, rxr_len_log2;
uint32_t req_ring_size, cmp_ring_size;
m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT;
if ((ri->reqRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)
|| (ri->cmpRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)) {
return -1;
}
req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE;
txr_len_log2 = pvscsi_log2(req_ring_size - 1);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: bool DebuggerGetTargetsFunction::RunAsync() {
DevToolsTargetImpl::EnumerateAllTargets(
base::Bind(&DebuggerGetTargetsFunction::SendTargetList, this));
return true;
}
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 AutocompleteEditModel::OnControlKeyChanged(bool pressed) {
if (pressed == (control_key_state_ == UP)) {
ControlKeyState old_state = control_key_state_;
control_key_state_ = pressed ? DOWN_WITHOUT_CHANGE : UP;
if ((control_key_state_ == DOWN_WITHOUT_CHANGE) && has_temporary_text_) {
InternalSetUserText(UserTextFromDisplayText(view_->GetText()));
has_temporary_text_ = false;
if (KeywordIsSelected())
AcceptKeyword();
}
if ((old_state != DOWN_WITH_CHANGE) && popup_->IsOpen()) {
view_->UpdatePopup();
}
}
}
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: IOHandler::IOHandler(DevToolsIOContext* io_context)
: DevToolsDomainHandler(IO::Metainfo::domainName),
io_context_(io_context),
process_host_(nullptr),
weak_factory_(this) {}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static zend_always_inline uint32_t zend_array_dup_elements(HashTable *source, HashTable *target, int static_keys, int with_holes)
{
uint32_t idx = 0;
Bucket *p = source->arData;
Bucket *q = target->arData;
Bucket *end = p + source->nNumUsed;
do {
if (!zend_array_dup_element(source, target, idx, p, q, 0, static_keys, with_holes)) {
uint32_t target_idx = idx;
idx++; p++;
while (p != end) {
if (zend_array_dup_element(source, target, target_idx, p, q, 0, static_keys, with_holes)) {
if (source->nInternalPointer == idx) {
target->nInternalPointer = target_idx;
}
target_idx++; q++;
}
idx++; p++;
}
return target_idx;
}
idx++; p++; q++;
} while (p != end);
return idx;
}
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 OneClickSigninSyncStarter::OnRegisteredForPolicy(
scoped_ptr<policy::CloudPolicyClient> client) {
SigninManager* signin = SigninManagerFactory::GetForProfile(profile_);
if (!client.get()) {
DVLOG(1) << "Policy registration failed";
ConfirmAndSignin();
return;
}
DCHECK(client->is_registered());
DVLOG(1) << "Policy registration succeeded: dm_token=" << client->dm_token();
DCHECK(!policy_client_);
policy_client_.swap(client);
EnsureBrowser();
content::WebContents* web_contents =
browser_->tab_strip_model()->GetActiveWebContents();
if (!web_contents) {
CancelSigninAndDelete();
return;
}
chrome::ShowProfileSigninConfirmationDialog(
browser_,
web_contents,
profile_,
signin->GetUsernameForAuthInProgress(),
new SigninDialogDelegate(weak_pointer_factory_.GetWeakPtr()));
}
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: InputImeEventRouter* GetInputImeEventRouter(Profile* profile) {
if (!profile)
return nullptr;
return extensions::InputImeEventRouterFactory::GetInstance()->GetRouter(
profile->GetOriginalProfile());
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void Document::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
{
if (!isContextThread()) {
postTask(AddConsoleMessageTask::create(source, level, message));
return;
}
if (Page* page = this->page())
page->console()->addMessage(source, level, message, requestIdentifier, this);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static BIGNUM *php_openssl_dh_pub_from_priv(BIGNUM *priv_key, BIGNUM *g, BIGNUM *p)
{
BIGNUM *pub_key, *priv_key_const_time;
BN_CTX *ctx;
pub_key = BN_new();
if (pub_key == NULL) {
return NULL;
}
priv_key_const_time = BN_new();
if (priv_key_const_time == NULL) {
BN_free(pub_key);
return NULL;
}
ctx = BN_CTX_new();
if (ctx == NULL) {
BN_free(pub_key);
BN_free(priv_key_const_time);
return NULL;
}
BN_with_flags(priv_key_const_time, priv_key, BN_FLG_CONSTTIME);
if (!BN_mod_exp_mont(pub_key, g, priv_key_const_time, p, ctx, NULL)) {
BN_free(pub_key);
pub_key = NULL;
}
BN_free(priv_key_const_time);
BN_CTX_free(ctx);
return pub_key;
}
CWE ID: CWE-754
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: MagickExport int LocaleUppercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l(c,c_locale));
#endif
return(toupper(c));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int QDECL paksort( const void *a, const void *b ) {
char *aa, *bb;
aa = *(char **)a;
bb = *(char **)b;
return FS_PathCmp( aa, bb );
}
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: OMX::buffer_id OMXNodeInstance::makeBufferID(OMX_BUFFERHEADERTYPE *bufferHeader) {
return (OMX::buffer_id)bufferHeader;
}
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 FrameLoader::StartNavigation(const FrameLoadRequest& passed_request,
WebFrameLoadType frame_load_type,
NavigationPolicy policy) {
CHECK(!IsBackForwardLoadType(frame_load_type));
DCHECK(passed_request.TriggeringEventInfo() !=
WebTriggeringEventInfo::kUnknown);
DCHECK(frame_->GetDocument());
if (HTMLFrameOwnerElement* element = frame_->DeprecatedLocalOwner())
element->CancelPendingLazyLoad();
if (in_stop_all_loaders_)
return;
FrameLoadRequest request(passed_request);
ResourceRequest& resource_request = request.GetResourceRequest();
const KURL& url = resource_request.Url();
Document* origin_document = request.OriginDocument();
resource_request.SetHasUserGesture(
LocalFrame::HasTransientUserActivation(frame_));
if (!PrepareRequestForThisFrame(request))
return;
Frame* target_frame =
request.Form() ? nullptr
: frame_->FindFrameForNavigation(
AtomicString(request.FrameName()), *frame_, url);
bool should_navigate_target_frame = policy == kNavigationPolicyCurrentTab;
if (target_frame && target_frame != frame_ && should_navigate_target_frame) {
if (target_frame->IsLocalFrame() &&
!ToLocalFrame(target_frame)->IsNavigationAllowed()) {
return;
}
bool was_in_same_page = target_frame->GetPage() == frame_->GetPage();
request.SetFrameName("_self");
target_frame->Navigate(request, frame_load_type);
Page* page = target_frame->GetPage();
if (!was_in_same_page && page)
page->GetChromeClient().Focus(frame_);
return;
}
SetReferrerForFrameRequest(request);
if (!target_frame && !request.FrameName().IsEmpty()) {
if (policy == kNavigationPolicyDownload) {
Client()->DownloadURL(resource_request,
DownloadCrossOriginRedirects::kFollow);
return; // Navigation/download will be handled by the client.
} else if (should_navigate_target_frame) {
resource_request.SetFrameType(
network::mojom::RequestContextFrameType::kAuxiliary);
CreateWindowForRequest(request, *frame_);
return; // Navigation will be handled by the new frame/window.
}
}
if (!frame_->IsNavigationAllowed() ||
frame_->GetDocument()->PageDismissalEventBeingDispatched() !=
Document::kNoDismissal) {
return;
}
frame_load_type = DetermineFrameLoadType(resource_request, origin_document,
KURL(), frame_load_type);
bool same_document_navigation =
policy == kNavigationPolicyCurrentTab &&
ShouldPerformFragmentNavigation(
request.Form(), resource_request.HttpMethod(), frame_load_type, url);
if (same_document_navigation) {
CommitSameDocumentNavigation(
url, frame_load_type, nullptr, request.ClientRedirect(),
origin_document,
request.TriggeringEventInfo() != WebTriggeringEventInfo::kNotFromEvent,
nullptr /* extra_data */);
return;
}
WebNavigationType navigation_type = DetermineNavigationType(
frame_load_type, resource_request.HttpBody() || request.Form(),
request.TriggeringEventInfo() != WebTriggeringEventInfo::kNotFromEvent);
resource_request.SetRequestContext(
DetermineRequestContextFromNavigationType(navigation_type));
resource_request.SetFrameType(
frame_->IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel
: network::mojom::RequestContextFrameType::kNested);
mojom::blink::NavigationInitiatorPtr navigation_initiator;
if (origin_document && origin_document->GetContentSecurityPolicy()
->ExperimentalFeaturesEnabled()) {
WebContentSecurityPolicyList initiator_csp =
origin_document->GetContentSecurityPolicy()
->ExposeForNavigationalChecks();
resource_request.SetInitiatorCSP(initiator_csp);
auto request = mojo::MakeRequest(&navigation_initiator);
origin_document->BindNavigationInitiatorRequest(std::move(request));
}
RecordLatestRequiredCSP();
ModifyRequestForCSP(resource_request, origin_document);
DCHECK(Client()->HasWebView());
if (url.PotentiallyDanglingMarkup() && url.ProtocolIsInHTTPFamily()) {
Deprecation::CountDeprecation(
frame_, WebFeature::kCanRequestURLHTTPContainingNewline);
return;
}
bool has_transient_activation =
LocalFrame::HasTransientUserActivation(frame_);
if (frame_->IsMainFrame() && origin_document &&
frame_->GetPage() == origin_document->GetPage()) {
LocalFrame::ConsumeTransientUserActivation(frame_);
}
Client()->BeginNavigation(
resource_request, origin_document, nullptr /* document_loader */,
navigation_type, policy, has_transient_activation, frame_load_type,
request.ClientRedirect() == ClientRedirectPolicy::kClientRedirect,
request.TriggeringEventInfo(), request.Form(),
request.ShouldCheckMainWorldContentSecurityPolicy(),
request.GetBlobURLToken(), request.GetInputStartTime(),
request.HrefTranslate().GetString(), std::move(navigation_initiator));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: ContentEncoding::ContentEncryption::~ContentEncryption() {
delete[] key_id;
delete[] signature;
delete[] sig_key_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: long ssl_get_algorithm2(SSL *s)
{
long alg2 = s->s3->tmp.new_cipher->algorithm2;
if (TLS1_get_version(s) >= TLS1_2_VERSION &&
alg2 == (SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF))
return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256;
return alg2;
}
CWE ID: CWE-310
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: ikev2_vid_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 isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void ServiceWorkerContextCore::NotifyRegistrationStored(int64_t registration_id,
const GURL& scope) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
observer_list_->Notify(
FROM_HERE, &ServiceWorkerContextCoreObserver::OnRegistrationStored,
registration_id, scope);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ShouldSwapProcesses(RenderViewHostManager* manager,
const NavigationEntryImpl* cur_entry,
const NavigationEntryImpl* new_entry) const {
return manager->ShouldSwapProcessesForNavigation(cur_entry, new_entry);
}
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: int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
init_get_bits8(&gb, buf, size);
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: void BackendImpl::OnExternalCacheHit(const std::string& key) {
background_queue_.OnExternalCacheHit(key);
}
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 V8TestObject::ReflectUnsignedShortAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_reflectUnsignedShortAttribute_Getter");
test_object_v8_internal::ReflectUnsignedShortAttributeAttributeGetter(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: TestResultCallback()
: callback_(base::Bind(&TestResultCallback::SetResult,
base::Unretained(this))) {}
CWE ID:
Target: 1
Example 2:
Code: static long rxrpc_read(const struct key *key,
char __user *buffer, size_t buflen)
{
const struct rxrpc_key_token *token;
const struct krb5_principal *princ;
size_t size;
__be32 __user *xdr, *oldxdr;
u32 cnlen, toksize, ntoks, tok, zero;
u16 toksizes[AFSTOKEN_MAX];
int loop;
_enter("");
/* we don't know what form we should return non-AFS keys in */
if (memcmp(key->description, "afs@", 4) != 0)
return -EOPNOTSUPP;
cnlen = strlen(key->description + 4);
#define RND(X) (((X) + 3) & ~3)
/* AFS keys we return in XDR form, so we need to work out the size of
* the XDR */
size = 2 * 4; /* flags, cellname len */
size += RND(cnlen); /* cellname */
size += 1 * 4; /* token count */
ntoks = 0;
for (token = key->payload.data; token; token = token->next) {
toksize = 4; /* sec index */
switch (token->security_index) {
case RXRPC_SECURITY_RXKAD:
toksize += 8 * 4; /* viceid, kvno, key*2, begin,
* end, primary, tktlen */
toksize += RND(token->kad->ticket_len);
break;
case RXRPC_SECURITY_RXK5:
princ = &token->k5->client;
toksize += 4 + princ->n_name_parts * 4;
for (loop = 0; loop < princ->n_name_parts; loop++)
toksize += RND(strlen(princ->name_parts[loop]));
toksize += 4 + RND(strlen(princ->realm));
princ = &token->k5->server;
toksize += 4 + princ->n_name_parts * 4;
for (loop = 0; loop < princ->n_name_parts; loop++)
toksize += RND(strlen(princ->name_parts[loop]));
toksize += 4 + RND(strlen(princ->realm));
toksize += 8 + RND(token->k5->session.data_len);
toksize += 4 * 8 + 2 * 4;
toksize += 4 + token->k5->n_addresses * 8;
for (loop = 0; loop < token->k5->n_addresses; loop++)
toksize += RND(token->k5->addresses[loop].data_len);
toksize += 4 + RND(token->k5->ticket_len);
toksize += 4 + RND(token->k5->ticket2_len);
toksize += 4 + token->k5->n_authdata * 8;
for (loop = 0; loop < token->k5->n_authdata; loop++)
toksize += RND(token->k5->authdata[loop].data_len);
break;
default: /* we have a ticket we can't encode */
BUG();
continue;
}
_debug("token[%u]: toksize=%u", ntoks, toksize);
ASSERTCMP(toksize, <=, AFSTOKEN_LENGTH_MAX);
toksizes[ntoks++] = toksize;
size += toksize + 4; /* each token has a length word */
}
#undef RND
if (!buffer || buflen < size)
return size;
xdr = (__be32 __user *) buffer;
zero = 0;
#define ENCODE(x) \
do { \
__be32 y = htonl(x); \
if (put_user(y, xdr++) < 0) \
goto fault; \
} while(0)
#define ENCODE_DATA(l, s) \
do { \
u32 _l = (l); \
ENCODE(l); \
if (copy_to_user(xdr, (s), _l) != 0) \
goto fault; \
if (_l & 3 && \
copy_to_user((u8 *)xdr + _l, &zero, 4 - (_l & 3)) != 0) \
goto fault; \
xdr += (_l + 3) >> 2; \
} while(0)
#define ENCODE64(x) \
do { \
__be64 y = cpu_to_be64(x); \
if (copy_to_user(xdr, &y, 8) != 0) \
goto fault; \
xdr += 8 >> 2; \
} while(0)
#define ENCODE_STR(s) \
do { \
const char *_s = (s); \
ENCODE_DATA(strlen(_s), _s); \
} while(0)
ENCODE(0); /* flags */
ENCODE_DATA(cnlen, key->description + 4); /* cellname */
ENCODE(ntoks);
tok = 0;
for (token = key->payload.data; token; token = token->next) {
toksize = toksizes[tok++];
ENCODE(toksize);
oldxdr = xdr;
ENCODE(token->security_index);
switch (token->security_index) {
case RXRPC_SECURITY_RXKAD:
ENCODE(token->kad->vice_id);
ENCODE(token->kad->kvno);
ENCODE_DATA(8, token->kad->session_key);
ENCODE(token->kad->start);
ENCODE(token->kad->expiry);
ENCODE(token->kad->primary_flag);
ENCODE_DATA(token->kad->ticket_len, token->kad->ticket);
break;
case RXRPC_SECURITY_RXK5:
princ = &token->k5->client;
ENCODE(princ->n_name_parts);
for (loop = 0; loop < princ->n_name_parts; loop++)
ENCODE_STR(princ->name_parts[loop]);
ENCODE_STR(princ->realm);
princ = &token->k5->server;
ENCODE(princ->n_name_parts);
for (loop = 0; loop < princ->n_name_parts; loop++)
ENCODE_STR(princ->name_parts[loop]);
ENCODE_STR(princ->realm);
ENCODE(token->k5->session.tag);
ENCODE_DATA(token->k5->session.data_len,
token->k5->session.data);
ENCODE64(token->k5->authtime);
ENCODE64(token->k5->starttime);
ENCODE64(token->k5->endtime);
ENCODE64(token->k5->renew_till);
ENCODE(token->k5->is_skey);
ENCODE(token->k5->flags);
ENCODE(token->k5->n_addresses);
for (loop = 0; loop < token->k5->n_addresses; loop++) {
ENCODE(token->k5->addresses[loop].tag);
ENCODE_DATA(token->k5->addresses[loop].data_len,
token->k5->addresses[loop].data);
}
ENCODE_DATA(token->k5->ticket_len, token->k5->ticket);
ENCODE_DATA(token->k5->ticket2_len, token->k5->ticket2);
ENCODE(token->k5->n_authdata);
for (loop = 0; loop < token->k5->n_authdata; loop++) {
ENCODE(token->k5->authdata[loop].tag);
ENCODE_DATA(token->k5->authdata[loop].data_len,
token->k5->authdata[loop].data);
}
break;
default:
BUG();
break;
}
ASSERTCMP((unsigned long)xdr - (unsigned long)oldxdr, ==,
toksize);
}
#undef ENCODE_STR
#undef ENCODE_DATA
#undef ENCODE64
#undef ENCODE
ASSERTCMP(tok, ==, ntoks);
ASSERTCMP((char __user *) xdr - buffer, ==, size);
_leave(" = %zu", size);
return size;
fault:
_leave(" = -EFAULT");
return -EFAULT;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void update_cr8_intercept(struct kvm_vcpu *vcpu)
{
int max_irr, tpr;
if (!kvm_x86_ops->update_cr8_intercept)
return;
if (!vcpu->arch.apic)
return;
if (!vcpu->arch.apic->vapic_addr)
max_irr = kvm_lapic_find_highest_irr(vcpu);
else
max_irr = -1;
if (max_irr != -1)
max_irr >>= 4;
tpr = kvm_lapic_get_cr8(vcpu);
kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j) {
input_block[j] = rnd.Rand8() - rnd.Rand8();
input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255;
}
if (i == 0)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = 255;
if (i == 1)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -255;
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebContentsImpl::WasHidden() {
if (capturer_count_ == 0) {
for (RenderWidgetHostView* view : GetRenderWidgetHostViewsInTree()) {
if (view)
view->Hide();
}
}
FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasHidden());
should_normally_be_visible_ = false;
}
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 WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
is_notifying_observers_ = true;
for (auto& observer : observers_)
observer.RenderFrameDeleted(render_frame_host);
is_notifying_observers_ = false;
#if BUILDFLAG(ENABLE_PLUGINS)
pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
#endif
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2 _U_)
{
register const struct ip6_rthdr *dp;
register const struct ip6_rthdr0 *dp0;
register const u_char *ep;
int i, len;
register const struct in6_addr *addr;
dp = (const struct ip6_rthdr *)bp;
len = dp->ip6r_len;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
ND_TCHECK(dp->ip6r_segleft);
ND_PRINT((ndo, "srcrt (len=%d", dp->ip6r_len)); /*)*/
ND_PRINT((ndo, ", type=%d", dp->ip6r_type));
ND_PRINT((ndo, ", segleft=%d", dp->ip6r_segleft));
switch (dp->ip6r_type) {
case IPV6_RTHDR_TYPE_0:
case IPV6_RTHDR_TYPE_2: /* Mobile IPv6 ID-20 */
dp0 = (const struct ip6_rthdr0 *)dp;
ND_TCHECK(dp0->ip6r0_reserved);
if (dp0->ip6r0_reserved || ndo->ndo_vflag) {
ND_PRINT((ndo, ", rsv=0x%0x",
EXTRACT_32BITS(&dp0->ip6r0_reserved)));
}
if (len % 2 == 1)
goto trunc;
len >>= 1;
addr = &dp0->ip6r0_addr[0];
for (i = 0; i < len; i++) {
if ((const u_char *)(addr + 1) > ep)
goto trunc;
ND_PRINT((ndo, ", [%d]%s", i, ip6addr_string(ndo, addr)));
addr++;
}
/*(*/
ND_PRINT((ndo, ") "));
return((dp0->ip6r0_len + 1) << 3);
break;
default:
goto trunc;
break;
}
trunc:
ND_PRINT((ndo, "[|srcrt]"));
return -1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void BrowserTabStripController::OnPreferenceChanged(
PrefServiceBase* service,
const std::string& pref_name) {
if (pref_name == prefs::kTabStripLayoutType) {
UpdateLayoutType();
}
}
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 pfkey_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &pfkey_seq_ops,
sizeof(struct seq_net_private));
}
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: create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ )
{
int rc = 0;
gnutls_session *session = gnutls_malloc(sizeof(gnutls_session));
gnutls_init(session, type);
# ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
/* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */
gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL);
/* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */
# else
gnutls_set_default_priority(*session);
gnutls_kx_set_priority(*session, tls_kx_order);
# endif
gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock));
switch (type) {
case GNUTLS_SERVER:
gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_s);
break;
case GNUTLS_CLIENT:
gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_c);
break;
}
do {
rc = gnutls_handshake(*session);
} while (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN);
if (rc < 0) {
crm_err("Handshake failed: %s", gnutls_strerror(rc));
gnutls_deinit(*session);
gnutls_free(session);
return NULL;
}
return session;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int clearCell(
MemPage *pPage, /* The page that contains the Cell */
unsigned char *pCell, /* First byte of the Cell */
CellInfo *pInfo /* Size information about the cell */
){
BtShared *pBt = pPage->pBt;
Pgno ovflPgno;
int rc;
int nOvfl;
u32 ovflPageSize;
assert( sqlite3_mutex_held(pPage->pBt->mutex) );
pPage->xParseCell(pPage, pCell, pInfo);
if( pInfo->nLocal==pInfo->nPayload ){
return SQLITE_OK; /* No overflow pages. Return without doing anything */
}
if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
}
ovflPgno = get4byte(pCell + pInfo->nSize - 4);
assert( pBt->usableSize > 4 );
ovflPageSize = pBt->usableSize - 4;
nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
assert( nOvfl>0 ||
(CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
);
while( nOvfl-- ){
Pgno iNext = 0;
MemPage *pOvfl = 0;
if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
/* 0 is not a legal page number and page 1 cannot be an
** overflow page. Therefore if ovflPgno<2 or past the end of the
** file the database must be corrupt. */
return SQLITE_CORRUPT_BKPT;
}
if( nOvfl ){
rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
if( rc ) return rc;
}
if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
&& sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
){
/* There is no reason any cursor should have an outstanding reference
** to an overflow page belonging to a cell that is being deleted/updated.
** So if there exists more than one reference to this page, then it
** must not really be an overflow page and the database must be corrupt.
** It is helpful to detect this before calling freePage2(), as
** freePage2() may zero the page contents if secure-delete mode is
** enabled. If this 'overflow' page happens to be a page that the
** caller is iterating through or using in some other way, this
** can be problematic.
*/
rc = SQLITE_CORRUPT_BKPT;
}else{
rc = freePage2(pBt, pOvfl, ovflPgno);
}
if( pOvfl ){
sqlite3PagerUnref(pOvfl->pDbPage);
}
if( rc ) return rc;
ovflPgno = iNext;
}
return SQLITE_OK;
}
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: StyleResolver::StyleResolver(Document& document)
: m_document(document)
, m_fontSelector(CSSFontSelector::create(&document))
, m_viewportStyleResolver(ViewportStyleResolver::create(&document))
, m_styleResourceLoader(document.fetcher())
, m_styleResolverStatsSequence(0)
, m_accessCount(0)
{
Element* root = document.documentElement();
m_fontSelector->registerForInvalidationCallbacks(this);
CSSDefaultStyleSheets::initDefaultStyle(root);
FrameView* view = document.view();
if (view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
else
m_medium = adoptPtr(new MediaQueryEvaluator("all"));
if (root)
m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
if (m_rootDefaultStyle && view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get()));
m_styleTree.clear();
initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors());
#if ENABLE(SVG_FONTS)
if (document.svgExtensions()) {
const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements();
HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
fontSelector()->addFontFaceRule((*it)->fontFaceRule());
}
#endif
document.styleEngine()->appendActiveAuthorStyleSheets(this);
}
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: PHP_FUNCTION(mcrypt_decrypt)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_string_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void ApplySafeSearchPolicy(std::unique_ptr<base::Value> legacy_safe_search,
std::unique_ptr<base::Value> google_safe_search,
std::unique_ptr<base::Value> legacy_youtube,
std::unique_ptr<base::Value> youtube_restrict) {
PolicyMap policies;
SetPolicy(&policies, key::kForceSafeSearch, std::move(legacy_safe_search));
SetPolicy(&policies, key::kForceGoogleSafeSearch,
std::move(google_safe_search));
SetPolicy(&policies, key::kForceYouTubeSafetyMode,
std::move(legacy_youtube));
SetPolicy(&policies, key::kForceYouTubeRestrict,
std::move(youtube_restrict));
UpdateProviderPolicy(policies);
}
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 emulator_pio_out_emulated(int size, unsigned short port,
const void *val, unsigned int count,
struct kvm_vcpu *vcpu)
{
trace_kvm_pio(1, port, size, 1);
vcpu->arch.pio.port = port;
vcpu->arch.pio.in = 0;
vcpu->arch.pio.count = count;
vcpu->arch.pio.size = size;
memcpy(vcpu->arch.pio_data, val, size * count);
if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
vcpu->arch.pio.count = 0;
return 1;
}
vcpu->run->exit_reason = KVM_EXIT_IO;
vcpu->run->io.direction = KVM_EXIT_IO_OUT;
vcpu->run->io.size = size;
vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
vcpu->run->io.count = count;
vcpu->run->io.port = port;
return 0;
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void show_object(struct object *obj,
struct strbuf *path, const char *component,
void *cb_data)
{
struct rev_list_info *info = cb_data;
finish_object(obj, path, component, cb_data);
if (info->flags & REV_LIST_QUIET)
return;
show_object_with_name(stdout, obj, path, component);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void add_client_options(struct dhcp_packet *packet)
{
int i, end, len;
udhcp_add_simple_option(packet, DHCP_MAX_SIZE, htons(IP_UDP_DHCP_SIZE));
/* Add a "param req" option with the list of options we'd like to have
* from stubborn DHCP servers. Pull the data from the struct in common.c.
* No bounds checking because it goes towards the head of the packet. */
end = udhcp_end_option(packet->options);
len = 0;
for (i = 1; i < DHCP_END; i++) {
if (client_config.opt_mask[i >> 3] & (1 << (i & 7))) {
packet->options[end + OPT_DATA + len] = i;
len++;
}
}
if (len) {
packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
packet->options[end + OPT_LEN] = len;
packet->options[end + OPT_DATA + len] = DHCP_END;
}
if (client_config.vendorclass)
udhcp_add_binary_option(packet, client_config.vendorclass);
if (client_config.hostname)
udhcp_add_binary_option(packet, client_config.hostname);
if (client_config.fqdn)
udhcp_add_binary_option(packet, client_config.fqdn);
/* Request broadcast replies if we have no IP addr */
if ((option_mask32 & OPT_B) && packet->ciaddr == 0)
packet->flags |= htons(BROADCAST_FLAG);
/* Add -x options if any */
{
struct option_set *curr = client_config.options;
while (curr) {
udhcp_add_binary_option(packet, curr->data);
curr = curr->next;
}
}
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void SetUpCommandLine(CommandLine* command_line) {
GpuFeatureTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableThreadedCompositing);
}
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: spnego_gss_set_sec_context_option(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
const gss_OID desired_object,
const gss_buffer_t value)
{
OM_uint32 ret;
ret = gss_set_sec_context_option(minor_status,
context_handle,
desired_object,
value);
return (ret);
}
CWE ID: CWE-18
Target: 1
Example 2:
Code: void LayerTreeHostImpl::SetNeedsMutate() {
TRACE_EVENT0("compositor-worker", "LayerTreeHostImpl::SetNeedsMutate");
client_->SetNeedsOneBeginImplFrameOnImplThread();
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int process_cmd_sock(int h)
{
sock_cmd_t cmd = {-1, 0, 0, 0, 0};
int fd = ts[h].cmd_fdr;
if(recv(fd, &cmd, sizeof(cmd), MSG_WAITALL) != sizeof(cmd))
{
APPL_TRACE_ERROR("recv cmd errno:%d", errno);
return FALSE;
}
APPL_TRACE_DEBUG("cmd.id:%d", cmd.id);
switch(cmd.id)
{
case CMD_ADD_FD:
add_poll(h, cmd.fd, cmd.type, cmd.flags, cmd.user_id);
break;
case CMD_REMOVE_FD:
for (int i = 1; i < MAX_POLL; ++i)
{
poll_slot_t *poll_slot = &ts[h].ps[i];
if (poll_slot->pfd.fd == cmd.fd)
{
remove_poll(h, poll_slot, poll_slot->flags);
break;
}
}
close(cmd.fd);
break;
case CMD_WAKEUP:
break;
case CMD_USER_PRIVATE:
asrt(ts[h].cmd_callback);
if(ts[h].cmd_callback)
ts[h].cmd_callback(fd, cmd.type, cmd.flags, cmd.user_id);
break;
case CMD_EXIT:
return FALSE;
default:
APPL_TRACE_DEBUG("unknown cmd: %d", cmd.id);
break;
}
return TRUE;
}
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 ZeroSuggestProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
TRACE_EVENT0("omnibox", "ZeroSuggestProvider::Start");
matches_.clear();
if (!input.from_omnibox_focus() || client()->IsOffTheRecord() ||
input.type() == metrics::OmniboxInputType::INVALID)
return;
Stop(true, false);
set_field_trial_triggered(false);
set_field_trial_triggered_in_session(false);
results_from_cache_ = false;
permanent_text_ = input.text();
current_query_ = input.current_url().spec();
current_title_ = input.current_title();
current_page_classification_ = input.current_page_classification();
current_url_match_ = MatchForCurrentURL();
std::string url_string = GetContextualSuggestionsUrl();
GURL suggest_url(url_string);
if (!suggest_url.is_valid())
return;
const TemplateURLService* template_url_service =
client()->GetTemplateURLService();
const TemplateURL* default_provider =
template_url_service->GetDefaultSearchProvider();
const bool can_send_current_url =
CanSendURL(input.current_url(), suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
GURL arbitrary_insecure_url(kArbitraryInsecureUrlString);
ZeroSuggestEligibility eligibility = ZeroSuggestEligibility::ELIGIBLE;
if (!can_send_current_url) {
const bool can_send_ordinary_url =
CanSendURL(arbitrary_insecure_url, suggest_url, default_provider,
current_page_classification_,
template_url_service->search_terms_data(), client());
eligibility = can_send_ordinary_url
? ZeroSuggestEligibility::URL_INELIGIBLE
: ZeroSuggestEligibility::GENERALLY_INELIGIBLE;
}
UMA_HISTOGRAM_ENUMERATION(
"Omnibox.ZeroSuggest.Eligible.OnFocus", static_cast<int>(eligibility),
static_cast<int>(ZeroSuggestEligibility::ELIGIBLE_MAX_VALUE));
if (can_send_current_url &&
!OmniboxFieldTrial::InZeroSuggestPersonalizedFieldTrial() &&
!OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
if (OmniboxFieldTrial::InZeroSuggestRedirectToChromeFieldTrial()) {
url_string +=
"/url=" + net::EscapePath(current_query_) +
OmniboxFieldTrial::ZeroSuggestRedirectToChromeAdditionalFields();
suggest_url = GURL(url_string);
} else {
base::string16 prefix;
TemplateURLRef::SearchTermsArgs search_term_args(prefix);
search_term_args.current_page_url = current_query_;
suggest_url =
GURL(default_provider->suggestions_url_ref().ReplaceSearchTerms(
search_term_args, template_url_service->search_terms_data()));
}
} else if (!ShouldShowNonContextualZeroSuggest(input.current_url())) {
return;
}
done_ = false;
MaybeUseCachedSuggestions();
Run(suggest_url);
}
CWE ID:
Target: 1
Example 2:
Code: static int handle_data_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc)
{
h2o_http2_data_payload_t payload;
h2o_http2_stream_t *stream;
int ret;
if ((ret = h2o_http2_decode_data_payload(&payload, frame, err_desc)) != 0)
return ret;
if (conn->state >= H2O_HTTP2_CONN_STATE_HALF_CLOSED)
return 0;
stream = h2o_http2_conn_get_stream(conn, frame->stream_id);
/* save the input in the request body buffer, or send error (and close the stream) */
if (stream == NULL) {
if (frame->stream_id <= conn->pull_stream_ids.max_open) {
send_stream_error(conn, frame->stream_id, H2O_HTTP2_ERROR_STREAM_CLOSED);
} else {
*err_desc = "invalid DATA frame";
return H2O_HTTP2_ERROR_PROTOCOL;
}
} else if (stream->state != H2O_HTTP2_STREAM_STATE_RECV_BODY) {
send_stream_error(conn, frame->stream_id, H2O_HTTP2_ERROR_STREAM_CLOSED);
h2o_http2_stream_reset(conn, stream);
stream = NULL;
} else if (stream->_req_body->size + payload.length > conn->super.ctx->globalconf->max_request_entity_size) {
send_stream_error(conn, frame->stream_id, H2O_HTTP2_ERROR_REFUSED_STREAM);
h2o_http2_stream_reset(conn, stream);
stream = NULL;
} else {
h2o_iovec_t buf = h2o_buffer_reserve(&stream->_req_body, payload.length);
if (buf.base != NULL) {
memcpy(buf.base, payload.data, payload.length);
stream->_req_body->size += payload.length;
/* handle request if request body is complete */
if ((frame->flags & H2O_HTTP2_FRAME_FLAG_END_STREAM) != 0) {
stream->req.entity = h2o_iovec_init(stream->_req_body->bytes, stream->_req_body->size);
execute_or_enqueue_request(conn, stream);
stream = NULL; /* no need to send window update for this stream */
}
} else {
/* memory allocation failed */
send_stream_error(conn, frame->stream_id, H2O_HTTP2_ERROR_STREAM_CLOSED);
h2o_http2_stream_reset(conn, stream);
stream = NULL;
}
}
/* consume buffer (and set window_update) */
update_input_window(conn, 0, &conn->_input_window, frame->length);
if (stream != NULL)
update_input_window(conn, stream->stream_id, &stream->input_window, frame->length);
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: void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
const std::string& key,
Value* data_value) {
if (!Extension::IdIsValid(extension_id)) {
NOTREACHED() << "Invalid extension_id " << extension_id;
return;
}
ScopedExtensionPrefUpdate update(prefs_, extension_id);
update->Set(key, data_value);
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: string_modifier_check(struct magic_set *ms, struct magic *m)
{
if ((ms->flags & MAGIC_CHECK) == 0)
return 0;
if (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0) {
file_magwarn(ms,
"'/BHhLl' modifiers are only allowed for pascal strings\n");
return -1;
}
switch (m->type) {
case FILE_BESTRING16:
case FILE_LESTRING16:
if (m->str_flags != 0) {
file_magwarn(ms,
"no modifiers allowed for 16-bit strings\n");
return -1;
}
break;
case FILE_STRING:
case FILE_PSTRING:
if ((m->str_flags & REGEX_OFFSET_START) != 0) {
file_magwarn(ms,
"'/%c' only allowed on regex and search\n",
CHAR_REGEX_OFFSET_START);
return -1;
}
break;
case FILE_SEARCH:
if (m->str_range == 0) {
file_magwarn(ms,
"missing range; defaulting to %d\n",
STRING_DEFAULT_RANGE);
m->str_range = STRING_DEFAULT_RANGE;
return -1;
}
break;
case FILE_REGEX:
if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
file_magwarn(ms, "'/%c' not allowed on regex\n",
CHAR_COMPACT_WHITESPACE);
return -1;
}
if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
file_magwarn(ms, "'/%c' not allowed on regex\n",
CHAR_COMPACT_OPTIONAL_WHITESPACE);
return -1;
}
break;
default:
file_magwarn(ms, "coding error: m->type=%d\n",
m->type);
return -1;
}
return 0;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool TextTrackCueList::Remove(TextTrackCue* cue) {
size_t index = list_.Find(cue);
if (index == kNotFound)
return false;
list_.EraseAt(index);
InvalidateCueIndex(index);
cue->InvalidateCueIndex();
return true;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int snd_seq_ioctl_create_port(struct snd_seq_client *client, void *arg)
{
struct snd_seq_port_info *info = arg;
struct snd_seq_client_port *port;
struct snd_seq_port_callback *callback;
/* it is not allowed to create the port for an another client */
if (info->addr.client != client->number)
return -EPERM;
port = snd_seq_create_port(client, (info->flags & SNDRV_SEQ_PORT_FLG_GIVEN_PORT) ? info->addr.port : -1);
if (port == NULL)
return -ENOMEM;
if (client->type == USER_CLIENT && info->kernel) {
snd_seq_delete_port(client, port->addr.port);
return -EINVAL;
}
if (client->type == KERNEL_CLIENT) {
if ((callback = info->kernel) != NULL) {
if (callback->owner)
port->owner = callback->owner;
port->private_data = callback->private_data;
port->private_free = callback->private_free;
port->event_input = callback->event_input;
port->c_src.open = callback->subscribe;
port->c_src.close = callback->unsubscribe;
port->c_dest.open = callback->use;
port->c_dest.close = callback->unuse;
}
}
info->addr = port->addr;
snd_seq_set_port_info(port, info);
snd_seq_system_client_ev_port_start(port->addr.client, port->addr.port);
return 0;
}
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: void MojoVideoEncodeAccelerator::UseOutputBitstreamBuffer(
const BitstreamBuffer& buffer) {
DVLOG(2) << __func__ << " buffer.id()= " << buffer.id()
<< " buffer.size()= " << buffer.size() << "B";
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(
buffer.handle().Duplicate(), buffer.size(), true /* read_only */);
vea_->UseOutputBitstreamBuffer(buffer.id(), std::move(buffer_handle));
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: int update_write_order_info(rdpContext* context, wStream* s,
ORDER_INFO* orderInfo, int offset)
{
size_t position;
position = Stream_GetPosition(s);
Stream_SetPosition(s, offset);
Stream_Write_UINT8(s, orderInfo->controlFlags); /* controlFlags (1 byte) */
if (orderInfo->controlFlags & ORDER_TYPE_CHANGE)
Stream_Write_UINT8(s, orderInfo->orderType); /* orderType (1 byte) */
update_write_field_flags(s, orderInfo->fieldFlags, orderInfo->controlFlags,
PRIMARY_DRAWING_ORDER_FIELD_BYTES[orderInfo->orderType]);
update_write_bounds(s, orderInfo);
Stream_SetPosition(s, position);
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 md_release(struct gendisk *disk, fmode_t mode)
{
struct mddev *mddev = disk->private_data;
BUG_ON(!mddev);
atomic_dec(&mddev->openers);
mddev_put(mddev);
}
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: ID3::getAlbumArt(size_t *length, String8 *mime) const {
*length = 0;
mime->setTo("");
Iterator it(
*this,
(mVersion == ID3_V2_3 || mVersion == ID3_V2_4) ? "APIC" : "PIC");
while (!it.done()) {
size_t size;
const uint8_t *data = it.getData(&size);
if (!data) {
return NULL;
}
if (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) {
uint8_t encoding = data[0];
mime->setTo((const char *)&data[1]);
size_t mimeLen = strlen((const char *)&data[1]) + 1;
#if 0
uint8_t picType = data[1 + mimeLen];
if (picType != 0x03) {
it.next();
continue;
}
#endif
size_t descLen = StringSize(&data[2 + mimeLen], encoding);
if (size < 2 ||
size - 2 < mimeLen ||
size - 2 - mimeLen < descLen) {
ALOGW("bogus album art sizes");
return NULL;
}
*length = size - 2 - mimeLen - descLen;
return &data[2 + mimeLen + descLen];
} else {
uint8_t encoding = data[0];
if (!memcmp(&data[1], "PNG", 3)) {
mime->setTo("image/png");
} else if (!memcmp(&data[1], "JPG", 3)) {
mime->setTo("image/jpeg");
} else if (!memcmp(&data[1], "-->", 3)) {
mime->setTo("text/plain");
} else {
return NULL;
}
#if 0
uint8_t picType = data[4];
if (picType != 0x03) {
it.next();
continue;
}
#endif
size_t descLen = StringSize(&data[5], encoding);
*length = size - 5 - descLen;
return &data[5 + descLen];
}
}
return NULL;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void conditionalConditionVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
imp->conditionalConditionVoidMethod();
}
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 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 &&
s->packet_length > DTLS1_RT_HEADER_LENGTH &&
s->packet[DTLS1_RT_HEADER_LENGTH] == 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: 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: xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) {
xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5];
int nbchar = 0;
int cur, l;
int count = 0;
SHRINK;
GROW;
cur = CUR_CHAR(l);
while ((cur != '<') && /* checked */
(cur != '&') &&
(IS_CHAR(cur))) /* test also done in xmlCurrentChar() */ {
if ((cur == ']') && (NXT(1) == ']') &&
(NXT(2) == '>')) {
if (cdata) break;
else {
xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL);
}
}
COPY_BUF(l,buf,nbchar,cur);
if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) {
buf[nbchar] = 0;
/*
* OK the segment is to be consumed as chars.
*/
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (areBlanks(ctxt, buf, nbchar, 0)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData,
buf, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData, buf, nbchar);
if ((ctxt->sax->characters !=
ctxt->sax->ignorableWhitespace) &&
(*ctxt->space == -1))
*ctxt->space = -2;
}
}
nbchar = 0;
/* something really bad happened in the SAX callback */
if (ctxt->instate != XML_PARSER_CONTENT)
return;
}
count++;
if (count > 50) {
GROW;
count = 0;
}
NEXTL(l);
cur = CUR_CHAR(l);
}
if (nbchar != 0) {
buf[nbchar] = 0;
/*
* OK the segment is to be consumed as chars.
*/
if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) {
if (areBlanks(ctxt, buf, nbchar, 0)) {
if (ctxt->sax->ignorableWhitespace != NULL)
ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar);
} else {
if (ctxt->sax->characters != NULL)
ctxt->sax->characters(ctxt->userData, buf, nbchar);
if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) &&
(*ctxt->space == -1))
*ctxt->space = -2;
}
}
}
if ((cur != 0) && (!IS_CHAR(cur))) {
/* Generate the error and skip the offending character */
xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
"PCDATA invalid Char value %d\n",
cur);
NEXTL(l);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void _patch_reloc (ut16 e_machine, RIOBind *iob, RBinElfReloc *rel, ut64 S, ut64 B, ut64 L) {
ut64 val;
ut64 A = rel->addend, P = rel->rva;
ut8 buf[8];
switch (e_machine) {
case EM_PPC64: {
int low = 0, word = 0;
switch (rel->type) {
case R_PPC64_REL16_HA:
word = 2;
val = (S + A - P + 0x8000) >> 16;
break;
case R_PPC64_REL16_LO:
word = 2;
val = (S + A - P) & 0xffff;
break;
case R_PPC64_REL14:
low = 14;
val = (st64)(S + A - P) >> 2;
break;
case R_PPC64_REL24:
low = 24;
val = (st64)(S + A - P) >> 2;
break;
case R_PPC64_REL32:
word = 4;
val = S + A - P;
break;
default:
break;
}
if (low) {
switch (low) {
case 14:
val &= (1 << 14) - 1;
iob->read_at (iob->io, rel->rva, buf, 2);
r_write_le32 (buf, (r_read_le32 (buf) & ~((1<<16) - (1<<2))) | val << 2);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 24:
val &= (1 << 24) - 1;
iob->read_at (iob->io, rel->rva, buf, 4);
r_write_le32 (buf, (r_read_le32 (buf) & ~((1<<26) - (1<<2))) | val << 2);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
}
} else if (word) {
switch (word) {
case 2:
r_write_le16 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 4:
r_write_le32 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
}
}
break;
}
case EM_X86_64: {
int word = 0;
switch (rel->type) {
case R_X86_64_8:
word = 1;
val = S + A;
break;
case R_X86_64_16:
word = 2;
val = S + A;
break;
case R_X86_64_32:
case R_X86_64_32S:
word = 4;
val = S + A;
break;
case R_X86_64_64:
word = 8;
val = S + A;
break;
case R_X86_64_GLOB_DAT:
case R_X86_64_JUMP_SLOT:
word = 4;
val = S;
break;
case R_X86_64_PC8:
word = 1;
val = S + A - P;
break;
case R_X86_64_PC16:
word = 2;
val = S + A - P;
break;
case R_X86_64_PC32:
word = 4;
val = S + A - P;
break;
case R_X86_64_PC64:
word = 8;
val = S + A - P;
break;
case R_X86_64_PLT32:
word = 4;
val = L + A - P;
break;
case R_X86_64_RELATIVE:
word = 8;
val = B + A;
break;
default:
break;
}
switch (word) {
case 0:
break;
case 1:
buf[0] = val;
iob->write_at (iob->io, rel->rva, buf, 1);
break;
case 2:
r_write_le16 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 4:
r_write_le32 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
case 8:
r_write_le64 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 8);
break;
}
break;
}
}
}
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: const CLSID& GetElevatorClsid() {
return InstallDetails::Get().elevator_clsid();
}
CWE ID: CWE-77
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: _TIFFmalloc(tmsize_t s)
{
return (malloc((size_t) s));
}
CWE ID: CWE-369
Target: 1
Example 2:
Code: void StyleResolver::processScopedRules(const RuleSet& authorRules, const KURL& sheetBaseURL, ContainerNode* scope)
{
const Vector<StyleRuleKeyframes*> keyframesRules = authorRules.keyframesRules();
for (unsigned i = 0; i < keyframesRules.size(); ++i)
ensureScopedStyleResolver(scope)->addKeyframeStyle(keyframesRules[i]);
const Vector<StyleRuleHost*> hostRules = authorRules.hostRules();
if (hostRules.size() && scope && scope->isInShadowTree()) {
bool enabled = buildScopedStyleTreeInDocumentOrder();
setBuildScopedStyleTreeInDocumentOrder(false);
bool hasDocumentSecurityOrigin = document().securityOrigin()->canRequest(sheetBaseURL);
for (unsigned i = 0; i < hostRules.size(); ++i)
ensureScopedStyleResolver(scope->shadowHost())->addHostRule(hostRules[i], hasDocumentSecurityOrigin, scope);
setBuildScopedStyleTreeInDocumentOrder(enabled);
}
addTreeBoundaryCrossingRules(authorRules.treeBoundaryCrossingRules(), scope);
if (!scope || scope->isDocumentNode()) {
const Vector<StyleRuleFontFace*> fontFaceRules = authorRules.fontFaceRules();
for (unsigned i = 0; i < fontFaceRules.size(); ++i)
fontSelector()->addFontFaceRule(fontFaceRules[i]);
if (fontFaceRules.size())
invalidateMatchedPropertiesCache();
} else {
addTreeBoundaryCrossingRules(authorRules.shadowDistributedRules(), scope);
}
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
{
struct bpf_verifier_stack_elem *elem;
int insn_idx;
if (env->head == NULL)
return -1;
memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
insn_idx = env->head->insn_idx;
if (prev_insn_idx)
*prev_insn_idx = env->head->prev_insn_idx;
elem = env->head->next;
kfree(env->head);
env->head = elem;
env->stack_size--;
return insn_idx;
}
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 int em_call(struct x86_emulate_ctxt *ctxt)
{
long rel = ctxt->src.val;
ctxt->src.val = (unsigned long)ctxt->_eip;
jmp_rel(ctxt, rel);
return em_push(ctxt);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int qib_assign_ctxt(struct file *fp, const struct qib_user_info *uinfo)
{
int ret;
int i_minor;
unsigned swmajor, swminor, alg = QIB_PORT_ALG_ACROSS;
/* Check to be sure we haven't already initialized this file */
if (ctxt_fp(fp)) {
ret = -EINVAL;
goto done;
}
/* for now, if major version is different, bail */
swmajor = uinfo->spu_userversion >> 16;
if (swmajor != QIB_USER_SWMAJOR) {
ret = -ENODEV;
goto done;
}
swminor = uinfo->spu_userversion & 0xffff;
if (swminor >= 11 && uinfo->spu_port_alg < QIB_PORT_ALG_COUNT)
alg = uinfo->spu_port_alg;
mutex_lock(&qib_mutex);
if (qib_compatible_subctxts(swmajor, swminor) &&
uinfo->spu_subctxt_cnt) {
ret = find_shared_ctxt(fp, uinfo);
if (ret > 0) {
ret = do_qib_user_sdma_queue_create(fp);
if (!ret)
assign_ctxt_affinity(fp, (ctxt_fp(fp))->dd);
goto done_ok;
}
}
i_minor = iminor(file_inode(fp)) - QIB_USER_MINOR_BASE;
if (i_minor)
ret = find_free_ctxt(i_minor - 1, fp, uinfo);
else {
int unit;
const unsigned int cpu = cpumask_first(¤t->cpus_allowed);
const unsigned int weight =
cpumask_weight(¤t->cpus_allowed);
if (weight == 1 && !test_bit(cpu, qib_cpulist))
if (!find_hca(cpu, &unit) && unit >= 0)
if (!find_free_ctxt(unit, fp, uinfo)) {
ret = 0;
goto done_chk_sdma;
}
ret = get_a_ctxt(fp, uinfo, alg);
}
done_chk_sdma:
if (!ret)
ret = do_qib_user_sdma_queue_create(fp);
done_ok:
mutex_unlock(&qib_mutex);
done:
return ret;
}
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 GpuCommandBufferStub::OnCreateVideoDecoder(
media::VideoCodecProfile profile,
IPC::Message* reply_message) {
int decoder_route_id = channel_->GenerateRouteID();
GpuCommandBufferMsg_CreateVideoDecoder::WriteReplyParams(
reply_message, decoder_route_id);
GpuVideoDecodeAccelerator* decoder =
new GpuVideoDecodeAccelerator(this, decoder_route_id, this);
video_decoders_.AddWithID(decoder, decoder_route_id);
channel_->AddRoute(decoder_route_id, decoder);
decoder->Initialize(profile, reply_message,
channel_->renderer_process());
}
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: jp2_box_t *jp2_box_get(jas_stream_t *in)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
jas_stream_t *tmpstream;
uint_fast32_t len;
uint_fast64_t extlen;
bool dataflag;
box = 0;
tmpstream = 0;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
goto error;
}
box->ops = &jp2_boxinfo_unk.ops;
if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) {
goto error;
}
boxinfo = jp2_boxinfolookup(box->type);
box->info = boxinfo;
box->ops = &boxinfo->ops;
box->len = len;
JAS_DBGLOG(10, (
"preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n",
'"', boxinfo->name, '"', box->type, box->len
));
if (box->len == 1) {
if (jp2_getuint64(in, &extlen)) {
goto error;
}
if (extlen > 0xffffffffUL) {
jas_eprintf("warning: cannot handle large 64-bit box length\n");
extlen = 0xffffffffUL;
}
box->len = extlen;
box->datalen = extlen - JP2_BOX_HDRLEN(true);
} else {
box->datalen = box->len - JP2_BOX_HDRLEN(false);
}
if (box->len != 0 && box->len < 8) {
goto error;
}
dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA));
if (dataflag) {
if (!(tmpstream = jas_stream_memopen(0, 0))) {
goto error;
}
if (jas_stream_copy(tmpstream, in, box->datalen)) {
box->ops = &jp2_boxinfo_unk.ops;
jas_eprintf("cannot copy box data\n");
goto error;
}
jas_stream_rewind(tmpstream);
if (box->ops->getdata) {
if ((*box->ops->getdata)(box, tmpstream)) {
jas_eprintf("cannot parse box data\n");
goto error;
}
}
jas_stream_close(tmpstream);
}
if (jas_getdbglevel() >= 1) {
jp2_box_dump(box, stderr);
}
return box;
error:
if (box) {
jp2_box_destroy(box);
}
if (tmpstream) {
jas_stream_close(tmpstream);
}
return 0;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static int posix_get_hrtimer_res(clockid_t which_clock, struct timespec64 *tp)
{
tp->tv_sec = 0;
tp->tv_nsec = hrtimer_resolution;
return 0;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void init_vmcb(struct vcpu_svm *svm)
{
struct vmcb_control_area *control = &svm->vmcb->control;
struct vmcb_save_area *save = &svm->vmcb->save;
svm->vcpu.fpu_active = 1;
svm->vcpu.arch.hflags = 0;
set_cr_intercept(svm, INTERCEPT_CR0_READ);
set_cr_intercept(svm, INTERCEPT_CR3_READ);
set_cr_intercept(svm, INTERCEPT_CR4_READ);
set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
set_dr_intercepts(svm);
set_exception_intercept(svm, PF_VECTOR);
set_exception_intercept(svm, UD_VECTOR);
set_exception_intercept(svm, MC_VECTOR);
set_exception_intercept(svm, AC_VECTOR);
set_intercept(svm, INTERCEPT_INTR);
set_intercept(svm, INTERCEPT_NMI);
set_intercept(svm, INTERCEPT_SMI);
set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
set_intercept(svm, INTERCEPT_RDPMC);
set_intercept(svm, INTERCEPT_CPUID);
set_intercept(svm, INTERCEPT_INVD);
set_intercept(svm, INTERCEPT_HLT);
set_intercept(svm, INTERCEPT_INVLPG);
set_intercept(svm, INTERCEPT_INVLPGA);
set_intercept(svm, INTERCEPT_IOIO_PROT);
set_intercept(svm, INTERCEPT_MSR_PROT);
set_intercept(svm, INTERCEPT_TASK_SWITCH);
set_intercept(svm, INTERCEPT_SHUTDOWN);
set_intercept(svm, INTERCEPT_VMRUN);
set_intercept(svm, INTERCEPT_VMMCALL);
set_intercept(svm, INTERCEPT_VMLOAD);
set_intercept(svm, INTERCEPT_VMSAVE);
set_intercept(svm, INTERCEPT_STGI);
set_intercept(svm, INTERCEPT_CLGI);
set_intercept(svm, INTERCEPT_SKINIT);
set_intercept(svm, INTERCEPT_WBINVD);
set_intercept(svm, INTERCEPT_MONITOR);
set_intercept(svm, INTERCEPT_MWAIT);
set_intercept(svm, INTERCEPT_XSETBV);
control->iopm_base_pa = iopm_base;
control->msrpm_base_pa = __pa(svm->msrpm);
control->int_ctl = V_INTR_MASKING_MASK;
init_seg(&save->es);
init_seg(&save->ss);
init_seg(&save->ds);
init_seg(&save->fs);
init_seg(&save->gs);
save->cs.selector = 0xf000;
save->cs.base = 0xffff0000;
/* Executable/Readable Code Segment */
save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
save->cs.limit = 0xffff;
save->gdtr.limit = 0xffff;
save->idtr.limit = 0xffff;
init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
svm_set_efer(&svm->vcpu, 0);
save->dr6 = 0xffff0ff0;
kvm_set_rflags(&svm->vcpu, 2);
save->rip = 0x0000fff0;
svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
/*
* svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
* It also updates the guest-visible cr0 value.
*/
svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
kvm_mmu_reset_context(&svm->vcpu);
save->cr4 = X86_CR4_PAE;
/* rdx = ?? */
if (npt_enabled) {
/* Setup VMCB for Nested Paging */
control->nested_ctl = 1;
clr_intercept(svm, INTERCEPT_INVLPG);
clr_exception_intercept(svm, PF_VECTOR);
clr_cr_intercept(svm, INTERCEPT_CR3_READ);
clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
save->g_pat = svm->vcpu.arch.pat;
save->cr3 = 0;
save->cr4 = 0;
}
svm->asid_generation = 0;
svm->nested.vmcb = 0;
svm->vcpu.arch.hflags = 0;
if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
control->pause_filter_count = 3000;
set_intercept(svm, INTERCEPT_PAUSE);
}
mark_all_dirty(svm->vmcb);
enable_gif(svm);
}
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 perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
struct pt_regs *regs, struct hlist_head *head, int rctx)
{
struct perf_sample_data data;
struct perf_event *event;
struct hlist_node *node;
struct perf_raw_record raw = {
.size = entry_size,
.data = record,
};
perf_sample_data_init(&data, addr);
data.raw = &raw;
hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
if (perf_tp_event_match(event, &data, regs))
perf_swevent_event(event, count, 1, &data, regs);
}
perf_swevent_put_recursion_context(rctx);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: cmsInt32Number CMSEXPORT cmsIT8SetTable(cmsHANDLE IT8, cmsUInt32Number nTable)
{
cmsIT8* it8 = (cmsIT8*) IT8;
if (nTable >= it8 ->TablesCount) {
if (nTable == it8 ->TablesCount) {
AllocTable(it8);
}
else {
SynError(it8, "Table %d is out of sequence", nTable);
return -1;
}
}
it8 ->nTable = nTable;
return (cmsInt32Number) nTable;
}
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: int CLASS nikon_e2100()
{
uchar t[12];
int i;
fseek (ifp, 0, SEEK_SET);
for (i=0; i < 1024; i++) {
fread (t, 1, 12, ifp);
if (((t[2] & t[4] & t[7] & t[9]) >> 4
& t[1] & t[6] & t[8] & t[11] & 3) != 3)
return 0;
}
return 1;
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(Phar, getStub)
{
size_t len;
char *buf;
php_stream *fp;
php_stream_filter *filter = NULL;
phar_entry_info *stub;
phar_entry_info *stub;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (SUCCESS == zend_hash_find(&(phar_obj->arc.archive->manifest), ".phar/stub.php", sizeof(".phar/stub.php")-1, (void **)&stub)) {
if (phar_obj->arc.archive->fp && !phar_obj->arc.archive->is_brandnew && !(stub->flags & PHAR_ENT_COMPRESSION_MASK)) {
fp = phar_obj->arc.archive->fp;
} else {
if (!(fp = php_stream_open_wrapper(phar_obj->arc.archive->fname, "rb", 0, NULL))) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to open phar \"%s\"", phar_obj->arc.archive->fname);
return;
}
if (stub->flags & PHAR_ENT_COMPRESSION_MASK) {
char *filter_name;
if ((filter_name = phar_decompress_filter(stub, 0)) != NULL) {
filter = php_stream_filter_create(filter_name, NULL, php_stream_is_persistent(fp) TSRMLS_CC);
} else {
filter = NULL;
}
if (!filter) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "phar error: unable to read stub of phar \"%s\" (cannot create %s filter)", phar_obj->arc.archive->fname, phar_decompress_filter(stub, 1));
return;
}
php_stream_filter_append(&fp->readfilters, filter);
}
}
if (!fp) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,
"Unable to read stub");
return;
}
php_stream_seek(fp, stub->offset_abs, SEEK_SET);
len = stub->uncompressed_filesize;
goto carry_on;
} else {
RETURN_STRINGL("", 0, 1);
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void ExtensionService::UpdateExtensionBlacklist(
const std::vector<std::string>& blacklist) {
std::set<std::string> blacklist_set;
for (unsigned int i = 0; i < blacklist.size(); ++i) {
if (Extension::IdIsValid(blacklist[i])) {
blacklist_set.insert(blacklist[i]);
}
}
extension_prefs_->UpdateBlacklist(blacklist_set);
std::vector<std::string> to_be_removed;
for (ExtensionList::const_iterator iter = extensions_.begin();
iter != extensions_.end(); ++iter) {
const Extension* extension = (*iter);
if (blacklist_set.find(extension->id()) != blacklist_set.end()) {
to_be_removed.push_back(extension->id());
}
}
for (unsigned int i = 0; i < to_be_removed.size(); ++i) {
UnloadExtension(to_be_removed[i], extension_misc::UNLOAD_REASON_DISABLE);
}
}
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 SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult(
const GURL& url,
const std::string& file_name,
const std::string& download_digest_sha256) {
if (client_) {
base::Value event(base::Value::Type::DICTIONARY);
event.SetStringKey(kKeyUrl, url.spec());
event.SetStringKey(kKeyFileName, file_name);
event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256);
event.SetStringKey(kKeyProfileUserName, GetProfileUserName());
ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event));
}
}
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: void CoordinatorImpl::UnregisterClientProcess(
mojom::ClientProcess* client_process) {
QueuedRequest* request = GetCurrentRequest();
if (request != nullptr) {
auto it = request->pending_responses.begin();
while (it != request->pending_responses.end()) {
std::set<QueuedRequest::PendingResponse>::iterator current = it++;
if (current->client != client_process)
continue;
RemovePendingResponse(client_process, current->type);
request->failed_memory_dump_count++;
}
FinalizeGlobalMemoryDumpIfAllManagersReplied();
}
for (auto& pair : in_progress_vm_region_requests_) {
QueuedVmRegionRequest* request = pair.second.get();
auto it = request->pending_responses.begin();
while (it != request->pending_responses.end()) {
auto current = it++;
if (*current == client_process) {
request->pending_responses.erase(current);
}
}
}
for (auto& pair : in_progress_vm_region_requests_) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&CoordinatorImpl::FinalizeVmRegionDumpIfAllManagersReplied,
base::Unretained(this), pair.second->dump_guid));
}
size_t num_deleted = clients_.erase(client_process);
DCHECK(num_deleted == 1);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void MultibufferDataSource::Read(int64_t position,
int size,
uint8_t* data,
const DataSource::ReadCB& read_cb) {
DVLOG(1) << "Read: " << position << " offset, " << size << " bytes";
DCHECK(!init_cb_);
DCHECK(read_cb);
{
base::AutoLock auto_lock(lock_);
DCHECK(!read_op_);
if (stop_signal_received_) {
read_cb.Run(kReadError);
return;
}
if (reader_) {
int bytes_read = reader_->TryReadAt(position, data, size);
if (bytes_read > 0) {
bytes_read_ += bytes_read;
seek_positions_.push_back(position + bytes_read);
if (seek_positions_.size() == 1) {
render_task_runner_->PostDelayedTask(
FROM_HERE,
base::Bind(&MultibufferDataSource::SeekTask,
weak_factory_.GetWeakPtr()),
kSeekDelay);
}
read_cb.Run(bytes_read);
return;
}
}
read_op_.reset(new ReadOperation(position, size, data, read_cb));
}
render_task_runner_->PostTask(
FROM_HERE,
base::Bind(&MultibufferDataSource::ReadTask, weak_factory_.GetWeakPtr()));
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GLSurfaceEGLSurfaceControl::GLSurfaceEGLSurfaceControl(
ANativeWindow* window,
scoped_refptr<base::SingleThreadTaskRunner> task_runner)
: root_surface_(new SurfaceControl::Surface(window, kRootSurfaceName)),
gpu_task_runner_(std::move(task_runner)),
weak_factory_(this) {}
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 struct page *follow_page_pte(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd, unsigned int flags,
struct dev_pagemap **pgmap)
{
struct mm_struct *mm = vma->vm_mm;
struct page *page;
spinlock_t *ptl;
pte_t *ptep, pte;
retry:
if (unlikely(pmd_bad(*pmd)))
return no_page_table(vma, flags);
ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
pte = *ptep;
if (!pte_present(pte)) {
swp_entry_t entry;
/*
* KSM's break_ksm() relies upon recognizing a ksm page
* even while it is being migrated, so for that case we
* need migration_entry_wait().
*/
if (likely(!(flags & FOLL_MIGRATION)))
goto no_page;
if (pte_none(pte))
goto no_page;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto no_page;
pte_unmap_unlock(ptep, ptl);
migration_entry_wait(mm, pmd, address);
goto retry;
}
if ((flags & FOLL_NUMA) && pte_protnone(pte))
goto no_page;
if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
pte_unmap_unlock(ptep, ptl);
return NULL;
}
page = vm_normal_page(vma, address, pte);
if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
/*
* Only return device mapping pages in the FOLL_GET case since
* they are only valid while holding the pgmap reference.
*/
*pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
if (*pgmap)
page = pte_page(pte);
else
goto no_page;
} else if (unlikely(!page)) {
if (flags & FOLL_DUMP) {
/* Avoid special (like zero) pages in core dumps */
page = ERR_PTR(-EFAULT);
goto out;
}
if (is_zero_pfn(pte_pfn(pte))) {
page = pte_page(pte);
} else {
int ret;
ret = follow_pfn_pte(vma, address, ptep, flags);
page = ERR_PTR(ret);
goto out;
}
}
if (flags & FOLL_SPLIT && PageTransCompound(page)) {
int ret;
get_page(page);
pte_unmap_unlock(ptep, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return ERR_PTR(ret);
goto retry;
}
if (flags & FOLL_GET)
get_page(page);
if (flags & FOLL_TOUCH) {
if ((flags & FOLL_WRITE) &&
!pte_dirty(pte) && !PageDirty(page))
set_page_dirty(page);
/*
* pte_mkyoung() would be more correct here, but atomic care
* is needed to avoid losing the dirty bit: it is easier to use
* mark_page_accessed().
*/
mark_page_accessed(page);
}
if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
/* Do not mlock pte-mapped THP */
if (PageTransCompound(page))
goto out;
/*
* The preliminary mapping check is mainly to avoid the
* pointless overhead of lock_page on the ZERO_PAGE
* which might bounce very badly if there is contention.
*
* If the page is already locked, we don't need to
* handle it now - vmscan will handle it later if and
* when it attempts to reclaim the page.
*/
if (page->mapping && trylock_page(page)) {
lru_add_drain(); /* push cached pages to LRU */
/*
* Because we lock page here, and migration is
* blocked by the pte's page reference, and we
* know the page is still mapped, we don't even
* need to check for file-cache page truncation.
*/
mlock_vma_page(page);
unlock_page(page);
}
}
out:
pte_unmap_unlock(ptep, ptl);
return page;
no_page:
pte_unmap_unlock(ptep, ptl);
if (!pte_none(pte))
return NULL;
return no_page_table(vma, flags);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void BaseMultipleFieldsDateAndTimeInputType::requiredAttributeChanged()
{
m_clearButton->releaseCapture();
updateClearButtonVisibility();
}
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 *print_string_ptr( const char *str )
{
const char *ptr;
char *ptr2, *out;
int len = 0;
unsigned char token;
if ( ! str )
return cJSON_strdup( "" );
ptr = str;
while ( ( token = *ptr ) && ++len ) {
if ( strchr( "\"\\\b\f\n\r\t", token ) )
++len;
else if ( token < 32 )
len += 5;
++ptr;
}
if ( ! ( out = (char*) cJSON_malloc( len + 3 ) ) )
return 0;
ptr2 = out;
ptr = str;
*ptr2++ = '\"';
while ( *ptr ) {
if ( (unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\' )
*ptr2++ = *ptr++;
else {
*ptr2++ = '\\';
switch ( token = *ptr++ ) {
case '\\': *ptr2++ = '\\'; break;
case '\"': *ptr2++ = '\"'; break;
case '\b': *ptr2++ = 'b'; break;
case '\f': *ptr2++ = 'f'; break;
case '\n': *ptr2++ = 'n'; break;
case '\r': *ptr2++ = 'r'; break;
case '\t': *ptr2++ = 't'; break;
default:
/* Escape and print. */
sprintf( ptr2, "u%04x", token );
ptr2 += 5;
break;
}
}
}
*ptr2++ = '\"';
*ptr2++ = 0;
return out;
}
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: RenderProcessHost* RenderProcessHostImpl::GetProcessHostForSite(
BrowserContext* browser_context,
const GURL& url) {
SiteProcessMap* map =
GetSiteProcessMapForBrowserContext(browser_context);
std::string site = SiteInstance::GetSiteForURL(browser_context, url)
.possibly_invalid_spec();
return map->FindProcess(site);
}
CWE ID:
Target: 1
Example 2:
Code: bool WebContentsImpl::IsCurrentlyAudible() {
return audio_stream_monitor()->IsCurrentlyAudible();
}
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: cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info)
{
int rc = -ENOMEM, xid;
struct cifsSesInfo *ses;
xid = GetXid();
ses = cifs_find_smb_ses(server, volume_info->username);
if (ses) {
cFYI(1, "Existing smb sess found (status=%d)", ses->status);
/* existing SMB ses has a server reference already */
cifs_put_tcp_session(server);
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our ses reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
if (ses->need_reconnect) {
cFYI(1, "Session needs reconnect");
rc = cifs_setup_session(xid, ses,
volume_info->local_nls);
if (rc) {
mutex_unlock(&ses->session_mutex);
/* problem -- put our reference */
cifs_put_smb_ses(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
}
mutex_unlock(&ses->session_mutex);
FreeXid(xid);
return ses;
}
cFYI(1, "Existing smb sess not found");
ses = sesInfoAlloc();
if (ses == NULL)
goto get_ses_fail;
/* new SMB session uses our server ref */
ses->server = server;
if (server->addr.sockAddr6.sin6_family == AF_INET6)
sprintf(ses->serverName, "%pI6",
&server->addr.sockAddr6.sin6_addr);
else
sprintf(ses->serverName, "%pI4",
&server->addr.sockAddr.sin_addr.s_addr);
if (volume_info->username)
strncpy(ses->userName, volume_info->username,
MAX_USERNAME_SIZE);
/* volume_info->password freed at unmount */
if (volume_info->password) {
ses->password = kstrdup(volume_info->password, GFP_KERNEL);
if (!ses->password)
goto get_ses_fail;
}
if (volume_info->domainname) {
int len = strlen(volume_info->domainname);
ses->domainName = kmalloc(len + 1, GFP_KERNEL);
if (ses->domainName)
strcpy(ses->domainName, volume_info->domainname);
}
ses->linux_uid = volume_info->linux_uid;
ses->overrideSecFlg = volume_info->secFlg;
mutex_lock(&ses->session_mutex);
rc = cifs_negotiate_protocol(xid, ses);
if (!rc)
rc = cifs_setup_session(xid, ses, volume_info->local_nls);
mutex_unlock(&ses->session_mutex);
if (rc)
goto get_ses_fail;
/* success, put it on the list */
write_lock(&cifs_tcp_ses_lock);
list_add(&ses->smb_ses_list, &server->smb_ses_list);
write_unlock(&cifs_tcp_ses_lock);
FreeXid(xid);
return ses;
get_ses_fail:
sesInfoFree(ses);
FreeXid(xid);
return ERR_PTR(rc);
}
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: rend_service_intro_established(origin_circuit_t *circuit,
const uint8_t *request,
size_t request_len)
{
rend_service_t *service;
rend_intro_point_t *intro;
char serviceid[REND_SERVICE_ID_LEN_BASE32+1];
(void) request;
(void) request_len;
tor_assert(circuit->rend_data);
/* XXX: This is version 2 specific (only supported one for now). */
const char *rend_pk_digest =
(char *) rend_data_get_pk_digest(circuit->rend_data, NULL);
if (circuit->base_.purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
log_warn(LD_PROTOCOL,
"received INTRO_ESTABLISHED cell on non-intro circuit.");
goto err;
}
service = rend_service_get_by_pk_digest(rend_pk_digest);
if (!service) {
log_warn(LD_REND, "Unknown service on introduction circuit %u.",
(unsigned)circuit->base_.n_circ_id);
goto err;
}
/* We've just successfully established a intro circuit to one of our
* introduction point, account for it. */
intro = find_intro_point(circuit);
if (intro == NULL) {
log_warn(LD_REND,
"Introduction circuit established without a rend_intro_point_t "
"object for service %s on circuit %u",
safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id);
goto err;
}
intro->circuit_established = 1;
/* We might not have every introduction point ready but at this point we
* know that the descriptor needs to be uploaded. */
service->desc_is_dirty = time(NULL);
circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO);
base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1,
rend_pk_digest, REND_SERVICE_ID_LEN);
log_info(LD_REND,
"Received INTRO_ESTABLISHED cell on circuit %u for service %s",
(unsigned)circuit->base_.n_circ_id, serviceid);
/* Getting a valid INTRODUCE_ESTABLISHED means we've successfully
* used the circ */
pathbias_mark_use_success(circuit);
return 0;
err:
circuit_mark_for_close(TO_CIRCUIT(circuit), END_CIRC_REASON_TORPROTOCOL);
return -1;
}
CWE ID: CWE-532
Target: 1
Example 2:
Code: static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
int ac3info, acmod, lfeon, bsmod;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
ac3info = avio_rb24(pb);
bsmod = (ac3info >> 14) & 0x7;
acmod = (ac3info >> 11) & 0x7;
lfeon = (ac3info >> 10) & 0x1;
st->codec->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon;
st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];
if (lfeon)
st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;
st->codec->audio_service_type = bsmod;
if (st->codec->channels > 1 && bsmod == 0x7)
st->codec->audio_service_type = AV_AUDIO_SERVICE_TYPE_KARAOKE;
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 size_t optsize (lua_State *L, char opt, const char **fmt) {
switch (opt) {
case 'B': case 'b': return sizeof(char);
case 'H': case 'h': return sizeof(short);
case 'L': case 'l': return sizeof(long);
case 'T': return sizeof(size_t);
case 'f': return sizeof(float);
case 'd': return sizeof(double);
case 'x': return 1;
case 'c': return getnum(L, fmt, 1);
case 'i': case 'I': {
int sz = getnum(L, fmt, sizeof(int));
if (sz > MAXINTSIZE)
luaL_error(L, "integral size %d is larger than limit of %d",
sz, MAXINTSIZE);
return sz;
}
default: return 0; /* other cases do not need alignment */
}
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: TileIndependenceTest()
: EncoderTest(GET_PARAM(0)),
md5_fw_order_(),
md5_inv_order_(),
n_tiles_(GET_PARAM(1)) {
init_flags_ = VPX_CODEC_USE_PSNR;
vpx_codec_dec_cfg_t cfg;
cfg.w = 704;
cfg.h = 144;
cfg.threads = 1;
fw_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void gain_control_data(bitfile *ld, ic_stream *ics)
{
uint8_t bd, wd, ad;
ssr_info *ssr = &(ics->ssr);
ssr->max_band = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,1000,"gain_control_data(): max_band"));
if (ics->window_sequence == ONLY_LONG_SEQUENCE)
{
for (bd = 1; bd <= ssr->max_band; bd++)
{
for (wd = 0; wd < 1; wd++)
{
ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
{
ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 5
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
}
}
}
} else if (ics->window_sequence == LONG_START_SEQUENCE) {
for (bd = 1; bd <= ssr->max_band; bd++)
{
for (wd = 0; wd < 2; wd++)
{
ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
{
ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
if (wd == 0)
{
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
} else {
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
}
}
}
}
} else if (ics->window_sequence == EIGHT_SHORT_SEQUENCE) {
for (bd = 1; bd <= ssr->max_band; bd++)
{
for (wd = 0; wd < 8; wd++)
{
ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
{
ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 2
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
}
}
}
} else if (ics->window_sequence == LONG_STOP_SEQUENCE) {
for (bd = 1; bd <= ssr->max_band; bd++)
{
for (wd = 0; wd < 2; wd++)
{
ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));
for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
{
ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
if (wd == 0)
{
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
} else {
ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 5
DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
}
}
}
}
}
}
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 unix_writable(const struct sock *sk)
{
return sk->sk_state != TCP_LISTEN &&
(atomic_read(&sk->sk_wmem_alloc) << 2) <= sk->sk_sndbuf;
}
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: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
zend_bool old_allow_url_fopen;
/*
xmlInitParser();
*/
old_allow_url_fopen = PG(allow_url_fopen);
PG(allow_url_fopen) = 1;
ctxt = xmlCreateFileParserCtxt(filename);
PG(allow_url_fopen) = old_allow_url_fopen;
if (ctxt) {
ctxt->keepBlanks = 0;
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: mcs_out_domain_params(STREAM s, int max_channels, int max_users, int max_tokens, int max_pdusize)
{
ber_out_header(s, MCS_TAG_DOMAIN_PARAMS, 32);
ber_out_integer(s, max_channels);
ber_out_integer(s, max_users);
ber_out_integer(s, max_tokens);
ber_out_integer(s, 1); /* num_priorities */
ber_out_integer(s, 0); /* min_throughput */
ber_out_integer(s, 1); /* max_height */
ber_out_integer(s, max_pdusize);
ber_out_integer(s, 2); /* ver_protocol */
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FileSystemManagerImpl::CreateWriter(const GURL& file_path,
CreateWriterCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
FileSystemURL url(context_->CrackURL(file_path));
base::Optional<base::File::Error> opt_error = ValidateFileSystemURL(url);
if (opt_error) {
std::move(callback).Run(opt_error.value(), nullptr);
return;
}
if (!security_policy_->CanWriteFileSystemFile(process_id_, url)) {
std::move(callback).Run(base::File::FILE_ERROR_SECURITY, nullptr);
return;
}
blink::mojom::FileWriterPtr writer;
mojo::MakeStrongBinding(std::make_unique<storage::FileWriterImpl>(
url, context_->CreateFileSystemOperationRunner(),
blob_storage_context_->context()->AsWeakPtr()),
MakeRequest(&writer));
std::move(callback).Run(base::File::FILE_OK, std::move(writer));
}
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: PaymentRequest::PaymentRequest(
content::RenderFrameHost* render_frame_host,
content::WebContents* web_contents,
std::unique_ptr<ContentPaymentRequestDelegate> delegate,
PaymentRequestWebContentsManager* manager,
PaymentRequestDisplayManager* display_manager,
mojo::InterfaceRequest<mojom::PaymentRequest> request,
ObserverForTest* observer_for_testing)
: web_contents_(web_contents),
delegate_(std::move(delegate)),
manager_(manager),
display_manager_(display_manager),
display_handle_(nullptr),
binding_(this, std::move(request)),
top_level_origin_(url_formatter::FormatUrlForSecurityDisplay(
web_contents_->GetLastCommittedURL())),
frame_origin_(url_formatter::FormatUrlForSecurityDisplay(
render_frame_host->GetLastCommittedURL())),
observer_for_testing_(observer_for_testing),
journey_logger_(delegate_->IsIncognito(),
ukm::GetSourceIdForWebContentsDocument(web_contents)),
weak_ptr_factory_(this) {
binding_.set_connection_error_handler(base::BindOnce(
&PaymentRequest::OnConnectionTerminated, weak_ptr_factory_.GetWeakPtr()));
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
#if DEBUG_INBOUND_EVENT_DETAILS
ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
#endif
bool needWake;
{ // acquire lock
AutoMutex _l(mLock);
ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
needWake = enqueueInboundEventLocked(newEntry);
} // release lock
if (needWake) {
mLooper->wake();
}
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int socket_create(uint16_t port)
{
int sfd = -1;
int yes = 1;
#ifdef WIN32
WSADATA wsa_data;
if (!wsa_init) {
if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) {
fprintf(stderr, "WSAStartup failed!\n");
ExitProcess(-1);
}
wsa_init = 1;
}
#endif
struct sockaddr_in saddr;
if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) {
perror("socket()");
return -1;
}
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
memset((void *) &saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
saddr.sin_port = htons(port);
if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) {
perror("bind()");
socket_close(sfd);
return -1;
}
if (listen(sfd, 1) == -1) {
perror("listen()");
socket_close(sfd);
return -1;
}
return sfd;
}
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: comics_check_decompress_command (gchar *mime_type,
ComicsDocument *comics_document,
GError **error)
{
gboolean success;
gchar *std_out, *std_err;
gint retval;
GError *err = NULL;
/* FIXME, use proper cbr/cbz mime types once they're
* included in shared-mime-info */
if (g_content_type_is_a (mime_type, "application/x-cbr") ||
g_content_type_is_a (mime_type, "application/x-rar")) {
/* The RARLAB provides a no-charge proprietary (freeware)
* decompress-only client for Linux called unrar. Another
* option is a GPLv2-licensed command-line tool developed by
* the Gna! project. Confusingly enough, the free software RAR
* decoder is also named unrar. For this reason we need to add
* some lines for disambiguation. Sorry for the added the
* complexity but it's life :)
* Finally, some distributions, like Debian, rename this free
* option as unrar-free.
* */
comics_document->selected_command =
g_find_program_in_path ("unrar");
if (comics_document->selected_command) {
/* We only use std_err to avoid printing useless error
* messages on the terminal */
success =
g_spawn_command_line_sync (
comics_document->selected_command,
&std_out, &std_err,
&retval, &err);
if (!success) {
g_propagate_error (error, err);
g_error_free (err);
return FALSE;
/* I don't check retval status because RARLAB unrar
* doesn't have a way to return 0 without involving an
* operation with a file*/
} else if (WIFEXITED (retval)) {
if (g_strrstr (std_out,"freeware") != NULL)
/* The RARLAB freeware client */
comics_document->command_usage = RARLABS;
else
/* The Gna! free software client */
comics_document->command_usage = GNAUNRAR;
g_free (std_out);
g_free (std_err);
return TRUE;
}
}
/* The Gna! free software client with Debian naming convention */
comics_document->selected_command =
g_find_program_in_path ("unrar-free");
if (comics_document->selected_command) {
comics_document->command_usage = GNAUNRAR;
return TRUE;
}
comics_document->selected_command =
g_find_program_in_path ("bsdtar");
if (comics_document->selected_command) {
comics_document->command_usage = TAR;
return TRUE;
}
} else if (g_content_type_is_a (mime_type, "application/x-cbz") ||
g_content_type_is_a (mime_type, "application/zip")) {
/* InfoZIP's unzip program */
comics_document->selected_command =
g_find_program_in_path ("unzip");
comics_document->alternative_command =
g_find_program_in_path ("zipnote");
if (comics_document->selected_command &&
comics_document->alternative_command) {
comics_document->command_usage = UNZIP;
return TRUE;
}
/* fallback mode using 7za and 7z from p7zip project */
comics_document->selected_command =
g_find_program_in_path ("7za");
if (comics_document->selected_command) {
comics_document->command_usage = P7ZIP;
return TRUE;
}
comics_document->selected_command =
g_find_program_in_path ("7z");
if (comics_document->selected_command) {
comics_document->command_usage = P7ZIP;
return TRUE;
}
comics_document->selected_command =
g_find_program_in_path ("bsdtar");
if (comics_document->selected_command) {
comics_document->command_usage = TAR;
return TRUE;
}
} else if (g_content_type_is_a (mime_type, "application/x-cb7") ||
g_content_type_is_a (mime_type, "application/x-7z-compressed")) {
/* 7zr, 7za and 7z are the commands from the p7zip project able
* to decompress .7z files */
comics_document->selected_command =
g_find_program_in_path ("7zr");
if (comics_document->selected_command) {
comics_document->command_usage = P7ZIP;
return TRUE;
}
comics_document->selected_command =
g_find_program_in_path ("7za");
if (comics_document->selected_command) {
comics_document->command_usage = P7ZIP;
return TRUE;
}
comics_document->selected_command =
g_find_program_in_path ("7z");
if (comics_document->selected_command) {
comics_document->command_usage = P7ZIP;
return TRUE;
}
comics_document->selected_command =
g_find_program_in_path ("bsdtar");
if (comics_document->selected_command) {
comics_document->command_usage = TAR;
return TRUE;
}
} else if (g_content_type_is_a (mime_type, "application/x-cbt") ||
g_content_type_is_a (mime_type, "application/x-tar")) {
/* tar utility (Tape ARchive) */
comics_document->selected_command =
g_find_program_in_path ("tar");
if (comics_document->selected_command) {
comics_document->command_usage = TAR;
return TRUE;
}
comics_document->selected_command =
g_find_program_in_path ("bsdtar");
if (comics_document->selected_command) {
comics_document->command_usage = TAR;
return TRUE;
}
} else {
g_set_error (error,
EV_DOCUMENT_ERROR,
EV_DOCUMENT_ERROR_INVALID,
_("Not a comic book MIME type: %s"),
mime_type);
return FALSE;
}
g_set_error_literal (error,
EV_DOCUMENT_ERROR,
EV_DOCUMENT_ERROR_INVALID,
_("Can’t find an appropriate command to "
"decompress this type of comic book"));
return FALSE;
}
CWE ID:
Target: 1
Example 2:
Code: void GfxState::setCTM(double a, double b, double c,
double d, double e, double f) {
int i;
ctm[0] = a;
ctm[1] = b;
ctm[2] = c;
ctm[3] = d;
ctm[4] = e;
ctm[5] = f;
for (i = 0; i < 6; ++i) {
if (ctm[i] > 1e10) {
ctm[i] = 1e10;
} else if (ctm[i] < -1e10) {
ctm[i] = -1e10;
}
}
}
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 sanity_check_raw_super(struct f2fs_sb_info *sbi,
struct buffer_head *bh)
{
struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
(bh->b_data + F2FS_SUPER_OFFSET);
struct super_block *sb = sbi->sb;
unsigned int blocksize;
if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) {
f2fs_msg(sb, KERN_INFO,
"Magic Mismatch, valid(0x%x) - read(0x%x)",
F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));
return 1;
}
/* Currently, support only 4KB page cache size */
if (F2FS_BLKSIZE != PAGE_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid page_cache_size (%lu), supports only 4KB\n",
PAGE_SIZE);
return 1;
}
/* Currently, support only 4KB block size */
blocksize = 1 << le32_to_cpu(raw_super->log_blocksize);
if (blocksize != F2FS_BLKSIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid blocksize (%u), supports only 4KB\n",
blocksize);
return 1;
}
/* check log blocks per segment */
if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) {
f2fs_msg(sb, KERN_INFO,
"Invalid log blocks per segment (%u)\n",
le32_to_cpu(raw_super->log_blocks_per_seg));
return 1;
}
/* Currently, support 512/1024/2048/4096 bytes sector size */
if (le32_to_cpu(raw_super->log_sectorsize) >
F2FS_MAX_LOG_SECTOR_SIZE ||
le32_to_cpu(raw_super->log_sectorsize) <
F2FS_MIN_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)",
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
if (le32_to_cpu(raw_super->log_sectors_per_block) +
le32_to_cpu(raw_super->log_sectorsize) !=
F2FS_MAX_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid log sectors per block(%u) log sectorsize(%u)",
le32_to_cpu(raw_super->log_sectors_per_block),
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
/* check reserved ino info */
if (le32_to_cpu(raw_super->node_ino) != 1 ||
le32_to_cpu(raw_super->meta_ino) != 2 ||
le32_to_cpu(raw_super->root_ino) != 3) {
f2fs_msg(sb, KERN_INFO,
"Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)",
le32_to_cpu(raw_super->node_ino),
le32_to_cpu(raw_super->meta_ino),
le32_to_cpu(raw_super->root_ino));
return 1;
}
/* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */
if (sanity_check_area_boundary(sbi, bh))
return 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: void NTPResourceCache::CreateNewTabHTML() {
PrefService* prefs = profile_->GetPrefs();
base::DictionaryValue load_time_data;
load_time_data.SetBoolean("bookmarkbarattached",
prefs->GetBoolean(prefs::kShowBookmarkBar));
load_time_data.SetBoolean("hasattribution",
ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage(
IDR_THEME_NTP_ATTRIBUTION));
load_time_data.SetBoolean("showMostvisited", should_show_most_visited_page_);
load_time_data.SetBoolean("showAppLauncherPromo",
ShouldShowAppLauncherPromo());
load_time_data.SetBoolean("showRecentlyClosed",
should_show_recently_closed_menu_);
load_time_data.SetString("title",
l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE));
load_time_data.SetString("mostvisited",
l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED));
load_time_data.SetString("suggestions",
l10n_util::GetStringUTF16(IDS_NEW_TAB_SUGGESTIONS));
load_time_data.SetString("restoreThumbnailsShort",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK));
load_time_data.SetString("recentlyclosed",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED));
load_time_data.SetString("webStoreTitle",
l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE));
load_time_data.SetString("webStoreTitleShort",
l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE_SHORT));
load_time_data.SetString("closedwindowsingle",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE));
load_time_data.SetString("closedwindowmultiple",
l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE));
load_time_data.SetString("attributionintro",
l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO));
load_time_data.SetString("thumbnailremovednotification",
l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION));
load_time_data.SetString("undothumbnailremove",
l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE));
load_time_data.SetString("removethumbnailtooltip",
l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP));
load_time_data.SetString("appuninstall",
l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL));
load_time_data.SetString("appoptions",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS));
load_time_data.SetString("appdetails",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DETAILS));
load_time_data.SetString("appcreateshortcut",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT));
load_time_data.SetString("appDefaultPageName",
l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME));
load_time_data.SetString("applaunchtypepinned",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED));
load_time_data.SetString("applaunchtyperegular",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR));
load_time_data.SetString("applaunchtypewindow",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW));
load_time_data.SetString("applaunchtypefullscreen",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN));
load_time_data.SetString("syncpromotext",
l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL));
load_time_data.SetString("syncLinkText",
l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS));
load_time_data.SetBoolean("shouldShowSyncLogin",
NTPLoginHandler::ShouldShow(profile_));
load_time_data.SetString("otherSessions",
l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LABEL));
load_time_data.SetString("otherSessionsEmpty",
l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EMPTY));
load_time_data.SetString("otherSessionsLearnMoreUrl",
l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LEARN_MORE_URL));
load_time_data.SetString("learnMore",
l10n_util::GetStringUTF16(IDS_LEARN_MORE));
load_time_data.SetString("webStoreLink",
GetUrlWithLang(GURL(extension_urls::GetWebstoreLaunchURL())));
load_time_data.SetString("appInstallHintText",
l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_INSTALL_HINT_LABEL));
load_time_data.SetBoolean("isDiscoveryInNTPEnabled",
NewTabUI::IsDiscoveryInNTPEnabled());
load_time_data.SetString("collapseSessionMenuItemText",
l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION));
load_time_data.SetString("expandSessionMenuItemText",
l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION));
load_time_data.SetString("restoreSessionMenuItemText",
l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL));
load_time_data.SetString("learn_more",
l10n_util::GetStringUTF16(IDS_LEARN_MORE));
load_time_data.SetString("tile_grid_screenreader_accessible_description",
l10n_util::GetStringUTF16(IDS_NEW_TAB_TILE_GRID_ACCESSIBLE_DESCRIPTION));
load_time_data.SetString("page_switcher_change_title",
l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_CHANGE_TITLE));
load_time_data.SetString("page_switcher_same_title",
l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_SAME_TITLE));
load_time_data.SetString("appsPromoTitle",
l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_APPS_PROMO_TITLE));
load_time_data.SetBoolean("isSwipeTrackingFromScrollEventsEnabled",
is_swipe_tracking_from_scroll_events_enabled_);
if (profile_->IsManaged())
should_show_apps_page_ = false;
load_time_data.SetBoolean("showApps", should_show_apps_page_);
load_time_data.SetBoolean("showWebStoreIcon",
!prefs->GetBoolean(prefs::kHideWebStoreIcon));
bool streamlined_hosted_apps = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableStreamlinedHostedApps);
load_time_data.SetBoolean("enableStreamlinedHostedApps",
streamlined_hosted_apps);
if (streamlined_hosted_apps) {
load_time_data.SetString("applaunchtypetab",
l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_TAB));
}
#if defined(OS_MACOSX)
load_time_data.SetBoolean(
"disableCreateAppShortcut",
CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppShims));
#endif
#if defined(OS_CHROMEOS)
load_time_data.SetString("expandMenu",
l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND));
#endif
NewTabPageHandler::GetLocalizedValues(profile_, &load_time_data);
NTPLoginHandler::GetLocalizedValues(profile_, &load_time_data);
webui::SetFontAndTextDirection(&load_time_data);
load_time_data.SetBoolean("anim",
gfx::Animation::ShouldRenderRichAnimation());
ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_);
int alignment = tp->GetDisplayProperty(
ThemeProperties::NTP_BACKGROUND_ALIGNMENT);
load_time_data.SetString("themegravity",
(alignment & ThemeProperties::ALIGN_RIGHT) ? "right" : "");
if (first_run::IsChromeFirstRun()) {
NotificationPromo::HandleClosed(NotificationPromo::NTP_NOTIFICATION_PROMO);
} else {
NotificationPromo notification_promo;
notification_promo.InitFromPrefs(NotificationPromo::NTP_NOTIFICATION_PROMO);
if (notification_promo.CanShow()) {
load_time_data.SetString("notificationPromoText",
notification_promo.promo_text());
DVLOG(1) << "Notification promo:" << notification_promo.promo_text();
}
NotificationPromo bubble_promo;
bubble_promo.InitFromPrefs(NotificationPromo::NTP_BUBBLE_PROMO);
if (bubble_promo.CanShow()) {
load_time_data.SetString("bubblePromoText",
bubble_promo.promo_text());
DVLOG(1) << "Bubble promo:" << bubble_promo.promo_text();
}
}
bool show_other_sessions_menu = should_show_other_devices_menu_ &&
!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableNTPOtherSessionsMenu);
load_time_data.SetBoolean("showOtherSessionsMenu", show_other_sessions_menu);
load_time_data.SetBoolean("isUserSignedIn",
!prefs->GetString(prefs::kGoogleServicesUsername).empty());
base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance().
GetRawDataResource(IDR_NEW_TAB_4_HTML));
webui::UseVersion2 version2;
std::string full_html =
webui::GetI18nTemplateHtml(new_tab_html, &load_time_data);
new_tab_html_ = base::RefCountedString::TakeString(&full_html);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void writeImageNodeToPasteboard(Pasteboard* pasteboard,
Node* node,
const String& title) {
DCHECK(pasteboard);
DCHECK(node);
RefPtr<Image> image = imageFromNode(*node);
if (!image.get())
return;
AtomicString urlString;
if (isHTMLImageElement(*node) || isHTMLInputElement(*node))
urlString = toHTMLElement(node)->getAttribute(srcAttr);
else if (isSVGImageElement(*node))
urlString = toSVGElement(node)->imageSourceURL();
else if (isHTMLEmbedElement(*node) || isHTMLObjectElement(*node) ||
isHTMLCanvasElement(*node))
urlString = toHTMLElement(node)->imageSourceURL();
KURL url = urlString.isEmpty()
? KURL()
: node->document().completeURL(
stripLeadingAndTrailingHTMLSpaces(urlString));
pasteboard->writeImage(image.get(), url, title);
}
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 set_sda(int state)
{
qrio_set_opendrain_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1, state);
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void testInspectorDefault(InspectorTest* test, gconstpointer)
{
test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL);
test->resizeView(200, 200);
test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0);
test->waitUntilLoadFinished();
test->showAndWaitUntilFinished(false);
GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector);
g_assert(inspectorView.get());
test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get()));
g_assert(!webkit_web_inspector_is_attached(test->m_inspector));
g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0);
Vector<InspectorTest::InspectorEvents>& events = test->m_events;
g_assert_cmpint(events.size(), ==, 2);
g_assert_cmpint(events[0], ==, InspectorTest::BringToFront);
g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow);
test->m_events.clear();
test->showAndWaitUntilFinished(true);
events = test->m_events;
g_assert_cmpint(events.size(), ==, 1);
g_assert_cmpint(events[0], ==, InspectorTest::BringToFront);
test->m_events.clear();
test->resizeViewAndAttach();
g_assert(webkit_web_inspector_is_attached(test->m_inspector));
events = test->m_events;
g_assert_cmpint(events.size(), ==, 1);
g_assert_cmpint(events[0], ==, InspectorTest::Attach);
test->m_events.clear();
test->detachAndWaitUntilWindowOpened();
g_assert(!webkit_web_inspector_is_attached(test->m_inspector));
events = test->m_events;
g_assert_cmpint(events.size(), ==, 2);
g_assert_cmpint(events[0], ==, InspectorTest::Detach);
g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow);
test->m_events.clear();
test->closeAndWaitUntilClosed();
events = test->m_events;
g_assert_cmpint(events.size(), ==, 1);
g_assert_cmpint(events[0], ==, InspectorTest::Closed);
test->m_events.clear();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool ContentSecurityPolicy::allowFontFromSource(
const KURL& url,
RedirectStatus redirectStatus,
SecurityViolationReportingPolicy reportingPolicy) const {
return isAllowedByAll<&CSPDirectiveList::allowFontFromSource>(
m_policies, url, redirectStatus, reportingPolicy);
}
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 set_register(pegasus_t *pegasus, __u16 indx, __u8 data)
{
int ret;
ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0),
PEGASUS_REQ_SET_REG, PEGASUS_REQT_WRITE, data,
indx, &data, 1, 1000);
if (ret < 0)
netif_dbg(pegasus, drv, pegasus->net,
"%s returned %d\n", __func__, ret);
return ret;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int cx24116_send_diseqc_msg(struct dvb_frontend *fe,
struct dvb_diseqc_master_cmd *d)
{
struct cx24116_state *state = fe->demodulator_priv;
int i, ret;
/* Dump DiSEqC message */
if (debug) {
printk(KERN_INFO "cx24116: %s(", __func__);
for (i = 0 ; i < d->msg_len ;) {
printk(KERN_INFO "0x%02x", d->msg[i]);
if (++i < d->msg_len)
printk(KERN_INFO ", ");
}
printk(") toneburst=%d\n", toneburst);
}
/* Validate length */
if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS))
return -EINVAL;
/* DiSEqC message */
for (i = 0; i < d->msg_len; i++)
state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];
/* DiSEqC message length */
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len;
/* Command length */
state->dsec_cmd.len = CX24116_DISEQC_MSGOFS +
state->dsec_cmd.args[CX24116_DISEQC_MSGLEN];
/* DiSEqC toneburst */
if (toneburst == CX24116_DISEQC_MESGCACHE)
/* Message is cached */
return 0;
else if (toneburst == CX24116_DISEQC_TONEOFF)
/* Message is sent without burst */
state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0;
else if (toneburst == CX24116_DISEQC_TONECACHE) {
/*
* Message is sent with derived else cached burst
*
* WRITE PORT GROUP COMMAND 38
*
* 0/A/A: E0 10 38 F0..F3
* 1/B/B: E0 10 38 F4..F7
* 2/C/A: E0 10 38 F8..FB
* 3/D/B: E0 10 38 FC..FF
*
* databyte[3]= 8421:8421
* ABCD:WXYZ
* CLR :SET
*
* WX= PORT SELECT 0..3 (X=TONEBURST)
* Y = VOLTAGE (0=13V, 1=18V)
* Z = BAND (0=LOW, 1=HIGH(22K))
*/
if (d->msg_len >= 4 && d->msg[2] == 0x38)
state->dsec_cmd.args[CX24116_DISEQC_BURST] =
((d->msg[3] & 4) >> 2);
if (debug)
dprintk("%s burst=%d\n", __func__,
state->dsec_cmd.args[CX24116_DISEQC_BURST]);
}
/* Wait for LNB ready */
ret = cx24116_wait_for_lnb(fe);
if (ret != 0)
return ret;
/* Wait for voltage/min repeat delay */
msleep(100);
/* Command */
ret = cx24116_cmd_execute(fe, &state->dsec_cmd);
if (ret != 0)
return ret;
/*
* Wait for send
*
* Eutelsat spec:
* >15ms delay + (XXX determine if FW does this, see set_tone)
* 13.5ms per byte +
* >15ms delay +
* 12.5ms burst +
* >15ms delay (XXX determine if FW does this, see set_tone)
*/
msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) +
((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60));
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct net_device *dev = ptr;
struct net *net = dev_net(dev);
struct netns_ipvs *ipvs = net_ipvs(net);
struct ip_vs_service *svc;
struct ip_vs_dest *dest;
unsigned int idx;
if (event != NETDEV_UNREGISTER || !ipvs)
return NOTIFY_DONE;
IP_VS_DBG(3, "%s() dev=%s\n", __func__, dev->name);
EnterFunction(2);
mutex_lock(&__ip_vs_mutex);
for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
list_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
if (net_eq(svc->net, net)) {
list_for_each_entry(dest, &svc->destinations,
n_list) {
__ip_vs_dev_reset(dest, dev);
}
}
}
list_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
if (net_eq(svc->net, net)) {
list_for_each_entry(dest, &svc->destinations,
n_list) {
__ip_vs_dev_reset(dest, dev);
}
}
}
}
list_for_each_entry(dest, &ipvs->dest_trash, n_list) {
__ip_vs_dev_reset(dest, dev);
}
mutex_unlock(&__ip_vs_mutex);
LeaveFunction(2);
return NOTIFY_DONE;
}
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: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::CreateHistogram(
PersistentHistogramData* histogram_data_ptr) {
if (!histogram_data_ptr) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA_POINTER);
NOTREACHED();
return nullptr;
}
if (histogram_data_ptr->histogram_type == SPARSE_HISTOGRAM) {
std::unique_ptr<HistogramBase> histogram =
SparseHistogram::PersistentCreate(this, histogram_data_ptr->name,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
histogram->SetFlags(histogram_data_ptr->flags);
RecordCreateHistogramResult(CREATE_HISTOGRAM_SUCCESS);
return histogram;
}
int32_t histogram_type = histogram_data_ptr->histogram_type;
int32_t histogram_flags = histogram_data_ptr->flags;
int32_t histogram_minimum = histogram_data_ptr->minimum;
int32_t histogram_maximum = histogram_data_ptr->maximum;
uint32_t histogram_bucket_count = histogram_data_ptr->bucket_count;
uint32_t histogram_ranges_ref = histogram_data_ptr->ranges_ref;
uint32_t histogram_ranges_checksum = histogram_data_ptr->ranges_checksum;
HistogramBase::Sample* ranges_data =
memory_allocator_->GetAsArray<HistogramBase::Sample>(
histogram_ranges_ref, kTypeIdRangesArray,
PersistentMemoryAllocator::kSizeAny);
const uint32_t max_buckets =
std::numeric_limits<uint32_t>::max() / sizeof(HistogramBase::Sample);
size_t required_bytes =
(histogram_bucket_count + 1) * sizeof(HistogramBase::Sample);
size_t allocated_bytes =
memory_allocator_->GetAllocSize(histogram_ranges_ref);
if (!ranges_data || histogram_bucket_count < 2 ||
histogram_bucket_count >= max_buckets ||
allocated_bytes < required_bytes) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_RANGES_ARRAY);
NOTREACHED();
return nullptr;
}
std::unique_ptr<const BucketRanges> created_ranges = CreateRangesFromData(
ranges_data, histogram_ranges_checksum, histogram_bucket_count + 1);
if (!created_ranges) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_RANGES_ARRAY);
NOTREACHED();
return nullptr;
}
const BucketRanges* ranges =
StatisticsRecorder::RegisterOrDeleteDuplicateRanges(
created_ranges.release());
size_t counts_bytes = CalculateRequiredCountsBytes(histogram_bucket_count);
PersistentMemoryAllocator::Reference counts_ref =
subtle::Acquire_Load(&histogram_data_ptr->counts_ref);
if (counts_bytes == 0 ||
(counts_ref != 0 &&
memory_allocator_->GetAllocSize(counts_ref) < counts_bytes)) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_COUNTS_ARRAY);
NOTREACHED();
return nullptr;
}
DelayedPersistentAllocation counts_data(memory_allocator_.get(),
&histogram_data_ptr->counts_ref,
kTypeIdCountsArray, counts_bytes, 0);
DelayedPersistentAllocation logged_data(
memory_allocator_.get(), &histogram_data_ptr->counts_ref,
kTypeIdCountsArray, counts_bytes, counts_bytes / 2,
/*make_iterable=*/false);
const char* name = histogram_data_ptr->name;
std::unique_ptr<HistogramBase> histogram;
switch (histogram_type) {
case HISTOGRAM:
histogram = Histogram::PersistentCreate(
name, histogram_minimum, histogram_maximum, ranges, counts_data,
logged_data, &histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case LINEAR_HISTOGRAM:
histogram = LinearHistogram::PersistentCreate(
name, histogram_minimum, histogram_maximum, ranges, counts_data,
logged_data, &histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case BOOLEAN_HISTOGRAM:
histogram = BooleanHistogram::PersistentCreate(
name, ranges, counts_data, logged_data,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
case CUSTOM_HISTOGRAM:
histogram = CustomHistogram::PersistentCreate(
name, ranges, counts_data, logged_data,
&histogram_data_ptr->samples_metadata,
&histogram_data_ptr->logged_metadata);
DCHECK(histogram);
break;
default:
NOTREACHED();
}
if (histogram) {
DCHECK_EQ(histogram_type, histogram->GetHistogramType());
histogram->SetFlags(histogram_flags);
RecordCreateHistogramResult(CREATE_HISTOGRAM_SUCCESS);
} else {
RecordCreateHistogramResult(CREATE_HISTOGRAM_UNKNOWN_TYPE);
}
return histogram;
}
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 SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = (mWidth * mHeight * 3) / 2;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int kernel_getsockopt(struct socket *sock, int level, int optname,
char *optval, int *optlen)
{
mm_segment_t oldfs = get_fs();
char __user *uoptval;
int __user *uoptlen;
int err;
uoptval = (char __user __force *) optval;
uoptlen = (int __user __force *) optlen;
set_fs(KERNEL_DS);
if (level == SOL_SOCKET)
err = sock_getsockopt(sock, level, optname, uoptval, uoptlen);
else
err = sock->ops->getsockopt(sock, level, optname, uoptval,
uoptlen);
set_fs(oldfs);
return err;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void print_maps(struct pid_info_t* info)
{
FILE *maps;
size_t offset;
char device[10];
long int inode;
char file[PATH_MAX];
strlcat(info->path, "maps", sizeof(info->path));
maps = fopen(info->path, "r");
if (!maps)
goto out;
while (fscanf(maps, "%*x-%*x %*s %zx %s %ld %s\n", &offset, device, &inode,
file) == 4) {
if (inode == 0 || !strcmp(device, "00:00"))
continue;
printf("%-9s %5d %10s %4s %9s %18s %9zd %10ld %s\n",
info->cmdline, info->pid, info->user, "mem",
"???", device, offset, inode, file);
}
fclose(maps);
out:
info->path[info->parent_length] = '\0';
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool initiate_stratum(struct pool *pool)
{
bool ret = false, recvd = false, noresume = false, sockd = false;
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
json_error_t err;
int n2size;
resend:
if (!setup_stratum_socket(pool)) {
sockd = false;
goto out;
}
sockd = true;
if (recvd) {
/* Get rid of any crap lying around if we're resending */
clear_sock(pool);
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
} else {
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
}
if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = get_sessionid(res_val);
if (!sessionid)
applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (!n2size) {
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
cg_wlock(&pool->data_lock);
pool->sessionid = sessionid;
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
if (sessionid)
applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
ret = true;
out:
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->sdiff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
pool->pool_no, pool->nonce1, pool->n2size);
}
} else {
if (recvd && !noresume) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
cg_wlock(&pool->data_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
cg_wunlock(&pool->data_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
noresume = true;
json_decref(val);
goto resend;
}
applog(LOG_DEBUG, "Initiate stratum failed");
if (sockd)
suspend_stratum(pool);
}
json_decref(val);
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ProcXResQueryClientIds (ClientPtr client)
{
REQUEST(xXResQueryClientIdsReq);
xXResClientIdSpec *specs = (void*) ((char*) stuff + sizeof(*stuff));
int rc;
ConstructClientIdCtx ctx;
InitConstructClientIdCtx(&ctx);
REQUEST_AT_LEAST_SIZE(xXResQueryClientIdsReq);
REQUEST_FIXED_SIZE(xXResQueryClientIdsReq,
stuff->numSpecs * sizeof(specs[0]));
rc = ConstructClientIds(client, stuff->numSpecs, specs, &ctx);
if (rc == Success) {
xXResQueryClientIdsReply rep = {
.type = X_Reply,
.sequenceNumber = client->sequence,
.length = bytes_to_int32(ctx.resultBytes),
.numIds = ctx.numIds
};
assert((ctx.resultBytes & 3) == 0);
if (client->swapped) {
swaps (&rep.sequenceNumber);
swapl (&rep.length);
swapl (&rep.numIds);
}
WriteToClient(client, sizeof(rep), &rep);
WriteFragmentsToClient(client, &ctx.response);
}
DestroyConstructClientIdCtx(&ctx);
return rc;
}
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 filter_block2d_8_c(const uint8_t *src_ptr,
const unsigned int src_stride,
const int16_t *HFilter,
const int16_t *VFilter,
uint8_t *dst_ptr,
unsigned int dst_stride,
unsigned int output_width,
unsigned int output_height) {
const int kInterp_Extend = 4;
const unsigned int intermediate_height =
(kInterp_Extend - 1) + output_height + kInterp_Extend;
/* Size of intermediate_buffer is max_intermediate_height * filter_max_width,
* where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height
* + kInterp_Extend
* = 3 + 16 + 4
* = 23
* and filter_max_width = 16
*/
uint8_t intermediate_buffer[71 * 64];
const int intermediate_next_stride = 1 - intermediate_height * output_width;
{
uint8_t *output_ptr = intermediate_buffer;
const int src_next_row_stride = src_stride - output_width;
unsigned int i, j;
src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1);
for (i = 0; i < intermediate_height; ++i) {
for (j = 0; j < output_width; ++j) {
const int temp = (src_ptr[0] * HFilter[0]) +
(src_ptr[1] * HFilter[1]) +
(src_ptr[2] * HFilter[2]) +
(src_ptr[3] * HFilter[3]) +
(src_ptr[4] * HFilter[4]) +
(src_ptr[5] * HFilter[5]) +
(src_ptr[6] * HFilter[6]) +
(src_ptr[7] * HFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
*output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT);
++src_ptr;
output_ptr += intermediate_height;
}
src_ptr += src_next_row_stride;
output_ptr += intermediate_next_stride;
}
}
{
uint8_t *src_ptr = intermediate_buffer;
const int dst_next_row_stride = dst_stride - output_width;
unsigned int i, j;
for (i = 0; i < output_height; ++i) {
for (j = 0; j < output_width; ++j) {
const int temp = (src_ptr[0] * VFilter[0]) +
(src_ptr[1] * VFilter[1]) +
(src_ptr[2] * VFilter[2]) +
(src_ptr[3] * VFilter[3]) +
(src_ptr[4] * VFilter[4]) +
(src_ptr[5] * VFilter[5]) +
(src_ptr[6] * VFilter[6]) +
(src_ptr[7] * VFilter[7]) +
(VP9_FILTER_WEIGHT >> 1); // Rounding
*dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT);
src_ptr += intermediate_height;
}
src_ptr += intermediate_next_stride;
dst_ptr += dst_next_row_stride;
}
}
}
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 usbhid_parse(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_descriptor *hdesc;
u32 quirks = 0;
unsigned int rsize = 0;
char *rdesc;
int ret, n;
quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (quirks & HID_QUIRK_IGNORE)
return -ENODEV;
/* Many keyboards and mice don't like to be polled for reports,
* so we will always set the HID_QUIRK_NOGET flag for them. */
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||
interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)
quirks |= HID_QUIRK_NOGET;
}
if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&
(!interface->desc.bNumEndpoints ||
usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {
dbg_hid("class descriptor not present\n");
return -ENODEV;
}
hid->version = le16_to_cpu(hdesc->bcdHID);
hid->country = hdesc->bCountryCode;
for (n = 0; n < hdesc->bNumDescriptors; n++)
if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)
rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);
if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
dbg_hid("weird size of report descriptor (%u)\n", rsize);
return -EINVAL;
}
rdesc = kmalloc(rsize, GFP_KERNEL);
if (!rdesc)
return -ENOMEM;
hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);
ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, rsize);
if (ret < 0) {
dbg_hid("reading report descriptor failed\n");
kfree(rdesc);
goto err;
}
ret = hid_parse_report(hid, rdesc, rsize);
kfree(rdesc);
if (ret) {
dbg_hid("parsing report descriptor failed\n");
goto err;
}
hid->quirks |= quirks;
return 0;
err:
return ret;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight)
{
static uch ppmline[256];
int maxval;
saved_infile = infile;
fgets(ppmline, 256, infile);
if (ppmline[0] != 'P' || ppmline[1] != '6') {
fprintf(stderr, "ERROR: not a PPM file\n");
return 1;
}
/* possible color types: P5 = grayscale (0), P6 = RGB (2), P8 = RGBA (6) */
if (ppmline[1] == '6') {
color_type = 2;
channels = 3;
} else if (ppmline[1] == '8') {
color_type = 6;
channels = 4;
} else /* if (ppmline[1] == '5') */ {
color_type = 0;
channels = 1;
}
do {
fgets(ppmline, 256, infile);
} while (ppmline[0] == '#');
sscanf(ppmline, "%lu %lu", &width, &height);
do {
fgets(ppmline, 256, infile);
} while (ppmline[0] == '#');
sscanf(ppmline, "%d", &maxval);
if (maxval != 255) {
fprintf(stderr, "ERROR: maxval = %d\n", maxval);
return 2;
}
bit_depth = 8;
*pWidth = width;
*pHeight = height;
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: base::string16 GetCertificateButtonTitle() const {
PageInfoBubbleView* page_info_bubble_view =
static_cast<PageInfoBubbleView*>(
PageInfoBubbleView::GetPageInfoBubble());
return page_info_bubble_view->certificate_button_->title()->text();
}
CWE ID: CWE-311
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: __u32 secure_ipv6_id(const __be32 daddr[4])
{
const struct keydata *keyptr;
__u32 hash[4];
keyptr = get_keyptr();
hash[0] = (__force __u32)daddr[0];
hash[1] = (__force __u32)daddr[1];
hash[2] = (__force __u32)daddr[2];
hash[3] = (__force __u32)daddr[3];
return half_md4_transform(hash, keyptr->secret);
}
CWE ID:
Target: 1
Example 2:
Code: void Browser::RendererResponsive(TabContents* source) {
browser::HideHungRendererDialog(source);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t MediaPlayer::setVolume(float leftVolume, float rightVolume)
{
ALOGV("MediaPlayer::setVolume(%f, %f)", leftVolume, rightVolume);
Mutex::Autolock _l(mLock);
mLeftVolume = leftVolume;
mRightVolume = rightVolume;
if (mPlayer != 0) {
return mPlayer->setVolume(leftVolume, rightVolume);
}
return OK;
}
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: z_check_file_permissions(gs_memory_t *mem, const char *fname, const int len, const char *permission)
{
i_ctx_t *i_ctx_p = get_minst_from_memory(mem)->i_ctx_p;
gs_parsed_file_name_t pname;
const char *permitgroup = permission[0] == 'r' ? "PermitFileReading" : "PermitFileWriting";
int code = gs_parse_file_name(&pname, fname, len, imemory);
if (code < 0)
return code;
if (pname.iodev && i_ctx_p->LockFilePermissions && strcmp(pname.iodev->dname, "%pipe%") == 0)
return gs_error_invalidfileaccess;
code = check_file_permissions(i_ctx_p, fname, len, permitgroup);
return code;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void DefaultTabHandler::TabReplacedAt(TabStripModel* tab_strip_model,
TabContentsWrapper* old_contents,
TabContentsWrapper* new_contents,
int index) {
delegate_->AsBrowser()->TabReplacedAt(tab_strip_model, old_contents,
new_contents, index);
}
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: QuicAsyncStatus QuicClientPromisedInfo::HandleClientRequest(
const SpdyHeaderBlock& request_headers,
QuicClientPushPromiseIndex::Delegate* delegate) {
if (session_->IsClosedStream(id_)) {
session_->DeletePromised(this);
return QUIC_FAILURE;
}
if (is_validating()) {
return QUIC_FAILURE;
}
client_request_delegate_ = delegate;
client_request_headers_.reset(new SpdyHeaderBlock(request_headers.Clone()));
if (!response_headers_) {
return QUIC_PENDING;
}
return FinalValidation();
}
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 sas_unregister_devs_sas_addr(struct domain_device *parent,
int phy_id, bool last)
{
struct expander_device *ex_dev = &parent->ex_dev;
struct ex_phy *phy = &ex_dev->ex_phy[phy_id];
struct domain_device *child, *n, *found = NULL;
if (last) {
list_for_each_entry_safe(child, n,
&ex_dev->children, siblings) {
if (SAS_ADDR(child->sas_addr) ==
SAS_ADDR(phy->attached_sas_addr)) {
set_bit(SAS_DEV_GONE, &child->state);
if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE ||
child->dev_type == SAS_FANOUT_EXPANDER_DEVICE)
sas_unregister_ex_tree(parent->port, child);
else
sas_unregister_dev(parent->port, child);
found = child;
break;
}
}
sas_disable_routing(parent, phy->attached_sas_addr);
}
memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE);
if (phy->port) {
sas_port_delete_phy(phy->port, phy->phy);
sas_device_set_phy(found, phy->port);
if (phy->port->num_phys == 0)
sas_port_delete(phy->port);
phy->port = NULL;
}
}
CWE ID:
Target: 1
Example 2:
Code: ipip6_tunnel_add_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a, int chg)
{
struct ip_tunnel_prl_entry *p;
int err = 0;
if (a->addr == htonl(INADDR_ANY))
return -EINVAL;
spin_lock(&ipip6_prl_lock);
for (p = t->prl; p; p = p->next) {
if (p->addr == a->addr) {
if (chg) {
p->flags = a->flags;
goto out;
}
err = -EEXIST;
goto out;
}
}
if (chg) {
err = -ENXIO;
goto out;
}
p = kzalloc(sizeof(struct ip_tunnel_prl_entry), GFP_KERNEL);
if (!p) {
err = -ENOBUFS;
goto out;
}
INIT_RCU_HEAD(&p->rcu_head);
p->next = t->prl;
p->addr = a->addr;
p->flags = a->flags;
t->prl_count++;
rcu_assign_pointer(t->prl, p);
out:
spin_unlock(&ipip6_prl_lock);
return err;
}
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: DECLAREcpFunc(cpContigTiles2SeparateTiles)
{
return cpImage(in, out,
readContigTilesIntoBuffer,
writeBufferToSeparateTiles,
imagelength, imagewidth, spp);
}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
: content::RenderViewObserver(render_view),
content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
print_web_view_(NULL),
is_preview_enabled_(IsPrintPreviewEnabled()),
is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()),
is_print_ready_metafile_sent_(false),
ignore_css_margins_(false),
user_cancelled_scripted_print_count_(0),
is_scripted_printing_blocked_(false),
notify_browser_of_print_failure_(true),
print_for_preview_(false) {
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void SVGDocumentExtensions::registerPendingSVGFontFaceElementsForRemoval(PassRefPtrWillBeRawPtr<SVGFontFaceElement> font)
{
m_pendingSVGFontFaceElementsForRemoval.add(font);
}
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 GDataFileSystem::GetFileByResourceIdOnUIThread(
const std::string& resource_id,
const GetFileCallback& get_file_callback,
const GetDownloadDataCallback& get_download_data_callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
directory_service_->GetEntryByResourceIdAsync(resource_id,
base::Bind(&GDataFileSystem::GetFileByEntryOnUIThread,
ui_weak_ptr_,
get_file_callback,
get_download_data_callback));
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void btif_hl_select_wakeup_callback( fd_set *p_org_set , int wakeup_signal){
BTIF_TRACE_DEBUG("entering %s wakeup_signal=0x%04x",__FUNCTION__, wakeup_signal);
if (wakeup_signal == btif_hl_signal_select_wakeup )
{
btif_hl_add_socket_to_set(p_org_set);
}
else if (wakeup_signal == btif_hl_signal_select_close_connected)
{
btif_hl_close_socket(p_org_set);
}
BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__);
}
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: static void schedule_bh(void (*handler)(void))
{
WARN_ON(work_pending(&floppy_work));
floppy_work_fn = handler;
queue_work(floppy_wq, &floppy_work);
}
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 update_rate_histogram(struct rate_hist *hist,
const vpx_codec_enc_cfg_t *cfg,
const vpx_codec_cx_pkt_t *pkt) {
int i;
int64_t then = 0;
int64_t avg_bitrate = 0;
int64_t sum_sz = 0;
const int64_t now = pkt->data.frame.pts * 1000 *
(uint64_t)cfg->g_timebase.num /
(uint64_t)cfg->g_timebase.den;
int idx = hist->frames++ % hist->samples;
hist->pts[idx] = now;
hist->sz[idx] = (int)pkt->data.frame.sz;
if (now < cfg->rc_buf_initial_sz)
return;
then = now;
/* Sum the size over the past rc_buf_sz ms */
for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
const int i_idx = (i - 1) % hist->samples;
then = hist->pts[i_idx];
if (now - then > cfg->rc_buf_sz)
break;
sum_sz += hist->sz[i_idx];
}
if (now == then)
return;
avg_bitrate = sum_sz * 8 * 1000 / (now - then);
idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
if (idx < 0)
idx = 0;
if (idx > RATE_BINS - 1)
idx = RATE_BINS - 1;
if (hist->bucket[idx].low > avg_bitrate)
hist->bucket[idx].low = (int)avg_bitrate;
if (hist->bucket[idx].high < avg_bitrate)
hist->bucket[idx].high = (int)avg_bitrate;
hist->bucket[idx].count++;
hist->total++;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: raptor_libxml_internalSubset(void* user_data, const xmlChar *name,
const xmlChar *ExternalID, const xmlChar *SystemID) {
raptor_sax2* sax2 = (raptor_sax2*)user_data;
libxml2_internalSubset(sax2->xc, name, ExternalID, SystemID);
}
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 Editor::Command::IdForHistogram() const {
return IsSupported() ? static_cast<int>(command_->command_type) : 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 MediaStreamDispatcherHost::BindRequest(
mojom::MediaStreamDispatcherHostRequest request) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
bindings_.AddBinding(this, std::move(request));
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: jbig2_find_segment(Jbig2Ctx *ctx, uint32_t number)
{
int index, index_max = ctx->segment_index - 1;
const Jbig2Ctx *global_ctx = ctx->global_ctx;
/* FIXME: binary search would be better */
for (index = index_max; index >= 0; index--)
if (ctx->segments[index]->number == number)
return (ctx->segments[index]);
if (global_ctx)
for (index = global_ctx->segment_index - 1; index >= 0; index--)
if (global_ctx->segments[index]->number == number)
return (global_ctx->segments[index]);
/* didn't find a match */
return NULL;
}
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: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t ofs = CDF_GETUINT32(p, (i << 1) + 1);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
if (nelements == 0) {
DPRINTF(("CDF_VECTOR with nelements == 0\n"));
goto out;
}
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
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 perf_event_overflow(struct perf_event *event, int nmi,
struct perf_sample_data *data,
struct pt_regs *regs)
{
return __perf_event_overflow(event, nmi, 1, data, regs);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: evdns_nameserver_free(struct nameserver *server)
{
if (server->socket >= 0)
evutil_closesocket(server->socket);
(void) event_del(&server->event);
event_debug_unassign(&server->event);
if (server->state == 0)
(void) event_del(&server->timeout_event);
if (server->probe_request) {
evdns_cancel_request(server->base, server->probe_request);
server->probe_request = NULL;
}
event_debug_unassign(&server->timeout_event);
mm_free(server);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void ExportTIFF_PhotographicSensitivity ( SXMPMeta * xmp, TIFF_Manager * exif ) {
try {
bool foundXMP, foundExif;
TIFF_Manager::TagInfo tagInfo;
std::string xmpValue;
XMP_OptionBits flags;
XMP_Int32 binValue = 0;
bool haveOldExif = true; // Default to old Exif if no version tag.
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_ExifVersion, &tagInfo );
if ( foundExif && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 4) ) {
haveOldExif = (strncmp ( (char*)tagInfo.dataPtr, "0230", 4 ) < 0);
}
if ( haveOldExif ) { // Exif version is before 2.3, use just the old tag and property.
foundXMP = xmp->GetProperty ( kXMP_NS_EXIF, "ISOSpeedRatings", 0, &flags );
if ( foundXMP && XMP_PropIsArray(flags) && (xmp->CountArrayItems ( kXMP_NS_EXIF, "ISOSpeedRatings" ) > 0) ) {
foundXMP = xmp->GetProperty_Int ( kXMP_NS_EXIF, "ISOSpeedRatings[1]", &binValue, 0 );
}
if ( ! foundXMP ) {
foundXMP = xmp->GetProperty_Int ( kXMP_NS_ExifEX, "PhotographicSensitivity", &binValue, 0 );
}
if ( foundXMP && (0 <= binValue) && (binValue <= 65535) ) {
xmp->DeleteProperty ( kXMP_NS_EXIF, "ISOSpeedRatings" ); // So namespace cleanup won't keep it.
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_PhotographicSensitivity, &tagInfo );
if ( ! foundExif ) {
exif->SetTag_Short ( kTIFF_ExifIFD, kTIFF_PhotographicSensitivity, (XMP_Uns16)binValue );
}
}
} else { // Exif version is 2.3 or newer, use the Exif 2.3 tags and properties.
if ( ! xmp->DoesPropertyExist ( kXMP_NS_ExifEX, "PhotographicSensitivity" ) ) {
foundXMP = xmp->GetProperty ( kXMP_NS_EXIF, "ISOSpeedRatings", 0, &flags );
if ( foundXMP && XMP_PropIsArray(flags) &&
(xmp->CountArrayItems ( kXMP_NS_EXIF, "ISOSpeedRatings" ) > 0) ) {
xmp->GetArrayItem ( kXMP_NS_EXIF, "ISOSpeedRatings", 1, &xmpValue, 0 );
xmp->SetProperty ( kXMP_NS_ExifEX, "PhotographicSensitivity", xmpValue.c_str() );
}
}
xmp->DeleteProperty ( kXMP_NS_EXIF, "ISOSpeedRatings" ); // Don't want it kept after namespace cleanup.
foundXMP = xmp->GetProperty_Int ( kXMP_NS_ExifEX, "PhotographicSensitivity", &binValue, 0 );
if ( foundXMP && (0 <= binValue) && (binValue <= 65535) ) { // The simpler low ISO case.
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_PhotographicSensitivity, &tagInfo );
if ( ! foundExif ) {
exif->SetTag_Short ( kTIFF_ExifIFD, kTIFF_PhotographicSensitivity, (XMP_Uns16)binValue );
}
} else if ( foundXMP ) { // The more commplex high ISO case.
bool havePhotographicSensitivityTag = exif->GetTag ( kTIFF_ExifIFD, kTIFF_PhotographicSensitivity, 0 );
bool haveSensitivityTypeTag = exif->GetTag ( kTIFF_ExifIFD, kTIFF_SensitivityType, 0 );
bool haveISOSpeedTag = exif->GetTag ( kTIFF_ExifIFD, kTIFF_ISOSpeed, 0 );
bool haveSensitivityTypeXMP = xmp->DoesPropertyExist ( kXMP_NS_ExifEX, "SensitivityType" );
bool haveISOSpeedXMP = xmp->DoesPropertyExist ( kXMP_NS_ExifEX, "ISOSpeed" );
if ( (! havePhotographicSensitivityTag) && (! haveSensitivityTypeTag) && (! haveISOSpeedTag) ) {
exif->SetTag_Short ( kTIFF_ExifIFD, kTIFF_PhotographicSensitivity, 65535 );
if ( (! haveSensitivityTypeXMP) && (! haveISOSpeedXMP) ) {
xmp->SetProperty ( kXMP_NS_ExifEX, "SensitivityType", "3" );
xmp->SetProperty_Int ( kXMP_NS_ExifEX, "ISOSpeed", binValue );
}
}
}
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_SensitivityType, &tagInfo );
if ( ! foundExif ) {
foundXMP = xmp->GetProperty_Int ( kXMP_NS_ExifEX, "SensitivityType", &binValue, 0 );
if ( foundXMP && (0 <= binValue) && (binValue <= 65535) ) {
exif->SetTag_Short ( kTIFF_ExifIFD, kTIFF_SensitivityType, (XMP_Uns16)binValue );
}
}
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_StandardOutputSensitivity, &tagInfo );
if ( ! foundExif ) {
foundXMP = xmp->GetProperty_Int ( kXMP_NS_ExifEX, "StandardOutputSensitivity", &binValue, 0 );
if ( foundXMP && (binValue >= 0) ) {
exif->SetTag_Long ( kTIFF_ExifIFD, kTIFF_StandardOutputSensitivity, (XMP_Uns32)binValue );
}
}
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_RecommendedExposureIndex, &tagInfo );
if ( ! foundExif ) {
foundXMP = xmp->GetProperty_Int ( kXMP_NS_ExifEX, "RecommendedExposureIndex", &binValue, 0 );
if ( foundXMP && (binValue >= 0) ) {
exif->SetTag_Long ( kTIFF_ExifIFD, kTIFF_RecommendedExposureIndex, (XMP_Uns32)binValue );
}
}
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_ISOSpeed, &tagInfo );
if ( ! foundExif ) {
foundXMP = xmp->GetProperty_Int ( kXMP_NS_ExifEX, "ISOSpeed", &binValue, 0 );
if ( foundXMP && (binValue >= 0) ) {
exif->SetTag_Long ( kTIFF_ExifIFD, kTIFF_ISOSpeed, (XMP_Uns32)binValue );
}
}
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_ISOSpeedLatitudeyyy, &tagInfo );
if ( ! foundExif ) {
foundXMP = xmp->GetProperty_Int ( kXMP_NS_ExifEX, "ISOSpeedLatitudeyyy", &binValue, 0 );
if ( foundXMP && (binValue >= 0) ) {
exif->SetTag_Long ( kTIFF_ExifIFD, kTIFF_ISOSpeedLatitudeyyy, (XMP_Uns32)binValue );
}
}
foundExif = exif->GetTag ( kTIFF_ExifIFD, kTIFF_ISOSpeedLatitudezzz, &tagInfo );
if ( ! foundExif ) {
foundXMP = xmp->GetProperty_Int ( kXMP_NS_ExifEX, "ISOSpeedLatitudezzz", &binValue, 0 );
if ( foundXMP && (binValue >= 0) ) {
exif->SetTag_Long ( kTIFF_ExifIFD, kTIFF_ISOSpeedLatitudezzz, (XMP_Uns32)binValue );
}
}
}
} catch ( ... ) {
}
} // ExportTIFF_PhotographicSensitivity
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 KioskNextHomeInterfaceBrokerImpl::GetAppController(
mojom::AppControllerRequest request) {
app_controller_->BindRequest(std::move(request));
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void nlmsg_free(struct nl_msg *msg)
{
if (!msg)
return;
msg->nm_refcnt--;
NL_DBG(4, "Returned message reference %p, %d remaining\n",
msg, msg->nm_refcnt);
if (msg->nm_refcnt < 0)
BUG();
if (msg->nm_refcnt <= 0) {
free(msg->nm_nlh);
NL_DBG(2, "msg %p: Freed\n", msg);
free(msg);
}
}
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 int cma_req_handler(struct ib_cm_id *cm_id, struct ib_cm_event *ib_event)
{
struct rdma_id_private *listen_id, *conn_id;
struct rdma_cm_event event;
int offset, ret;
u8 smac[ETH_ALEN];
u8 alt_smac[ETH_ALEN];
u8 *psmac = smac;
u8 *palt_smac = alt_smac;
int is_iboe = ((rdma_node_get_transport(cm_id->device->node_type) ==
RDMA_TRANSPORT_IB) &&
(rdma_port_get_link_layer(cm_id->device,
ib_event->param.req_rcvd.port) ==
IB_LINK_LAYER_ETHERNET));
listen_id = cm_id->context;
if (!cma_check_req_qp_type(&listen_id->id, ib_event))
return -EINVAL;
if (cma_disable_callback(listen_id, RDMA_CM_LISTEN))
return -ECONNABORTED;
memset(&event, 0, sizeof event);
offset = cma_user_data_offset(listen_id);
event.event = RDMA_CM_EVENT_CONNECT_REQUEST;
if (ib_event->event == IB_CM_SIDR_REQ_RECEIVED) {
conn_id = cma_new_udp_id(&listen_id->id, ib_event);
event.param.ud.private_data = ib_event->private_data + offset;
event.param.ud.private_data_len =
IB_CM_SIDR_REQ_PRIVATE_DATA_SIZE - offset;
} else {
conn_id = cma_new_conn_id(&listen_id->id, ib_event);
cma_set_req_event_data(&event, &ib_event->param.req_rcvd,
ib_event->private_data, offset);
}
if (!conn_id) {
ret = -ENOMEM;
goto err1;
}
mutex_lock_nested(&conn_id->handler_mutex, SINGLE_DEPTH_NESTING);
ret = cma_acquire_dev(conn_id, listen_id);
if (ret)
goto err2;
conn_id->cm_id.ib = cm_id;
cm_id->context = conn_id;
cm_id->cm_handler = cma_ib_handler;
/*
* Protect against the user destroying conn_id from another thread
* until we're done accessing it.
*/
atomic_inc(&conn_id->refcount);
ret = conn_id->id.event_handler(&conn_id->id, &event);
if (ret)
goto err3;
if (is_iboe) {
if (ib_event->param.req_rcvd.primary_path != NULL)
rdma_addr_find_smac_by_sgid(
&ib_event->param.req_rcvd.primary_path->sgid,
psmac, NULL);
else
psmac = NULL;
if (ib_event->param.req_rcvd.alternate_path != NULL)
rdma_addr_find_smac_by_sgid(
&ib_event->param.req_rcvd.alternate_path->sgid,
palt_smac, NULL);
else
palt_smac = NULL;
}
/*
* Acquire mutex to prevent user executing rdma_destroy_id()
* while we're accessing the cm_id.
*/
mutex_lock(&lock);
if (is_iboe)
ib_update_cm_av(cm_id, psmac, palt_smac);
if (cma_comp(conn_id, RDMA_CM_CONNECT) &&
(conn_id->id.qp_type != IB_QPT_UD))
ib_send_cm_mra(cm_id, CMA_CM_MRA_SETTING, NULL, 0);
mutex_unlock(&lock);
mutex_unlock(&conn_id->handler_mutex);
mutex_unlock(&listen_id->handler_mutex);
cma_deref_id(conn_id);
return 0;
err3:
cma_deref_id(conn_id);
/* Destroy the CM ID by returning a non-zero value. */
conn_id->cm_id.ib = NULL;
err2:
cma_exch(conn_id, RDMA_CM_DESTROYING);
mutex_unlock(&conn_id->handler_mutex);
err1:
mutex_unlock(&listen_id->handler_mutex);
if (conn_id)
rdma_destroy_id(&conn_id->id);
return ret;
}
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 SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer = inHeader->pBuffer
+ inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void process_bin_complete_sasl_auth(conn *c) {
assert(settings.sasl);
const char *out = NULL;
unsigned int outlen = 0;
assert(c->item);
init_sasl_conn(c);
int nkey = c->binary_header.request.keylen;
int vlen = c->binary_header.request.bodylen - nkey;
char mech[nkey+1];
memcpy(mech, ITEM_key((item*)c->item), nkey);
mech[nkey] = 0x00;
if (settings.verbose)
fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen);
const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item);
int result=-1;
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_SASL_AUTH:
result = sasl_server_start(c->sasl_conn, mech,
challenge, vlen,
&out, &outlen);
break;
case PROTOCOL_BINARY_CMD_SASL_STEP:
result = sasl_server_step(c->sasl_conn,
challenge, vlen,
&out, &outlen);
break;
default:
assert(false); /* CMD should be one of the above */
/* This code is pretty much impossible, but makes the compiler
happier */
if (settings.verbose) {
fprintf(stderr, "Unhandled command %d with challenge %s\n",
c->cmd, challenge);
}
break;
}
item_unlink(c->item);
if (settings.verbose) {
fprintf(stderr, "sasl result code: %d\n", result);
}
switch(result) {
case SASL_OK:
write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated"));
break;
case SASL_CONTINUE:
add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen);
if(outlen > 0) {
add_iov(c, out, outlen);
}
conn_set_state(c, conn_mwrite);
c->write_and_go = conn_new_cmd;
break;
default:
if (settings.verbose)
fprintf(stderr, "Unknown sasl response: %d\n", result);
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, 0);
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength)
{
uint32 row, nrows, rowsperstrip;
tstrip_t strip = 0;
tsize_t stripsize;
TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
for (row = 0; row < imagelength; row += rowsperstrip)
{
nrows = (row + rowsperstrip > imagelength) ?
imagelength - row : rowsperstrip;
stripsize = TIFFVStripSize(out, nrows);
if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0)
{
TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1);
return 1;
}
buf += stripsize;
}
return 0;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: atol10(const char *p, size_t char_cnt)
{
uint64_t l;
int digit;
l = 0;
digit = *p - '0';
while (digit >= 0 && digit < 10 && char_cnt-- > 0) {
l = (l * 10) + digit;
digit = *++p - '0';
}
return (l);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: xps_free_font(xps_context_t *ctx, xps_font_t *font)
{
if (font->font)
{
gs_font_finalize(ctx->memory, font->font);
gs_free_object(ctx->memory, font->font, "font object");
}
xps_free(ctx, font);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static v8::Handle<v8::Value> fooCallback(const v8::Arguments& args)
{
INC_STATS("DOM.Float64Array.foo");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
Float64Array* imp = V8Float64Array::toNative(args.Holder());
EXCEPTION_BLOCK(Float32Array*, array, V8Float32Array::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Float32Array::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
return toV8(imp->foo(array), args.GetIsolate());
}
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: CancelPendingTask() {
filter_->ResumeAttachOrDestroy(element_instance_id_,
MSG_ROUTING_NONE /* no plugin frame */);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: FoFiType1C *FoFiType1C::make(char *fileA, int lenA) {
FoFiType1C *ff;
ff = new FoFiType1C(fileA, lenA, gFalse);
if (!ff->parse()) {
delete ff;
return NULL;
}
return ff;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
{
fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
fflush(stderr);
}
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: bool_t auth_gssapi_unwrap_data(
OM_uint32 *major,
OM_uint32 *minor,
gss_ctx_id_t context,
uint32_t seq_num,
XDR *in_xdrs,
bool_t (*xdr_func)(),
caddr_t xdr_ptr)
{
gss_buffer_desc in_buf, out_buf;
XDR temp_xdrs;
uint32_t verf_seq_num;
int conf, qop;
unsigned int length;
PRINTF(("gssapi_unwrap_data: starting\n"));
*major = GSS_S_COMPLETE;
*minor = 0; /* assumption */
in_buf.value = NULL;
out_buf.value = NULL;
if (! xdr_bytes(in_xdrs, (char **) &in_buf.value,
&length, (unsigned int) -1)) {
PRINTF(("gssapi_unwrap_data: deserializing encrypted data failed\n"));
temp_xdrs.x_op = XDR_FREE;
(void)xdr_bytes(&temp_xdrs, (char **) &in_buf.value, &length,
(unsigned int) -1);
return FALSE;
}
in_buf.length = length;
*major = gss_unseal(minor, context, &in_buf, &out_buf, &conf,
&qop);
free(in_buf.value);
if (*major != GSS_S_COMPLETE)
return FALSE;
PRINTF(("gssapi_unwrap_data: %llu bytes data, %llu bytes sealed\n",
(unsigned long long)out_buf.length,
(unsigned long long)in_buf.length));
xdrmem_create(&temp_xdrs, out_buf.value, out_buf.length, XDR_DECODE);
/* deserialize the sequence number */
if (! xdr_u_int32(&temp_xdrs, &verf_seq_num)) {
PRINTF(("gssapi_unwrap_data: deserializing verf_seq_num failed\n"));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
if (verf_seq_num != seq_num) {
PRINTF(("gssapi_unwrap_data: seq %d specified, read %d\n",
seq_num, verf_seq_num));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
PRINTF(("gssapi_unwrap_data: unwrap seq_num %d okay\n", verf_seq_num));
/* deserialize the arguments into xdr_ptr */
if (! (*xdr_func)(&temp_xdrs, xdr_ptr)) {
PRINTF(("gssapi_unwrap_data: deserializing arguments failed\n"));
gss_release_buffer(minor, &out_buf);
xdr_free(xdr_func, xdr_ptr);
XDR_DESTROY(&temp_xdrs);
return FALSE;
}
PRINTF(("gssapi_unwrap_data: succeeding\n\n"));
gss_release_buffer(minor, &out_buf);
XDR_DESTROY(&temp_xdrs);
return TRUE;
}
CWE ID:
Target: 1
Example 2:
Code: static int opfsub(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 1:
if ( op->operands[0].type & OT_MEMORY ) {
if ( op->operands[0].type & OT_DWORD ) {
data[l++] = 0xd8;
data[l++] = 0x20 | op->operands[0].regs[0];
} else if ( op->operands[0].type & OT_QWORD ) {
data[l++] = 0xdc;
data[l++] = 0x20 | op->operands[0].regs[0];
} else {
return -1;
}
} else {
return -1;
}
break;
case 2:
if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL && op->operands[0].reg == 0 &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL ) {
data[l++] = 0xd8;
data[l++] = 0xe0 | op->operands[1].reg;
} else if ( op->operands[0].type & OT_FPUREG & ~OT_REGALL &&
op->operands[1].type & OT_FPUREG & ~OT_REGALL && op->operands[1].reg == 0 ) {
data[l++] = 0xdc;
data[l++] = 0xe8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer,
apr_size_t len, int linelimit)
{
apr_size_t i = 0;
while (i < len) {
char c = buffer[i];
ap_xlate_proto_from_ascii(&c, 1);
/* handle CRLF after the chunk */
if (ctx->state == BODY_CHUNK_END) {
if (c == LF) {
ctx->state = BODY_CHUNK;
}
i++;
continue;
}
/* handle start of the chunk */
if (ctx->state == BODY_CHUNK) {
if (!apr_isxdigit(c)) {
/*
* Detect invalid character at beginning. This also works for empty
* chunk size lines.
*/
return APR_EGENERAL;
}
else {
ctx->state = BODY_CHUNK_PART;
}
ctx->remaining = 0;
ctx->chunkbits = sizeof(long) * 8;
ctx->chunk_used = 0;
}
/* handle a chunk part, or a chunk extension */
/*
* In theory, we are supposed to expect CRLF only, but our
* test suite sends LF only. Tolerate a missing CR.
*/
if (c == ';' || c == CR) {
ctx->state = BODY_CHUNK_EXT;
}
else if (c == LF) {
if (ctx->remaining) {
ctx->state = BODY_CHUNK_DATA;
}
else {
ctx->state = BODY_CHUNK_TRAILER;
}
}
else if (ctx->state != BODY_CHUNK_EXT) {
int xvalue = 0;
/* ignore leading zeros */
if (!ctx->remaining && c == '0') {
i++;
continue;
}
if (c >= '0' && c <= '9') {
xvalue = c - '0';
}
else if (c >= 'A' && c <= 'F') {
xvalue = c - 'A' + 0xa;
}
else if (c >= 'a' && c <= 'f') {
xvalue = c - 'a' + 0xa;
}
else {
/* bogus character */
return APR_EGENERAL;
}
ctx->remaining = (ctx->remaining << 4) | xvalue;
ctx->chunkbits -= 4;
if (ctx->chunkbits <= 0 || ctx->remaining < 0) {
/* overflow */
return APR_ENOSPC;
}
}
i++;
}
/* sanity check */
ctx->chunk_used += len;
if (ctx->chunk_used < 0 || ctx->chunk_used > linelimit) {
return APR_ENOSPC;
}
return APR_SUCCESS;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: i915_gem_execbuffer2(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct drm_i915_gem_execbuffer2 *args = data;
struct drm_i915_gem_exec_object2 *exec2_list = NULL;
int ret;
if (args->buffer_count < 1) {
DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count);
return -EINVAL;
}
exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count,
GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
if (exec2_list == NULL)
exec2_list = drm_malloc_ab(sizeof(*exec2_list),
args->buffer_count);
if (exec2_list == NULL) {
DRM_DEBUG("Failed to allocate exec list for %d buffers\n",
args->buffer_count);
return -ENOMEM;
}
ret = copy_from_user(exec2_list,
(struct drm_i915_relocation_entry __user *)
(uintptr_t) args->buffers_ptr,
sizeof(*exec2_list) * args->buffer_count);
if (ret != 0) {
DRM_DEBUG("copy %d exec entries failed %d\n",
args->buffer_count, ret);
drm_free_large(exec2_list);
return -EFAULT;
}
ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
if (!ret) {
/* Copy the new buffer offsets back to the user's exec list. */
ret = copy_to_user((struct drm_i915_relocation_entry __user *)
(uintptr_t) args->buffers_ptr,
exec2_list,
sizeof(*exec2_list) * args->buffer_count);
if (ret) {
ret = -EFAULT;
DRM_DEBUG("failed to copy %d exec entries "
"back to user (%d)\n",
args->buffer_count, ret);
}
}
drm_free_large(exec2_list);
return ret;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: struct rxe_mem *lookup_mem(struct rxe_pd *pd, int access, u32 key,
enum lookup_type type)
{
struct rxe_mem *mem;
struct rxe_dev *rxe = to_rdev(pd->ibpd.device);
int index = key >> 8;
if (index >= RXE_MIN_MR_INDEX && index <= RXE_MAX_MR_INDEX) {
mem = rxe_pool_get_index(&rxe->mr_pool, index);
if (!mem)
goto err1;
} else {
goto err1;
}
if ((type == lookup_local && mem->lkey != key) ||
(type == lookup_remote && mem->rkey != key))
goto err2;
if (mem->pd != pd)
goto err2;
if (access && !(access & mem->access))
goto err2;
if (mem->state != RXE_MEM_STATE_VALID)
goto err2;
return mem;
err2:
rxe_drop_ref(mem);
err1:
return NULL;
}
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: irc_server_get_tags_to_send (const char *tags)
{
int length;
char *buf;
if (!tags && !irc_server_send_default_tags)
return NULL;
if (!tags)
return strdup (irc_server_send_default_tags);
if (!irc_server_send_default_tags)
return strdup (tags);
/* concatenate tags and irc_server_send_default_tags */
length = strlen (tags) + 1 + strlen (irc_server_send_default_tags) + 1;
buf = malloc (length);
if (buf)
snprintf (buf, length, "%s,%s", tags, irc_server_send_default_tags);
return buf;
}
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: Platform::IntPoint InRegionScrollableArea::calculateMaximumScrollPosition(const Platform::IntSize& viewportSize, const Platform::IntSize& contentsSize, float overscrollLimitFactor) const
{
ASSERT(!allowsOverscroll());
return Platform::IntPoint(std::max(contentsSize.width() - viewportSize.width(), 0) + overscrollLimitFactor,
std::max(contentsSize.height() - viewportSize.height(), 0) + overscrollLimitFactor);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void check_http_proxy(HashTable *var_table)
{
if (zend_hash_str_exists(var_table, "HTTP_PROXY", sizeof("HTTP_PROXY")-1)) {
char *local_proxy = getenv("HTTP_PROXY");
if (!local_proxy) {
zend_hash_str_del(var_table, "HTTP_PROXY", sizeof("HTTP_PROXY")-1);
} else {
zval local_zval;
ZVAL_STRING(&local_zval, local_proxy);
zend_hash_str_update(var_table, "HTTP_PROXY", sizeof("HTTP_PROXY")-1, &local_zval);
}
}
}
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: static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
struct sctp_association *assoc,
sctp_socket_type_t type)
{
struct sctp_sock *oldsp = sctp_sk(oldsk);
struct sctp_sock *newsp = sctp_sk(newsk);
struct sctp_bind_bucket *pp; /* hash list port iterator */
struct sctp_endpoint *newep = newsp->ep;
struct sk_buff *skb, *tmp;
struct sctp_ulpevent *event;
struct sctp_bind_hashbucket *head;
struct list_head tmplist;
/* Migrate socket buffer sizes and all the socket level options to the
* new socket.
*/
newsk->sk_sndbuf = oldsk->sk_sndbuf;
newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
/* Brute force copy old sctp opt. */
if (oldsp->do_auto_asconf) {
memcpy(&tmplist, &newsp->auto_asconf_list, sizeof(tmplist));
inet_sk_copy_descendant(newsk, oldsk);
memcpy(&newsp->auto_asconf_list, &tmplist, sizeof(tmplist));
} else
inet_sk_copy_descendant(newsk, oldsk);
/* Restore the ep value that was overwritten with the above structure
* copy.
*/
newsp->ep = newep;
newsp->hmac = NULL;
/* Hook this new socket in to the bind_hash list. */
head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
inet_sk(oldsk)->inet_num)];
local_bh_disable();
spin_lock(&head->lock);
pp = sctp_sk(oldsk)->bind_hash;
sk_add_bind_node(newsk, &pp->owner);
sctp_sk(newsk)->bind_hash = pp;
inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
spin_unlock(&head->lock);
local_bh_enable();
/* Copy the bind_addr list from the original endpoint to the new
* endpoint so that we can handle restarts properly
*/
sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
&oldsp->ep->base.bind_addr, GFP_KERNEL);
/* Move any messages in the old socket's receive queue that are for the
* peeled off association to the new socket's receive queue.
*/
sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsk->sk_receive_queue);
__skb_queue_tail(&newsk->sk_receive_queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clean up any messages pending delivery due to partial
* delivery. Three cases:
* 1) No partial deliver; no work.
* 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
* 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
*/
skb_queue_head_init(&newsp->pd_lobby);
atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
struct sk_buff_head *queue;
/* Decide which queue to move pd_lobby skbs to. */
if (assoc->ulpq.pd_mode) {
queue = &newsp->pd_lobby;
} else
queue = &newsk->sk_receive_queue;
/* Walk through the pd_lobby, looking for skbs that
* need moved to the new socket.
*/
sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
__skb_unlink(skb, &oldsp->pd_lobby);
__skb_queue_tail(queue, skb);
sctp_skb_set_owner_r_frag(skb, newsk);
}
}
/* Clear up any skbs waiting for the partial
* delivery to finish.
*/
if (assoc->ulpq.pd_mode)
sctp_clear_pd(oldsk, NULL);
}
sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp)
sctp_skb_set_owner_r_frag(skb, newsk);
sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp)
sctp_skb_set_owner_r_frag(skb, newsk);
/* Set the type of socket to indicate that it is peeled off from the
* original UDP-style socket or created with the accept() call on a
* TCP-style socket..
*/
newsp->type = type;
/* Mark the new socket "in-use" by the user so that any packets
* that may arrive on the association after we've moved it are
* queued to the backlog. This prevents a potential race between
* backlog processing on the old socket and new-packet processing
* on the new socket.
*
* The caller has just allocated newsk so we can guarantee that other
* paths won't try to lock it and then oldsk.
*/
lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
sctp_assoc_migrate(assoc, newsk);
/* If the association on the newsk is already closed before accept()
* is called, set RCV_SHUTDOWN flag.
*/
if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
newsk->sk_shutdown |= RCV_SHUTDOWN;
newsk->sk_state = SCTP_SS_ESTABLISHED;
release_sock(newsk);
}
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: static void SetUpTestCase() {
input_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1;
output_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kOutputBufferSize));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int nfsd_lookup_parent(struct svc_rqst *rqstp, struct dentry *dparent, struct svc_export **exp, struct dentry **dentryp)
{
struct svc_export *exp2;
struct path path = {.mnt = mntget((*exp)->ex_path.mnt),
.dentry = dget(dparent)};
follow_to_parent(&path);
exp2 = rqst_exp_parent(rqstp, &path);
if (PTR_ERR(exp2) == -ENOENT) {
*dentryp = dget(dparent);
} else if (IS_ERR(exp2)) {
path_put(&path);
return PTR_ERR(exp2);
} else {
*dentryp = dget(path.dentry);
exp_put(*exp);
*exp = exp2;
}
path_put(&path);
return 0;
}
CWE ID: CWE-404
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: pimv1_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
register const u_char *ep;
register u_char type;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
ND_TCHECK(bp[1]);
type = bp[1];
ND_PRINT((ndo, " %s", tok2str(pimv1_type_str, "[type %u]", type)));
switch (type) {
case PIMV1_TYPE_QUERY:
if (ND_TTEST(bp[8])) {
switch (bp[8] >> 4) {
case 0:
ND_PRINT((ndo, " Dense-mode"));
break;
case 1:
ND_PRINT((ndo, " Sparse-mode"));
break;
case 2:
ND_PRINT((ndo, " Sparse-Dense-mode"));
break;
default:
ND_PRINT((ndo, " mode-%d", bp[8] >> 4));
break;
}
}
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[10],2);
ND_PRINT((ndo, " (Hold-time "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[10]));
ND_PRINT((ndo, ")"));
}
break;
case PIMV1_TYPE_REGISTER:
ND_TCHECK2(bp[8], 20); /* ip header */
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[20]),
ipaddr_string(ndo, &bp[24])));
break;
case PIMV1_TYPE_REGISTER_STOP:
ND_TCHECK2(bp[12], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[8]),
ipaddr_string(ndo, &bp[12])));
break;
case PIMV1_TYPE_RP_REACHABILITY:
if (ndo->ndo_vflag) {
ND_TCHECK2(bp[22], 2);
ND_PRINT((ndo, " group %s", ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_PRINT((ndo, " RP %s hold ", ipaddr_string(ndo, &bp[16])));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[22]));
}
break;
case PIMV1_TYPE_ASSERT:
ND_TCHECK2(bp[16], sizeof(struct in_addr));
ND_PRINT((ndo, " for %s > %s", ipaddr_string(ndo, &bp[16]),
ipaddr_string(ndo, &bp[8])));
if (EXTRACT_32BITS(&bp[12]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[12])));
ND_TCHECK2(bp[24], 4);
ND_PRINT((ndo, " %s pref %d metric %d",
(bp[20] & 0x80) ? "RP-tree" : "SPT",
EXTRACT_32BITS(&bp[20]) & 0x7fffffff,
EXTRACT_32BITS(&bp[24])));
break;
case PIMV1_TYPE_JOIN_PRUNE:
case PIMV1_TYPE_GRAFT:
case PIMV1_TYPE_GRAFT_ACK:
if (ndo->ndo_vflag)
pimv1_join_prune_print(ndo, &bp[8], len - 8);
break;
}
ND_TCHECK(bp[4]);
if ((bp[4] >> 4) != 1)
ND_PRINT((ndo, " [v%d]", bp[4] >> 4));
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
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: static netdev_tx_t hns_nic_net_xmit(struct sk_buff *skb,
struct net_device *ndev)
{
struct hns_nic_priv *priv = netdev_priv(ndev);
int ret;
assert(skb->queue_mapping < ndev->ae_handle->q_num);
ret = hns_nic_net_xmit_hw(ndev, skb,
&tx_ring_data(priv, skb->queue_mapping));
if (ret == NETDEV_TX_OK) {
netif_trans_update(ndev);
ndev->stats.tx_bytes += skb->len;
ndev->stats.tx_packets++;
}
return (netdev_tx_t)ret;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: Write_CVT_Stretched( TT_ExecContext exc,
FT_ULong idx,
FT_F26Dot6 value )
{
exc->cvt[idx] = FT_DivFix( value, Current_Ratio( exc ) );
}
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: void WorkerFetchContext::DispatchWillSendRequest(
unsigned long identifier,
ResourceRequest& request,
const ResourceResponse& redirect_response,
const FetchInitiatorInfo& initiator_info) {
probe::willSendRequest(global_scope_, identifier, nullptr, request,
redirect_response, initiator_info);
}
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_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode,
const char *name, size_t namelen)
{
char *copy;
/*
* Refuse names with embedded NUL bytes.
* XXX: Do we need to push an error onto the error stack?
*/
if (name && memchr(name, '\0', namelen))
return 0;
if (mode == SET_HOST && id->hosts) {
string_stack_free(id->hosts);
id->hosts = NULL;
}
if (name == NULL || namelen == 0)
return 1;
copy = strndup(name, namelen);
if (copy == NULL)
return 0;
if (id->hosts == NULL &&
(id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) {
free(copy);
return 0;
}
if (!sk_OPENSSL_STRING_push(id->hosts, copy)) {
free(copy);
if (sk_OPENSSL_STRING_num(id->hosts) == 0) {
sk_OPENSSL_STRING_free(id->hosts);
id->hosts = NULL;
}
return 0;
}
return 1;
}
CWE ID: CWE-295
Target: 1
Example 2:
Code: static int init_phdr(ELFOBJ *bin) {
ut32 phdr_size;
ut8 phdr[sizeof (Elf_(Phdr))] = {0};
int i, j, len;
if (!bin->ehdr.e_phnum) {
return false;
}
if (bin->phdr) {
return true;
}
if (!UT32_MUL (&phdr_size, (ut32)bin->ehdr.e_phnum, sizeof (Elf_(Phdr)))) {
return false;
}
if (!phdr_size) {
return false;
}
if (phdr_size > bin->size) {
return false;
}
if (phdr_size > (ut32)bin->size) {
return false;
}
if (bin->ehdr.e_phoff > bin->size) {
return false;
}
if (bin->ehdr.e_phoff + phdr_size > bin->size) {
return false;
}
if (!(bin->phdr = calloc (phdr_size, 1))) {
perror ("malloc (phdr)");
return false;
}
for (i = 0; i < bin->ehdr.e_phnum; i++) {
j = 0;
len = r_buf_read_at (bin->b, bin->ehdr.e_phoff + i * sizeof (Elf_(Phdr)), phdr, sizeof (Elf_(Phdr)));
if (len < 1) {
bprintf ("Warning: read (phdr)\n");
R_FREE (bin->phdr);
return false;
}
bin->phdr[i].p_type = READ32 (phdr, j)
#if R_BIN_ELF64
bin->phdr[i].p_flags = READ32 (phdr, j)
bin->phdr[i].p_offset = READ64 (phdr, j)
bin->phdr[i].p_vaddr = READ64 (phdr, j)
bin->phdr[i].p_paddr = READ64 (phdr, j)
bin->phdr[i].p_filesz = READ64 (phdr, j)
bin->phdr[i].p_memsz = READ64 (phdr, j)
bin->phdr[i].p_align = READ64 (phdr, j)
#else
bin->phdr[i].p_offset = READ32 (phdr, j)
bin->phdr[i].p_vaddr = READ32 (phdr, j)
bin->phdr[i].p_paddr = READ32 (phdr, j)
bin->phdr[i].p_filesz = READ32 (phdr, j)
bin->phdr[i].p_memsz = READ32 (phdr, j)
bin->phdr[i].p_flags = READ32 (phdr, j)
bin->phdr[i].p_align = READ32 (phdr, j)
#endif
}
sdb_num_set (bin->kv, "elf_phdr.offset", bin->ehdr.e_phoff, 0);
sdb_num_set (bin->kv, "elf_phdr.size", sizeof (Elf_(Phdr)), 0);
sdb_set (bin->kv, "elf_p_type.cparse", "enum elf_p_type {PT_NULL=0,PT_LOAD=1,PT_DYNAMIC=2,"
"PT_INTERP=3,PT_NOTE=4,PT_SHLIB=5,PT_PHDR=6,PT_LOOS=0x60000000,"
"PT_HIOS=0x6fffffff,PT_LOPROC=0x70000000,PT_HIPROC=0x7fffffff};", 0);
sdb_set (bin->kv, "elf_p_flags.cparse", "enum elf_p_flags {PF_None=0,PF_Exec=1,"
"PF_Write=2,PF_Write_Exec=3,PF_Read=4,PF_Read_Exec=5,PF_Read_Write=6,"
"PF_Read_Write_Exec=7};", 0);
#if R_BIN_ELF64
sdb_set (bin->kv, "elf_phdr.format", "[4]E[4]Eqqqqqq (elf_p_type)type (elf_p_flags)flags"
" offset vaddr paddr filesz memsz align", 0);
#else
sdb_set (bin->kv, "elf_phdr.format", "[4]Exxxxx[4]Ex (elf_p_type)type offset vaddr paddr"
" filesz memsz (elf_p_flags)flags align", 0);
#endif
return true;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GLES2DecoderImpl::GetTexParameterImpl(
GLenum target, GLenum pname, GLfloat* fparams, GLint* iparams,
const char* function_name) {
TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget(
&state_, target);
if (!texture_ref) {
LOCAL_SET_GL_ERROR(
GL_INVALID_OPERATION, function_name, "unknown texture for target");
return;
}
Texture* texture = texture_ref->texture();
switch (pname) {
case GL_TEXTURE_MAX_ANISOTROPY_EXT:
if (workarounds().init_texture_max_anisotropy) {
texture->InitTextureMaxAnisotropyIfNeeded(target);
}
break;
case GL_TEXTURE_IMMUTABLE_LEVELS:
if (gl_version_info().IsLowerThanGL(4, 2)) {
GLint levels = texture->GetImmutableLevels();
if (fparams) {
fparams[0] = static_cast<GLfloat>(levels);
} else {
iparams[0] = levels;
}
return;
}
break;
if (workarounds().use_shadowed_tex_level_params) {
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->base_level());
} else {
iparams[0] = texture->base_level();
}
return;
}
break;
case GL_TEXTURE_MAX_LEVEL:
if (workarounds().use_shadowed_tex_level_params) {
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->max_level());
} else {
iparams[0] = texture->max_level();
}
return;
}
break;
case GL_TEXTURE_SWIZZLE_R:
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->swizzle_r());
} else {
iparams[0] = texture->swizzle_r();
}
return;
case GL_TEXTURE_SWIZZLE_G:
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->swizzle_g());
} else {
iparams[0] = texture->swizzle_g();
}
return;
case GL_TEXTURE_SWIZZLE_B:
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->swizzle_b());
} else {
iparams[0] = texture->swizzle_b();
}
return;
case GL_TEXTURE_SWIZZLE_A:
if (fparams) {
fparams[0] = static_cast<GLfloat>(texture->swizzle_a());
} else {
iparams[0] = texture->swizzle_a();
}
return;
default:
break;
}
if (fparams) {
api()->glGetTexParameterfvFn(target, pname, fparams);
} else {
api()->glGetTexParameterivFn(target, pname, iparams);
}
}
CWE ID: CWE-119
Output: | 1 |
Subsets and Splits