prompt
stringlengths 799
20.4k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void virtio_gpu_set_scanout(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_simple_resource *res;
struct virtio_gpu_scanout *scanout;
pixman_format_code_t format;
uint32_t offset;
int bpp;
struct virtio_gpu_set_scanout ss;
VIRTIO_GPU_FILL_CMD(ss);
trace_virtio_gpu_cmd_set_scanout(ss.scanout_id, ss.resource_id,
ss.r.width, ss.r.height, ss.r.x, ss.r.y);
if (ss.scanout_id >= g->conf.max_outputs) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
g->enable = 1;
if (ss.resource_id == 0) {
scanout = &g->scanout[ss.scanout_id];
if (scanout->resource_id) {
res = virtio_gpu_find_resource(g, scanout->resource_id);
if (res) {
res->scanout_bitmask &= ~(1 << ss.scanout_id);
}
}
if (ss.scanout_id == 0) {
qemu_log_mask(LOG_GUEST_ERROR,
"%s: illegal scanout id specified %d",
__func__, ss.scanout_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID;
return;
}
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, NULL);
scanout->ds = NULL;
scanout->width = 0;
scanout->height = 0;
return;
}
/* create a surface for this scanout */
res = virtio_gpu_find_resource(g, ss.resource_id);
if (!res) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal resource specified %d\n",
__func__, ss.resource_id);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID;
return;
}
if (ss.r.x > res->width ||
ss.r.y > res->height ||
ss.r.width > res->width ||
ss.r.height > res->height ||
ss.r.x + ss.r.width > res->width ||
ss.r.y + ss.r.height > res->height) {
qemu_log_mask(LOG_GUEST_ERROR, "%s: illegal scanout %d bounds for"
" resource %d, (%d,%d)+%d,%d vs %d %d\n",
__func__, ss.scanout_id, ss.resource_id, ss.r.x, ss.r.y,
ss.r.width, ss.r.height, res->width, res->height);
cmd->error = VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER;
return;
}
scanout = &g->scanout[ss.scanout_id];
format = pixman_image_get_format(res->image);
bpp = (PIXMAN_FORMAT_BPP(format) + 7) / 8;
offset = (ss.r.x * bpp) + ss.r.y * pixman_image_get_stride(res->image);
if (!scanout->ds || surface_data(scanout->ds)
!= ((uint8_t *)pixman_image_get_data(res->image) + offset) ||
scanout->width != ss.r.width ||
scanout->height != ss.r.height) {
pixman_image_t *rect;
void *ptr = (uint8_t *)pixman_image_get_data(res->image) + offset;
rect = pixman_image_create_bits(format, ss.r.width, ss.r.height, ptr,
pixman_image_get_stride(res->image));
pixman_image_ref(res->image);
pixman_image_set_destroy_function(rect, virtio_unref_resource,
res->image);
/* realloc the surface ptr */
scanout->ds = qemu_create_displaysurface_pixman(rect);
if (!scanout->ds) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
return;
}
dpy_gfx_replace_surface(g->scanout[ss.scanout_id].con, scanout->ds);
}
scanout->resource_id = ss.resource_id;
scanout->x = ss.r.x;
scanout->y = ss.r.y;
scanout->width = ss.r.width;
scanout->height = ss.r.height;
}
CWE ID: CWE-772
Target: 1
Example 2:
Code: cmsBool Type_UcrBg_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
{
cmsUcrBg* Value = (cmsUcrBg*) Ptr;
cmsUInt32Number TextSize;
char* Text;
if (!_cmsWriteUInt32Number(io, Value ->Ucr ->nEntries)) return FALSE;
if (!_cmsWriteUInt16Array(io, Value ->Ucr ->nEntries, Value ->Ucr ->Table16)) return FALSE;
if (!_cmsWriteUInt32Number(io, Value ->Bg ->nEntries)) return FALSE;
if (!_cmsWriteUInt16Array(io, Value ->Bg ->nEntries, Value ->Bg ->Table16)) return FALSE;
TextSize = cmsMLUgetASCII(Value ->Desc, cmsNoLanguage, cmsNoCountry, NULL, 0);
Text = (char*) _cmsMalloc(self ->ContextID, TextSize);
if (cmsMLUgetASCII(Value ->Desc, cmsNoLanguage, cmsNoCountry, Text, TextSize) != TextSize) return FALSE;
if (!io ->Write(io, TextSize, Text)) return FALSE;
_cmsFree(self ->ContextID, Text);
return TRUE;
cmsUNUSED_PARAMETER(nItems);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,
unsigned long end, unsigned long vmflag)
{
unsigned long addr;
/* do a global flush by default */
unsigned long base_pages_to_flush = TLB_FLUSH_ALL;
preempt_disable();
if (current->active_mm != mm)
goto out;
if (!current->mm) {
leave_mm(smp_processor_id());
goto out;
}
if ((end != TLB_FLUSH_ALL) && !(vmflag & VM_HUGETLB))
base_pages_to_flush = (end - start) >> PAGE_SHIFT;
if (base_pages_to_flush > tlb_single_page_flush_ceiling) {
base_pages_to_flush = TLB_FLUSH_ALL;
count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ALL);
local_flush_tlb();
} else {
/* flush range by one by one 'invlpg' */
for (addr = start; addr < end; addr += PAGE_SIZE) {
count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ONE);
__flush_tlb_single(addr);
}
}
trace_tlb_flush(TLB_LOCAL_MM_SHOOTDOWN, base_pages_to_flush);
out:
if (base_pages_to_flush == TLB_FLUSH_ALL) {
start = 0UL;
end = TLB_FLUSH_ALL;
}
if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids)
flush_tlb_others(mm_cpumask(mm), mm, start, end);
preempt_enable();
}
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: int module_load(
YR_SCAN_CONTEXT* context,
YR_OBJECT* module_object,
void* module_data,
size_t module_data_size)
{
set_integer(1, module_object, "constants.one");
set_integer(2, module_object, "constants.two");
set_string("foo", module_object, "constants.foo");
set_string("", module_object, "constants.empty");
set_integer(1, module_object, "struct_array[1].i");
set_integer(0, module_object, "integer_array[%i]", 0);
set_integer(1, module_object, "integer_array[%i]", 1);
set_integer(2, module_object, "integer_array[%i]", 2);
set_string("foo", module_object, "string_array[%i]", 0);
set_string("bar", module_object, "string_array[%i]", 1);
set_string("baz", module_object, "string_array[%i]", 2);
set_sized_string("foo\0bar", 7, module_object, "string_array[%i]", 3);
set_string("foo", module_object, "string_dict[%s]", "foo");
set_string("bar", module_object, "string_dict[\"bar\"]");
set_string("foo", module_object, "struct_dict[%s].s", "foo");
set_integer(1, module_object, "struct_dict[%s].i", "foo");
return ERROR_SUCCESS;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
{
unsigned long current_rip = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
return current_rip == linear_rip;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderFrameHostImpl::SubresourceResponseStarted(const GURL& url,
const GURL& referrer,
const std::string& method,
ResourceType resource_type,
const std::string& ip,
uint32_t cert_status) {
delegate_->SubresourceResponseStarted(url, referrer, method, resource_type,
ip, cert_status);
}
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 uint16_t transmit_data(serial_data_type_t type, uint8_t *data, uint16_t length) {
assert(data != NULL);
assert(length > 0);
if (type < DATA_TYPE_COMMAND || type > DATA_TYPE_SCO) {
LOG_ERROR("%s invalid data type: %d", __func__, type);
return 0;
}
--data;
uint8_t previous_byte = *data;
*(data) = type;
++length;
uint16_t transmitted_length = 0;
while (length > 0) {
ssize_t ret = write(uart_fd, data + transmitted_length, length);
switch (ret) {
case -1:
LOG_ERROR("In %s, error writing to the uart serial port: %s", __func__, strerror(errno));
goto done;
case 0:
goto done;
default:
transmitted_length += ret;
length -= ret;
break;
}
}
done:;
*(data) = previous_byte;
if (transmitted_length > 0)
--transmitted_length;
return transmitted_length;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: std::string ProfileSyncService::QuerySyncStatusSummary() {
if (unrecoverable_error_detected_) {
return "Unrecoverable error detected";
} else if (!backend_.get()) {
return "Syncing not enabled";
} else if (backend_.get() && !HasSyncSetupCompleted()) {
return "First time sync setup incomplete";
} else if (backend_.get() && HasSyncSetupCompleted() &&
data_type_manager_.get() &&
data_type_manager_->state() != DataTypeManager::CONFIGURED) {
return "Datatypes not fully initialized";
} else if (ShouldPushChanges()) {
return "Sync service initialized";
} else {
return "Status unknown: Internal error?";
}
}
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 void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
UNIXCB(skb).secid = scm->secid;
}
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 ExtensionsGuestViewMessageFilter::MimeHandlerViewGuestCreatedCallback(
int element_instance_id,
int embedder_render_process_id,
int embedder_render_frame_id,
int32_t plugin_frame_routing_id,
const gfx::Size& element_size,
mime_handler::BeforeUnloadControlPtrInfo before_unload_control,
bool is_full_page_plugin,
WebContents* web_contents) {
auto* guest_view = MimeHandlerViewGuest::FromWebContents(web_contents);
if (!guest_view)
return;
guest_view->SetBeforeUnloadController(std::move(before_unload_control));
int guest_instance_id = guest_view->guest_instance_id();
auto* rfh = RenderFrameHost::FromID(embedder_render_process_id,
embedder_render_frame_id);
if (!rfh)
return;
guest_view->SetEmbedderFrame(embedder_render_process_id,
embedder_render_frame_id);
base::DictionaryValue attach_params;
attach_params.SetInteger(guest_view::kElementWidth, element_size.width());
attach_params.SetInteger(guest_view::kElementHeight, element_size.height());
auto* manager = GuestViewManager::FromBrowserContext(browser_context_);
if (!manager) {
guest_view::bad_message::ReceivedBadMessage(
this,
guest_view::bad_message::GVMF_UNEXPECTED_MESSAGE_BEFORE_GVM_CREATION);
guest_view->Destroy(true);
return;
}
manager->AttachGuest(embedder_render_process_id, element_instance_id,
guest_instance_id, attach_params);
if (!content::MimeHandlerViewMode::UsesCrossProcessFrame()) {
rfh->Send(new ExtensionsGuestViewMsg_CreateMimeHandlerViewGuestACK(
element_instance_id));
return;
}
auto* plugin_rfh = RenderFrameHost::FromID(embedder_render_process_id,
plugin_frame_routing_id);
if (!plugin_rfh) {
plugin_rfh = RenderFrameHost::FromPlaceholderId(embedder_render_process_id,
plugin_frame_routing_id);
}
if (!plugin_rfh) {
guest_view->GetEmbedderFrame()->Send(
new ExtensionsGuestViewMsg_RetryCreatingMimeHandlerViewGuest(
element_instance_id));
guest_view->Destroy(true);
return;
}
if (guest_view->web_contents()->CanAttachToOuterContentsFrame(plugin_rfh)) {
guest_view->AttachToOuterWebContentsFrame(plugin_rfh, element_instance_id,
is_full_page_plugin);
} else {
frame_navigation_helpers_[element_instance_id] =
std::make_unique<FrameNavigationHelper>(
plugin_rfh, guest_view->guest_instance_id(), element_instance_id,
is_full_page_plugin, this);
}
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int __init floppy_setup(char *str)
{
int i;
int param;
int ints[11];
str = get_options(str, ARRAY_SIZE(ints), ints);
if (str) {
for (i = 0; i < ARRAY_SIZE(config_params); i++) {
if (strcmp(str, config_params[i].name) == 0) {
if (ints[0])
param = ints[1];
else
param = config_params[i].def_param;
if (config_params[i].fn)
config_params[i].fn(ints, param,
config_params[i].
param2);
if (config_params[i].var) {
DPRINT("%s=%d\n", str, param);
*config_params[i].var = param;
}
return 1;
}
}
}
if (str) {
DPRINT("unknown floppy option [%s]\n", str);
DPRINT("allowed options are:");
for (i = 0; i < ARRAY_SIZE(config_params); i++)
pr_cont(" %s", config_params[i].name);
pr_cont("\n");
} else
DPRINT("botched floppy option\n");
DPRINT("Read Documentation/blockdev/floppy.txt\n");
return 0;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Notification::Notification(ExecutionContext* context, const WebNotificationData& data)
: ActiveDOMObject(context)
, m_data(data)
, m_persistentId(kInvalidPersistentId)
, m_state(NotificationStateIdle)
, m_asyncRunner(AsyncMethodRunner<Notification>::create(this, &Notification::show))
{
ASSERT(notificationManager());
}
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: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static char *php_session_encode(int *newlen TSRMLS_DC) /* {{{ */
{
char *ret = NULL;
IF_SESSION_VARS() {
if (!PS(serializer)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
ret = NULL;
} else if (PS(serializer)->encode(&ret, newlen TSRMLS_CC) == FAILURE) {
ret = NULL;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot encode non-existent session");
}
return ret;
}
/* }}} */
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 struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie)
{
struct rtable *rt = (struct rtable *) dst;
/* All IPV4 dsts are created with ->obsolete set to the value
* DST_OBSOLETE_FORCE_CHK which forces validation calls down
* into this function always.
*
* When a PMTU/redirect information update invalidates a route,
* this is indicated by setting obsolete to DST_OBSOLETE_KILL or
* DST_OBSOLETE_DEAD by dst_free().
*/
if (dst->obsolete != DST_OBSOLETE_FORCE_CHK || rt_is_expired(rt))
return NULL;
return dst;
}
CWE ID: CWE-17
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: vsock_stream_recvmsg(struct kiocb *kiocb,
struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk;
struct vsock_sock *vsk;
int err;
size_t target;
ssize_t copied;
long timeout;
struct vsock_transport_recv_notify_data recv_data;
DEFINE_WAIT(wait);
sk = sock->sk;
vsk = vsock_sk(sk);
err = 0;
lock_sock(sk);
if (sk->sk_state != SS_CONNECTED) {
/* Recvmsg is supposed to return 0 if a peer performs an
* orderly shutdown. Differentiate between that case and when a
* peer has not connected or a local shutdown occured with the
* SOCK_DONE flag.
*/
if (sock_flag(sk, SOCK_DONE))
err = 0;
else
err = -ENOTCONN;
goto out;
}
if (flags & MSG_OOB) {
err = -EOPNOTSUPP;
goto out;
}
/* We don't check peer_shutdown flag here since peer may actually shut
* down, but there can be data in the queue that a local socket can
* receive.
*/
if (sk->sk_shutdown & RCV_SHUTDOWN) {
err = 0;
goto out;
}
/* It is valid on Linux to pass in a zero-length receive buffer. This
* is not an error. We may as well bail out now.
*/
if (!len) {
err = 0;
goto out;
}
/* We must not copy less than target bytes into the user's buffer
* before returning successfully, so we wait for the consume queue to
* have that much data to consume before dequeueing. Note that this
* makes it impossible to handle cases where target is greater than the
* queue size.
*/
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
if (target >= transport->stream_rcvhiwat(vsk)) {
err = -ENOMEM;
goto out;
}
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
copied = 0;
err = transport->notify_recv_init(vsk, target, &recv_data);
if (err < 0)
goto out;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
while (1) {
s64 ready = vsock_stream_has_data(vsk);
if (ready < 0) {
/* Invalid queue pair content. XXX This should be
* changed to a connection reset in a later change.
*/
err = -ENOMEM;
goto out_wait;
} else if (ready > 0) {
ssize_t read;
err = transport->notify_recv_pre_dequeue(
vsk, target, &recv_data);
if (err < 0)
break;
read = transport->stream_dequeue(
vsk, msg->msg_iov,
len - copied, flags);
if (read < 0) {
err = -ENOMEM;
break;
}
copied += read;
err = transport->notify_recv_post_dequeue(
vsk, target, read,
!(flags & MSG_PEEK), &recv_data);
if (err < 0)
goto out_wait;
if (read >= target || flags & MSG_PEEK)
break;
target -= read;
} else {
if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN)
|| (vsk->peer_shutdown & SEND_SHUTDOWN)) {
break;
}
/* Don't wait for non-blocking sockets. */
if (timeout == 0) {
err = -EAGAIN;
break;
}
err = transport->notify_recv_pre_block(
vsk, target, &recv_data);
if (err < 0)
break;
release_sock(sk);
timeout = schedule_timeout(timeout);
lock_sock(sk);
if (signal_pending(current)) {
err = sock_intr_errno(timeout);
break;
} else if (timeout == 0) {
err = -EAGAIN;
break;
}
prepare_to_wait(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
}
}
if (sk->sk_err)
err = -sk->sk_err;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
err = 0;
if (copied > 0) {
/* We only do these additional bookkeeping/notification steps
* if we actually copied something out of the queue pair
* instead of just peeking ahead.
*/
if (!(flags & MSG_PEEK)) {
/* If the other side has shutdown for sending and there
* is nothing more to read, then modify the socket
* state.
*/
if (vsk->peer_shutdown & SEND_SHUTDOWN) {
if (vsock_stream_has_data(vsk) <= 0) {
sk->sk_state = SS_UNCONNECTED;
sock_set_flag(sk, SOCK_DONE);
sk->sk_state_change(sk);
}
}
}
err = copied;
}
out_wait:
finish_wait(sk_sleep(sk), &wait);
out:
release_sock(sk);
return err;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: int insn_get_modrm_rm_off(struct insn *insn, struct pt_regs *regs)
{
return get_reg_offset(insn, regs, REG_TYPE_RM);
}
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 ipgre_rcv(struct sk_buff *skb)
{
struct iphdr *iph;
u8 *h;
__be16 flags;
__sum16 csum = 0;
__be32 key = 0;
u32 seqno = 0;
struct ip_tunnel *tunnel;
int offset = 4;
__be16 gre_proto;
if (!pskb_may_pull(skb, 16))
goto drop_nolock;
iph = ip_hdr(skb);
h = skb->data;
flags = *(__be16*)h;
if (flags&(GRE_CSUM|GRE_KEY|GRE_ROUTING|GRE_SEQ|GRE_VERSION)) {
/* - Version must be 0.
- We do not support routing headers.
*/
if (flags&(GRE_VERSION|GRE_ROUTING))
goto drop_nolock;
if (flags&GRE_CSUM) {
switch (skb->ip_summed) {
case CHECKSUM_COMPLETE:
csum = csum_fold(skb->csum);
if (!csum)
break;
/* fall through */
case CHECKSUM_NONE:
skb->csum = 0;
csum = __skb_checksum_complete(skb);
skb->ip_summed = CHECKSUM_COMPLETE;
}
offset += 4;
}
if (flags&GRE_KEY) {
key = *(__be32*)(h + offset);
offset += 4;
}
if (flags&GRE_SEQ) {
seqno = ntohl(*(__be32*)(h + offset));
offset += 4;
}
}
gre_proto = *(__be16 *)(h + 2);
rcu_read_lock();
if ((tunnel = ipgre_tunnel_lookup(skb->dev,
iph->saddr, iph->daddr, key,
gre_proto))) {
struct pcpu_tstats *tstats;
secpath_reset(skb);
skb->protocol = gre_proto;
/* WCCP version 1 and 2 protocol decoding.
* - Change protocol to IP
* - When dealing with WCCPv2, Skip extra 4 bytes in GRE header
*/
if (flags == 0 && gre_proto == htons(ETH_P_WCCP)) {
skb->protocol = htons(ETH_P_IP);
if ((*(h + offset) & 0xF0) != 0x40)
offset += 4;
}
skb->mac_header = skb->network_header;
__pskb_pull(skb, offset);
skb_postpull_rcsum(skb, skb_transport_header(skb), offset);
skb->pkt_type = PACKET_HOST;
#ifdef CONFIG_NET_IPGRE_BROADCAST
if (ipv4_is_multicast(iph->daddr)) {
/* Looped back packet, drop it! */
if (rt_is_output_route(skb_rtable(skb)))
goto drop;
tunnel->dev->stats.multicast++;
skb->pkt_type = PACKET_BROADCAST;
}
#endif
if (((flags&GRE_CSUM) && csum) ||
(!(flags&GRE_CSUM) && tunnel->parms.i_flags&GRE_CSUM)) {
tunnel->dev->stats.rx_crc_errors++;
tunnel->dev->stats.rx_errors++;
goto drop;
}
if (tunnel->parms.i_flags&GRE_SEQ) {
if (!(flags&GRE_SEQ) ||
(tunnel->i_seqno && (s32)(seqno - tunnel->i_seqno) < 0)) {
tunnel->dev->stats.rx_fifo_errors++;
tunnel->dev->stats.rx_errors++;
goto drop;
}
tunnel->i_seqno = seqno + 1;
}
/* Warning: All skb pointers will be invalidated! */
if (tunnel->dev->type == ARPHRD_ETHER) {
if (!pskb_may_pull(skb, ETH_HLEN)) {
tunnel->dev->stats.rx_length_errors++;
tunnel->dev->stats.rx_errors++;
goto drop;
}
iph = ip_hdr(skb);
skb->protocol = eth_type_trans(skb, tunnel->dev);
skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
}
tstats = this_cpu_ptr(tunnel->dev->tstats);
tstats->rx_packets++;
tstats->rx_bytes += skb->len;
__skb_tunnel_rx(skb, tunnel->dev);
skb_reset_network_header(skb);
ipgre_ecn_decapsulate(iph, skb);
netif_rx(skb);
rcu_read_unlock();
return 0;
}
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0);
drop:
rcu_read_unlock();
drop_nolock:
kfree_skb(skb);
return 0;
}
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: bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
#if defined(ENABLE_BASIC_PRINTING)
IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
#endif // ENABLE_BASIC_PRINTING
IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
SetScriptedPrintBlocked)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
CWE ID:
Target: 1
Example 2:
Code: double WebPagePrivate::currentZoomFactor() const
{
return currentScale();
}
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 base64decode_block(unsigned char *target, const char *data, size_t data_size)
{
int w1,w2,w3,w4;
int i;
size_t n;
if (!data || (data_size <= 0)) {
return 0;
}
n = 0;
i = 0;
while (n < data_size-3) {
w1 = base64_table[(int)data[n]];
w2 = base64_table[(int)data[n+1]];
w3 = base64_table[(int)data[n+2]];
w4 = base64_table[(int)data[n+3]];
if (w2 >= 0) {
target[i++] = (char)((w1*4 + (w2 >> 4)) & 255);
}
if (w3 >= 0) {
target[i++] = (char)((w2*16 + (w3 >> 2)) & 255);
}
if (w4 >= 0) {
target[i++] = (char)((w3*64 + w4) & 255);
}
n+=4;
}
return i;
}
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: GDataDirectory* AddDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service,
int sequence_id) {
GDataDirectory* dir = new GDataDirectory(NULL, directory_service);
const std::string dir_name = "dir" + base::IntToString(sequence_id);
const std::string resource_id = std::string("dir_resource_id:") +
dir_name;
dir->set_title(dir_name);
dir->set_resource_id(resource_id);
GDataFileError error = GDATA_FILE_ERROR_FAILED;
FilePath moved_file_path;
directory_service->MoveEntryToDirectory(
parent->GetFilePath(),
dir,
base::Bind(&test_util::CopyResultsFromFileMoveCallback,
&error,
&moved_file_path));
test_util::RunBlockingPoolTask();
EXPECT_EQ(GDATA_FILE_OK, error);
EXPECT_EQ(parent->GetFilePath().AppendASCII(dir_name), moved_file_path);
return dir;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int pseudo_lld_bus_match(struct device *dev,
struct device_driver *dev_driver)
{
return 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 FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL(
const String& source,
Document* owner_document) {
Document* document = frame_->GetDocument();
if (!document_loader_ ||
document->PageDismissalEventBeingDispatched() != Document::kNoDismissal)
return;
UseCounter::Count(*document, WebFeature::kReplaceDocumentViaJavaScriptURL);
const KURL& url = document->Url();
WebGlobalObjectReusePolicy global_object_reuse_policy =
frame_->ShouldReuseDefaultView(url)
? WebGlobalObjectReusePolicy::kUseExisting
: WebGlobalObjectReusePolicy::kCreateNew;
StopAllLoaders();
SubframeLoadingDisabler disabler(document);
frame_->DetachChildren();
if (!frame_->IsAttached() || document != frame_->GetDocument())
return;
frame_->GetDocument()->Shutdown();
Client()->TransitionToCommittedForNewPage();
document_loader_->ReplaceDocumentWhileExecutingJavaScriptURL(
url, owner_document, global_object_reuse_policy, source);
}
CWE ID: CWE-285
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 parse_arguments(int *argc_p, const char ***argv_p)
{
static poptContext pc;
char *ref = lp_refuse_options(module_id);
const char *arg, **argv = *argv_p;
int argc = *argc_p;
int opt;
if (ref && *ref)
set_refuse_options(ref);
set_refuse_options("log-file*");
#ifdef ICONV_OPTION
if (!*lp_charset(module_id))
set_refuse_options("iconv");
#endif
}
CWE ID:
Target: 1
Example 2:
Code: xmlHaltParser(xmlParserCtxtPtr ctxt) {
if (ctxt == NULL)
return;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
if (ctxt->input != NULL) {
/*
* in case there was a specific allocation deallocate before
* overriding base
*/
if (ctxt->input->free != NULL) {
ctxt->input->free((xmlChar *) ctxt->input->base);
ctxt->input->free = NULL;
}
ctxt->input->cur = BAD_CAST"";
ctxt->input->base = ctxt->input->cur;
}
}
CWE ID: CWE-611
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void rds_tcp_kill_sock(struct net *net)
{
struct rds_tcp_connection *tc, *_tc;
LIST_HEAD(tmp_list);
struct rds_tcp_net *rtn = net_generic(net, rds_tcp_netid);
struct socket *lsock = rtn->rds_tcp_listen_sock;
rtn->rds_tcp_listen_sock = NULL;
rds_tcp_listen_stop(lsock, &rtn->rds_tcp_accept_w);
spin_lock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &rds_tcp_conn_list, t_tcp_node) {
struct net *c_net = read_pnet(&tc->t_cpath->cp_conn->c_net);
if (net != c_net || !tc->t_sock)
continue;
if (!list_has_conn(&tmp_list, tc->t_cpath->cp_conn)) {
list_move_tail(&tc->t_tcp_node, &tmp_list);
} else {
list_del(&tc->t_tcp_node);
tc->t_tcp_node_detached = true;
}
}
spin_unlock_irq(&rds_tcp_conn_lock);
list_for_each_entry_safe(tc, _tc, &tmp_list, t_tcp_node)
rds_conn_destroy(tc->t_cpath->cp_conn);
}
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: dump_threads(void)
{
FILE *fp;
char time_buf[26];
element e;
vrrp_t *vrrp;
char *file_name;
file_name = make_file_name("/tmp/thread_dump.dat",
"vrrp",
#if HAVE_DECL_CLONE_NEWNET
global_data->network_namespace,
#else
NULL,
#endif
global_data->instance_name);
fp = fopen(file_name, "a");
FREE(file_name);
set_time_now();
ctime_r(&time_now.tv_sec, time_buf);
fprintf(fp, "\n%.19s.%6.6ld: Thread dump\n", time_buf, time_now.tv_usec);
dump_thread_data(master, fp);
fprintf(fp, "alloc = %lu\n", master->alloc);
fprintf(fp, "\n");
LIST_FOREACH(vrrp_data->vrrp, vrrp, e) {
ctime_r(&vrrp->sands.tv_sec, time_buf);
fprintf(fp, "VRRP instance %s, sands %.19s.%6.6lu, status %s\n", vrrp->iname, time_buf, vrrp->sands.tv_usec,
vrrp->state == VRRP_STATE_INIT ? "INIT" :
vrrp->state == VRRP_STATE_BACK ? "BACKUP" :
vrrp->state == VRRP_STATE_MAST ? "MASTER" :
vrrp->state == VRRP_STATE_FAULT ? "FAULT" :
vrrp->state == VRRP_STATE_STOP ? "STOP" :
vrrp->state == VRRP_DISPATCHER ? "DISPATCHER" : "unknown");
}
fclose(fp);
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: polkit_backend_interactive_authority_check_authorization_finish (PolkitBackendAuthority *authority,
GAsyncResult *res,
GError **error)
{
GSimpleAsyncResult *simple;
PolkitAuthorizationResult *result;
simple = G_SIMPLE_ASYNC_RESULT (res);
g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == polkit_backend_interactive_authority_check_authorization);
result = NULL;
if (g_simple_async_result_propagate_error (simple, error))
goto out;
result = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
out:
return result;
}
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: char *M_fs_path_tmpdir(M_fs_system_t sys_type)
{
char *d = NULL;
char *out = NULL;
M_fs_error_t res;
#ifdef _WIN32
size_t len = M_fs_path_get_path_max(M_FS_SYSTEM_WINDOWS)+1;
d = M_malloc_zero(len);
/* Return is length without NULL. */
if (GetTempPath((DWORD)len, d) >= len) {
M_free(d);
d = NULL;
}
#elif defined(__APPLE__)
d = M_fs_path_mac_tmpdir();
#else
const char *const_temp;
/* Try Unix env var. */
# ifdef HAVE_SECURE_GETENV
const_temp = secure_getenv("TMPDIR");
# else
const_temp = getenv("TMPDIR");
# endif
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
/* Fallback to some "standard" system paths. */
if (d == NULL) {
const_temp = "/tmp";
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
}
if (d == NULL) {
const_temp = "/var/tmp";
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
}
#endif
if (d != NULL) {
res = M_fs_path_norm(&out, d, M_FS_PATH_NORM_ABSOLUTE, sys_type);
if (res != M_FS_ERROR_SUCCESS) {
out = NULL;
}
}
M_free(d);
return out;
}
CWE ID: CWE-732
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm, js_Ast *finallystm)
{
int L1, L2, L3;
L1 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the try block */
L2 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the catch block */
cstm(J, F, finallystm); /* inline finally block */
emit(J, F, OP_THROW); /* rethrow exception */
}
label(J, F, L2);
if (F->strict) {
checkfutureword(J, F, catchvar);
if (!strcmp(catchvar->string, "arguments"))
jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode");
if (!strcmp(catchvar->string, "eval"))
jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode");
}
emitline(J, F, catchvar);
emitstring(J, F, OP_CATCH, catchvar->string);
cstm(J, F, catchstm);
emit(J, F, OP_ENDCATCH);
L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */
}
label(J, F, L1);
cstm(J, F, trystm);
emit(J, F, OP_ENDTRY);
label(J, F, L3);
cstm(J, F, finallystm);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: PHP_FUNCTION(mcrypt_module_close)
{
MCRYPT_GET_TD_ARG
zend_list_delete(Z_LVAL_P(mcryptind));
RETURN_TRUE;
}
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: SYSCALL_DEFINE0(vfork)
{
return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, 0,
0, NULL, NULL);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC)
{
int s_den;
unsigned u_den;
switch(format) {
case TAG_FMT_SBYTE: return *(signed char *)value;
case TAG_FMT_BYTE: return *(uchar *)value;
case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel);
case TAG_FMT_URATIONAL:
u_den = php_ifd_get32u(4+(char *)value, motorola_intel);
if (u_den == 0) {
return 0;
} else {
return php_ifd_get32u(value, motorola_intel) / u_den;
}
case TAG_FMT_SRATIONAL:
s_den = php_ifd_get32s(4+(char *)value, motorola_intel);
if (s_den == 0) {
return 0;
} else {
return php_ifd_get32s(value, motorola_intel) / s_den;
}
case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel);
case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel);
/* Not sure if this is correct (never seen float used in Exif format) */
case TAG_FMT_SINGLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single");
#endif
return (size_t)*(float *)value;
case TAG_FMT_DOUBLE:
#ifdef EXIF_DEBUG
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double");
#endif
return (size_t)*(double *)value;
}
return 0;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: ExceptionInfo *magick_unused(exception))
{
magick_unreferenced(file);
magick_unreferenced(exception);
return(MagickTrue);
}
CWE ID: CWE-22
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ZEND_API int zend_ts_hash_index_exists(TsHashTable *ht, zend_ulong h)
{
int retval;
begin_read(ht);
retval = zend_hash_index_exists(TS_HASH(ht), h);
end_read(ht);
return retval;
}
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 icmp6_send(struct sk_buff *skb, u8 type, u8 code, __u32 info,
const struct in6_addr *force_saddr)
{
struct net *net = dev_net(skb->dev);
struct inet6_dev *idev = NULL;
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct sock *sk;
struct ipv6_pinfo *np;
const struct in6_addr *saddr = NULL;
struct dst_entry *dst;
struct icmp6hdr tmp_hdr;
struct flowi6 fl6;
struct icmpv6_msg msg;
struct sockcm_cookie sockc_unused = {0};
struct ipcm6_cookie ipc6;
int iif = 0;
int addr_type = 0;
int len;
int err = 0;
u32 mark = IP6_REPLY_MARK(net, skb->mark);
if ((u8 *)hdr < skb->head ||
(skb_network_header(skb) + sizeof(*hdr)) > skb_tail_pointer(skb))
return;
/*
* Make sure we respect the rules
* i.e. RFC 1885 2.4(e)
* Rule (e.1) is enforced by not using icmp6_send
* in any code that processes icmp errors.
*/
addr_type = ipv6_addr_type(&hdr->daddr);
if (ipv6_chk_addr(net, &hdr->daddr, skb->dev, 0) ||
ipv6_chk_acast_addr_src(net, skb->dev, &hdr->daddr))
saddr = &hdr->daddr;
/*
* Dest addr check
*/
if (addr_type & IPV6_ADDR_MULTICAST || skb->pkt_type != PACKET_HOST) {
if (type != ICMPV6_PKT_TOOBIG &&
!(type == ICMPV6_PARAMPROB &&
code == ICMPV6_UNK_OPTION &&
(opt_unrec(skb, info))))
return;
saddr = NULL;
}
addr_type = ipv6_addr_type(&hdr->saddr);
/*
* Source addr check
*/
if (__ipv6_addr_needs_scope_id(addr_type))
iif = skb->dev->ifindex;
else
iif = l3mdev_master_ifindex(skb_dst(skb)->dev);
/*
* Must not send error if the source does not uniquely
* identify a single node (RFC2463 Section 2.4).
* We check unspecified / multicast addresses here,
* and anycast addresses will be checked later.
*/
if ((addr_type == IPV6_ADDR_ANY) || (addr_type & IPV6_ADDR_MULTICAST)) {
net_dbg_ratelimited("icmp6_send: addr_any/mcast source [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
return;
}
/*
* Never answer to a ICMP packet.
*/
if (is_ineligible(skb)) {
net_dbg_ratelimited("icmp6_send: no reply to icmp error [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
return;
}
mip6_addr_swap(skb);
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_ICMPV6;
fl6.daddr = hdr->saddr;
if (force_saddr)
saddr = force_saddr;
if (saddr)
fl6.saddr = *saddr;
fl6.flowi6_mark = mark;
fl6.flowi6_oif = iif;
fl6.fl6_icmp_type = type;
fl6.fl6_icmp_code = code;
security_skb_classify_flow(skb, flowi6_to_flowi(&fl6));
sk = icmpv6_xmit_lock(net);
if (!sk)
return;
sk->sk_mark = mark;
np = inet6_sk(sk);
if (!icmpv6_xrlim_allow(sk, type, &fl6))
goto out;
tmp_hdr.icmp6_type = type;
tmp_hdr.icmp6_code = code;
tmp_hdr.icmp6_cksum = 0;
tmp_hdr.icmp6_pointer = htonl(info);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
ipc6.tclass = np->tclass;
fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel);
dst = icmpv6_route_lookup(net, skb, sk, &fl6);
if (IS_ERR(dst))
goto out;
ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
ipc6.dontfrag = np->dontfrag;
ipc6.opt = NULL;
msg.skb = skb;
msg.offset = skb_network_offset(skb);
msg.type = type;
len = skb->len - msg.offset;
len = min_t(unsigned int, len, IPV6_MIN_MTU - sizeof(struct ipv6hdr) - sizeof(struct icmp6hdr));
if (len < 0) {
net_dbg_ratelimited("icmp: len problem [%pI6c > %pI6c]\n",
&hdr->saddr, &hdr->daddr);
goto out_dst_release;
}
rcu_read_lock();
idev = __in6_dev_get(skb->dev);
err = ip6_append_data(sk, icmpv6_getfrag, &msg,
len + sizeof(struct icmp6hdr),
sizeof(struct icmp6hdr),
&ipc6, &fl6, (struct rt6_info *)dst,
MSG_DONTWAIT, &sockc_unused);
if (err) {
ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTERRORS);
ip6_flush_pending_frames(sk);
} else {
err = icmpv6_push_pending_frames(sk, &fl6, &tmp_hdr,
len + sizeof(struct icmp6hdr));
}
rcu_read_unlock();
out_dst_release:
dst_release(dst);
out:
icmpv6_xmit_unlock(sk);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int sctp_v6_available(union sctp_addr *addr, struct sctp_sock *sp)
{
int type;
const struct in6_addr *in6 = (const struct in6_addr *)&addr->v6.sin6_addr;
type = ipv6_addr_type(in6);
if (IPV6_ADDR_ANY == type)
return 1;
if (type == IPV6_ADDR_MAPPED) {
if (sp && !sp->v4mapped)
return 0;
if (sp && ipv6_only_sock(sctp_opt2sk(sp)))
return 0;
sctp_v6_map_v4(addr);
return sctp_get_af_specific(AF_INET)->available(addr, sp);
}
if (!(type & IPV6_ADDR_UNICAST))
return 0;
return ipv6_chk_addr(sock_net(&sp->inet.sk), in6, NULL, 0);
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: EGLNativeWindowType RenderingHelper::PlatformCreateWindow(int top_left_x,
int top_left_y) {
int depth = DefaultDepth(x_display_, DefaultScreen(x_display_));
XSetWindowAttributes window_attributes;
window_attributes.background_pixel =
BlackPixel(x_display_, DefaultScreen(x_display_));
window_attributes.override_redirect = true;
Window x_window = XCreateWindow(
x_display_, DefaultRootWindow(x_display_),
top_left_x, top_left_y, width_, height_,
0 /* border width */,
depth, CopyFromParent /* class */, CopyFromParent /* visual */,
(CWBackPixel | CWOverrideRedirect), &window_attributes);
x_windows_.push_back(x_window);
XStoreName(x_display_, x_window, "VideoDecodeAcceleratorTest");
XSelectInput(x_display_, x_window, ExposureMask);
XMapWindow(x_display_, x_window);
return x_window;
}
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: store_image_check(PNG_CONST png_store* ps, png_const_structp pp, int iImage)
{
png_const_bytep image = ps->image;
if (image[-1] != 0xed || image[ps->cb_image] != 0xfe)
png_error(pp, "image overwrite");
else
{
png_size_t cbRow = ps->cb_row;
png_uint_32 rows = ps->image_h;
image += iImage * (cbRow+5) * ps->image_h;
image += 2; /* skip image first row markers */
while (rows-- > 0)
{
if (image[-2] != 190 || image[-1] != 239)
png_error(pp, "row start overwritten");
if (image[cbRow] != 222 || image[cbRow+1] != 173 ||
image[cbRow+2] != 17)
png_error(pp, "row end overwritten");
image += cbRow+5;
}
}
}
CWE ID:
Target: 1
Example 2:
Code: void GLES2DecoderImpl::DoVertexAttrib1f(GLuint index, GLfloat v0) {
VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_->GetVertexAttribInfo(index);
if (!info) {
SetGLError(GL_INVALID_VALUE, "glVertexAttrib1f", "index out of range");
return;
}
VertexAttribManager::VertexAttribInfo::Vec4 value;
value.v[0] = v0;
value.v[1] = 0.0f;
value.v[2] = 0.0f;
value.v[3] = 1.0f;
info->set_value(value);
glVertexAttrib1f(index, v0);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PlatformSensorProviderAndroid::CreateAbsoluteOrientationEulerAnglesSensor(
JNIEnv* env,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
if (static_cast<bool>(Java_PlatformSensorProvider_hasSensorType(
env, j_object_,
static_cast<jint>(
mojom::SensorType::ABSOLUTE_ORIENTATION_QUATERNION)))) {
auto sensor_fusion_algorithm =
std::make_unique<OrientationEulerAnglesFusionAlgorithmUsingQuaternion>(
true /* absolute */);
PlatformSensorFusion::Create(std::move(mapping), this,
std::move(sensor_fusion_algorithm), callback);
} else {
auto sensor_fusion_algorithm = std::make_unique<
AbsoluteOrientationEulerAnglesFusionAlgorithmUsingAccelerometerAndMagnetometer>();
PlatformSensorFusion::Create(std::move(mapping), this,
std::move(sensor_fusion_algorithm), callback);
}
}
CWE ID: CWE-732
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: create_surface_from_thumbnail_data (guchar *data,
gint width,
gint height,
gint rowstride)
{
guchar *cairo_pixels;
cairo_surface_t *surface;
static cairo_user_data_key_t key;
int j;
cairo_pixels = (guchar *)g_malloc (4 * width * height);
surface = cairo_image_surface_create_for_data ((unsigned char *)cairo_pixels,
CAIRO_FORMAT_RGB24,
width, height, 4 * width);
cairo_surface_set_user_data (surface, &key,
cairo_pixels, (cairo_destroy_func_t)g_free);
for (j = height; j; j--) {
guchar *p = data;
guchar *q = cairo_pixels;
guchar *end = p + 3 * width;
while (p < end) {
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
q[0] = p[2];
q[1] = p[1];
q[2] = p[0];
#else
q[1] = p[0];
q[2] = p[1];
q[3] = p[2];
#endif
p += 3;
q += 4;
}
data += rowstride;
cairo_pixels += 4 * width;
}
return surface;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: long vorbis_book_decode(codebook *book, oggpack_buffer *b){
if(book->dec_type)return -1;
return decode_packed_entry_number(book,b);
}
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 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;
}
#ifdef SO_NOSIGPIPE
if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#endif
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: FT_Stream_EnterFrame( FT_Stream stream,
FT_ULong count )
{
FT_Error error = FT_Err_Ok;
FT_ULong read_bytes;
/* check for nested frame access */
FT_ASSERT( stream && stream->cursor == 0 );
if ( stream->read )
{
/* allocate the frame in memory */
FT_Memory memory = stream->memory;
/* simple sanity check */
if ( count > stream->size )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" frame size (%lu) larger than stream size (%lu)\n",
count, stream->size ));
error = FT_Err_Invalid_Stream_Operation;
goto Exit;
}
#ifdef FT_DEBUG_MEMORY
/* assume _ft_debug_file and _ft_debug_lineno are already set */
stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error );
if ( error )
goto Exit;
#else
if ( FT_QALLOC( stream->base, count ) )
goto Exit;
#endif
/* read it */
read_bytes = stream->read( stream, stream->pos,
stream->base, count );
if ( read_bytes < count )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" invalid read; expected %lu bytes, got %lu\n",
count, read_bytes ));
FT_FREE( stream->base );
error = FT_Err_Invalid_Stream_Operation;
}
stream->cursor = stream->base;
stream->limit = stream->cursor + count;
stream->pos += read_bytes;
}
else
{
/* check current and new position */
if ( stream->pos >= stream->size ||
stream->pos + count > stream->size )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n",
stream->pos, count, stream->size ));
error = FT_Err_Invalid_Stream_Operation;
goto Exit;
}
/* set cursor */
stream->cursor = stream->base + stream->pos;
stream->limit = stream->cursor + count;
stream->pos += count;
}
Exit:
return error;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void TearDownEnvironment() {
sink_ = nullptr;
process_host_ = nullptr;
if (view_)
DestroyView(view_);
parent_view_->Destroy();
delete parent_host_;
browser_context_.reset();
aura_test_helper_->TearDown();
base::RunLoop().RunUntilIdle();
ImageTransportFactory::Terminate();
}
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 netdev_features_t hns_nic_fix_features(
struct net_device *netdev, netdev_features_t features)
{
struct hns_nic_priv *priv = netdev_priv(netdev);
switch (priv->enet_ver) {
case AE_VERSION_1:
features &= ~(NETIF_F_TSO | NETIF_F_TSO6 |
NETIF_F_HW_VLAN_CTAG_FILTER);
break;
default:
break;
}
return features;
}
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: M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode, M_fs_progress_cb_t cb, M_uint32 progress_flags)
{
char *norm_path_old;
char *norm_path_new;
char *join_path_old;
char *join_path_new;
M_fs_dir_entries_t *entries;
const M_fs_dir_entry_t *entry;
M_fs_info_t *info;
M_fs_progress_t *progress = NULL;
M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE;
M_fs_type_t type;
size_t len;
size_t i;
M_uint64 total_count = 0;
M_uint64 total_size = 0;
M_uint64 total_size_progress = 0;
M_uint64 entry_size;
M_fs_error_t res;
if (path_old == NULL || *path_old == '\0' || path_new == NULL || *path_new == '\0') {
return M_FS_ERROR_INVALID;
}
/* It's okay if new path doesn't exist. */
res = M_fs_path_norm(&norm_path_new, path_new, M_FS_PATH_NORM_RESDIR, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
return res;
}
/* If a path is a file and the destination is a directory the file should be copied
* into the directory. E.g. /file.txt -> /dir = /dir/file.txt */
if (M_fs_isfileintodir(path_old, path_new, &norm_path_old)) {
M_free(norm_path_new);
res = M_fs_copy(path_old, norm_path_old, mode, cb, progress_flags);
M_free(norm_path_old);
return res;
}
/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path
* existing to rename because any check we perform may not be true when rename is called. */
res = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
progress = M_fs_progress_create();
res = M_fs_info(&info, path_old, (mode & M_FS_FILE_MODE_PRESERVE_PERMS)?M_FS_PATH_INFO_FLAGS_NONE:M_FS_PATH_INFO_FLAGS_BASIC);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
type = M_fs_info_get_type(info);
/* There is a race condition where the path could not exist but be created between the exists check and calling
* rename to move the file but there isn't much we can do in this case. copy will delete and the file so this
* situation won't cause an error. */
if (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return M_FS_ERROR_FILE_EXISTS;
}
entries = M_fs_dir_entries_create();
/* No need to destroy info because it's now owned by entries and will be destroyed when entries is destroyed.
* M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is
* stored in the entry. */
M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path_new, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC));
if (type == M_FS_TYPE_DIR) {
if (mode & M_FS_FILE_MODE_PRESERVE_PERMS) {
filter |= M_FS_DIR_WALK_FILTER_READ_INFO_FULL;
} else if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) {
filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC;
}
/* Get all the files under the dir. */
M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path_old, NULL, filter));
}
/* Put all dirs first. We need to ensure the dir(s) exist before we can copy files. */
M_fs_dir_entries_sort(entries, M_FS_DIR_SORT_ISDIR, M_TRUE, M_FS_DIR_SORT_NAME_CASECMP, M_TRUE);
len = M_fs_dir_entries_len(entries);
if (cb) {
total_size = 0;
for (i=0; i<len; i++) {
entry = M_fs_dir_entries_at(entries, i);
entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry));
total_size += entry_size;
type = M_fs_dir_entry_get_type(entry);
/* The total isn't the total number of files but the total number of operations.
* Making dirs and symlinks is one operation and copying a file will be split into
* multiple operations. Copying uses the M_FS_BUF_SIZE to read and write in
* chunks. We determine how many chunks will be needed to read the entire file and
* use that for the number of operations for the file. */
if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) {
total_count++;
} else {
total_count += (entry_size + M_FS_BUF_SIZE - 1) / M_FS_BUF_SIZE;
}
}
/* Change the progress total size to reflect all entries. */
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total(progress, total_size);
}
/* Change the progress count to reflect the count. */
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count_total(progress, total_count);
}
}
for (i=0; i<len; i++) {
entry = M_fs_dir_entries_at(entries, i);
type = M_fs_dir_entry_get_type(entry);
join_path_old = M_fs_path_join(norm_path_old, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO);
join_path_new = M_fs_path_join(norm_path_new, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO);
entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry));
total_size_progress += entry_size;
if (cb) {
M_fs_progress_set_path(progress, join_path_new);
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current(progress, entry_size);
}
}
/* op */
if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) {
if (type == M_FS_TYPE_DIR) {
res = M_fs_dir_mkdir(join_path_new, M_FALSE, NULL);
} else if (type == M_FS_TYPE_SYMLINK) {
res = M_fs_symlink(join_path_new, M_fs_dir_entry_get_resolved_name(entry));
}
if (res == M_FS_ERROR_SUCCESS && (mode & M_FS_FILE_MODE_PRESERVE_PERMS)) {
res = M_fs_perms_set_perms(M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)), join_path_new);
}
} else {
res = M_fs_copy_file(join_path_old, join_path_new, mode, cb, progress_flags, progress, M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)));
}
M_free(join_path_old);
M_free(join_path_new);
/* Call the callback and stop processing if requested. */
if ((type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) && cb) {
M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry));
M_fs_progress_set_result(progress, res);
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total_progess(progress, total_size_progress);
}
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current_progress(progress, entry_size);
}
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1);
}
if (!cb(progress)) {
res = M_FS_ERROR_CANCELED;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
/* Delete the file(s) if it could not be copied properly, but only if we are not overwriting.
* If we're overwriting then there could be other files in that location (especially if it's a dir). */
if (res != M_FS_ERROR_SUCCESS && !(mode & M_FS_FILE_MODE_OVERWRITE)) {
M_fs_delete(path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);
}
M_fs_dir_entries_destroy(entries);
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: Eina_Bool ewk_frame_back(Evas_Object* ewkFrame)
{
return ewk_frame_navigate(ewkFrame, -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: void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols,
int stride, int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = splitbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += numcols;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < numcols; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += numcols;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void on_read(h2o_socket_t *sock, int status)
{
h2o_http2_conn_t *conn = sock->data;
if (status != 0) {
h2o_socket_read_stop(conn->sock);
close_connection(conn);
return;
}
update_idle_timeout(conn);
parse_input(conn);
/* write immediately, if there is no write in flight and if pending write exists */
if (h2o_timeout_is_linked(&conn->_write.timeout_entry)) {
h2o_timeout_unlink(&conn->_write.timeout_entry);
do_emit_writereq(conn);
}
}
CWE ID:
Target: 1
Example 2:
Code: PanoramiXExtensionInit(void)
{
int i;
Bool success = FALSE;
ExtensionEntry *extEntry;
ScreenPtr pScreen = screenInfo.screens[0];
PanoramiXScreenPtr pScreenPriv;
if (noPanoramiXExtension)
return;
if (!dixRegisterPrivateKey(&PanoramiXScreenKeyRec, PRIVATE_SCREEN, 0)) {
noPanoramiXExtension = TRUE;
return;
}
if (!dixRegisterPrivateKey
(&PanoramiXGCKeyRec, PRIVATE_GC, sizeof(PanoramiXGCRec))) {
noPanoramiXExtension = TRUE;
return;
}
PanoramiXNumScreens = screenInfo.numScreens;
if (PanoramiXNumScreens == 1) { /* Only 1 screen */
noPanoramiXExtension = TRUE;
return;
}
while (panoramiXGeneration != serverGeneration) {
extEntry = AddExtension(PANORAMIX_PROTOCOL_NAME, 0, 0,
ProcPanoramiXDispatch,
SProcPanoramiXDispatch, PanoramiXResetProc,
StandardMinorOpcode);
if (!extEntry)
break;
/*
* First make sure all the basic allocations succeed. If not,
* run in non-PanoramiXeen mode.
*/
FOR_NSCREENS(i) {
pScreen = screenInfo.screens[i];
pScreenPriv = malloc(sizeof(PanoramiXScreenRec));
dixSetPrivate(&pScreen->devPrivates, PanoramiXScreenKey,
pScreenPriv);
if (!pScreenPriv) {
noPanoramiXExtension = TRUE;
return;
}
pScreenPriv->CreateGC = pScreen->CreateGC;
pScreenPriv->CloseScreen = pScreen->CloseScreen;
pScreen->CreateGC = XineramaCreateGC;
pScreen->CloseScreen = XineramaCloseScreen;
}
XRC_DRAWABLE = CreateNewResourceClass();
XRT_WINDOW = CreateNewResourceType(XineramaDeleteResource,
"XineramaWindow");
if (XRT_WINDOW)
XRT_WINDOW |= XRC_DRAWABLE;
XRT_PIXMAP = CreateNewResourceType(XineramaDeleteResource,
"XineramaPixmap");
if (XRT_PIXMAP)
XRT_PIXMAP |= XRC_DRAWABLE;
XRT_GC = CreateNewResourceType(XineramaDeleteResource, "XineramaGC");
XRT_COLORMAP = CreateNewResourceType(XineramaDeleteResource,
"XineramaColormap");
if (XRT_WINDOW && XRT_PIXMAP && XRT_GC && XRT_COLORMAP) {
panoramiXGeneration = serverGeneration;
success = TRUE;
}
SetResourceTypeErrorValue(XRT_WINDOW, BadWindow);
SetResourceTypeErrorValue(XRT_PIXMAP, BadPixmap);
SetResourceTypeErrorValue(XRT_GC, BadGC);
SetResourceTypeErrorValue(XRT_COLORMAP, BadColor);
}
if (!success) {
noPanoramiXExtension = TRUE;
ErrorF(PANORAMIX_PROTOCOL_NAME " extension failed to initialize\n");
return;
}
XineramaInitData();
/*
* Put our processes into the ProcVector
*/
for (i = 256; i--;)
SavedProcVector[i] = ProcVector[i];
ProcVector[X_CreateWindow] = PanoramiXCreateWindow;
ProcVector[X_ChangeWindowAttributes] = PanoramiXChangeWindowAttributes;
ProcVector[X_DestroyWindow] = PanoramiXDestroyWindow;
ProcVector[X_DestroySubwindows] = PanoramiXDestroySubwindows;
ProcVector[X_ChangeSaveSet] = PanoramiXChangeSaveSet;
ProcVector[X_ReparentWindow] = PanoramiXReparentWindow;
ProcVector[X_MapWindow] = PanoramiXMapWindow;
ProcVector[X_MapSubwindows] = PanoramiXMapSubwindows;
ProcVector[X_UnmapWindow] = PanoramiXUnmapWindow;
ProcVector[X_UnmapSubwindows] = PanoramiXUnmapSubwindows;
ProcVector[X_ConfigureWindow] = PanoramiXConfigureWindow;
ProcVector[X_CirculateWindow] = PanoramiXCirculateWindow;
ProcVector[X_GetGeometry] = PanoramiXGetGeometry;
ProcVector[X_TranslateCoords] = PanoramiXTranslateCoords;
ProcVector[X_CreatePixmap] = PanoramiXCreatePixmap;
ProcVector[X_FreePixmap] = PanoramiXFreePixmap;
ProcVector[X_CreateGC] = PanoramiXCreateGC;
ProcVector[X_ChangeGC] = PanoramiXChangeGC;
ProcVector[X_CopyGC] = PanoramiXCopyGC;
ProcVector[X_SetDashes] = PanoramiXSetDashes;
ProcVector[X_SetClipRectangles] = PanoramiXSetClipRectangles;
ProcVector[X_FreeGC] = PanoramiXFreeGC;
ProcVector[X_ClearArea] = PanoramiXClearToBackground;
ProcVector[X_CopyArea] = PanoramiXCopyArea;
ProcVector[X_CopyPlane] = PanoramiXCopyPlane;
ProcVector[X_PolyPoint] = PanoramiXPolyPoint;
ProcVector[X_PolyLine] = PanoramiXPolyLine;
ProcVector[X_PolySegment] = PanoramiXPolySegment;
ProcVector[X_PolyRectangle] = PanoramiXPolyRectangle;
ProcVector[X_PolyArc] = PanoramiXPolyArc;
ProcVector[X_FillPoly] = PanoramiXFillPoly;
ProcVector[X_PolyFillRectangle] = PanoramiXPolyFillRectangle;
ProcVector[X_PolyFillArc] = PanoramiXPolyFillArc;
ProcVector[X_PutImage] = PanoramiXPutImage;
ProcVector[X_GetImage] = PanoramiXGetImage;
ProcVector[X_PolyText8] = PanoramiXPolyText8;
ProcVector[X_PolyText16] = PanoramiXPolyText16;
ProcVector[X_ImageText8] = PanoramiXImageText8;
ProcVector[X_ImageText16] = PanoramiXImageText16;
ProcVector[X_CreateColormap] = PanoramiXCreateColormap;
ProcVector[X_FreeColormap] = PanoramiXFreeColormap;
ProcVector[X_CopyColormapAndFree] = PanoramiXCopyColormapAndFree;
ProcVector[X_InstallColormap] = PanoramiXInstallColormap;
ProcVector[X_UninstallColormap] = PanoramiXUninstallColormap;
ProcVector[X_AllocColor] = PanoramiXAllocColor;
ProcVector[X_AllocNamedColor] = PanoramiXAllocNamedColor;
ProcVector[X_AllocColorCells] = PanoramiXAllocColorCells;
ProcVector[X_AllocColorPlanes] = PanoramiXAllocColorPlanes;
ProcVector[X_FreeColors] = PanoramiXFreeColors;
ProcVector[X_StoreColors] = PanoramiXStoreColors;
ProcVector[X_StoreNamedColor] = PanoramiXStoreNamedColor;
PanoramiXRenderInit();
PanoramiXFixesInit();
PanoramiXDamageInit();
#ifdef COMPOSITE
PanoramiXCompositeInit();
#endif
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static char *hintsCallback(const char *buf, int *color, int *bold) {
if (!pref.hints) return NULL;
int i, argc, buflen = strlen(buf);
sds *argv = sdssplitargs(buf,&argc);
int endspace = buflen && isspace(buf[buflen-1]);
/* Check if the argument list is empty and return ASAP. */
if (argc == 0) {
sdsfreesplitres(argv,argc);
return NULL;
}
for (i = 0; i < helpEntriesLen; i++) {
if (!(helpEntries[i].type & CLI_HELP_COMMAND)) continue;
if (strcasecmp(argv[0],helpEntries[i].full) == 0)
{
*color = 90;
*bold = 0;
sds hint = sdsnew(helpEntries[i].org->params);
/* Remove arguments from the returned hint to show only the
* ones the user did not yet typed. */
int toremove = argc-1;
while(toremove > 0 && sdslen(hint)) {
if (hint[0] == '[') break;
if (hint[0] == ' ') toremove--;
sdsrange(hint,1,-1);
}
/* Add an initial space if needed. */
if (!endspace) {
sds newhint = sdsnewlen(" ",1);
newhint = sdscatsds(newhint,hint);
sdsfree(hint);
hint = newhint;
}
sdsfreesplitres(argv,argc);
return hint;
}
}
sdsfreesplitres(argv,argc);
return NULL;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_openargs *arg)
{
__be32 *p;
/*
* opcode 4, seqid 4, share_access 4, share_deny 4, clientid 8, ownerlen 4,
* owner 4 = 32
*/
RESERVE_SPACE(8);
WRITE32(OP_OPEN);
WRITE32(arg->seqid->sequence->counter);
encode_share_access(xdr, arg->open_flags);
RESERVE_SPACE(28);
WRITE64(arg->clientid);
WRITE32(16);
WRITEMEM("open id:", 8);
WRITE64(arg->id);
}
CWE ID:
Target: 1
Example 2:
Code: bool FileBrowserPrivateGetDriveEntryPropertiesFunction::RunAsync() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
using api::file_browser_private::GetDriveEntryProperties::Params;
const scoped_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
properties_list_.resize(params->file_urls.size());
for (size_t i = 0; i < params->file_urls.size(); i++) {
const GURL url = GURL(params->file_urls[i]);
const base::FilePath local_path = file_manager::util::GetLocalPathFromURL(
render_view_host(), GetProfile(), url);
properties_list_[i] = make_linked_ptr(new DriveEntryProperties);
SingleDriveEntryPropertiesGetter::Start(
local_path,
properties_list_[i],
GetProfile(),
base::Bind(&FileBrowserPrivateGetDriveEntryPropertiesFunction::
CompleteGetFileProperties,
this));
}
return true;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DocumentLoader::CommitNavigation(const AtomicString& mime_type,
const KURL& overriding_url) {
if (state_ != kProvisional)
return;
if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) {
SetHistoryItemStateForCommit(
GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_,
HistoryNavigationType::kDifferentDocument);
}
DCHECK_EQ(state_, kProvisional);
GetFrameLoader().CommitProvisionalLoad();
if (!frame_)
return;
const AtomicString& encoding = GetResponse().TextEncodingName();
Document* owner_document = nullptr;
if (Document::ShouldInheritSecurityOriginFromOwner(Url())) {
Frame* owner_frame = frame_->Tree().Parent();
if (!owner_frame)
owner_frame = frame_->Loader().Opener();
if (owner_frame && owner_frame->IsLocalFrame())
owner_document = ToLocalFrame(owner_frame)->GetDocument();
}
DCHECK(frame_->GetPage());
ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing;
if (!Document::ThreadedParsingEnabledForTesting())
parsing_policy = kForceSynchronousParsing;
InstallNewDocument(Url(), owner_document,
frame_->ShouldReuseDefaultView(Url())
? WebGlobalObjectReusePolicy::kUseExisting
: WebGlobalObjectReusePolicy::kCreateNew,
mime_type, encoding, InstallNewDocumentReason::kNavigation,
parsing_policy, overriding_url);
parser_->SetDocumentWasLoadedAsPartOfNavigation();
if (request_.WasDiscarded())
frame_->GetDocument()->SetWasDiscarded(true);
frame_->GetDocument()->MaybeHandleHttpRefresh(
response_.HttpHeaderField(HTTPNames::Refresh),
Document::kHttpRefreshFromHeader);
}
CWE ID: CWE-285
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 au1100fb_fb_mmap(struct fb_info *fbi, struct vm_area_struct *vma)
{
struct au1100fb_device *fbdev;
unsigned int len;
unsigned long start=0, off;
fbdev = to_au1100fb_device(fbi);
if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) {
return -EINVAL;
}
start = fbdev->fb_phys & PAGE_MASK;
len = PAGE_ALIGN((start & ~PAGE_MASK) + fbdev->fb_len);
off = vma->vm_pgoff << PAGE_SHIFT;
if ((vma->vm_end - vma->vm_start + off) > len) {
return -EINVAL;
}
off += start;
vma->vm_pgoff = off >> PAGE_SHIFT;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
pgprot_val(vma->vm_page_prot) |= (6 << 9); //CCA=6
if (io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot)) {
return -EAGAIN;
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RedirectNotificationObserver::Wait() {
if (seen_ && seen_twice_)
return;
running_ = true;
message_loop_runner_ = new MessageLoopRunner;
message_loop_runner_->Run();
EXPECT_TRUE(seen_);
}
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: ssl_do_connect (server * serv)
{
char buf[128];
g_sess = serv->server_session;
if (SSL_connect (serv->ssl) <= 0)
{
char err_buf[128];
int err;
g_sess = NULL;
if ((err = ERR_get_error ()) > 0)
{
ERR_error_string (err, err_buf);
snprintf (buf, sizeof (buf), "(%d) %s", err, err_buf);
EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL,
NULL, NULL, 0);
if (ERR_GET_REASON (err) == SSL_R_WRONG_VERSION_NUMBER)
PrintText (serv->server_session, _("Are you sure this is a SSL capable server and port?\n"));
server_cleanup (serv);
if (prefs.hex_net_auto_reconnectonfail)
auto_reconnect (serv, FALSE, -1);
return (0); /* remove it (0) */
}
}
g_sess = NULL;
if (SSL_is_init_finished (serv->ssl))
{
struct cert_info cert_info;
struct chiper_info *chiper_info;
int verify_error;
int i;
if (!_SSL_get_cert_info (&cert_info, serv->ssl))
{
snprintf (buf, sizeof (buf), "* Certification info:");
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
snprintf (buf, sizeof (buf), " Subject:");
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
for (i = 0; cert_info.subject_word[i]; i++)
{
snprintf (buf, sizeof (buf), " %s", cert_info.subject_word[i]);
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
}
snprintf (buf, sizeof (buf), " Issuer:");
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
for (i = 0; cert_info.issuer_word[i]; i++)
{
snprintf (buf, sizeof (buf), " %s", cert_info.issuer_word[i]);
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
}
snprintf (buf, sizeof (buf), " Public key algorithm: %s (%d bits)",
cert_info.algorithm, cert_info.algorithm_bits);
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
/*if (cert_info.rsa_tmp_bits)
{
snprintf (buf, sizeof (buf),
" Public key algorithm uses ephemeral key with %d bits",
cert_info.rsa_tmp_bits);
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
}*/
snprintf (buf, sizeof (buf), " Sign algorithm %s",
cert_info.sign_algorithm/*, cert_info.sign_algorithm_bits*/);
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
snprintf (buf, sizeof (buf), " Valid since %s to %s",
cert_info.notbefore, cert_info.notafter);
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
} else
{
snprintf (buf, sizeof (buf), " * No Certificate");
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
}
chiper_info = _SSL_get_cipher_info (serv->ssl); /* static buffer */
snprintf (buf, sizeof (buf), "* Cipher info:");
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL,
0);
snprintf (buf, sizeof (buf), " Version: %s, cipher %s (%u bits)",
chiper_info->version, chiper_info->chiper,
chiper_info->chiper_bits);
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL,
0);
verify_error = SSL_get_verify_result (serv->ssl);
switch (verify_error)
{
case X509_V_OK:
/* snprintf (buf, sizeof (buf), "* Verify OK (?)"); */
/* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */
break;
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
case X509_V_ERR_CERT_HAS_EXPIRED:
if (serv->accept_invalid_cert)
{
snprintf (buf, sizeof (buf), "* Verify E: %s.? (%d) -- Ignored",
X509_verify_cert_error_string (verify_error),
verify_error);
EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL,
NULL, 0);
break;
}
default:
snprintf (buf, sizeof (buf), "%s.? (%d)",
X509_verify_cert_error_string (verify_error),
verify_error);
EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL,
NULL, 0);
server_cleanup (serv);
return (0);
}
server_stopconnecting (serv);
/* activate gtk poll */
server_connected (serv);
return (0); /* remove it (0) */
} else
{
if (serv->ssl->session && serv->ssl->session->time + SSLTMOUT < time (NULL))
{
snprintf (buf, sizeof (buf), "SSL handshake timed out");
EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL,
NULL, NULL, 0);
server_cleanup (serv); /* ->connecting = FALSE */
if (prefs.hex_net_auto_reconnectonfail)
auto_reconnect (serv, FALSE, -1);
return (0); /* remove it (0) */
}
return (1); /* call it more (1) */
}
}
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: void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
{
if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element)) {
loadFullDefaultStyle();
changedDefaultStyle = true;
}
if (element->isSVGElement() && !svgStyleSheet) {
svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
changedDefaultStyle = true;
}
if (!mediaControlsStyleSheet && (isHTMLVideoElement(element) || element->hasTagName(audioTag))) {
String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::theme().extraMediaControlsStyleSheet();
mediaControlsStyleSheet = parseUASheet(mediaRules);
defaultStyle->addRulesFromSheet(mediaControlsStyleSheet, screenEval());
defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet, printEval());
changedDefaultStyle = true;
}
if (!fullscreenStyleSheet && FullscreenElementStack::isFullScreen(&element->document())) {
String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::theme().extraFullScreenStyleSheet();
fullscreenStyleSheet = parseUASheet(fullscreenRules);
defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
changedDefaultStyle = true;
}
ASSERT(defaultStyle->features().idsInRules.isEmpty());
ASSERT(defaultStyle->features().siblingRules.isEmpty());
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void GLES2DecoderImpl::DoUniform4iv(
GLint fake_location, GLsizei count, const GLint* value) {
GLenum type = 0;
GLint real_location = -1;
if (!PrepForSetUniformByLocation(fake_location,
"glUniform4iv",
Program::kUniform4i,
&real_location,
&type,
&count)) {
return;
}
glUniform4iv(real_location, count, value);
}
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: SPR_SetMax(struct rx_call *call, afs_int32 aid, afs_int32 gflag)
{
afs_int32 code;
afs_int32 cid = ANONYMOUSID;
code = setMax(call, aid, gflag, &cid);
osi_auditU(call, PTS_SetMaxEvent, code, AUD_ID, aid, AUD_LONG, gflag,
AUD_END);
ViceLog(125, ("PTS_SetMax: code %d cid %d aid %d gflag %d\n", code, cid, aid, gflag));
return code;
}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Element* siblingWithAriaRole(String role, Node* node) {
Node* parent = node->parentNode();
if (!parent)
return 0;
for (Element* sibling = ElementTraversal::firstChild(*parent); sibling;
sibling = ElementTraversal::nextSibling(*sibling)) {
const AtomicString& siblingAriaRole =
AccessibleNode::getProperty(sibling, AOMStringProperty::kRole);
if (equalIgnoringCase(siblingAriaRole, role))
return sibling;
}
return 0;
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: bool RenderWidgetHostViewAura::NeedsInputGrab() {
return popup_type_ == WebKit::WebPopupTypeSelect;
}
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 StartExplicitSync(const StartSyncArgs& args,
content::WebContents* contents,
OneClickSigninSyncStarter::StartSyncMode start_mode,
ConfirmEmailDialogDelegate::Action action) {
if (action == ConfirmEmailDialogDelegate::START_SYNC) {
StartSync(args, start_mode);
RedirectToNtpOrAppsPageIfNecessary(contents, args.source);
} else {
if (signin::IsContinueUrlForWebBasedSigninFlow(
contents->GetVisibleURL())) {
base::MessageLoopProxy::current()->PostNonNestableTask(
FROM_HERE,
base::Bind(RedirectToNtpOrAppsPageWithIds,
contents->GetRenderProcessHost()->GetID(),
contents->GetRoutingID(),
args.source));
}
if (action == ConfirmEmailDialogDelegate::CREATE_NEW_USER) {
chrome::ShowSettingsSubPage(args.browser,
std::string(chrome::kSearchUsersSubPage));
}
}
}
CWE ID: CWE-287
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 LayerTreeHost::PushPropertiesTo(LayerTreeImpl* tree_impl) {
tree_impl->set_needs_full_tree_sync(needs_full_tree_sync_);
needs_full_tree_sync_ = false;
if (hud_layer_.get()) {
LayerImpl* hud_impl = tree_impl->LayerById(hud_layer_->id());
tree_impl->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl*>(hud_impl));
} else {
tree_impl->set_hud_layer(nullptr);
}
tree_impl->set_background_color(background_color_);
tree_impl->set_has_transparent_background(has_transparent_background_);
tree_impl->set_have_scroll_event_handlers(have_scroll_event_handlers_);
tree_impl->set_event_listener_properties(
EventListenerClass::kTouchStartOrMove,
event_listener_properties(EventListenerClass::kTouchStartOrMove));
tree_impl->set_event_listener_properties(
EventListenerClass::kMouseWheel,
event_listener_properties(EventListenerClass::kMouseWheel));
tree_impl->set_event_listener_properties(
EventListenerClass::kTouchEndOrCancel,
event_listener_properties(EventListenerClass::kTouchEndOrCancel));
if (page_scale_layer_ && inner_viewport_scroll_layer_) {
tree_impl->SetViewportLayersFromIds(
overscroll_elasticity_layer_ ? overscroll_elasticity_layer_->id()
: Layer::INVALID_ID,
page_scale_layer_->id(), inner_viewport_scroll_layer_->id(),
outer_viewport_scroll_layer_ ? outer_viewport_scroll_layer_->id()
: Layer::INVALID_ID);
DCHECK(inner_viewport_scroll_layer_->IsContainerForFixedPositionLayers());
} else {
tree_impl->ClearViewportLayers();
}
tree_impl->RegisterSelection(selection_);
bool property_trees_changed_on_active_tree =
tree_impl->IsActiveTree() && tree_impl->property_trees()->changed;
if (root_layer_ && property_trees_changed_on_active_tree) {
if (property_trees_.sequence_number ==
tree_impl->property_trees()->sequence_number)
tree_impl->property_trees()->PushChangeTrackingTo(&property_trees_);
else
tree_impl->MoveChangeTrackingToLayers();
}
tree_impl->SetPropertyTrees(&property_trees_);
tree_impl->PushPageScaleFromMainThread(
page_scale_factor_, min_page_scale_factor_, max_page_scale_factor_);
tree_impl->set_browser_controls_shrink_blink_size(
browser_controls_shrink_blink_size_);
tree_impl->set_top_controls_height(top_controls_height_);
tree_impl->set_bottom_controls_height(bottom_controls_height_);
tree_impl->PushBrowserControlsFromMainThread(top_controls_shown_ratio_);
tree_impl->elastic_overscroll()->PushFromMainThread(elastic_overscroll_);
if (tree_impl->IsActiveTree())
tree_impl->elastic_overscroll()->PushPendingToActive();
tree_impl->set_painted_device_scale_factor(painted_device_scale_factor_);
tree_impl->SetDeviceColorSpace(device_color_space_);
if (pending_page_scale_animation_) {
tree_impl->SetPendingPageScaleAnimation(
std::move(pending_page_scale_animation_));
}
DCHECK(!tree_impl->ViewportSizeInvalid());
tree_impl->set_has_ever_been_drawn(false);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: pdf14_text_begin(gx_device * dev, gs_gstate * pgs,
const gs_text_params_t * text, gs_font * font,
gx_path * path, const gx_device_color * pdcolor,
const gx_clip_path * pcpath, gs_memory_t * memory,
gs_text_enum_t ** ppenum)
{
int code;
gs_text_enum_t *penum;
if_debug0m('v', memory, "[v]pdf14_text_begin\n");
pdf14_set_marking_params(dev, pgs);
code = gx_default_text_begin(dev, pgs, text, font, path, pdcolor, pcpath,
memory, &penum);
if (code < 0)
return code;
*ppenum = (gs_text_enum_t *)penum;
return code;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int have_callable_console(void)
{
struct console *con;
for_each_console(con)
if (con->flags & CON_ANYTIME)
return 1;
return 0;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void VP8XChunk::height(XMP_Uns32 val)
{
PutLE24(&this->data[7], val - 1);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: check_1_6_dummy(kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr)
{
int i;
char *password = *passptr;
/* Old-style randkey operations disallowed tickets to start. */
if (password == NULL || !(mask & KADM5_ATTRIBUTES) ||
!(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX))
return;
/* The 1.6 dummy password was the octets 1..255. */
for (i = 0; (unsigned char) password[i] == i + 1; i++);
if (password[i] != '\0' || i != 255)
return;
/* This will make the caller use a random password instead. */
*passptr = NULL;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct arpt_entry *)e);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: _fep_open_control_socket (Fep *fep)
{
struct sockaddr_un sun;
char *path;
int fd;
ssize_t sun_len;
fd = socket (AF_UNIX, SOCK_STREAM, 0);
if (fd < 0)
{
perror ("socket");
return -1;
}
path = create_socket_name ("fep-XXXXXX/control");
if (strlen (path) + 1 >= sizeof(sun.sun_path))
{
fep_log (FEP_LOG_LEVEL_WARNING,
"unix domain socket path too long: %d + 1 >= %d",
strlen (path),
sizeof (sun.sun_path));
free (path);
return -1;
}
memset (&sun, 0, sizeof(sun));
sun.sun_family = AF_UNIX;
#ifdef __linux__
sun.sun_path[0] = '\0';
memcpy (sun.sun_path + 1, path, strlen (path));
sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (path) + 1;
remove_control_socket (path);
#else
memcpy (sun.sun_path, path, strlen (path));
sun_len = sizeof (struct sockaddr_un);
#endif
if (bind (fd, (const struct sockaddr *) &sun, sun_len) < 0)
{
perror ("bind");
free (path);
close (fd);
return -1;
}
if (listen (fd, 5) < 0)
{
perror ("listen");
free (path);
close (fd);
return -1;
}
fep->server = fd;
fep->control_socket_path = path;
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static size_t rtnl_port_size(const struct net_device *dev,
u32 ext_filter_mask)
{
size_t port_size = nla_total_size(4) /* PORT_VF */
+ nla_total_size(PORT_PROFILE_MAX) /* PORT_PROFILE */
+ nla_total_size(sizeof(struct ifla_port_vsi))
/* PORT_VSI_TYPE */
+ nla_total_size(PORT_UUID_MAX) /* PORT_INSTANCE_UUID */
+ nla_total_size(PORT_UUID_MAX) /* PORT_HOST_UUID */
+ nla_total_size(1) /* PROT_VDP_REQUEST */
+ nla_total_size(2); /* PORT_VDP_RESPONSE */
size_t vf_ports_size = nla_total_size(sizeof(struct nlattr));
size_t vf_port_size = nla_total_size(sizeof(struct nlattr))
+ port_size;
size_t port_self_size = nla_total_size(sizeof(struct nlattr))
+ port_size;
if (!dev->netdev_ops->ndo_get_vf_port || !dev->dev.parent ||
!(ext_filter_mask & RTEXT_FILTER_VF))
return 0;
if (dev_num_vf(dev->dev.parent))
return port_self_size + vf_ports_size +
vf_port_size * dev_num_vf(dev->dev.parent);
else
return port_self_size;
}
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: content::WebUIDataSource* CreateOobeUIDataSource(
const base::DictionaryValue& localized_strings,
const std::string& display_type) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIOobeHost);
source->AddLocalizedStrings(localized_strings);
source->SetJsonPath(kStringsJSPath);
if (display_type == OobeUI::kOobeDisplay) {
source->SetDefaultResource(IDR_OOBE_HTML);
source->AddResourcePath(kOobeJSPath, IDR_OOBE_JS);
source->AddResourcePath(kCustomElementsHTMLPath,
IDR_CUSTOM_ELEMENTS_OOBE_HTML);
source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_OOBE_JS);
} else {
source->SetDefaultResource(IDR_LOGIN_HTML);
source->AddResourcePath(kLoginJSPath, IDR_LOGIN_JS);
source->AddResourcePath(kCustomElementsHTMLPath,
IDR_CUSTOM_ELEMENTS_LOGIN_HTML);
source->AddResourcePath(kCustomElementsJSPath,
IDR_CUSTOM_ELEMENTS_LOGIN_JS);
}
source->AddResourcePath(kPolymerConfigJSPath, IDR_POLYMER_CONFIG_JS);
source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS);
source->OverrideContentSecurityPolicyFrameSrc(
base::StringPrintf(
"frame-src chrome://terms/ %s/;",
extensions::kGaiaAuthExtensionOrigin));
source->OverrideContentSecurityPolicyObjectSrc("object-src *;");
bool is_webview_signin_enabled = StartupUtils::IsWebviewSigninEnabled();
source->AddResourcePath("gaia_auth_host.js", is_webview_signin_enabled ?
IDR_GAIA_AUTH_AUTHENTICATOR_JS : IDR_GAIA_AUTH_HOST_JS);
source->AddResourcePath(kEnrollmentHTMLPath,
is_webview_signin_enabled
? IDR_OOBE_ENROLLMENT_WEBVIEW_HTML
: IDR_OOBE_ENROLLMENT_HTML);
source->AddResourcePath(kEnrollmentCSSPath,
is_webview_signin_enabled
? IDR_OOBE_ENROLLMENT_WEBVIEW_CSS
: IDR_OOBE_ENROLLMENT_CSS);
source->AddResourcePath(kEnrollmentJSPath,
is_webview_signin_enabled
? IDR_OOBE_ENROLLMENT_WEBVIEW_JS
: IDR_OOBE_ENROLLMENT_JS);
if (display_type == OobeUI::kOobeDisplay) {
source->AddResourcePath("Roboto-Thin.ttf", IDR_FONT_ROBOTO_THIN);
source->AddResourcePath("Roboto-Light.ttf", IDR_FONT_ROBOTO_LIGHT);
source->AddResourcePath("Roboto-Regular.ttf", IDR_FONT_ROBOTO_REGULAR);
source->AddResourcePath("Roboto-Medium.ttf", IDR_FONT_ROBOTO_MEDIUM);
source->AddResourcePath("Roboto-Bold.ttf", IDR_FONT_ROBOTO_BOLD);
}
return source;
}
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: sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option)
{
ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option);
Mutex::Autolock lock(mLock);
Mutex::Autolock glock(sLock);
mThumbnail.clear();
if (mRetriever == NULL) {
ALOGE("retriever is not initialized");
return NULL;
}
VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option);
if (frame == NULL) {
ALOGE("failed to capture a video frame");
return NULL;
}
size_t size = sizeof(VideoFrame) + frame->mSize;
sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient");
if (heap == NULL) {
ALOGE("failed to create MemoryDealer");
delete frame;
return NULL;
}
mThumbnail = new MemoryBase(heap, 0, size);
if (mThumbnail == NULL) {
ALOGE("not enough memory for VideoFrame size=%u", size);
delete frame;
return NULL;
}
VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer());
frameCopy->mWidth = frame->mWidth;
frameCopy->mHeight = frame->mHeight;
frameCopy->mDisplayWidth = frame->mDisplayWidth;
frameCopy->mDisplayHeight = frame->mDisplayHeight;
frameCopy->mSize = frame->mSize;
frameCopy->mRotationAngle = frame->mRotationAngle;
ALOGV("rotation: %d", frameCopy->mRotationAngle);
frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame);
memcpy(frameCopy->mData, frame->mData, frame->mSize);
delete frame; // Fix memory leakage
return mThumbnail;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: net::Error ResourceDispatcherHostImpl::BeginDownload(
scoped_ptr<net::URLRequest> request,
bool is_content_initiated,
ResourceContext* context,
int child_id,
int route_id,
bool prefer_cache,
const DownloadSaveInfo& save_info,
const DownloadStartedCallback& started_callback) {
if (is_shutdown_)
return CallbackAndReturn(started_callback, net::ERR_INSUFFICIENT_RESOURCES);
const GURL& url = request->original_url();
char url_buf[128];
base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
base::debug::Alias(url_buf);
CHECK(ContainsKey(active_resource_contexts_, context));
const net::URLRequestContext* request_context = context->GetRequestContext();
request->set_referrer(MaybeStripReferrer(GURL(request->referrer())).spec());
request->set_context(request_context);
int extra_load_flags = net::LOAD_IS_DOWNLOAD;
if (prefer_cache) {
if (request->get_upload() != NULL)
extra_load_flags |= net::LOAD_ONLY_FROM_CACHE;
else
extra_load_flags |= net::LOAD_PREFERRING_CACHE;
} else {
extra_load_flags |= net::LOAD_DISABLE_CACHE;
}
request->set_load_flags(request->load_flags() | extra_load_flags);
if (!ChildProcessSecurityPolicyImpl::GetInstance()->
CanRequestURL(child_id, url)) {
VLOG(1) << "Denied unauthorized download request for "
<< url.possibly_invalid_spec();
return CallbackAndReturn(started_callback, net::ERR_ACCESS_DENIED);
}
request_id_--;
scoped_refptr<ResourceHandler> handler(
CreateResourceHandlerForDownload(request.get(), context, child_id,
route_id, request_id_,
is_content_initiated, save_info,
started_callback));
if (!request_context->job_factory()->IsHandledURL(url)) {
VLOG(1) << "Download request for unsupported protocol: "
<< url.possibly_invalid_spec();
return net::ERR_ACCESS_DENIED;
}
ResourceRequestInfoImpl* extra_info =
CreateRequestInfo(handler, child_id, route_id, true, context);
extra_info->AssociateWithRequest(request.get()); // Request takes ownership.
request->set_delegate(this);
BeginRequestInternal(request.release());
return net::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: int user_path_at_empty(int dfd, const char __user *name, unsigned flags,
struct path *path, int *empty)
{
struct nameidata nd;
struct filename *tmp = getname_flags(name, flags, empty);
int err = PTR_ERR(tmp);
if (!IS_ERR(tmp)) {
BUG_ON(flags & LOOKUP_PARENT);
err = filename_lookup(dfd, tmp, flags, &nd);
putname(tmp);
if (!err)
*path = nd.path;
}
return err;
}
CWE ID: CWE-59
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool ndp_msg_check_valid(struct ndp_msg *msg)
{
size_t len = ndp_msg_payload_len(msg);
enum ndp_msg_type msg_type = ndp_msg_type(msg);
if (len < ndp_msg_type_info(msg_type)->raw_struct_size)
return false;
return true;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: str_of_minor_format (int format)
{ switch (SF_CODEC (format))
{ CASE_NAME (SF_FORMAT_PCM_S8) ;
CASE_NAME (SF_FORMAT_PCM_16) ;
CASE_NAME (SF_FORMAT_PCM_24) ;
CASE_NAME (SF_FORMAT_PCM_32) ;
CASE_NAME (SF_FORMAT_PCM_U8) ;
CASE_NAME (SF_FORMAT_FLOAT) ;
CASE_NAME (SF_FORMAT_DOUBLE) ;
CASE_NAME (SF_FORMAT_ULAW) ;
CASE_NAME (SF_FORMAT_ALAW) ;
CASE_NAME (SF_FORMAT_IMA_ADPCM) ;
CASE_NAME (SF_FORMAT_MS_ADPCM) ;
CASE_NAME (SF_FORMAT_GSM610) ;
CASE_NAME (SF_FORMAT_VOX_ADPCM) ;
CASE_NAME (SF_FORMAT_G721_32) ;
CASE_NAME (SF_FORMAT_G723_24) ;
CASE_NAME (SF_FORMAT_G723_40) ;
CASE_NAME (SF_FORMAT_DWVW_12) ;
CASE_NAME (SF_FORMAT_DWVW_16) ;
CASE_NAME (SF_FORMAT_DWVW_24) ;
CASE_NAME (SF_FORMAT_DWVW_N) ;
CASE_NAME (SF_FORMAT_DPCM_8) ;
CASE_NAME (SF_FORMAT_DPCM_16) ;
CASE_NAME (SF_FORMAT_VORBIS) ;
default :
break ;
} ;
return "BAD_MINOR_FORMAT" ;
} /* str_of_minor_format */
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: logger_stop_signal_cb (const void *pointer, void *data,
const char *signal, const char *type_data,
void *signal_data)
{
struct t_logger_buffer *ptr_logger_buffer;
/* make C compiler happy */
(void) pointer;
(void) data;
(void) signal;
(void) type_data;
ptr_logger_buffer = logger_buffer_search_buffer (signal_data);
if (ptr_logger_buffer)
logger_stop (ptr_logger_buffer, 0);
return WEECHAT_RC_OK;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void btif_av_event_deep_copy(uint16_t event, char* p_dest, char* p_src) {
BTIF_TRACE_DEBUG("%s", __func__);
tBTA_AV* av_src = (tBTA_AV*)p_src;
tBTA_AV* av_dest = (tBTA_AV*)p_dest;
maybe_non_aligned_memcpy(av_dest, av_src, sizeof(*av_src));
switch (event) {
case BTA_AV_META_MSG_EVT:
if (av_src->meta_msg.p_data && av_src->meta_msg.len) {
av_dest->meta_msg.p_data = (uint8_t*)osi_calloc(av_src->meta_msg.len);
memcpy(av_dest->meta_msg.p_data, av_src->meta_msg.p_data,
av_src->meta_msg.len);
}
if (av_src->meta_msg.p_msg) {
av_dest->meta_msg.p_msg = (tAVRC_MSG*)osi_calloc(sizeof(tAVRC_MSG));
memcpy(av_dest->meta_msg.p_msg, av_src->meta_msg.p_msg,
sizeof(tAVRC_MSG));
tAVRC_MSG* p_msg_src = av_src->meta_msg.p_msg;
tAVRC_MSG* p_msg_dest = av_dest->meta_msg.p_msg;
if ((p_msg_src->hdr.opcode == AVRC_OP_VENDOR) &&
(p_msg_src->vendor.p_vendor_data && p_msg_src->vendor.vendor_len)) {
p_msg_dest->vendor.p_vendor_data =
(uint8_t*)osi_calloc(p_msg_src->vendor.vendor_len);
memcpy(p_msg_dest->vendor.p_vendor_data,
p_msg_src->vendor.p_vendor_data, p_msg_src->vendor.vendor_len);
}
}
break;
default:
break;
}
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int may_open(struct path *path, int acc_mode, int flag)
{
struct dentry *dentry = path->dentry;
struct inode *inode = dentry->d_inode;
int error;
/* O_PATH? */
if (!acc_mode)
return 0;
if (!inode)
return -ENOENT;
switch (inode->i_mode & S_IFMT) {
case S_IFLNK:
return -ELOOP;
case S_IFDIR:
if (acc_mode & MAY_WRITE)
return -EISDIR;
break;
case S_IFBLK:
case S_IFCHR:
if (path->mnt->mnt_flags & MNT_NODEV)
return -EACCES;
/*FALLTHRU*/
case S_IFIFO:
case S_IFSOCK:
flag &= ~O_TRUNC;
break;
}
error = inode_permission(inode, acc_mode);
if (error)
return error;
/*
* An append-only file must be opened in append mode for writing.
*/
if (IS_APPEND(inode)) {
if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND))
return -EPERM;
if (flag & O_TRUNC)
return -EPERM;
}
/* O_NOATIME can only be set by the owner or superuser */
if (flag & O_NOATIME && !inode_owner_or_capable(inode))
return -EPERM;
return 0;
}
CWE ID: CWE-59
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
{
int i;
unsigned char a, b, c, d;
*dst_len = 0;
for (i = 0; i < src_len; i += 4) {
a = b64reverse(src[i]);
if (a >= 254) {
return i;
}
b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
if (b >= 254) {
return i + 1;
}
c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
if (c == 254) {
return i + 2;
}
d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
if (d == 254) {
return i + 3;
}
dst[(*dst_len)++] = (a << 2) + (b >> 4);
if (c != 255) {
dst[(*dst_len)++] = (b << 4) + (c >> 2);
if (d != 255) {
dst[(*dst_len)++] = (c << 6) + d;
}
}
}
return -1;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void rds6_inc_info_copy(struct rds_incoming *inc,
struct rds_info_iterator *iter,
struct in6_addr *saddr, struct in6_addr *daddr,
int flip)
{
struct rds6_info_message minfo6;
minfo6.seq = be64_to_cpu(inc->i_hdr.h_sequence);
minfo6.len = be32_to_cpu(inc->i_hdr.h_len);
if (flip) {
minfo6.laddr = *daddr;
minfo6.faddr = *saddr;
minfo6.lport = inc->i_hdr.h_dport;
minfo6.fport = inc->i_hdr.h_sport;
} else {
minfo6.laddr = *saddr;
minfo6.faddr = *daddr;
minfo6.lport = inc->i_hdr.h_sport;
minfo6.fport = inc->i_hdr.h_dport;
}
rds_info_copy(iter, &minfo6, sizeof(minfo6));
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: LogData::LogData()
: routing_id(0),
type(0),
sent(0),
receive(0),
dispatch(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 TextTrack::addCue(TextTrackCue* cue) {
DCHECK(cue);
if (std::isnan(cue->startTime()) || std::isnan(cue->endTime()) ||
cue->startTime() < 0 || cue->endTime() < 0)
return;
if (TextTrack* cue_track = cue->track())
cue_track->removeCue(cue, ASSERT_NO_EXCEPTION);
cue->SetTrack(this);
EnsureTextTrackCueList()->Add(cue);
if (GetCueTimeline() && mode_ != DisabledKeyword())
GetCueTimeline()->AddCue(this, cue);
}
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: ftc_snode_load( FTC_SNode snode,
FTC_Manager manager,
FT_UInt gindex,
FT_ULong *asize )
{
FT_Error error;
FTC_GNode gnode = FTC_GNODE( snode );
FTC_Family family = gnode->family;
FT_Memory memory = manager->memory;
FT_Face face;
FTC_SBit sbit;
FTC_SFamilyClass clazz;
if ( (FT_UInt)(gindex - gnode->gindex) >= snode->count )
{
FT_ERROR(( "ftc_snode_load: invalid glyph index" ));
return FT_THROW( Invalid_Argument );
}
sbit = snode->sbits + ( gindex - gnode->gindex );
clazz = (FTC_SFamilyClass)family->clazz;
sbit->buffer = 0;
error = clazz->family_load_glyph( family, gindex, manager, &face );
if ( error )
goto BadGlyph;
{
FT_Int temp;
FT_GlyphSlot slot = face->glyph;
FT_Bitmap* bitmap = &slot->bitmap;
FT_Pos xadvance, yadvance; /* FT_GlyphSlot->advance.{x|y} */
if ( slot->format != FT_GLYPH_FORMAT_BITMAP )
{
FT_TRACE0(( "ftc_snode_load:"
" glyph loaded didn't return a bitmap\n" ));
goto BadGlyph;
}
/* Check that our values fit into 8-bit containers! */
/* If this is not the case, our bitmap is too large */
/* and we will leave it as `missing' with sbit.buffer = 0 */
#define CHECK_CHAR( d ) ( temp = (FT_Char)d, temp == d )
#define CHECK_BYTE( d ) ( temp = (FT_Byte)d, temp == d )
/* horizontal advance in pixels */
xadvance = ( slot->advance.x + 32 ) >> 6;
yadvance = ( slot->advance.y + 32 ) >> 6;
if ( !CHECK_BYTE( bitmap->rows ) ||
!CHECK_BYTE( bitmap->width ) ||
!CHECK_CHAR( bitmap->pitch ) ||
!CHECK_CHAR( slot->bitmap_left ) ||
!CHECK_CHAR( slot->bitmap_top ) ||
!CHECK_CHAR( xadvance ) ||
!CHECK_CHAR( yadvance ) )
{
FT_TRACE2(( "ftc_snode_load:"
" glyph too large for small bitmap cache\n"));
goto BadGlyph;
}
sbit->width = (FT_Byte)bitmap->width;
sbit->height = (FT_Byte)bitmap->rows;
sbit->pitch = (FT_Char)bitmap->pitch;
sbit->left = (FT_Char)slot->bitmap_left;
sbit->top = (FT_Char)slot->bitmap_top;
sbit->xadvance = (FT_Char)xadvance;
sbit->yadvance = (FT_Char)yadvance;
sbit->format = (FT_Byte)bitmap->pixel_mode;
sbit->max_grays = (FT_Byte)(bitmap->num_grays - 1);
/* copy the bitmap into a new buffer -- ignore error */
error = ftc_sbit_copy_bitmap( sbit, bitmap, memory );
/* now, compute size */
if ( asize )
*asize = FT_ABS( sbit->pitch ) * sbit->height;
} /* glyph loading successful */
/* ignore the errors that might have occurred -- */
/* we mark unloaded glyphs with `sbit.buffer == 0' */
/* and `width == 255', `height == 0' */
/* */
if ( error && FT_ERR_NEQ( error, Out_Of_Memory ) )
{
BadGlyph:
sbit->width = 255;
sbit->height = 0;
sbit->buffer = NULL;
error = FT_Err_Ok;
if ( asize )
*asize = 0;
}
return error;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int regset_xregset_fpregs_active(struct task_struct *target, const struct user_regset *regset)
{
struct fpu *target_fpu = &target->thread.fpu;
if (boot_cpu_has(X86_FEATURE_FXSR) && target_fpu->fpstate_active)
return regset->n;
else
return 0;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ChromeClientImpl::EnumerateChosenDirectory(FileChooser* file_chooser) {
WebViewClient* client = web_view_->Client();
if (!client)
return;
WebFileChooserCompletionImpl* chooser_completion =
new WebFileChooserCompletionImpl(file_chooser);
DCHECK(file_chooser);
DCHECK(file_chooser->Params().selected_files.size());
if (!client->EnumerateChosenDirectory(
file_chooser->Params().selected_files[0], chooser_completion))
chooser_completion->DidChooseFile(WebVector<WebString>());
}
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: parse_range(char *str, size_t file_sz, int *nranges)
{
static struct range ranges[MAX_RANGES];
int i = 0;
char *p, *q;
/* Extract range unit */
if ((p = strchr(str, '=')) == NULL)
return (NULL);
*p++ = '\0';
/* Check if it's a bytes range spec */
if (strcmp(str, "bytes") != 0)
return (NULL);
while ((q = strchr(p, ',')) != NULL) {
*q++ = '\0';
/* Extract start and end positions */
if (parse_range_spec(p, file_sz, &ranges[i]) == 0)
continue;
i++;
if (i == MAX_RANGES)
return (NULL);
p = q;
}
if (parse_range_spec(p, file_sz, &ranges[i]) != 0)
i++;
*nranges = i;
return (i ? ranges : NULL);
}
CWE ID: CWE-770
Target: 1
Example 2:
Code: int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
loff_t lstart, loff_t length)
{
struct super_block *sb = inode->i_sb;
struct address_space *mapping = inode->i_mapping;
unsigned partial_start, partial_end;
ext4_fsblk_t start, end;
loff_t byte_end = (lstart + length - 1);
int err = 0;
partial_start = lstart & (sb->s_blocksize - 1);
partial_end = byte_end & (sb->s_blocksize - 1);
start = lstart >> sb->s_blocksize_bits;
end = byte_end >> sb->s_blocksize_bits;
/* Handle partial zero within the single block */
if (start == end &&
(partial_start || (partial_end != sb->s_blocksize - 1))) {
err = ext4_block_zero_page_range(handle, mapping,
lstart, length);
return err;
}
/* Handle partial zero out on the start of the range */
if (partial_start) {
err = ext4_block_zero_page_range(handle, mapping,
lstart, sb->s_blocksize);
if (err)
return err;
}
/* Handle partial zero out on the end of the range */
if (partial_end != sb->s_blocksize - 1)
err = ext4_block_zero_page_range(handle, mapping,
byte_end - partial_end,
partial_end + 1);
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: void kernel_sigaction(int sig, __sighandler_t action)
{
spin_lock_irq(¤t->sighand->siglock);
current->sighand->action[sig - 1].sa.sa_handler = action;
if (action == SIG_IGN) {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, sig);
flush_sigqueue_mask(&mask, ¤t->signal->shared_pending);
flush_sigqueue_mask(&mask, ¤t->pending);
recalc_sigpending();
}
spin_unlock_irq(¤t->sighand->siglock);
}
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: fm_mgr_config_mgr_connect
(
fm_config_conx_hdl *hdl,
fm_mgr_type_t mgr
)
{
char s_path[256];
char c_path[256];
char *mgr_prefix;
p_hsm_com_client_hdl_t *mgr_hdl;
pid_t pid;
memset(s_path,0,sizeof(s_path));
memset(c_path,0,sizeof(c_path));
pid = getpid();
switch ( mgr )
{
case FM_MGR_SM:
mgr_prefix = HSM_FM_SCK_SM;
mgr_hdl = &hdl->sm_hdl;
break;
case FM_MGR_PM:
mgr_prefix = HSM_FM_SCK_PM;
mgr_hdl = &hdl->pm_hdl;
break;
case FM_MGR_FE:
mgr_prefix = HSM_FM_SCK_FE;
mgr_hdl = &hdl->fe_hdl;
break;
default:
return FM_CONF_INIT_ERR;
}
sprintf(s_path,"%s%s%d",HSM_FM_SCK_PREFIX,mgr_prefix,hdl->instance);
sprintf(c_path,"%s%s%d_C_%lu",HSM_FM_SCK_PREFIX,mgr_prefix,
hdl->instance, (long unsigned)pid);
if ( *mgr_hdl == NULL )
{
if ( hcom_client_init(mgr_hdl,s_path,c_path,32768) != HSM_COM_OK )
{
return FM_CONF_INIT_ERR;
}
}
if ( hcom_client_connect(*mgr_hdl) == HSM_COM_OK )
{
hdl->conx_mask |= mgr;
return FM_CONF_OK;
}
return FM_CONF_CONX_ERR;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int hmac_sha256_digest(struct ahash_request *req)
{
int ret2, ret1;
ret1 = hmac_sha256_init(req);
if (ret1)
goto out;
ret1 = ahash_update(req);
ret2 = ahash_final(req);
out:
return ret1 ? ret1 : ret2;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool SimplifiedBackwardsTextIterator::handleTextNode()
{
m_lastTextNode = m_node;
int startOffset;
int offsetInNode;
RenderText* renderer = handleFirstLetter(startOffset, offsetInNode);
if (!renderer)
return true;
String text = renderer->text();
if (!renderer->firstTextBox() && text.length() > 0)
return true;
m_positionEndOffset = m_offset;
m_offset = startOffset + offsetInNode;
m_positionNode = m_node;
m_positionStartOffset = m_offset;
ASSERT(0 <= m_positionStartOffset - offsetInNode && m_positionStartOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(1 <= m_positionEndOffset - offsetInNode && m_positionEndOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(m_positionStartOffset <= m_positionEndOffset);
m_textLength = m_positionEndOffset - m_positionStartOffset;
m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode);
ASSERT(m_textCharacters >= text.characters());
ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length()));
m_lastCharacter = text[m_positionEndOffset - 1];
return !m_shouldHandleFirstLetter;
}
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: OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() {
CHECK(mHandle != NULL);
memset(mHandle, 0, sizeof(tagvideoEncControls));
CHECK(mEncParams != NULL);
memset(mEncParams, 0, sizeof(tagvideoEncOptions));
if (!PVGetDefaultEncOption(mEncParams, 0)) {
ALOGE("Failed to get default encoding parameters");
return OMX_ErrorUndefined;
}
mEncParams->encMode = mEncodeMode;
mEncParams->encWidth[0] = mWidth;
mEncParams->encHeight[0] = mHeight;
mEncParams->encFrameRate[0] = mFramerate >> 16; // mFramerate is in Q16 format
mEncParams->rcType = VBR_1;
mEncParams->vbvDelay = 5.0f;
mEncParams->profile_level = CORE_PROFILE_LEVEL2;
mEncParams->packetSize = 32;
mEncParams->rvlcEnable = PV_OFF;
mEncParams->numLayers = 1;
mEncParams->timeIncRes = 1000;
mEncParams->tickPerSrc = ((int64_t)mEncParams->timeIncRes << 16) / mFramerate;
mEncParams->bitRate[0] = mBitrate;
mEncParams->iQuant[0] = 15;
mEncParams->pQuant[0] = 12;
mEncParams->quantType[0] = 0;
mEncParams->noFrameSkipped = PV_OFF;
if (mColorFormat != OMX_COLOR_FormatYUV420Planar || mInputDataIsMeta) {
free(mInputFrameData);
mInputFrameData = NULL;
if (((uint64_t)mWidth * mHeight) > ((uint64_t)INT32_MAX / 3)) {
ALOGE("b/25812794, Buffer size is too big.");
return OMX_ErrorBadParameter;
}
mInputFrameData =
(uint8_t *) malloc((mWidth * mHeight * 3 ) >> 1);
CHECK(mInputFrameData != NULL);
}
if (mWidth % 16 != 0 || mHeight % 16 != 0) {
ALOGE("Video frame size %dx%d must be a multiple of 16",
mWidth, mHeight);
return OMX_ErrorBadParameter;
}
if (mIDRFrameRefreshIntervalInSec < 0) {
mEncParams->intraPeriod = -1;
} else if (mIDRFrameRefreshIntervalInSec == 0) {
mEncParams->intraPeriod = 1; // All I frames
} else {
mEncParams->intraPeriod =
(mIDRFrameRefreshIntervalInSec * mFramerate) >> 16;
}
mEncParams->numIntraMB = 0;
mEncParams->sceneDetect = PV_ON;
mEncParams->searchRange = 16;
mEncParams->mv8x8Enable = PV_OFF;
mEncParams->gobHeaderInterval = 0;
mEncParams->useACPred = PV_ON;
mEncParams->intraDCVlcTh = 0;
return OMX_ErrorNone;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int asf_read_header(AVFormatContext *s)
{
ASFContext *asf = s->priv_data;
AVIOContext *pb = s->pb;
const GUIDParseTable *g = NULL;
ff_asf_guid guid;
int i, ret;
uint64_t size;
asf->preroll = 0;
asf->is_simple_index = 0;
ff_get_guid(pb, &guid);
if (ff_guidcmp(&guid, &ff_asf_header))
return AVERROR_INVALIDDATA;
avio_skip(pb, 8); // skip header object size
avio_skip(pb, 6); // skip number of header objects and 2 reserved bytes
asf->data_reached = 0;
/* 1 is here instead of pb->eof_reached because (when not streaming), Data are skipped
* for the first time,
* Index object is processed and got eof and then seeking back to the Data is performed.
*/
while (1) {
if (avio_tell(pb) == asf->offset)
break;
asf->offset = avio_tell(pb);
if ((ret = ff_get_guid(pb, &guid)) < 0) {
if (ret == AVERROR_EOF && asf->data_reached)
break;
else
goto failed;
}
g = find_guid(guid);
if (g) {
asf->unknown_offset = asf->offset;
asf->is_header = 1;
if ((ret = g->read_object(s, g)) < 0)
goto failed;
} else {
size = avio_rl64(pb);
align_position(pb, asf->offset, size);
}
if (asf->data_reached &&
(!(pb->seekable & AVIO_SEEKABLE_NORMAL) ||
(asf->b_flags & ASF_FLAG_BROADCAST)))
break;
}
if (!asf->data_reached) {
av_log(s, AV_LOG_ERROR, "Data Object was not found.\n");
ret = AVERROR_INVALIDDATA;
goto failed;
}
if (pb->seekable & AVIO_SEEKABLE_NORMAL)
avio_seek(pb, asf->first_packet_offset, SEEK_SET);
for (i = 0; i < asf->nb_streams; i++) {
const char *rfc1766 = asf->asf_sd[asf->asf_st[i]->lang_idx].langs;
AVStream *st = s->streams[asf->asf_st[i]->index];
set_language(s, rfc1766, &st->metadata);
}
for (i = 0; i < ASF_MAX_STREAMS; i++) {
AVStream *st = NULL;
st = find_stream(s, i);
if (st) {
av_dict_copy(&st->metadata, asf->asf_sd[i].asf_met, AV_DICT_IGNORE_SUFFIX);
if (asf->asf_sd[i].aspect_ratio.num > 0 && asf->asf_sd[i].aspect_ratio.den > 0) {
st->sample_aspect_ratio.num = asf->asf_sd[i].aspect_ratio.num;
st->sample_aspect_ratio.den = asf->asf_sd[i].aspect_ratio.den;
}
}
}
return 0;
failed:
asf_read_close(s);
return ret;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void vmxnet3_activate_device(VMXNET3State *s)
{
int i;
VMW_CFPRN("MTU is %u", s->mtu);
s->max_rx_frags =
VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG);
if (s->max_rx_frags == 0) {
s->max_rx_frags = 1;
}
VMW_CFPRN("Max RX fragments is %u", s->max_rx_frags);
s->event_int_idx =
VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx);
assert(vmxnet3_verify_intx(s, s->event_int_idx));
VMW_CFPRN("Events interrupt line is %u", s->event_int_idx);
s->auto_int_masking =
VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask);
VMW_CFPRN("Automatic interrupt masking is %d", (int)s->auto_int_masking);
s->txq_num =
VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues);
s->rxq_num =
VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues);
VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num);
assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES);
qdescr_table_pa =
VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA);
VMW_CFPRN("TX queues descriptors table is at 0x%" PRIx64, qdescr_table_pa);
/*
* Worst-case scenario is a packet that holds all TX rings space so
* we calculate total size of all TX rings for max TX fragments number
*/
s->max_tx_frags = 0;
/* TX queues */
for (i = 0; i < s->txq_num; i++) {
VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues);
VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num);
assert(s->txq_num <= VMXNET3_DEVICE_MAX_TX_QUEUES);
qdescr_table_pa =
VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA);
VMW_CFPRN("TX Queue %d interrupt: %d", i, s->txq_descr[i].intr_idx);
/* Read rings memory locations for TX queues */
pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA);
size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize);
vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size,
sizeof(struct Vmxnet3_TxDesc), false);
VMXNET3_RING_DUMP(VMW_CFPRN, "TX", i, &s->txq_descr[i].tx_ring);
s->max_tx_frags += size;
/* TXC ring */
pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA);
size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize);
vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size,
sizeof(struct Vmxnet3_TxCompDesc), true);
VMXNET3_RING_DUMP(VMW_CFPRN, "TXC", i, &s->txq_descr[i].comp_ring);
s->txq_descr[i].tx_stats_pa =
qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats);
memset(&s->txq_descr[i].txq_stats, 0,
sizeof(s->txq_descr[i].txq_stats));
/* Fill device-managed parameters for queues */
VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa,
ctrl.txThreshold,
VMXNET3_DEF_TX_THRESHOLD);
}
/* Preallocate TX packet wrapper */
VMW_CFPRN("Max TX fragments is %u", s->max_tx_frags);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
/* Read rings memory locations for RX queues */
for (i = 0; i < s->rxq_num; i++) {
int j;
hwaddr qd_pa =
qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) +
i * sizeof(struct Vmxnet3_RxQueueDesc);
/* Read interrupt number for this RX queue */
s->rxq_descr[i].intr_idx =
VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx);
assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx));
VMW_CFPRN("RX Queue %d interrupt: %d", i, s->rxq_descr[i].intr_idx);
/* Read rings memory locations */
for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) {
/* RX rings */
pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]);
size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]);
vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size,
sizeof(struct Vmxnet3_RxDesc), false);
VMW_CFPRN("RX queue %d:%d: Base: %" PRIx64 ", Size: %d",
i, j, pa, size);
}
/* RXC ring */
pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA);
size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize);
vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size,
sizeof(struct Vmxnet3_RxCompDesc), true);
VMW_CFPRN("RXC queue %d: Base: %" PRIx64 ", Size: %d", i, pa, size);
s->rxq_descr[i].rx_stats_pa =
qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats);
memset(&s->rxq_descr[i].rxq_stats, 0,
sizeof(s->rxq_descr[i].rxq_stats));
}
vmxnet3_validate_interrupts(s);
/* Make sure everything is in place before device activation */
smp_wmb();
vmxnet3_reset_mac(s);
s->device_active = true;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info,
size_t* gc_info_index_slot) {
DCHECK(gc_info);
DCHECK(gc_info_index_slot);
DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, ());
MutexLocker locker(mutex);
if (*gc_info_index_slot)
return;
int index = ++gc_info_index_;
size_t gc_info_index = static_cast<size_t>(index);
CHECK(gc_info_index < GCInfoTable::kMaxIndex);
if (gc_info_index >= gc_info_table_size_)
Resize();
g_gc_info_table[gc_info_index] = gc_info;
ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: void ChromeContentBrowserClient::AllowCertificateError(
SSLCertErrorHandler* handler,
bool overridable,
Callback2<SSLCertErrorHandler*, bool>::Type* callback) {
TabContents* tab = tab_util::GetTabContentsByID(
handler->render_process_host_id(),
handler->tab_contents_id());
if (!tab) {
NOTREACHED();
return;
}
prerender::PrerenderManager* prerender_manager =
tab->profile()->GetPrerenderManager();
if (prerender_manager && prerender_manager->IsTabContentsPrerendering(tab)) {
if (prerender_manager->prerender_tracker()->TryCancel(
handler->render_process_host_id(),
handler->tab_contents_id(),
prerender::FINAL_STATUS_SSL_ERROR)) {
handler->CancelRequest();
return;
}
}
SSLBlockingPage* blocking_page = new SSLBlockingPage(
handler, overridable, callback);
blocking_page->Show();
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: XML_SetEndElementHandler(XML_Parser parser,
XML_EndElementHandler end) {
if (parser != NULL)
parser->m_endElementHandler = end;
}
CWE ID: CWE-611
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: CWD_API void realpath_cache_del(const char *path, int path_len TSRMLS_DC) /* {{{ */
{
#ifdef PHP_WIN32
unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC);
#else
unsigned long key = realpath_cache_key(path, path_len);
#endif
unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0]));
realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n];
while (*bucket != NULL) {
if (key == (*bucket)->key && path_len == (*bucket)->path_len &&
memcmp(path, (*bucket)->path, path_len) == 0) {
realpath_cache_bucket *r = *bucket;
*bucket = (*bucket)->next;
/* if the pointers match then only subtract the length of the path */
if(r->path == r->realpath) {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1;
} else {
CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1;
}
free(r);
return;
} else {
bucket = &(*bucket)->next;
}
}
}
/* }}} */
CWE ID: CWE-190
Target: 1
Example 2:
Code: void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
int32_t targetFlags, BitSet32 pointerIds) {
if (targetFlags & InputTarget::FLAG_SPLIT) {
split = true;
}
for (size_t i = 0; i < windows.size(); i++) {
TouchedWindow& touchedWindow = windows.editItemAt(i);
if (touchedWindow.windowHandle == windowHandle) {
touchedWindow.targetFlags |= targetFlags;
if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
}
touchedWindow.pointerIds.value |= pointerIds.value;
return;
}
}
windows.push();
TouchedWindow& touchedWindow = windows.editTop();
touchedWindow.windowHandle = windowHandle;
touchedWindow.targetFlags = targetFlags;
touchedWindow.pointerIds = pointerIds;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ssize_t read_mem(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
phys_addr_t p = *ppos;
ssize_t read, sz;
void *ptr;
if (p != *ppos)
return 0;
if (!valid_phys_addr_range(p, count))
return -EFAULT;
read = 0;
#ifdef __ARCH_HAS_NO_PAGE_ZERO_MAPPED
/* we don't have page 0 mapped on sparc and m68k.. */
if (p < PAGE_SIZE) {
sz = size_inside_page(p, count);
if (sz > 0) {
if (clear_user(buf, sz))
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
}
#endif
while (count > 0) {
unsigned long remaining;
sz = size_inside_page(p, count);
if (!range_is_allowed(p >> PAGE_SHIFT, count))
return -EPERM;
/*
* On ia64 if a page has been mapped somewhere as uncached, then
* it must also be accessed uncached by the kernel or data
* corruption may occur.
*/
ptr = xlate_dev_mem_ptr(p);
if (!ptr)
return -EFAULT;
remaining = copy_to_user(buf, ptr, sz);
unxlate_dev_mem_ptr(p, ptr);
if (remaining)
return -EFAULT;
buf += sz;
p += sz;
count -= sz;
read += sz;
}
*ppos += read;
return read;
}
CWE ID: CWE-732
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %lu, expected %zu", outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void ChromeClientImpl::setWindowRect(const FloatRect& r)
{
if (m_webView->client())
m_webView->client()->setWindowRect(IntRect(r));
}
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 xhci_class_init(ObjectClass *klass, void *data)
{
PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
DeviceClass *dc = DEVICE_CLASS(klass);
dc->vmsd = &vmstate_xhci;
dc->props = xhci_properties;
dc->reset = xhci_reset;
set_bit(DEVICE_CATEGORY_USB, dc->categories);
k->realize = usb_xhci_realize;
k->exit = usb_xhci_exit;
k->vendor_id = PCI_VENDOR_ID_NEC;
k->device_id = PCI_DEVICE_ID_NEC_UPD720200;
k->class_id = PCI_CLASS_SERIAL_USB;
k->revision = 0x03;
k->is_express = 1;
}
CWE ID: CWE-835
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ThreadHeap::WriteBarrier(void* value) {
DCHECK(thread_state_->IsIncrementalMarking());
DCHECK(value);
DCHECK_NE(value, reinterpret_cast<void*>(-1));
BasePage* const page = PageFromObject(value);
HeapObjectHeader* const header =
page->IsLargeObjectPage()
? static_cast<LargeObjectPage*>(page)->GetHeapObjectHeader()
: static_cast<NormalPage*>(page)->FindHeaderFromAddress(
reinterpret_cast<Address>(const_cast<void*>(value)));
if (header->IsMarked())
return;
header->Mark();
marking_worklist_->Push(
WorklistTaskId::MainThread,
{header->Payload(), ThreadHeap::GcInfo(header->GcInfoIndex())->trace_});
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int dnxhd_decode_dct_block_12_444(const DNXHDContext *ctx,
RowContext *row, int n)
{
return dnxhd_decode_dct_block(ctx, row, n, 6, 32, 4, 2);
}
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 bool write_hci_command(hci_packet_t type, const void *packet, size_t length) {
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_FD)
goto error;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(0x7F000001);
addr.sin_port = htons(8873);
if (connect(sock, (const struct sockaddr *)&addr, sizeof(addr)) == -1)
goto error;
if (send(sock, &type, 1, 0) != 1)
goto error;
if (send(sock, &length, 2, 0) != 2)
goto error;
if (send(sock, packet, length, 0) != (ssize_t)length)
goto error;
close(sock);
return true;
error:;
close(sock);
return false;
}
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 __scm_destroy(struct scm_cookie *scm)
{
struct scm_fp_list *fpl = scm->fp;
int i;
if (fpl) {
scm->fp = NULL;
for (i=fpl->count-1; i>=0; i--)
fput(fpl->fp[i]);
kfree(fpl);
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void http_reset_txn(struct session *s)
{
http_end_txn(s);
http_init_txn(s);
s->be = s->fe;
s->logs.logwait = s->fe->to_log;
s->logs.level = 0;
session_del_srv_conn(s);
s->target = NULL;
/* re-init store persistence */
s->store_count = 0;
s->uniq_id = global.req_count++;
s->pend_pos = NULL;
s->req->flags |= CF_READ_DONTWAIT; /* one read is usually enough */
/* We must trim any excess data from the response buffer, because we
* may have blocked an invalid response from a server that we don't
* want to accidentely forward once we disable the analysers, nor do
* we want those data to come along with next response. A typical
* example of such data would be from a buggy server responding to
* a HEAD with some data, or sending more than the advertised
* content-length.
*/
if (unlikely(s->rep->buf->i))
s->rep->buf->i = 0;
s->req->rto = s->fe->timeout.client;
s->req->wto = TICK_ETERNITY;
s->rep->rto = TICK_ETERNITY;
s->rep->wto = s->fe->timeout.client;
s->req->rex = TICK_ETERNITY;
s->req->wex = TICK_ETERNITY;
s->req->analyse_exp = TICK_ETERNITY;
s->rep->rex = TICK_ETERNITY;
s->rep->wex = TICK_ETERNITY;
s->rep->analyse_exp = TICK_ETERNITY;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void OMXNodeInstance::invalidateBufferID(OMX::buffer_id buffer __unused) {
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static v8::Handle<v8::Value> getObjectParameter(const v8::Arguments& args, ObjectType objectType)
{
if (args.Length() != 2)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
unsigned target = toInt32(args[0]);
unsigned pname = toInt32(args[1]);
WebGLGetInfo info;
switch (objectType) {
case kBuffer:
info = context->getBufferParameter(target, pname, ec);
break;
case kRenderbuffer:
info = context->getRenderbufferParameter(target, pname, ec);
break;
case kTexture:
info = context->getTexParameter(target, pname, ec);
break;
case kVertexAttrib:
info = context->getVertexAttrib(target, pname, ec);
break;
default:
notImplemented();
break;
}
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
return toV8Object(info, args.GetIsolate());
}
CWE ID:
Target: 1
Example 2:
Code: void HTMLFormElement::AddToPastNamesMap(Element* element,
const AtomicString& past_name) {
if (past_name.IsEmpty())
return;
if (!past_names_map_)
past_names_map_ = new PastNamesMap;
past_names_map_->Set(past_name, element);
}
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: XID CreatePictureFromSkiaPixmap(Display* display, XID pixmap) {
XID picture = XRenderCreatePicture(
display, pixmap, GetRenderARGB32Format(display), 0, NULL);
return picture;
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int install_thread_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
BUG_ON(new->thread_keyring);
ret = install_thread_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret;
}
return commit_creds(new);
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: static void ffs_data_get(struct ffs_data *ffs)
{
ENTER();
atomic_inc(&ffs->ref);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int check_acl(struct inode *inode, int mask)
{
#ifdef CONFIG_FS_POSIX_ACL
struct posix_acl *acl;
if (mask & MAY_NOT_BLOCK) {
acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS);
if (!acl)
return -EAGAIN;
/* no ->get_acl() calls in RCU mode... */
if (is_uncached_acl(acl))
return -ECHILD;
return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK);
}
acl = get_acl(inode, ACL_TYPE_ACCESS);
if (IS_ERR(acl))
return PTR_ERR(acl);
if (acl) {
int error = posix_acl_permission(inode, acl, mask);
posix_acl_release(acl);
return error;
}
#endif
return -EAGAIN;
}
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 char* allocFromUTF32(const char32_t* in, size_t len)
{
if (len == 0) {
return getEmptyString();
}
const ssize_t bytes = utf32_to_utf8_length(in, len);
if (bytes < 0) {
return getEmptyString();
}
SharedBuffer* buf = SharedBuffer::alloc(bytes+1);
ALOG_ASSERT(buf, "Unable to allocate shared buffer");
if (!buf) {
return getEmptyString();
}
char* str = (char*) buf->data();
utf32_to_utf8(in, len, str);
return str;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ExtensionSidebarDefaults* Extension::LoadExtensionSidebarDefaults(
const DictionaryValue* extension_sidebar, std::string* error) {
scoped_ptr<ExtensionSidebarDefaults> result(new ExtensionSidebarDefaults());
std::string default_icon;
if (extension_sidebar->HasKey(keys::kSidebarDefaultIcon)) {
if (!extension_sidebar->GetString(keys::kSidebarDefaultIcon,
&default_icon) ||
default_icon.empty()) {
*error = errors::kInvalidSidebarDefaultIconPath;
return NULL;
}
result->set_default_icon_path(default_icon);
}
string16 default_title;
if (extension_sidebar->HasKey(keys::kSidebarDefaultTitle)) {
if (!extension_sidebar->GetString(keys::kSidebarDefaultTitle,
&default_title)) {
*error = errors::kInvalidSidebarDefaultTitle;
return NULL;
}
}
result->set_default_title(default_title);
std::string default_page;
if (extension_sidebar->HasKey(keys::kSidebarDefaultPage)) {
if (!extension_sidebar->GetString(keys::kSidebarDefaultPage,
&default_page) ||
default_page.empty()) {
*error = errors::kInvalidSidebarDefaultPage;
return NULL;
}
GURL url = extension_sidebar_utils::ResolveRelativePath(
default_page, this, error);
if (!url.is_valid())
return NULL;
result->set_default_page(url);
}
return result.release();
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/*tex If no number follows |/CharStrings|, let's read the next line. */
if (sscanf(p, "%i", &i) != 1) {
strcpy(t1_buf_array, t1_line_array);
t1_getline();
strcat(t1_buf_array, t1_line_array);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
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: ProcXIChangeHierarchy(ClientPtr client)
{
xXIAnyHierarchyChangeInfo *any;
size_t len; /* length of data remaining in request */
int rc = Success;
int flags[MAXDEVICES] = { 0 };
REQUEST(xXIChangeHierarchyReq);
REQUEST_AT_LEAST_SIZE(xXIChangeHierarchyReq);
if (!stuff->num_changes)
return rc;
len = ((size_t)stuff->length << 2) - sizeof(xXIAnyHierarchyChangeInfo);
any = (xXIAnyHierarchyChangeInfo *) &stuff[1];
while (stuff->num_changes--) {
if (len < sizeof(xXIAnyHierarchyChangeInfo)) {
rc = BadLength;
goto unwind;
}
SWAPIF(swaps(&any->type));
SWAPIF(swaps(&any->length));
if (len < ((size_t)any->length << 2))
return BadLength;
#define CHANGE_SIZE_MATCH(type) \
do { \
if ((len < sizeof(type)) || (any->length != (sizeof(type) >> 2))) { \
rc = BadLength; \
goto unwind; \
} \
} while(0)
switch (any->type) {
case XIAddMaster:
{
xXIAddMasterInfo *c = (xXIAddMasterInfo *) any;
/* Variable length, due to appended name string */
if (len < sizeof(xXIAddMasterInfo)) {
rc = BadLength;
goto unwind;
}
SWAPIF(swaps(&c->name_len));
if (c->name_len > (len - sizeof(xXIAddMasterInfo))) {
rc = BadLength;
goto unwind;
}
rc = add_master(client, c, flags);
if (rc != Success)
goto unwind;
}
break;
case XIRemoveMaster:
{
xXIRemoveMasterInfo *r = (xXIRemoveMasterInfo *) any;
CHANGE_SIZE_MATCH(xXIRemoveMasterInfo);
rc = remove_master(client, r, flags);
if (rc != Success)
goto unwind;
}
break;
case XIDetachSlave:
{
xXIDetachSlaveInfo *c = (xXIDetachSlaveInfo *) any;
CHANGE_SIZE_MATCH(xXIDetachSlaveInfo);
rc = detach_slave(client, c, flags);
if (rc != Success)
goto unwind;
}
break;
case XIAttachSlave:
{
xXIAttachSlaveInfo *c = (xXIAttachSlaveInfo *) any;
CHANGE_SIZE_MATCH(xXIAttachSlaveInfo);
rc = attach_slave(client, c, flags);
if (rc != Success)
goto unwind;
}
break;
}
len -= any->length * 4;
any = (xXIAnyHierarchyChangeInfo *) ((char *) any + any->length * 4);
}
unwind:
XISendDeviceHierarchyEvent(flags);
return rc;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: OVS_EXCLUDED(ofproto_mutex)
{
rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, fm->priority,
OVS_VERSION_MAX, fm->cookie, fm->cookie_mask, OFPP_ANY,
OFPG_ANY);
rule_criteria_require_rw(&ofm->criteria,
(fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
/* Must create a new flow in advance for the case that no matches are
* found. Also used for template for multiple modified flows. */
add_flow_init(ofproto, ofm, fm);
return 0;
}
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: void ChildProcessLauncherHelper::SetProcessPriorityOnLauncherThread(
base::Process process,
const ChildProcessLauncherPriority& priority) {
JNIEnv* env = AttachCurrentThread();
DCHECK(env);
return Java_ChildProcessLauncherHelperImpl_setPriority(
env, java_peer_, process.Handle(), priority.visible,
priority.has_media_stream, priority.has_foreground_service_worker,
priority.frame_depth, priority.intersects_viewport,
priority.boost_for_pending_views, static_cast<jint>(priority.importance));
}
CWE ID: CWE-664
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: ftrace_regex_lseek(struct file *file, loff_t offset, int whence)
{
loff_t ret;
if (file->f_mode & FMODE_READ)
ret = seq_lseek(file, offset, whence);
else
file->f_pos = ret = 1;
return ret;
}
CWE ID:
Target: 1
Example 2:
Code: static int mailimf_month_name_parse(const char * message, size_t length,
size_t * indx, int * result)
{
size_t cur_token;
int month;
int guessed_month;
int r;
cur_token = * indx;
guessed_month = guess_month(message, length, cur_token);
if (guessed_month == -1)
return MAILIMF_ERROR_PARSE;
r = mailimf_token_case_insensitive_parse(message, length,
&cur_token,
month_names[guessed_month - 1].str);
if (r != MAILIMF_NO_ERROR)
return r;
month = guessed_month;
* result = month;
* indx = cur_token;
return MAILIMF_NO_ERROR;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ipgre_open(struct net_device *dev)
{
struct ip_tunnel *t = netdev_priv(dev);
if (ipv4_is_multicast(t->parms.iph.daddr)) {
struct flowi fl = { .oif = t->parms.link,
.nl_u = { .ip4_u =
{ .daddr = t->parms.iph.daddr,
.saddr = t->parms.iph.saddr,
.tos = RT_TOS(t->parms.iph.tos) } },
.proto = IPPROTO_GRE };
struct rtable *rt;
if (ip_route_output_key(dev_net(dev), &rt, &fl))
return -EADDRNOTAVAIL;
dev = rt->u.dst.dev;
ip_rt_put(rt);
if (__in_dev_get_rtnl(dev) == NULL)
return -EADDRNOTAVAIL;
t->mlink = dev->ifindex;
ip_mc_inc_group(__in_dev_get_rtnl(dev), t->parms.iph.daddr);
}
return 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: TestNativeHandler::TestNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetWakeEventPage",
base::Bind(&TestNativeHandler::GetWakeEventPage, base::Unretained(this)));
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: dfawarn (char const *mesg)
{
static enum { DW_NONE = 0, DW_POSIX, DW_GNU } mode;
if (mode == DW_NONE)
mode = (getenv ("POSIXLY_CORRECT") ? DW_POSIX : DW_GNU);
if (mode == DW_GNU)
dfaerror (mesg);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LocalFileSystem::deleteFileSystemInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
FileSystemType type,
PassRefPtr<CallbackWrapper> callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString());
fileSystem()->deleteFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release());
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool RenderFrameHostManager::CanSubframeSwapProcess(
const GURL& dest_url,
SiteInstance* source_instance,
SiteInstance* dest_instance,
bool was_server_redirect) {
DCHECK(!source_instance || !dest_instance);
GURL resolved_url = dest_url;
if (url::Origin::Create(resolved_url).unique()) {
if (source_instance) {
resolved_url = source_instance->GetSiteURL();
} else if (dest_instance) {
resolved_url = dest_instance->GetSiteURL();
} else {
if (!was_server_redirect)
return false;
}
}
if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(),
resolved_url)) {
DCHECK(!dest_instance ||
dest_instance == render_frame_host_->GetSiteInstance());
return false;
}
return true;
}
CWE ID: CWE-285
Target: 1
Example 2:
Code: void AutocompleteEditModel::SetSuggestedText(
const string16& text,
InstantCompleteBehavior behavior) {
instant_complete_behavior_ = behavior;
if (instant_complete_behavior_ == INSTANT_COMPLETE_NOW) {
if (!text.empty())
FinalizeInstantQuery(view_->GetText(), text, false);
else
view_->SetInstantSuggestion(text, false);
} else {
DCHECK((behavior == INSTANT_COMPLETE_DELAYED) ||
(behavior == INSTANT_COMPLETE_NEVER));
view_->SetInstantSuggestion(text, behavior == INSTANT_COMPLETE_DELAYED);
}
}
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: lrmd_remote_listen(gpointer data)
{
int csock = 0;
int flag = 0;
unsigned laddr = 0;
struct sockaddr addr;
gnutls_session_t *session = NULL;
crm_client_t *new_client = NULL;
static struct mainloop_fd_callbacks lrmd_remote_fd_cb = {
.dispatch = lrmd_remote_client_msg,
.destroy = lrmd_remote_client_destroy,
};
laddr = sizeof(addr);
memset(&addr, 0, sizeof(addr));
getsockname(ssock, &addr, &laddr);
/* accept the connection */
if (addr.sa_family == AF_INET6) {
struct sockaddr_in6 sa;
char addr_str[INET6_ADDRSTRLEN];
laddr = sizeof(sa);
memset(&sa, 0, sizeof(sa));
csock = accept(ssock, &sa, &laddr);
get_ip_str((struct sockaddr *)&sa, addr_str, INET6_ADDRSTRLEN);
crm_info("New remote connection from %s", addr_str);
} else {
struct sockaddr_in sa;
char addr_str[INET_ADDRSTRLEN];
laddr = sizeof(sa);
memset(&sa, 0, sizeof(sa));
csock = accept(ssock, &sa, &laddr);
get_ip_str((struct sockaddr *)&sa, addr_str, INET_ADDRSTRLEN);
crm_info("New remote connection from %s", addr_str);
}
if (csock == -1) {
crm_err("accept socket failed");
return TRUE;
}
if ((flag = fcntl(csock, F_GETFL)) >= 0) {
if (fcntl(csock, F_SETFL, flag | O_NONBLOCK) < 0) {
crm_err("fcntl() write failed");
close(csock);
return TRUE;
}
} else {
crm_err("fcntl() read failed");
close(csock);
return TRUE;
}
session = create_psk_tls_session(csock, GNUTLS_SERVER, psk_cred_s);
if (session == NULL) {
crm_err("TLS session creation failed");
close(csock);
return TRUE;
}
new_client = calloc(1, sizeof(crm_client_t));
new_client->remote = calloc(1, sizeof(crm_remote_t));
new_client->kind = CRM_CLIENT_TLS;
new_client->remote->tls_session = session;
new_client->id = crm_generate_uuid();
new_client->remote->auth_timeout =
g_timeout_add(LRMD_REMOTE_AUTH_TIMEOUT, lrmd_auth_timeout_cb, new_client);
crm_notice("LRMD client connection established. %p id: %s", new_client, new_client->id);
new_client->remote->source =
mainloop_add_fd("lrmd-remote-client", G_PRIORITY_DEFAULT, csock, new_client,
&lrmd_remote_fd_cb);
g_hash_table_insert(client_connections, new_client->id, new_client);
/* Alert other clients of the new connection */
notify_of_new_client(new_client);
return TRUE;
}
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: int kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot)
{
gfn_t gfn, end_gfn;
pfn_t pfn;
int r = 0;
struct iommu_domain *domain = kvm->arch.iommu_domain;
int flags;
/* check if iommu exists and in use */
if (!domain)
return 0;
gfn = slot->base_gfn;
end_gfn = gfn + slot->npages;
flags = IOMMU_READ;
if (!(slot->flags & KVM_MEM_READONLY))
flags |= IOMMU_WRITE;
if (!kvm->arch.iommu_noncoherent)
flags |= IOMMU_CACHE;
while (gfn < end_gfn) {
unsigned long page_size;
/* Check if already mapped */
if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) {
gfn += 1;
continue;
}
/* Get the page size we could use to map */
page_size = kvm_host_page_size(kvm, gfn);
/* Make sure the page_size does not exceed the memslot */
while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn)
page_size >>= 1;
/* Make sure gfn is aligned to the page size we want to map */
while ((gfn << PAGE_SHIFT) & (page_size - 1))
page_size >>= 1;
/* Make sure hva is aligned to the page size we want to map */
while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1))
page_size >>= 1;
/*
* Pin all pages we are about to map in memory. This is
* important because we unmap and unpin in 4kb steps later.
*/
pfn = kvm_pin_pages(slot, gfn, page_size);
if (is_error_noslot_pfn(pfn)) {
gfn += 1;
continue;
}
/* Map into IO address space */
r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn),
page_size, flags);
if (r) {
printk(KERN_ERR "kvm_iommu_map_address:"
"iommu failed to map pfn=%llx\n", pfn);
kvm_unpin_pages(kvm, pfn, page_size);
goto unmap_pages;
}
gfn += page_size >> PAGE_SHIFT;
}
return 0;
unmap_pages:
kvm_iommu_put_pages(kvm, slot->base_gfn, gfn - slot->base_gfn);
return r;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void BluetoothSocketListenFunction::OnCreateServiceError(
const std::string& message) {
DCHECK_CURRENTLY_ON(work_thread_id());
Respond(Error(message));
}
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 btreeEndTransaction(Btree *p){
BtShared *pBt = p->pBt;
sqlite3 *db = p->db;
assert( sqlite3BtreeHoldsMutex(p) );
#ifndef SQLITE_OMIT_AUTOVACUUM
pBt->bDoTruncate = 0;
#endif
if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
/* If there are other active statements that belong to this database
** handle, downgrade to a read-only transaction. The other statements
** may still be reading from the database. */
downgradeAllSharedCacheTableLocks(p);
p->inTrans = TRANS_READ;
}else{
/* If the handle had any kind of transaction open, decrement the
** transaction count of the shared btree. If the transaction count
** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
** call below will unlock the pager. */
if( p->inTrans!=TRANS_NONE ){
clearAllSharedCacheTableLocks(p);
pBt->nTransaction--;
if( 0==pBt->nTransaction ){
pBt->inTransaction = TRANS_NONE;
}
}
/* Set the current transaction state to TRANS_NONE and unlock the
** pager if this call closed the only read or write transaction. */
p->inTrans = TRANS_NONE;
unlockBtreeIfUnused(pBt);
}
btreeIntegrity(p);
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ping_unhash(struct sock *sk)
{
struct inet_sock *isk = inet_sk(sk);
pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
if (sk_hashed(sk)) {
write_lock_bh(&ping_table.lock);
hlist_nulls_del(&sk->sk_nulls_node);
sk_nulls_node_init(&sk->sk_nulls_node);
sock_put(sk);
isk->inet_num = 0;
isk->inet_sport = 0;
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&ping_table.lock);
}
}
CWE ID:
Target: 1
Example 2:
Code: static int async_encrypt(struct ablkcipher_request *req)
{
struct crypto_tfm *tfm = req->base.tfm;
struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher;
struct blkcipher_desc desc = {
.tfm = __crypto_blkcipher_cast(tfm),
.info = req->info,
.flags = req->base.flags,
};
return alg->encrypt(&desc, req->dst, req->src, req->nbytes);
}
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 BrowserProcessMainImpl::Shutdown() {
if (state_ != STATE_STARTED) {
CHECK_NE(state_, STATE_SHUTTING_DOWN);
return;
MessagePump::Get()->Stop();
WebContentsUnloader::GetInstance()->Shutdown();
if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) {
BrowserContext::AssertNoContextsExist();
}
browser_main_runner_->Shutdown();
browser_main_runner_.reset();
if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) {
BrowserContext::AssertNoContextsExist();
}
browser_main_runner_->Shutdown();
browser_main_runner_.reset();
exit_manager_.reset();
main_delegate_.reset();
platform_delegate_.reset();
state_ = STATE_SHUTDOWN;
}
BrowserProcessMain::BrowserProcessMain() {}
BrowserProcessMain::~BrowserProcessMain() {}
ProcessModel BrowserProcessMain::GetProcessModelOverrideFromEnv() {
static bool g_initialized = false;
static ProcessModel g_process_model = PROCESS_MODEL_UNDEFINED;
if (g_initialized) {
return g_process_model;
}
g_initialized = true;
std::unique_ptr<base::Environment> env = base::Environment::Create();
if (IsEnvironmentOptionEnabled("SINGLE_PROCESS", env.get())) {
g_process_model = PROCESS_MODEL_SINGLE_PROCESS;
} else {
std::string model = GetEnvironmentOption("PROCESS_MODEL", env.get());
if (!model.empty()) {
if (model == "multi-process") {
g_process_model = PROCESS_MODEL_MULTI_PROCESS;
} else if (model == "single-process") {
g_process_model = PROCESS_MODEL_SINGLE_PROCESS;
} else if (model == "process-per-site-instance") {
g_process_model = PROCESS_MODEL_PROCESS_PER_SITE_INSTANCE;
} else if (model == "process-per-view") {
g_process_model = PROCESS_MODEL_PROCESS_PER_VIEW;
} else if (model == "process-per-site") {
g_process_model = PROCESS_MODEL_PROCESS_PER_SITE;
} else if (model == "site-per-process") {
g_process_model = PROCESS_MODEL_SITE_PER_PROCESS;
} else {
LOG(WARNING) << "Invalid process mode: " << model;
}
}
}
return g_process_model;
}
BrowserProcessMain* BrowserProcessMain::GetInstance() {
static BrowserProcessMainImpl g_instance;
return &g_instance;
}
} // namespace oxide
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 Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && (end - (char *)defs > i); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1 || (char *)UINTPTR_MAX - vstart < vdaux) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: void bdrv_register(BlockDriver *bdrv)
{
/* Block drivers without coroutine functions need emulation */
if (!bdrv->bdrv_co_readv) {
bdrv->bdrv_co_readv = bdrv_co_readv_em;
bdrv->bdrv_co_writev = bdrv_co_writev_em;
/* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
* the block driver lacks aio we need to emulate that too.
*/
if (!bdrv->bdrv_aio_readv) {
/* add AIO emulation layer */
bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
}
}
QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
}
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: QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag)
{
QString ret;
QString tag;
int i = data->openHtmlTags.count() - 1;
for ( ; i >= 0 ; --i)
{
tag = data->openHtmlTags.at(i);
ret += QLatin1String("</") + tag + QLatin1Char('>');
if (tag == _tag)
{
data->openHtmlTags.removeAt(i);
break;
}
}
ret += openTags(data, i);
return ret;
}
CWE ID:
Output: | 1 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 16