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 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
UWORD16 u2_height;
UWORD16 u2_width;
if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND;
}
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u2_width = impeg2d_bit_stream_get(ps_stream,12);
u2_height = impeg2d_bit_stream_get(ps_stream,12);
if ((u2_width != ps_dec->u2_horizontal_size)
|| (u2_height != ps_dec->u2_vertical_size))
{
if (0 == ps_dec->u2_header_done)
{
/* This is the first time we are reading the resolution */
ps_dec->u2_horizontal_size = u2_width;
ps_dec->u2_vertical_size = u2_height;
if (0 == ps_dec->u4_frm_buf_stride)
{
ps_dec->u4_frm_buf_stride = (UWORD32) (u2_width);
}
}
else
{
if((u2_width > ps_dec->u2_create_max_width)
|| (u2_height > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = u2_height;
ps_dec->u2_reinit_max_width = u2_width;
return e_error;
}
else
{
/* The resolution has changed */
return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED;
}
}
}
if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width)
|| (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
return SET_IVD_FATAL_ERROR(e_error);
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* aspect_ratio_info (4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Frame rate code(4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4);
if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE)
{
return IMPEG2D_FRM_HDR_DECODE_ERR;
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* bit_rate_value (18 bits) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,18);
GET_MARKER_BIT(ps_dec,ps_stream);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,11);
/*------------------------------------------------------------------------*/
/* Quantization matrix for the intra blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
/*------------------------------------------------------------------------*/
/* Quantization matrix for the inter blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void efx_fini_napi(struct efx_nic *efx)
{
struct efx_channel *channel;
efx_for_each_channel(channel, efx)
efx_fini_napi_channel(channel);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
struct address_space *mapping = inode->i_mapping;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Write out all dirty pages to avoid race conditions
* Then release them.
*/
if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
ret = filemap_write_and_wait_range(mapping, offset,
offset + len - 1);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
mutex_lock(&inode->i_mutex);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
offset + len > i_size_read(inode)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags, mode);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/* Now release the pages and zero block aligned part of pages*/
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags, mode);
if (ret)
goto out_dio;
}
if (!partial_begin && !partial_end)
goto out_dio;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_dio;
}
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
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: jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)
{
jas_matrix_t *y;
int i;
int j;
y = jas_matrix_create(x->numrows_, x->numcols_);
for (i = 0; i < x->numrows_; ++i) {
for (j = 0; j < x->numcols_; ++j) {
*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
}
}
return y;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: bool FileEnumerator::IsDirectory(const FindInfo& info) {
return S_ISDIR(info.stat.st_mode);
}
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: devzvol_readdir(struct vnode *dvp, struct uio *uiop, struct cred *cred,
int *eofp, caller_context_t *ct_unused, int flags_unused)
{
struct sdev_node *sdvp = VTOSDEV(dvp);
char *ptr;
sdcmn_err13(("zv readdir of '%s' %s'", sdvp->sdev_path,
sdvp->sdev_name));
if (strcmp(sdvp->sdev_path, ZVOL_DIR) == 0) {
struct vnode *vp;
rw_exit(&sdvp->sdev_contents);
(void) devname_lookup_func(sdvp, "dsk", &vp, cred,
devzvol_create_dir, SDEV_VATTR);
VN_RELE(vp);
(void) devname_lookup_func(sdvp, "rdsk", &vp, cred,
devzvol_create_dir, SDEV_VATTR);
VN_RELE(vp);
rw_enter(&sdvp->sdev_contents, RW_READER);
return (devname_readdir_func(dvp, uiop, cred, eofp, 0));
}
if (uiop->uio_offset == 0)
devzvol_prunedir(sdvp);
ptr = sdvp->sdev_path + strlen(ZVOL_DIR);
if ((strcmp(ptr, "/dsk") == 0) || (strcmp(ptr, "/rdsk") == 0)) {
rw_exit(&sdvp->sdev_contents);
devzvol_create_pool_dirs(dvp);
rw_enter(&sdvp->sdev_contents, RW_READER);
return (devname_readdir_func(dvp, uiop, cred, eofp, 0));
}
ptr = strchr(ptr + 1, '/') + 1;
rw_exit(&sdvp->sdev_contents);
sdev_iter_datasets(dvp, ZFS_IOC_DATASET_LIST_NEXT, ptr);
rw_enter(&sdvp->sdev_contents, RW_READER);
return (devname_readdir_func(dvp, uiop, cred, eofp, 0));
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: UserCloudPolicyManagerFactoryChromeOS::CreateManagerForProfile(
Profile* profile,
bool force_immediate_load,
scoped_refptr<base::SequencedTaskRunner> background_task_runner) {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (chromeos::ProfileHelper::IsSigninProfile(profile))
return scoped_ptr<UserCloudPolicyManagerChromeOS>();
chromeos::User* user =
chromeos::ProfileHelper::Get()->GetUserByProfile(profile);
CHECK(user);
const std::string& username = user->email();
if (user->GetType() != user_manager::USER_TYPE_REGULAR ||
BrowserPolicyConnector::IsNonEnterpriseUser(username)) {
return scoped_ptr<UserCloudPolicyManagerChromeOS>();
}
policy::BrowserPolicyConnectorChromeOS* connector =
g_browser_process->platform_part()->browser_policy_connector_chromeos();
UserAffiliation affiliation = connector->GetUserAffiliation(username);
const bool is_managed_user = affiliation == USER_AFFILIATION_MANAGED;
const bool is_browser_restart =
command_line->HasSwitch(chromeos::switches::kLoginUser);
const bool wait_for_initial_policy = is_managed_user && !is_browser_restart;
DeviceManagementService* device_management_service =
connector->device_management_service();
if (wait_for_initial_policy)
device_management_service->ScheduleInitialization(0);
base::FilePath profile_dir = profile->GetPath();
const base::FilePath legacy_dir = profile_dir.Append(kDeviceManagementDir);
const base::FilePath policy_cache_file = legacy_dir.Append(kPolicy);
const base::FilePath token_cache_file = legacy_dir.Append(kToken);
const base::FilePath component_policy_cache_dir =
profile_dir.Append(kPolicy).Append(kComponentsDir);
const base::FilePath external_data_dir =
profile_dir.Append(kPolicy).Append(kPolicyExternalDataDir);
base::FilePath policy_key_dir;
CHECK(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &policy_key_dir));
scoped_ptr<UserCloudPolicyStoreChromeOS> store(
new UserCloudPolicyStoreChromeOS(
chromeos::DBusThreadManager::Get()->GetCryptohomeClient(),
chromeos::DBusThreadManager::Get()->GetSessionManagerClient(),
background_task_runner,
username, policy_key_dir, token_cache_file, policy_cache_file));
scoped_refptr<base::SequencedTaskRunner> backend_task_runner =
content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
content::BrowserThread::GetBlockingPool()->GetSequenceToken());
scoped_refptr<base::SequencedTaskRunner> io_task_runner =
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::IO);
scoped_ptr<CloudExternalDataManager> external_data_manager(
new UserCloudExternalDataManager(base::Bind(&GetChromePolicyDetails),
backend_task_runner,
io_task_runner,
external_data_dir,
store.get()));
if (force_immediate_load)
store->LoadImmediately();
scoped_refptr<base::SequencedTaskRunner> file_task_runner =
content::BrowserThread::GetMessageLoopProxyForThread(
content::BrowserThread::FILE);
scoped_ptr<UserCloudPolicyManagerChromeOS> manager(
new UserCloudPolicyManagerChromeOS(
store.PassAs<CloudPolicyStore>(),
external_data_manager.Pass(),
component_policy_cache_dir,
wait_for_initial_policy,
base::TimeDelta::FromSeconds(kInitialPolicyFetchTimeoutSeconds),
base::MessageLoopProxy::current(),
file_task_runner,
io_task_runner));
bool wildcard_match = false;
if (connector->IsEnterpriseManaged() &&
chromeos::LoginUtils::IsWhitelisted(username, &wildcard_match) &&
wildcard_match &&
!connector->IsNonEnterpriseUser(username)) {
manager->EnableWildcardLoginCheck(username);
}
manager->Init(
SchemaRegistryServiceFactory::GetForContext(profile)->registry());
manager->Connect(g_browser_process->local_state(),
device_management_service,
g_browser_process->system_request_context(),
affiliation);
DCHECK(managers_.find(profile) == managers_.end());
managers_[profile] = manager.get();
return manager.Pass();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static size_t curl_read(char *data, size_t size, size_t nmemb, void *ctx)
{
php_curl *ch = (php_curl *)ctx;
php_curl_read *t = ch->handlers->read;
int length = 0;
switch (t->method) {
case PHP_CURL_DIRECT:
if (t->fp) {
length = fread(data, size, nmemb, t->fp);
}
break;
case PHP_CURL_USER: {
zval argv[3];
zval retval;
int error;
zend_fcall_info fci;
ZVAL_RES(&argv[0], ch->res);
Z_ADDREF(argv[0]);
if (t->res) {
ZVAL_RES(&argv[1], t->res);
Z_ADDREF(argv[1]);
} else {
ZVAL_NULL(&argv[1]);
}
ZVAL_LONG(&argv[2], (int)size * nmemb);
fci.size = sizeof(fci);
fci.function_table = EG(function_table);
ZVAL_COPY_VALUE(&fci.function_name, &t->func_name);
fci.object = NULL;
fci.retval = &retval;
fci.param_count = 3;
fci.params = argv;
fci.no_separation = 0;
fci.symbol_table = NULL;
ch->in_callback = 1;
error = zend_call_function(&fci, &t->fci_cache);
ch->in_callback = 0;
if (error == FAILURE) {
php_error_docref(NULL, E_WARNING, "Cannot call the CURLOPT_READFUNCTION");
#if LIBCURL_VERSION_NUM >= 0x070c01 /* 7.12.1 */
length = CURL_READFUNC_ABORT;
#endif
} else if (!Z_ISUNDEF(retval)) {
_php_curl_verify_handlers(ch, 1);
if (Z_TYPE(retval) == IS_STRING) {
length = MIN((int) (size * nmemb), Z_STRLEN(retval));
memcpy(data, Z_STRVAL(retval), length);
}
zval_ptr_dtor(&retval);
}
zval_ptr_dtor(&argv[0]);
zval_ptr_dtor(&argv[1]);
zval_ptr_dtor(&argv[2]);
break;
}
}
return length;
}
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 BrowserLauncherItemController::TabDetachedAt(TabContents* contents,
int index) {
launcher_controller()->UpdateAppState(
contents->web_contents(), ChromeLauncherController::APP_STATE_REMOVED);
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
{
ulonglong tmp;
if (jas_iccgetuint(in, 2, &tmp))
return -1;
*val = tmp;
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: int RenderBlock::lineCount(const RootInlineBox* stopRootInlineBox, bool* found) const
{
int count = 0;
if (style()->visibility() == VISIBLE) {
if (childrenInline())
for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox()) {
count++;
if (box == stopRootInlineBox) {
if (found)
*found = true;
break;
}
}
else
for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling())
if (shouldCheckLines(obj)) {
bool recursiveFound = false;
count += toRenderBlock(obj)->lineCount(stopRootInlineBox, &recursiveFound);
if (recursiveFound) {
if (found)
*found = true;
break;
}
}
}
return count;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CloudPolicyController::HandlePolicyResponse(
const em::DevicePolicyResponse& response) {
if (response.response_size() > 0) {
if (response.response_size() > 1) {
LOG(WARNING) << "More than one policy in the response of the device "
<< "management server, discarding.";
}
if (response.response(0).error_code() !=
DeviceManagementBackend::kErrorServicePolicyNotFound) {
cache_->SetPolicy(response.response(0));
SetState(STATE_POLICY_VALID);
} else {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchBadResponse,
kMetricPolicySize);
SetState(STATE_POLICY_UNAVAILABLE);
}
} else {
UMA_HISTOGRAM_ENUMERATION(kMetricPolicy, kMetricPolicyFetchBadResponse,
kMetricPolicySize);
}
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int search_old_relocation(struct reloc_struct_t *reloc_table, ut32 addr_to_patch, int n_reloc) {
int i;
for (i = 0; i < n_reloc; i++) {
if (addr_to_patch == reloc_table[i].data_offset) {
return i;
}
}
return -1;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool ShouldSupportIetfFormatQuicAltSvc(
const VariationParameters& quic_trial_params) {
return base::LowerCaseEqualsASCII(
GetVariationParam(quic_trial_params, "support_ietf_format_quic_altsvc"),
"true");
}
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: header_gets (SF_PRIVATE *psf, char *ptr, int bufsize)
{ int k ;
for (k = 0 ; k < bufsize - 1 ; k++)
{ if (psf->headindex < psf->headend)
{ ptr [k] = psf->header [psf->headindex] ;
psf->headindex ++ ;
}
else
{ psf->headend += psf_fread (psf->header + psf->headend, 1, 1, psf) ;
ptr [k] = psf->header [psf->headindex] ;
psf->headindex = psf->headend ;
} ;
if (ptr [k] == '\n')
break ;
} ;
ptr [k] = 0 ;
return k ;
} /* header_gets */
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int HttpStreamParser::DoReadHeadersComplete(int result) {
if (result == 0)
result = ERR_CONNECTION_CLOSED;
if (result < 0 && result != ERR_CONNECTION_CLOSED) {
io_state_ = STATE_DONE;
return result;
}
if (result == ERR_CONNECTION_CLOSED && read_buf_->offset() == 0 &&
connection_->is_reused()) {
io_state_ = STATE_DONE;
return result;
}
if (read_buf_->offset() == 0 && result != ERR_CONNECTION_CLOSED)
response_->response_time = base::Time::Now();
if (result == ERR_CONNECTION_CLOSED) {
io_state_ = STATE_DONE;
return ERR_EMPTY_RESPONSE;
} else {
int end_offset;
if (response_header_start_offset_ >= 0) {
io_state_ = STATE_READ_BODY_COMPLETE;
end_offset = read_buf_->offset();
} else {
io_state_ = STATE_BODY_PENDING;
end_offset = 0;
}
int rv = DoParseResponseHeaders(end_offset);
if (rv < 0)
return rv;
return result;
}
}
read_buf_->set_offset(read_buf_->offset() + result);
DCHECK_LE(read_buf_->offset(), read_buf_->capacity());
DCHECK_GE(result, 0);
int end_of_header_offset = ParseResponseHeaders();
if (end_of_header_offset < -1)
return end_of_header_offset;
if (end_of_header_offset == -1) {
io_state_ = STATE_READ_HEADERS;
if (read_buf_->offset() - read_buf_unused_offset_ >= kMaxHeaderBufSize) {
io_state_ = STATE_DONE;
return ERR_RESPONSE_HEADERS_TOO_BIG;
}
} else {
read_buf_unused_offset_ = end_of_header_offset;
if (response_->headers->response_code() / 100 == 1) {
io_state_ = STATE_REQUEST_SENT;
response_header_start_offset_ = -1;
} else {
io_state_ = STATE_BODY_PENDING;
CalculateResponseBodySize();
if (response_body_length_ == 0) {
io_state_ = STATE_DONE;
int extra_bytes = read_buf_->offset() - read_buf_unused_offset_;
if (extra_bytes) {
CHECK_GT(extra_bytes, 0);
memmove(read_buf_->StartOfBuffer(),
read_buf_->StartOfBuffer() + read_buf_unused_offset_,
extra_bytes);
}
read_buf_->SetCapacity(extra_bytes);
read_buf_unused_offset_ = 0;
return OK;
}
}
}
return result;
}
CWE ID:
Target: 1
Example 2:
Code: error::Error GLES2DecoderImpl::HandleStencilThenCoverStrokePathCHROMIUM(
uint32_t immediate_data_size,
const volatile void* cmd_data) {
static const char kFunctionName[] = "glStencilThenCoverStrokePathCHROMIUM";
const volatile gles2::cmds::StencilThenCoverStrokePathCHROMIUM& c =
*static_cast<
const volatile gles2::cmds::StencilThenCoverStrokePathCHROMIUM*>(
cmd_data);
if (!features().chromium_path_rendering)
return error::kUnknownCommand;
PathCommandValidatorContext v(this, kFunctionName);
GLenum cover_mode = GL_BOUNDING_BOX_CHROMIUM;
if (!v.GetCoverMode(c, &cover_mode))
return v.error();
GLuint service_id = 0;
if (!path_manager()->GetPath(static_cast<GLuint>(c.path), &service_id))
return error::kNoError;
GLint reference = static_cast<GLint>(c.reference);
GLuint mask = static_cast<GLuint>(c.mask);
if (!CheckBoundDrawFramebufferValid(kFunctionName))
return error::kNoError;
ApplyDirtyState();
api()->glStencilThenCoverStrokePathNVFn(service_id, reference, mask,
cover_mode);
return error::kNoError;
}
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 ReduceImageColors(const Image *image,CubeInfo *cube_info)
{
#define ReduceImageTag "Reduce/Image"
MagickBooleanType
proceed;
MagickOffsetType
offset;
size_t
span;
cube_info->next_threshold=0.0;
if (cube_info->colors > cube_info->maximum_colors)
{
MagickRealType
*quantize_error;
/*
Enable rapid reduction of the number of unique colors.
*/
quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
sizeof(*quantize_error));
if (quantize_error != (MagickRealType *) NULL)
{
(void) QuantizeErrorFlatten(cube_info,cube_info->root,0,
quantize_error);
qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType),
MagickRealTypeCompare);
if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100))
cube_info->next_threshold=quantize_error[cube_info->nodes-110*
(cube_info->maximum_colors+1)/100];
quantize_error=(MagickRealType *) RelinquishMagickMemory(
quantize_error);
}
}
for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
{
cube_info->pruning_threshold=cube_info->next_threshold;
cube_info->next_threshold=cube_info->root->quantize_error-1;
cube_info->colors=0;
Reduce(cube_info,cube_info->root);
offset=(MagickOffsetType) span-cube_info->colors;
proceed=SetImageProgress(image,ReduceImageTag,offset,span-
cube_info->maximum_colors+1);
if (proceed == MagickFalse)
break;
}
}
CWE ID: CWE-772
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AppCacheDatabase::UpgradeSchema() {
return DeleteExistingAndCreateNewDatabase();
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: cmsBool AddMLUBlock(cmsMLU* mlu, cmsUInt32Number size, const wchar_t *Block,
cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode)
{
cmsUInt32Number Offset;
cmsUInt8Number* Ptr;
if (mlu == NULL) return FALSE;
if (mlu ->UsedEntries >= mlu ->AllocatedEntries) {
if (!GrowMLUtable(mlu)) return FALSE;
}
if (SearchMLUEntry(mlu, LanguageCode, CountryCode) >= 0) return FALSE; // Only one is allowed!
while ((mlu ->PoolSize - mlu ->PoolUsed) < size) {
if (!GrowMLUpool(mlu)) return FALSE;
}
Offset = mlu ->PoolUsed;
Ptr = (cmsUInt8Number*) mlu ->MemPool;
if (Ptr == NULL) return FALSE;
memmove(Ptr + Offset, Block, size);
mlu ->PoolUsed += size;
mlu ->Entries[mlu ->UsedEntries].StrW = Offset;
mlu ->Entries[mlu ->UsedEntries].Len = size;
mlu ->Entries[mlu ->UsedEntries].Country = CountryCode;
mlu ->Entries[mlu ->UsedEntries].Language = LanguageCode;
mlu ->UsedEntries++;
return TRUE;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int handle_cr(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification, val;
int cr;
int reg;
int err;
exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
cr = exit_qualification & 15;
reg = (exit_qualification >> 8) & 15;
switch ((exit_qualification >> 4) & 3) {
case 0: /* mov to cr */
val = kvm_register_readl(vcpu, reg);
trace_kvm_cr_write(cr, val);
switch (cr) {
case 0:
err = handle_set_cr0(vcpu, val);
kvm_complete_insn_gp(vcpu, err);
return 1;
case 3:
err = kvm_set_cr3(vcpu, val);
kvm_complete_insn_gp(vcpu, err);
return 1;
case 4:
err = handle_set_cr4(vcpu, val);
kvm_complete_insn_gp(vcpu, err);
return 1;
case 8: {
u8 cr8_prev = kvm_get_cr8(vcpu);
u8 cr8 = (u8)val;
err = kvm_set_cr8(vcpu, cr8);
kvm_complete_insn_gp(vcpu, err);
if (lapic_in_kernel(vcpu))
return 1;
if (cr8_prev <= cr8)
return 1;
vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
return 0;
}
}
break;
case 2: /* clts */
handle_clts(vcpu);
trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
skip_emulated_instruction(vcpu);
vmx_fpu_activate(vcpu);
return 1;
case 1: /*mov from cr*/
switch (cr) {
case 3:
val = kvm_read_cr3(vcpu);
kvm_register_write(vcpu, reg, val);
trace_kvm_cr_read(cr, val);
skip_emulated_instruction(vcpu);
return 1;
case 8:
val = kvm_get_cr8(vcpu);
kvm_register_write(vcpu, reg, val);
trace_kvm_cr_read(cr, val);
skip_emulated_instruction(vcpu);
return 1;
}
break;
case 3: /* lmsw */
val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
kvm_lmsw(vcpu, val);
skip_emulated_instruction(vcpu);
return 1;
default:
break;
}
vcpu->run->exit_reason = 0;
vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
(int)(exit_qualification >> 4) & 3, cr);
return 0;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: gss_inquire_context(
OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
gss_union_ctx_id_t ctx;
gss_mechanism mech;
OM_uint32 status, temp_minor;
gss_OID actual_mech;
gss_name_t localTargName = NULL, localSourceName = NULL;
status = val_inq_ctx_args(minor_status,
context_handle,
src_name, targ_name,
lifetime_rec,
mech_type, ctx_flags,
locally_initiated, opened);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (!mech || !mech->gss_inquire_context || !mech->gss_display_name ||
!mech->gss_release_name) {
return (GSS_S_UNAVAILABLE);
}
status = mech->gss_inquire_context(
minor_status,
ctx->internal_ctx_id,
(src_name ? &localSourceName : NULL),
(targ_name ? &localTargName : NULL),
lifetime_rec,
&actual_mech,
ctx_flags,
locally_initiated,
opened);
if (status != GSS_S_COMPLETE) {
map_error(minor_status, mech);
return status;
}
/* need to convert names */
if (src_name) {
if (localSourceName) {
status = gssint_convert_name_to_union_name(minor_status, mech,
localSourceName, src_name);
if (status != GSS_S_COMPLETE) {
if (localTargName)
mech->gss_release_name(&temp_minor, &localTargName);
return (status);
}
} else {
*src_name = GSS_C_NO_NAME;
}
}
if (targ_name) {
if (localTargName) {
status = gssint_convert_name_to_union_name(minor_status, mech,
localTargName, targ_name);
if (status != GSS_S_COMPLETE) {
if (src_name)
(void) gss_release_name(&temp_minor, src_name);
return (status);
}
}
else {
*targ_name = GSS_C_NO_NAME;
}
}
if (mech_type)
*mech_type = gssint_get_public_oid(actual_mech);
return(GSS_S_COMPLETE);
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: PHP_RSHUTDOWN_FUNCTION(date)
{
if (DATEG(timezone)) {
efree(DATEG(timezone));
}
DATEG(timezone) = NULL;
if(DATEG(tzcache)) {
zend_hash_destroy(DATEG(tzcache));
FREE_HASHTABLE(DATEG(tzcache));
DATEG(tzcache) = NULL;
}
if (DATEG(last_errors)) {
timelib_error_container_dtor(DATEG(last_errors));
DATEG(last_errors) = NULL;
}
return SUCCESS;
}
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: gss_get_mic (minor_status,
context_handle,
qop_req,
message_buffer,
msg_token)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
gss_qop_t qop_req;
gss_buffer_t message_buffer;
gss_buffer_t msg_token;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_get_mic_args(minor_status, context_handle,
qop_req, message_buffer, msg_token);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_get_mic) {
status = mech->gss_get_mic(
minor_status,
ctx->internal_ctx_id,
qop_req,
message_buffer,
msg_token);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
return (GSS_S_BAD_MECH);
}
CWE ID: CWE-415
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
: host_id_(host_id),
gpu_process_(base::kNullProcessHandle),
in_process_(false),
software_rendering_(false),
kind_(kind),
process_launched_(false) {
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) ||
CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU))
in_process_ = true;
DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
g_gpu_process_hosts[kind] = this;
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
process_.reset(
new BrowserChildProcessHostImpl(content::PROCESS_TYPE_GPU, this));
}
CWE ID:
Target: 1
Example 2:
Code: DnsPacket *dns_packet_ref(DnsPacket *p) {
if (!p)
return NULL;
assert(!p->on_stack);
assert(p->n_ref > 0);
p->n_ref++;
return p;
}
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 OPJ_BOOL bmp_read_rle8_data(FILE* IN, OPJ_UINT8* pData,
OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
OPJ_UINT32 x, y;
OPJ_UINT8 *pix;
const OPJ_UINT8 *beyond;
beyond = pData + stride * height;
pix = pData;
x = y = 0U;
while (y < height) {
int c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
if (c) {
int j, c1_int;
OPJ_UINT8 c1;
c1_int = getc(IN);
if (c1_int == EOF) {
return OPJ_FALSE;
}
c1 = (OPJ_UINT8)c1_int;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
*pix = c1;
}
} else {
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
if (c == 0x00) { /* EOL */
x = 0;
++y;
pix = pData + y * stride + x;
} else if (c == 0x01) { /* EOP */
break;
} else if (c == 0x02) { /* MOVE by dxdy */
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
x += (OPJ_UINT32)c;
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
y += (OPJ_UINT32)c;
pix = pData + y * stride + x;
} else { /* 03 .. 255 */
int j;
for (j = 0; (j < c) && (x < width) &&
((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
int c1_int;
OPJ_UINT8 c1;
c1_int = getc(IN);
if (c1_int == EOF) {
return OPJ_FALSE;
}
c1 = (OPJ_UINT8)c1_int;
*pix = c1;
}
if ((OPJ_UINT32)c & 1U) { /* skip padding byte */
c = getc(IN);
if (c == EOF) {
return OPJ_FALSE;
}
}
}
}
}/* while() */
return OPJ_TRUE;
}
CWE ID: CWE-400
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: CStarter::removeDeferredJobs() {
bool ret = true;
if ( this->deferral_tid == -1 ) {
return ( ret );
}
m_deferred_job_update = true;
if ( daemonCore->Cancel_Timer( this->deferral_tid ) >= 0 ) {
dprintf( D_FULLDEBUG, "Cancelled time deferred execution for "
"Job %d.%d\n",
this->jic->jobCluster(),
this->jic->jobProc() );
this->deferral_tid = -1;
} else {
MyString error = "Failed to cancel deferred execution timer for Job ";
error += this->jic->jobCluster();
error += ".";
error += this->jic->jobProc();
EXCEPT( error.Value() );
ret = false;
}
return ( ret );
}
CWE ID: CWE-134
Target: 1
Example 2:
Code: void SerializedFlashMenu::WriteToMessage(IPC::Message* m) const {
WriteMenu(m, pp_menu_);
}
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 SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
struct CERTDistNamesStr *caNames,
struct CERTCertificateStr **pRetCert,
struct SECKEYPrivateKeyStr **pRetKey)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
struct Curl_easy *data = connssl->data;
const char *nickname = connssl->client_nickname;
if(connssl->obj_clicert) {
/* use the cert/key provided by PEM reader */
static const char pem_slotname[] = "PEM Token #1";
SECItem cert_der = { 0, NULL, 0 };
void *proto_win = SSL_RevealPinArg(sock);
struct CERTCertificateStr *cert;
struct SECKEYPrivateKeyStr *key;
PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
if(NULL == slot) {
failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
return SECFailure;
}
if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
&cert_der) != SECSuccess) {
failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
PK11_FreeSlot(slot);
return SECFailure;
}
cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
SECITEM_FreeItem(&cert_der, PR_FALSE);
if(NULL == cert) {
failf(data, "NSS: client certificate from file not found");
PK11_FreeSlot(slot);
return SECFailure;
}
key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
PK11_FreeSlot(slot);
if(NULL == key) {
failf(data, "NSS: private key from file not found");
CERT_DestroyCertificate(cert);
return SECFailure;
}
infof(data, "NSS: client certificate from file\n");
display_cert_info(data, cert);
*pRetCert = cert;
*pRetKey = key;
return SECSuccess;
}
/* use the default NSS hook */
if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
pRetCert, pRetKey)
|| NULL == *pRetCert) {
if(NULL == nickname)
failf(data, "NSS: client certificate not found (nickname not "
"specified)");
else
failf(data, "NSS: client certificate not found: %s", nickname);
return SECFailure;
}
/* get certificate nickname if any */
nickname = (*pRetCert)->nickname;
if(NULL == nickname)
nickname = "[unknown]";
if(NULL == *pRetKey) {
failf(data, "NSS: private key not found for certificate: %s", nickname);
return SECFailure;
}
infof(data, "NSS: using client certificate: %s\n", nickname);
display_cert_info(data, *pRetCert);
return SECSuccess;
}
CWE ID: CWE-287
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 long vhost_net_set_backend(struct vhost_net *n, unsigned index, int fd)
{
struct socket *sock, *oldsock;
struct vhost_virtqueue *vq;
struct vhost_net_virtqueue *nvq;
struct vhost_net_ubuf_ref *ubufs, *oldubufs = NULL;
int r;
mutex_lock(&n->dev.mutex);
r = vhost_dev_check_owner(&n->dev);
if (r)
goto err;
if (index >= VHOST_NET_VQ_MAX) {
r = -ENOBUFS;
goto err;
}
vq = &n->vqs[index].vq;
nvq = &n->vqs[index];
mutex_lock(&vq->mutex);
/* Verify that ring has been setup correctly. */
if (!vhost_vq_access_ok(vq)) {
r = -EFAULT;
goto err_vq;
}
sock = get_socket(fd);
if (IS_ERR(sock)) {
r = PTR_ERR(sock);
goto err_vq;
}
/* start polling new socket */
oldsock = rcu_dereference_protected(vq->private_data,
lockdep_is_held(&vq->mutex));
if (sock != oldsock) {
ubufs = vhost_net_ubuf_alloc(vq,
sock && vhost_sock_zcopy(sock));
if (IS_ERR(ubufs)) {
r = PTR_ERR(ubufs);
goto err_ubufs;
}
vhost_net_disable_vq(n, vq);
rcu_assign_pointer(vq->private_data, sock);
r = vhost_init_used(vq);
if (r)
goto err_used;
r = vhost_net_enable_vq(n, vq);
if (r)
goto err_used;
oldubufs = nvq->ubufs;
nvq->ubufs = ubufs;
n->tx_packets = 0;
n->tx_zcopy_err = 0;
n->tx_flush = false;
}
mutex_unlock(&vq->mutex);
if (oldubufs) {
vhost_net_ubuf_put_and_wait(oldubufs);
mutex_lock(&vq->mutex);
vhost_zerocopy_signal_used(n, vq);
mutex_unlock(&vq->mutex);
}
if (oldsock) {
vhost_net_flush_vq(n, index);
fput(oldsock->file);
}
mutex_unlock(&n->dev.mutex);
return 0;
err_used:
rcu_assign_pointer(vq->private_data, oldsock);
vhost_net_enable_vq(n, vq);
if (ubufs)
vhost_net_ubuf_put_and_wait(ubufs);
err_ubufs:
fput(sock->file);
err_vq:
mutex_unlock(&vq->mutex);
err:
mutex_unlock(&n->dev.mutex);
return r;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: on_error(void *user_data, Evas_Object *webview, void *event_info)
{
Eina_Strbuf* buffer;
const Ewk_Error *error = (const Ewk_Error *)event_info;
/* This is a cancellation, do not display the error page */
if (ewk_error_cancellation_get(error))
return;
buffer = eina_strbuf_new();
eina_strbuf_append_printf(buffer, "<html><body><div style=\"color:#ff0000\">ERROR!</div><br><div>Code: %d<br>Description: %s<br>URL: %s</div></body</html>",
ewk_error_code_get(error), ewk_error_description_get(error), ewk_error_url_get(error));
ewk_view_html_string_load(webview, eina_strbuf_string_get(buffer), 0, ewk_error_url_get(error));
eina_strbuf_free(buffer);
}
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 entity_table_opt determine_entity_table(int all, int doctype)
{
entity_table_opt retval = {NULL};
assert(!(doctype == ENT_HTML_DOC_XML1 && all));
if (all) {
retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ?
entity_ms_table_html5 : entity_ms_table_html4;
} else {
retval.table = (doctype == ENT_HTML_DOC_HTML401) ?
stage3_table_be_noapos_00000 : stage3_table_be_apos_00000;
}
return retval;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ContextualSearchFieldTrial::ContextualSearchFieldTrial()
: is_resolver_url_prefix_cached_(false),
is_surrounding_size_cached_(false),
surrounding_size_(0),
is_icing_surrounding_size_cached_(false),
icing_surrounding_size_(0),
is_send_base_page_url_disabled_cached_(false),
is_send_base_page_url_disabled_(false),
is_decode_mentions_disabled_cached_(false),
is_decode_mentions_disabled_(false),
is_now_on_tap_bar_integration_enabled_cached_(false),
is_now_on_tap_bar_integration_enabled_(false) {}
CWE ID:
Target: 1
Example 2:
Code: static void uio_free_minor(struct uio_device *idev)
{
mutex_lock(&minor_lock);
idr_remove(&uio_idr, idev->minor);
mutex_unlock(&minor_lock);
}
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: chunk_new_with_alloc_size(size_t alloc)
{
chunk_t *ch;
ch = tor_malloc(alloc);
ch->next = NULL;
ch->datalen = 0;
#ifdef DEBUG_CHUNK_ALLOC
ch->DBG_alloc = alloc;
#endif
ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
total_bytes_allocated_in_chunks += alloc;
ch->data = &ch->mem[0];
return ch;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void cJSON_ReplaceItemInObject( cJSON *object, const char *string, cJSON *newitem )
{
int i = 0;
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) ) {
++i;
c = c->next;
}
if ( c ) {
newitem->string = cJSON_strdup( string );
cJSON_ReplaceItemInArray( object, i, newitem );
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void DrawPath(GraphicsContext& context,
DisplayItemClient& client,
DisplayItem::Type type,
unsigned count) {
if (DrawingRecorder::UseCachedDrawingIfPossible(context, client, type))
return;
DrawingRecorder recorder(context, client, type);
SkPath path;
path.moveTo(0, 0);
path.lineTo(0, 100);
path.lineTo(50, 50);
path.lineTo(100, 100);
path.lineTo(100, 0);
path.close();
PaintFlags flags;
flags.setAntiAlias(true);
for (unsigned i = 0; i < count; i++)
context.DrawPath(path, flags);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret, countersize;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size) {
BUGPRINT("Wrong len argument\n");
return -EINVAL;
}
if (tmp.entries_size == 0) {
BUGPRINT("Entries_size never zero\n");
return -EINVAL;
}
/* overflow check */
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
BUGPRINT("Couldn't copy entries from userspace\n");
ret = -EFAULT;
goto free_entries;
}
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: Mat_VarReadNextInfo4(mat_t *mat)
{
int M,O,data_type,class_type;
mat_int32_t tmp;
long nBytes;
size_t readresult;
matvar_t *matvar = NULL;
union {
mat_uint32_t u;
mat_uint8_t c[4];
} endian;
if ( mat == NULL || mat->fp == NULL )
return NULL;
else if ( NULL == (matvar = Mat_VarCalloc()) )
return NULL;
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
endian.u = 0x01020304;
/* See if MOPT may need byteswapping */
if ( tmp < 0 || tmp > 4052 ) {
if ( Mat_int32Swap(&tmp) > 4052 ) {
Mat_VarFree(matvar);
return NULL;
}
}
M = (int)floor(tmp / 1000.0);
switch ( M ) {
case 0:
/* IEEE little endian */
mat->byteswap = endian.c[0] != 4;
break;
case 1:
/* IEEE big endian */
mat->byteswap = endian.c[0] != 1;
break;
default:
/* VAX, Cray, or bogus */
Mat_VarFree(matvar);
return NULL;
}
tmp -= M*1000;
O = (int)floor(tmp / 100.0);
/* O must be zero */
if ( 0 != O ) {
Mat_VarFree(matvar);
return NULL;
}
tmp -= O*100;
data_type = (int)floor(tmp / 10.0);
/* Convert the V4 data type */
switch ( data_type ) {
case 0:
matvar->data_type = MAT_T_DOUBLE;
break;
case 1:
matvar->data_type = MAT_T_SINGLE;
break;
case 2:
matvar->data_type = MAT_T_INT32;
break;
case 3:
matvar->data_type = MAT_T_INT16;
break;
case 4:
matvar->data_type = MAT_T_UINT16;
break;
case 5:
matvar->data_type = MAT_T_UINT8;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
tmp -= data_type*10;
class_type = (int)floor(tmp / 1.0);
switch ( class_type ) {
case 0:
matvar->class_type = MAT_C_DOUBLE;
break;
case 1:
matvar->class_type = MAT_C_CHAR;
break;
case 2:
matvar->class_type = MAT_C_SPARSE;
break;
default:
Mat_VarFree(matvar);
return NULL;
}
matvar->rank = 2;
matvar->dims = (size_t*)calloc(2, sizeof(*matvar->dims));
if ( NULL == matvar->dims ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[0] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( mat->byteswap )
Mat_int32Swap(&tmp);
matvar->dims[1] = tmp;
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&(matvar->isComplex),sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( matvar->isComplex && MAT_C_CHAR == matvar->class_type ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(&tmp,sizeof(int),1,(FILE*)mat->fp);
if ( 1 != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
if ( mat->byteswap )
Mat_int32Swap(&tmp);
/* Check that the length of the variable name is at least 1 */
if ( tmp < 1 ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->name = (char*)malloc(tmp);
if ( NULL == matvar->name ) {
Mat_VarFree(matvar);
return NULL;
}
readresult = fread(matvar->name,1,tmp,(FILE*)mat->fp);
if ( tmp != readresult ) {
Mat_VarFree(matvar);
return NULL;
}
matvar->internal->datapos = ftell((FILE*)mat->fp);
if ( matvar->internal->datapos == -1L ) {
Mat_VarFree(matvar);
Mat_Critical("Couldn't determine file position");
return NULL;
}
{
int err;
size_t tmp2 = Mat_SizeOf(matvar->data_type);
if ( matvar->isComplex )
tmp2 *= 2;
err = SafeMulDims(matvar, &tmp2);
if ( err ) {
Mat_VarFree(matvar);
Mat_Critical("Integer multiplication overflow");
return NULL;
}
nBytes = (long)tmp2;
}
(void)fseek((FILE*)mat->fp,nBytes,SEEK_CUR);
return matvar;
}
CWE ID:
Target: 1
Example 2:
Code: static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile)
{
size_t
length;
ssize_t
count;
unsigned char
*p;
unsigned short
id;
length=GetStringInfoLength(profile);
p=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadProfileByte(&p,&length) != 0x38)
continue;
if (ReadProfileByte(&p,&length) != 0x42)
continue;
if (ReadProfileByte(&p,&length) != 0x49)
continue;
if (ReadProfileByte(&p,&length) != 0x4D)
continue;
if (length < 7)
return(MagickFalse);
id=ReadProfileMSBShort(&p,&length);
count=(ssize_t) ReadProfileByte(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
p+=count;
if ((*p & 0x01) == 0)
(void) ReadProfileByte(&p,&length);
count=(ssize_t) ReadProfileMSBLong(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
if ((id == 0x3ED) && (count == 16))
{
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian, (unsigned int) (image->resolution.x*2.54*
65536.0),p);
else
WriteProfileLong(MSBEndian, (unsigned int) (image->resolution.x*
65536.0),p);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4);
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian, (unsigned int) (image->resolution.y*2.54*
65536.0),p+8);
else
WriteProfileLong(MSBEndian, (unsigned int) (image->resolution.y*
65536.0),p+8);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12);
}
p+=count;
length-=count;
}
return(MagickTrue);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct mobj *alloc_ta_mem(size_t size)
{
#ifdef CFG_PAGED_USER_TA
return mobj_paged_alloc(size);
#else
struct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr);
if (mobj)
memset(mobj_get_va(mobj, 0), 0, size);
return mobj;
#endif
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ipt_do_table(struct sk_buff *skb,
const struct nf_hook_state *state,
struct xt_table *table)
{
unsigned int hook = state->hook;
static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long))));
const struct iphdr *ip;
/* Initializing verdict to NF_DROP keeps gcc happy. */
unsigned int verdict = NF_DROP;
const char *indev, *outdev;
const void *table_base;
struct ipt_entry *e, **jumpstack;
unsigned int stackidx, cpu;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
/* Initialization */
stackidx = 0;
ip = ip_hdr(skb);
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
/* We handle fragments by dealing with the first fragment as
* if it was a normal packet. All other fragments are treated
* normally, except that they will NEVER match rules that ask
* things we don't know, ie. tcp syn flag or ports). If the
* rule is also a fragment-specific rule, non-fragments won't
* match it. */
acpar.fragoff = ntohs(ip->frag_off) & IP_OFFSET;
acpar.thoff = ip_hdrlen(skb);
acpar.hotdrop = false;
acpar.state = state;
WARN_ON(!(table->valid_hooks & (1 << hook)));
local_bh_disable();
addend = xt_write_recseq_begin();
private = READ_ONCE(table->private); /* Address dependency. */
cpu = smp_processor_id();
table_base = private->entries;
jumpstack = (struct ipt_entry **)private->jumpstack[cpu];
/* Switch to alternate jumpstack if we're being invoked via TEE.
* TEE issues XT_CONTINUE verdict on original skb so we must not
* clobber the jumpstack.
*
* For recursion via REJECT or SYNPROXY the stack will be clobbered
* but it is no problem since absolute verdict is issued by these.
*/
if (static_key_false(&xt_tee_enabled))
jumpstack += private->stacksize * __this_cpu_read(nf_skb_duplicated);
e = get_entry(table_base, private->hook_entry[hook]);
do {
const struct xt_entry_target *t;
const struct xt_entry_match *ematch;
struct xt_counters *counter;
WARN_ON(!e);
if (!ip_packet_match(ip, indev, outdev,
&e->ip, acpar.fragoff)) {
no_match:
e = ipt_next_entry(e);
continue;
}
xt_ematch_foreach(ematch, e) {
acpar.match = ematch->u.kernel.match;
acpar.matchinfo = ematch->data;
if (!acpar.match->match(skb, &acpar))
goto no_match;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, skb->len, 1);
t = ipt_get_target(e);
WARN_ON(!t->u.kernel.target);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
/* The packet is traced: log it */
if (unlikely(skb->nf_trace))
trace_packet(state->net, skb, hook, state->in,
state->out, table->name, private, e);
#endif
/* Standard target? */
if (!t->u.kernel.target->target) {
int v;
v = ((struct xt_standard_target *)t)->verdict;
if (v < 0) {
/* Pop from stack? */
if (v != XT_RETURN) {
verdict = (unsigned int)(-v) - 1;
break;
}
if (stackidx == 0) {
e = get_entry(table_base,
private->underflow[hook]);
} else {
e = jumpstack[--stackidx];
e = ipt_next_entry(e);
}
continue;
}
if (table_base + v != ipt_next_entry(e) &&
!(e->ip.flags & IPT_F_GOTO))
jumpstack[stackidx++] = e;
e = get_entry(table_base, v);
continue;
}
acpar.target = t->u.kernel.target;
acpar.targinfo = t->data;
verdict = t->u.kernel.target->target(skb, &acpar);
if (verdict == XT_CONTINUE) {
/* Target might have changed stuff. */
ip = ip_hdr(skb);
e = ipt_next_entry(e);
} else {
/* Verdict */
break;
}
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else return verdict;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: ExtensionAppModelBuilderTest() {}
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 DownloadManagerImpl::OnUrlDownloadHandlerCreated(
download::UrlDownloadHandler::UniqueUrlDownloadHandlerPtr downloader) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (downloader)
url_download_handlers_.push_back(std::move(downloader));
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int tcos_select_file(sc_card_t *card,
const sc_path_t *in_path,
sc_file_t **file_out)
{
sc_context_t *ctx;
sc_apdu_t apdu;
sc_file_t *file=NULL;
u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
unsigned int i;
int r, pathlen;
assert(card != NULL && in_path != NULL);
ctx=card->ctx;
memcpy(path, in_path->value, in_path->len);
pathlen = in_path->len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04);
switch (in_path->type) {
case SC_PATH_TYPE_FILE_ID:
if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS;
/* fall through */
case SC_PATH_TYPE_FROM_CURRENT:
apdu.p1 = 9;
break;
case SC_PATH_TYPE_DF_NAME:
apdu.p1 = 4;
break;
case SC_PATH_TYPE_PATH:
apdu.p1 = 8;
if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2;
if (pathlen == 0) apdu.p1 = 0;
break;
case SC_PATH_TYPE_PARENT:
apdu.p1 = 3;
pathlen = 0;
break;
default:
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.lc = pathlen;
apdu.data = path;
apdu.datalen = pathlen;
if (file_out != NULL) {
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
} else {
apdu.resplen = 0;
apdu.le = 0;
apdu.p2 = 0x0C;
apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r);
if (apdu.resplen < 1 || apdu.resp[0] != 0x62){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
file = sc_file_new();
if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
*file_out = file;
file->path = *in_path;
for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){
int j, len=apdu.resp[i+1];
unsigned char type=apdu.resp[i], *d=apdu.resp+i+2;
switch (type) {
case 0x80:
case 0x81:
file->size=0;
for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j];
break;
case 0x82:
file->shareable = (d[0] & 0x40) ? 1 : 0;
file->ef_structure = d[0] & 7;
switch ((d[0]>>3) & 7) {
case 0: file->type = SC_FILE_TYPE_WORKING_EF; break;
case 7: file->type = SC_FILE_TYPE_DF; break;
default:
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]);
SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
break;
case 0x83:
file->id = (d[0]<<8) | d[1];
break;
case 0x84:
memcpy(file->name, d, len);
file->namelen = len;
break;
case 0x86:
sc_file_set_sec_attr(file, d, len);
break;
default:
if (len>0) sc_file_set_prop_attr(file, d, len);
}
}
file->magic = SC_FILE_MAGIC;
parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len);
return 0;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: void WebContentsImpl::DetachInterstitialPage(bool has_focus) {
bool interstitial_pausing_throbber =
ShowingInterstitialPage() && interstitial_page_->pause_throbber();
if (ShowingInterstitialPage())
interstitial_page_ = nullptr;
if (has_focus && GetRenderViewHost()->GetWidget()->GetView())
GetRenderViewHost()->GetWidget()->GetView()->Focus();
for (auto& observer : observers_)
observer.DidDetachInterstitialPage();
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(static_cast<RenderWidgetHostViewBase*>(
GetRenderManager()->current_frame_host()->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
GetRenderManager()->current_frame_host()->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
if (interstitial_pausing_throbber && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int http_close(URLContext *h)
{
int ret = 0;
HTTPContext *s = h->priv_data;
#if CONFIG_ZLIB
inflateEnd(&s->inflate_stream);
av_freep(&s->inflate_buffer);
#endif /* CONFIG_ZLIB */
if (!s->end_chunked_post)
/* Close the write direction by sending the end of chunked encoding. */
ret = http_shutdown(h, h->flags);
if (s->hd)
ffurl_closep(&s->hd);
av_dict_free(&s->chained_options);
return ret;
}
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: status_t IPCThreadState::executeCommand(int32_t cmd)
{
BBinder* obj;
RefBase::weakref_type* refs;
status_t result = NO_ERROR;
switch ((uint32_t)cmd) {
case BR_ERROR:
result = mIn.readInt32();
break;
case BR_OK:
break;
case BR_ACQUIRE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
ALOG_ASSERT(refs->refBase() == obj,
"BR_ACQUIRE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
obj->incStrong(mProcess.get());
IF_LOG_REMOTEREFS() {
LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);
obj->printRefs();
}
mOut.writeInt32(BC_ACQUIRE_DONE);
mOut.writePointer((uintptr_t)refs);
mOut.writePointer((uintptr_t)obj);
break;
case BR_RELEASE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
ALOG_ASSERT(refs->refBase() == obj,
"BR_RELEASE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
IF_LOG_REMOTEREFS() {
LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);
obj->printRefs();
}
mPendingStrongDerefs.push(obj);
break;
case BR_INCREFS:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
refs->incWeak(mProcess.get());
mOut.writeInt32(BC_INCREFS_DONE);
mOut.writePointer((uintptr_t)refs);
mOut.writePointer((uintptr_t)obj);
break;
case BR_DECREFS:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
mPendingWeakDerefs.push(refs);
break;
case BR_ATTEMPT_ACQUIRE:
refs = (RefBase::weakref_type*)mIn.readPointer();
obj = (BBinder*)mIn.readPointer();
{
const bool success = refs->attemptIncStrong(mProcess.get());
ALOG_ASSERT(success && refs->refBase() == obj,
"BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",
refs, obj, refs->refBase());
mOut.writeInt32(BC_ACQUIRE_RESULT);
mOut.writeInt32((int32_t)success);
}
break;
case BR_TRANSACTION:
{
binder_transaction_data tr;
result = mIn.read(&tr, sizeof(tr));
ALOG_ASSERT(result == NO_ERROR,
"Not enough command data for brTRANSACTION");
if (result != NO_ERROR) break;
Parcel buffer;
buffer.ipcSetDataReference(
reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),
tr.data_size,
reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),
tr.offsets_size/sizeof(binder_size_t), freeBuffer, this);
const pid_t origPid = mCallingPid;
const uid_t origUid = mCallingUid;
const int32_t origStrictModePolicy = mStrictModePolicy;
const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;
mCallingPid = tr.sender_pid;
mCallingUid = tr.sender_euid;
mLastTransactionBinderFlags = tr.flags;
int curPrio = getpriority(PRIO_PROCESS, mMyThreadId);
if (gDisableBackgroundScheduling) {
if (curPrio > ANDROID_PRIORITY_NORMAL) {
setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL);
}
} else {
if (curPrio >= ANDROID_PRIORITY_BACKGROUND) {
set_sched_policy(mMyThreadId, SP_BACKGROUND);
}
}
Parcel reply;
status_t error;
IF_LOG_TRANSACTIONS() {
TextOutput::Bundle _b(alog);
alog << "BR_TRANSACTION thr " << (void*)pthread_self()
<< " / obj " << tr.target.ptr << " / code "
<< TypeCode(tr.code) << ": " << indent << buffer
<< dedent << endl
<< "Data addr = "
<< reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)
<< ", offsets addr="
<< reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;
}
if (tr.target.ptr) {
sp<BBinder> b((BBinder*)tr.cookie);
error = b->transact(tr.code, buffer, &reply, tr.flags);
} else {
error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);
}
if ((tr.flags & TF_ONE_WAY) == 0) {
LOG_ONEWAY("Sending reply to %d!", mCallingPid);
if (error < NO_ERROR) reply.setError(error);
sendReply(reply, 0);
} else {
LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);
}
mCallingPid = origPid;
mCallingUid = origUid;
mStrictModePolicy = origStrictModePolicy;
mLastTransactionBinderFlags = origTransactionBinderFlags;
IF_LOG_TRANSACTIONS() {
TextOutput::Bundle _b(alog);
alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "
<< tr.target.ptr << ": " << indent << reply << dedent << endl;
}
}
break;
case BR_DEAD_BINDER:
{
BpBinder *proxy = (BpBinder*)mIn.readPointer();
proxy->sendObituary();
mOut.writeInt32(BC_DEAD_BINDER_DONE);
mOut.writePointer((uintptr_t)proxy);
} break;
case BR_CLEAR_DEATH_NOTIFICATION_DONE:
{
BpBinder *proxy = (BpBinder*)mIn.readPointer();
proxy->getWeakRefs()->decWeak(proxy);
} break;
case BR_FINISHED:
result = TIMED_OUT;
break;
case BR_NOOP:
break;
case BR_SPAWN_LOOPER:
mProcess->spawnPooledThread(false);
break;
default:
printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
result = UNKNOWN_ERROR;
break;
}
if (result != NO_ERROR) {
mLastError = result;
}
return result;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static const char *req_useragent_ip_field(request_rec *r)
{
return r->useragent_ip;
}
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 Free_PairPos2( HB_PairPosFormat2* ppf2,
HB_UShort format1,
HB_UShort format2)
{
HB_UShort m, n, count1, count2;
HB_Class1Record* c1r;
HB_Class2Record* c2r;
if ( ppf2->Class1Record )
{
c1r = ppf2->Class1Record;
count1 = ppf2->Class1Count;
count2 = ppf2->Class2Count;
for ( m = 0; m < count1; m++ )
{
c2r = c1r[m].Class2Record;
for ( n = 0; n < count2; n++ )
{
if ( format1 )
Free_ValueRecord( &c2r[n].Value1, format1 );
if ( format2 )
Free_ValueRecord( &c2r[n].Value2, format2 );
}
FREE( c2r );
}
FREE( c1r );
_HB_OPEN_Free_ClassDefinition( &ppf2->ClassDef2 );
_HB_OPEN_Free_ClassDefinition( &ppf2->ClassDef1 );
}
}
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 rsRetVal createSocket(instanceConf_t* info, void** sock) {
int rv;
sublist* sub;
*sock = zsocket_new(s_context, info->type);
if (!sock) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zsocket_new failed: %s, for type %d",
zmq_strerror(errno),info->type);
/* DK: invalid params seems right here */
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: socket of type %d created successfully\n", info->type)
/* Set options *before* the connect/bind. */
if (info->identity) zsocket_set_identity(*sock, info->identity);
if (info->sndBuf > -1) zsocket_set_sndbuf(*sock, info->sndBuf);
if (info->rcvBuf > -1) zsocket_set_rcvbuf(*sock, info->rcvBuf);
if (info->linger > -1) zsocket_set_linger(*sock, info->linger);
if (info->backlog > -1) zsocket_set_backlog(*sock, info->backlog);
if (info->sndTimeout > -1) zsocket_set_sndtimeo(*sock, info->sndTimeout);
if (info->rcvTimeout > -1) zsocket_set_rcvtimeo(*sock, info->rcvTimeout);
if (info->maxMsgSize > -1) zsocket_set_maxmsgsize(*sock, info->maxMsgSize);
if (info->rate > -1) zsocket_set_rate(*sock, info->rate);
if (info->recoveryIVL > -1) zsocket_set_recovery_ivl(*sock, info->recoveryIVL);
if (info->multicastHops > -1) zsocket_set_multicast_hops(*sock, info->multicastHops);
if (info->reconnectIVL > -1) zsocket_set_reconnect_ivl(*sock, info->reconnectIVL);
if (info->reconnectIVLMax > -1) zsocket_set_reconnect_ivl_max(*sock, info->reconnectIVLMax);
if (info->ipv4Only > -1) zsocket_set_ipv4only(*sock, info->ipv4Only);
if (info->affinity > -1) zsocket_set_affinity(*sock, info->affinity);
if (info->sndHWM > -1 ) zsocket_set_sndhwm(*sock, info->sndHWM);
if (info->rcvHWM > -1 ) zsocket_set_rcvhwm(*sock, info->rcvHWM);
/* Set subscriptions.*/
if (info->type == ZMQ_SUB) {
for(sub = info->subscriptions; sub!=NULL; sub=sub->next) {
zsocket_set_subscribe(*sock, sub->subscribe);
}
}
/* Do the bind/connect... */
if (info->action==ACTION_CONNECT) {
rv = zsocket_connect(*sock, info->description);
if (rv == -1) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zmq_connect using %s failed: %s",
info->description, zmq_strerror(errno));
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: connect for %s successful\n",info->description);
} else {
rv = zsocket_bind(*sock, info->description);
if (rv == -1) {
errmsg.LogError(0,
RS_RET_INVALID_PARAMS,
"zmq_bind using %s failed: %s",
info->description, zmq_strerror(errno));
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("imzmq3: bind for %s successful\n",info->description);
}
return RS_RET_OK;
}
CWE ID: CWE-134
Target: 1
Example 2:
Code: void MostVisitedSitesBridge::AddOrRemoveBlacklistedUrl(
JNIEnv* env,
const JavaParamRef<jobject>& obj,
const JavaParamRef<jstring>& j_url,
jboolean add_url) {
GURL url(ConvertJavaStringToUTF8(env, j_url));
most_visited_->AddOrRemoveBlacklistedUrl(url, add_url);
}
CWE ID: CWE-17
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 queue_delete(struct snd_seq_queue *q)
{
/* stop and release the timer */
snd_seq_timer_stop(q->timer);
snd_seq_timer_close(q);
/* wait until access free */
snd_use_lock_sync(&q->use_lock);
/* release resources... */
snd_seq_prioq_delete(&q->tickq);
snd_seq_prioq_delete(&q->timeq);
snd_seq_timer_delete(&q->timer);
kfree(q);
}
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: DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host,
DevToolsAgentHostClient* client)
: binding_(this),
agent_host_(agent_host),
client_(client),
process_host_id_(ChildProcessHost::kInvalidUniqueID),
host_(nullptr),
dispatcher_(new protocol::UberDispatcher(this)),
weak_factory_(this) {
dispatcher_->setFallThroughForNotFound(true);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void btif_hl_disable(void){
BTIF_TRACE_DEBUG("%s", __FUNCTION__);
if ((p_btif_hl_cb->state != BTIF_HL_STATE_DISABLING) &&
(p_btif_hl_cb->state != BTIF_HL_STATE_DISABLED))
{
btif_hl_set_state(BTIF_HL_STATE_DISABLING);
BTA_HlDisable();
}
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int tcp_v6_connect(struct sock *sk, struct sockaddr *uaddr,
int addr_len)
{
struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr;
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct in6_addr *saddr = NULL, *final_p, final;
struct flowi6 fl6;
struct dst_entry *dst;
int addr_type;
int err;
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (usin->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
memset(&fl6, 0, sizeof(fl6));
if (np->sndflow) {
fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK;
IP6_ECN_flow_init(fl6.flowlabel);
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
struct ip6_flowlabel *flowlabel;
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
fl6_sock_release(flowlabel);
}
}
/*
* connect() to INADDR_ANY means loopback (BSD'ism).
*/
if (ipv6_addr_any(&usin->sin6_addr))
usin->sin6_addr.s6_addr[15] = 0x1;
addr_type = ipv6_addr_type(&usin->sin6_addr);
if (addr_type & IPV6_ADDR_MULTICAST)
return -ENETUNREACH;
if (addr_type&IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
usin->sin6_scope_id) {
/* If interface is set while binding, indices
* must coincide.
*/
if (sk->sk_bound_dev_if &&
sk->sk_bound_dev_if != usin->sin6_scope_id)
return -EINVAL;
sk->sk_bound_dev_if = usin->sin6_scope_id;
}
/* Connect to link-local address requires an interface */
if (!sk->sk_bound_dev_if)
return -EINVAL;
}
if (tp->rx_opt.ts_recent_stamp &&
!ipv6_addr_equal(&sk->sk_v6_daddr, &usin->sin6_addr)) {
tp->rx_opt.ts_recent = 0;
tp->rx_opt.ts_recent_stamp = 0;
tp->write_seq = 0;
}
sk->sk_v6_daddr = usin->sin6_addr;
np->flow_label = fl6.flowlabel;
/*
* TCP over IPv4
*/
if (addr_type == IPV6_ADDR_MAPPED) {
u32 exthdrlen = icsk->icsk_ext_hdr_len;
struct sockaddr_in sin;
SOCK_DEBUG(sk, "connect: ipv4 mapped\n");
if (__ipv6_only_sock(sk))
return -ENETUNREACH;
sin.sin_family = AF_INET;
sin.sin_port = usin->sin6_port;
sin.sin_addr.s_addr = usin->sin6_addr.s6_addr32[3];
icsk->icsk_af_ops = &ipv6_mapped;
sk->sk_backlog_rcv = tcp_v4_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
tp->af_specific = &tcp_sock_ipv6_mapped_specific;
#endif
err = tcp_v4_connect(sk, (struct sockaddr *)&sin, sizeof(sin));
if (err) {
icsk->icsk_ext_hdr_len = exthdrlen;
icsk->icsk_af_ops = &ipv6_specific;
sk->sk_backlog_rcv = tcp_v6_do_rcv;
#ifdef CONFIG_TCP_MD5SIG
tp->af_specific = &tcp_sock_ipv6_specific;
#endif
goto failure;
}
np->saddr = sk->sk_v6_rcv_saddr;
return err;
}
if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr))
saddr = &sk->sk_v6_rcv_saddr;
fl6.flowi6_proto = IPPROTO_TCP;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = saddr ? *saddr : np->saddr;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = usin->sin6_port;
fl6.fl6_sport = inet->inet_sport;
final_p = fl6_update_dst(&fl6, np->opt, &final);
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto failure;
}
if (!saddr) {
saddr = &fl6.saddr;
sk->sk_v6_rcv_saddr = *saddr;
}
/* set the source address */
np->saddr = *saddr;
inet->inet_rcv_saddr = LOOPBACK4_IPV6;
sk->sk_gso_type = SKB_GSO_TCPV6;
__ip6_dst_store(sk, dst, NULL, NULL);
if (tcp_death_row.sysctl_tw_recycle &&
!tp->rx_opt.ts_recent_stamp &&
ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr))
tcp_fetch_timewait_stamp(sk, dst);
icsk->icsk_ext_hdr_len = 0;
if (np->opt)
icsk->icsk_ext_hdr_len = (np->opt->opt_flen +
np->opt->opt_nflen);
tp->rx_opt.mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) - sizeof(struct ipv6hdr);
inet->inet_dport = usin->sin6_port;
tcp_set_state(sk, TCP_SYN_SENT);
err = inet6_hash_connect(&tcp_death_row, sk);
if (err)
goto late_failure;
sk_set_txhash(sk);
if (!tp->write_seq && likely(!tp->repair))
tp->write_seq = secure_tcpv6_sequence_number(np->saddr.s6_addr32,
sk->sk_v6_daddr.s6_addr32,
inet->inet_sport,
inet->inet_dport);
err = tcp_connect(sk);
if (err)
goto late_failure;
return 0;
late_failure:
tcp_set_state(sk, TCP_CLOSE);
__sk_dst_reset(sk);
failure:
inet->inet_dport = 0;
sk->sk_route_caps = 0;
return err;
}
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::unique_ptr<WebContents> CreateWebContents() {
std::unique_ptr<WebContents> web_contents = CreateTestWebContents();
content::WebContentsTester::For(web_contents.get())
->NavigateAndCommit(GURL("https://www.example.com"));
return web_contents;
}
CWE ID:
Target: 1
Example 2:
Code: void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
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: PassRefPtr<RTCSessionDescriptionDescriptor> RTCPeerConnectionHandlerDummy::localDescription()
{
return 0;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: vips_malloc( VipsObject *object, size_t size )
{
void *buf;
buf = g_malloc( size );
if( object ) {
g_signal_connect( object, "postclose",
G_CALLBACK( vips_malloc_cb ), buf );
object->local_memory += size;
}
return( buf );
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int vorbis_validate(uint8 *data)
{
static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
return memcmp(data, vorbis, 6) == 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void* ipc_rcu_alloc(int size)
{
void* out;
/*
* We prepend the allocation with the rcu struct, and
* workqueue if necessary (for vmalloc).
*/
if (rcu_use_vmalloc(size)) {
out = vmalloc(HDRLEN_VMALLOC + size);
if (out) {
out += HDRLEN_VMALLOC;
container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 1;
container_of(out, struct ipc_rcu_hdr, data)->refcount = 1;
}
} else {
out = kmalloc(HDRLEN_KMALLOC + size, GFP_KERNEL);
if (out) {
out += HDRLEN_KMALLOC;
container_of(out, struct ipc_rcu_hdr, data)->is_vmalloc = 0;
container_of(out, struct ipc_rcu_hdr, data)->refcount = 1;
}
}
return out;
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(SplTempFileObject, __construct)
{
long max_memory = PHP_STREAM_MAX_MEM;
char tmp_fname[48];
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
if (max_memory < 0) {
intern->file_name = "php://memory";
intern->file_name_len = 12;
} else if (ZEND_NUM_ARGS()) {
intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory);
intern->file_name = tmp_fname;
} else {
intern->file_name = "php://temp";
intern->file_name_len = 10;
}
intern->u.file.open_mode = "wb";
intern->u.file.open_mode_len = 1;
intern->u.file.zcontext = NULL;
if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) {
intern->_path_len = 0;
intern->_path = estrndup("", 0);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
} /* }}} */
/* {{{ proto void SplFileObject::rewind()
CWE ID: CWE-190
Target: 1
Example 2:
Code: int jp2_validate(jas_stream_t *in)
{
char buf[JP2_VALIDATELEN];
int i;
int n;
#if 0
jas_stream_t *tmpstream;
jp2_box_t *box;
#endif
assert(JAS_STREAM_MAXPUTBACK >= JP2_VALIDATELEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, JP2_VALIDATELEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < JP2_VALIDATELEN) {
return -1;
}
/* Is the box type correct? */
if (((buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7]) !=
JP2_BOX_JP)
{
return -1;
}
return 0;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FileSystemOperationRunner::DidFinish(const OperationID id,
StatusCallback callback,
base::File::Error rv) {
if (is_beginning_operation_) {
finished_operations_.insert(id);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&FileSystemOperationRunner::DidFinish,
weak_ptr_, id, std::move(callback), rv));
return;
}
std::move(callback).Run(rv);
FinishOperation(id);
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
char
postscript_file[MaxTextExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MaxTextExtent];
if ((clone_info=CloneImageInfo(image_info)) == NULL)
return(image);
clone_info->blob=(void *) NULL;
clone_info->length=0;
/* Obtain temporary file */
(void) AcquireUniqueFilename(postscript_file);
ps_file=fopen_utf8(postscript_file,"wb");
if (ps_file == (FILE *) NULL)
goto FINISH;
/* Copy postscript to temporary file */
(void) SeekBlob(image,PS_Offset,SEEK_SET);
(void) ReadBlob(image, 2*MaxTextExtent, magick);
(void) SeekBlob(image,PS_Offset,SEEK_SET);
while(PS_Size-- > 0)
{
(void) fputc(ReadBlobByte(image),ps_file);
}
(void) fclose(ps_file);
/* Detect file format - Check magic.mgk configuration file. */
magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
/* printf("Detected:%s \n",magic_info->name); */
if(exception->severity != UndefinedException) goto FINISH_UNL;
if(magic_info->name == (char *) NULL) goto FINISH_UNL;
(void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
image2=ReadImage(clone_info,exception);
if (!image2)
goto FINISH_UNL;
/*
Replace current image with new image while copying base image
attributes.
*/
(void) CopyMagickMemory(image2->filename,image->filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MaxTextExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MaxTextExtent);
image2->depth=image->depth;
DestroyBlob(image2);
image2->blob=ReferenceBlob(image->blob);
if ((image->rows == 0) || (image->columns == 0))
DeleteImageFromList(&image);
AppendImageToList(&image,image2);
FINISH_UNL:
(void) RelinquishUniqueFileResource(postscript_file);
FINISH:
DestroyImageInfo(clone_info);
return(image);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static jobject android_net_wifi_get_driver_version(JNIEnv *env, jclass cls, jint iface) {
JNIHelper helper(env);
int buffer_length = 256;
char *buffer = (char *)malloc(buffer_length);
if (!buffer) return NULL;
memset(buffer, 0, buffer_length);
wifi_interface_handle handle = getIfaceHandle(helper, cls, iface);
ALOGD("android_net_wifi_get_driver_version = %p", handle);
if (handle == 0) {
return NULL;
}
wifi_error result = hal_fn.wifi_get_driver_version(handle, buffer, buffer_length);
if (result == WIFI_SUCCESS) {
ALOGD("buffer is %p, length is %d", buffer, buffer_length);
JNIObject<jstring> driver_version = helper.newStringUTF(buffer);
free(buffer);
return driver_version.detach();
} else {
ALOGD("Fail to get driver version");
free(buffer);
return NULL;
}
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GfxDeviceNColorSpace::getCMYK(GfxColor *color, GfxCMYK *cmyk) {
double x[gfxColorMaxComps], c[gfxColorMaxComps];
GfxColor color2;
int i;
for (i = 0; i < nComps; ++i) {
x[i] = colToDbl(color->c[i]);
}
func->transform(x, c);
for (i = 0; i < alt->getNComps(); ++i) {
color2.c[i] = dblToCol(c[i]);
}
alt->getCMYK(&color2, cmyk);
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void VRDisplay::ProcessScheduledAnimations(double timestamp) {
Document* doc = this->GetDocument();
if (!doc || display_blurred_ || !scripted_animation_controller_)
return;
TRACE_EVENT1("gpu", "VRDisplay::OnVSync", "frame", vr_frame_id_);
AutoReset<bool> animating(&in_animation_frame_, true);
pending_raf_ = false;
scripted_animation_controller_->ServiceScriptedAnimations(timestamp);
if (is_presenting_ && !capabilities_->hasExternalDisplay()) {
Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask(
BLINK_FROM_HERE, WTF::Bind(&VRDisplay::ProcessScheduledWindowAnimations,
WrapWeakPersistent(this), timestamp));
}
}
CWE ID:
Target: 1
Example 2:
Code: static ssize_t __fuse_direct_read(struct fuse_io_priv *io,
struct iov_iter *iter,
loff_t *ppos)
{
ssize_t res;
struct file *file = io->file;
struct inode *inode = file_inode(file);
if (is_bad_inode(inode))
return -EIO;
res = fuse_direct_io(io, iter, ppos, 0);
fuse_invalidate_attr(inode);
return res;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool HaveValuesChanged(const SensorReading& lhs, const SensorReading& rhs) {
for (size_t i = 0; i < SensorReadingRaw::kValuesCount; ++i) {
if (lhs.raw.values[i] != rhs.raw.values[i])
return true;
}
return false;
}
CWE ID: CWE-732
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ContentBrowserClient::ShouldSwapProcessesForNavigation(
const GURL& current_url,
const GURL& new_url) {
return false;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void _6502_anal_update_flags(RAnalOp *op, int flags) {
/* FIXME: $b9 instead of $b8 to prevent the bug triggered by: A = 0 - 0xff - 1 */
if (flags & _6502_FLAGS_B) r_strbuf_append (&op->esil, ",$b9,C,=");
if (flags & _6502_FLAGS_C) r_strbuf_append (&op->esil, ",$c7,C,=");
if (flags & _6502_FLAGS_Z) r_strbuf_append (&op->esil, ",$z,Z,=");
if (flags & _6502_FLAGS_N) r_strbuf_append (&op->esil, ",$s,N,=");
}
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: MagickExport MagickBooleanType SetQuantumDepth(const Image *image,
QuantumInfo *quantum_info,const size_t depth)
{
size_t
extent,
quantum;
/*
Allocate the quantum pixel buffer.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
quantum_info->depth=depth;
if (quantum_info->format == FloatingPointQuantumFormat)
{
if (quantum_info->depth > 32)
quantum_info->depth=64;
else
if (quantum_info->depth > 16)
quantum_info->depth=32;
else
quantum_info->depth=16;
}
if (quantum_info->pixels != (unsigned char **) NULL)
DestroyQuantumPixels(quantum_info);
quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8;
extent=image->columns*quantum;
if ((image->columns != 0) && (quantum != (extent/image->columns)))
return(MagickFalse);
return(AcquireQuantumPixels(quantum_info,extent));
}
CWE ID: CWE-369
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int netbk_set_skb_gso(struct xenvif *vif,
struct sk_buff *skb,
struct xen_netif_extra_info *gso)
{
if (!gso->u.gso.size) {
netdev_dbg(vif->dev, "GSO size must not be zero.\n");
return -EINVAL;
}
/* Currently only TCPv4 S.O. is supported. */
if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) {
netdev_dbg(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type);
return -EINVAL;
}
skb_shinfo(skb)->gso_size = gso->u.gso.size;
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
struct ext4_inode_info *ei)
{
struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
__u16 csum_lo;
__u16 csum_hi = 0;
__u32 csum;
csum_lo = le16_to_cpu(raw->i_checksum_lo);
raw->i_checksum_lo = 0;
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
csum_hi = le16_to_cpu(raw->i_checksum_hi);
raw->i_checksum_hi = 0;
}
csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
EXT4_INODE_SIZE(inode->i_sb));
raw->i_checksum_lo = cpu_to_le16(csum_lo);
if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
raw->i_checksum_hi = cpu_to_le16(csum_hi);
return csum;
}
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 TestAppendTabsToTabStrip(bool focus_tab_strip) {
LifecycleUnit* first_lifecycle_unit = nullptr;
LifecycleUnit* second_lifecycle_unit = nullptr;
CreateTwoTabs(focus_tab_strip, &first_lifecycle_unit,
&second_lifecycle_unit);
const base::TimeTicks first_tab_last_focused_time =
first_lifecycle_unit->GetLastFocusedTime();
const base::TimeTicks second_tab_last_focused_time =
second_lifecycle_unit->GetLastFocusedTime();
task_runner_->FastForwardBy(kShortDelay);
LifecycleUnit* third_lifecycle_unit = nullptr;
EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_))
.WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) {
third_lifecycle_unit = lifecycle_unit;
if (focus_tab_strip) {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_TRUE(IsFocused(second_lifecycle_unit));
} else {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_EQ(second_tab_last_focused_time,
second_lifecycle_unit->GetLastFocusedTime());
}
EXPECT_EQ(NowTicks(), third_lifecycle_unit->GetLastFocusedTime());
}));
std::unique_ptr<content::WebContents> third_web_contents =
CreateAndNavigateWebContents();
content::WebContents* raw_third_web_contents = third_web_contents.get();
tab_strip_model_->AppendWebContents(std::move(third_web_contents), false);
testing::Mock::VerifyAndClear(&source_observer_);
EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_third_web_contents));
CloseTabsAndExpectNotifications(
tab_strip_model_.get(),
{first_lifecycle_unit, second_lifecycle_unit, third_lifecycle_unit});
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WT_InterpolateMono (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_I32 *pMixBuffer;
const EAS_I8 *pLoopEnd;
const EAS_I8 *pCurrentPhaseInt;
EAS_I32 numSamples;
EAS_I32 gain;
EAS_I32 gainIncrement;
EAS_I32 currentPhaseFrac;
EAS_I32 phaseInc;
EAS_I32 tmp0;
EAS_I32 tmp1;
EAS_I32 tmp2;
EAS_I8 *pLoopStart;
numSamples = pWTIntFrame->numSamples;
pMixBuffer = pWTIntFrame->pMixBuffer;
/* calculate gain increment */
gainIncrement = (pWTIntFrame->gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS);
if (gainIncrement < 0)
gainIncrement++;
gain = pWTIntFrame->prevGain << 16;
pCurrentPhaseInt = pWTVoice->pPhaseAccum;
currentPhaseFrac = pWTVoice->phaseFrac;
phaseInc = pWTIntFrame->phaseIncrement;
pLoopStart = pWTVoice->pLoopStart;
pLoopEnd = pWTVoice->pLoopEnd + 1;
InterpolationLoop:
tmp0 = (EAS_I32)(pCurrentPhaseInt - pLoopEnd);
if (tmp0 >= 0)
pCurrentPhaseInt = pLoopStart + tmp0;
tmp0 = *pCurrentPhaseInt;
tmp1 = *(pCurrentPhaseInt + 1);
tmp2 = phaseInc + currentPhaseFrac;
tmp1 = tmp1 - tmp0;
tmp1 = tmp1 * currentPhaseFrac;
tmp1 = tmp0 + (tmp1 >> NUM_EG1_FRAC_BITS);
pCurrentPhaseInt += (tmp2 >> NUM_PHASE_FRAC_BITS);
currentPhaseFrac = tmp2 & PHASE_FRAC_MASK;
gain += gainIncrement;
tmp2 = (gain >> SYNTH_UPDATE_PERIOD_IN_BITS);
tmp0 = *pMixBuffer;
tmp2 = tmp1 * tmp2;
tmp2 = (tmp2 >> 9);
tmp0 = tmp2 + tmp0;
*pMixBuffer++ = tmp0;
numSamples--;
if (numSamples > 0)
goto InterpolationLoop;
pWTVoice->pPhaseAccum = pCurrentPhaseInt;
pWTVoice->phaseFrac = currentPhaseFrac;
/*lint -e{702} <avoid divide>*/
pWTVoice->gain = (EAS_I16)(gain >> SYNTH_UPDATE_PERIOD_IN_BITS);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool ExtensionRegistry::AddEnabled(
const scoped_refptr<const Extension>& extension) {
return enabled_extensions_.Insert(extension);
}
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: ZSTD_compressSequences_internal(seqStore_t* seqStorePtr,
ZSTD_entropyCTables_t const* prevEntropy,
ZSTD_entropyCTables_t* nextEntropy,
ZSTD_CCtx_params const* cctxParams,
void* dst, size_t dstCapacity,
void* workspace, size_t wkspSize,
const int bmi2)
{
const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
ZSTD_strategy const strategy = cctxParams->cParams.strategy;
U32 count[MaxSeq+1];
FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */
const seqDef* const sequences = seqStorePtr->sequencesStart;
const BYTE* const ofCodeTable = seqStorePtr->ofCode;
const BYTE* const llCodeTable = seqStorePtr->llCode;
const BYTE* const mlCodeTable = seqStorePtr->mlCode;
BYTE* const ostart = (BYTE*)dst;
BYTE* const oend = ostart + dstCapacity;
BYTE* op = ostart;
size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
BYTE* seqHead;
BYTE* lastNCount = NULL;
ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
/* Compress literals */
{ const BYTE* const literals = seqStorePtr->litStart;
size_t const litSize = seqStorePtr->lit - literals;
int const disableLiteralCompression = (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);
size_t const cSize = ZSTD_compressLiterals(
&prevEntropy->huf, &nextEntropy->huf,
cctxParams->cParams.strategy, disableLiteralCompression,
op, dstCapacity,
literals, litSize,
workspace, wkspSize,
bmi2);
if (ZSTD_isError(cSize))
return cSize;
assert(cSize <= dstCapacity);
op += cSize;
}
/* Sequences Header */
if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/) return ERROR(dstSize_tooSmall);
if (nbSeq < 0x7F)
*op++ = (BYTE)nbSeq;
else if (nbSeq < LONGNBSEQ)
op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
else
op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
if (nbSeq==0) {
/* Copy the old tables over as if we repeated them */
memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
return op - ostart;
}
/* seqHead : flags for FSE encoding type */
seqHead = op++;
/* convert length/distances into codes */
ZSTD_seqToCodes(seqStorePtr);
/* build CTable for Literal Lengths */
{ U32 max = MaxLL;
size_t const mostFrequent = HIST_countFast_wksp(count, &max, llCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
DEBUGLOG(5, "Building LL table");
nextEntropy->fse.litlength_repeatMode = prevEntropy->fse.litlength_repeatMode;
LLtype = ZSTD_selectEncodingType(&nextEntropy->fse.litlength_repeatMode, count, max, mostFrequent, nbSeq, LLFSELog, prevEntropy->fse.litlengthCTable, LL_defaultNorm, LL_defaultNormLog, ZSTD_defaultAllowed, strategy);
assert(set_basic < set_compressed && set_rle < set_compressed);
assert(!(LLtype < set_compressed && nextEntropy->fse.litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
{ size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype,
count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL,
prevEntropy->fse.litlengthCTable, sizeof(prevEntropy->fse.litlengthCTable),
workspace, wkspSize);
if (ZSTD_isError(countSize)) return countSize;
if (LLtype == set_compressed)
lastNCount = op;
op += countSize;
} }
/* build CTable for Offsets */
{ U32 max = MaxOff;
size_t const mostFrequent = HIST_countFast_wksp(count, &max, ofCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
/* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
DEBUGLOG(5, "Building OF table");
nextEntropy->fse.offcode_repeatMode = prevEntropy->fse.offcode_repeatMode;
Offtype = ZSTD_selectEncodingType(&nextEntropy->fse.offcode_repeatMode, count, max, mostFrequent, nbSeq, OffFSELog, prevEntropy->fse.offcodeCTable, OF_defaultNorm, OF_defaultNormLog, defaultPolicy, strategy);
assert(!(Offtype < set_compressed && nextEntropy->fse.offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
{ size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype,
count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
prevEntropy->fse.offcodeCTable, sizeof(prevEntropy->fse.offcodeCTable),
workspace, wkspSize);
if (ZSTD_isError(countSize)) return countSize;
if (Offtype == set_compressed)
lastNCount = op;
op += countSize;
} }
/* build CTable for MatchLengths */
{ U32 max = MaxML;
size_t const mostFrequent = HIST_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
DEBUGLOG(5, "Building ML table");
nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode;
MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode, count, max, mostFrequent, nbSeq, MLFSELog, prevEntropy->fse.matchlengthCTable, ML_defaultNorm, ML_defaultNormLog, ZSTD_defaultAllowed, strategy);
assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
{ size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype,
count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML,
prevEntropy->fse.matchlengthCTable, sizeof(prevEntropy->fse.matchlengthCTable),
workspace, wkspSize);
if (ZSTD_isError(countSize)) return countSize;
if (MLtype == set_compressed)
lastNCount = op;
op += countSize;
} }
*seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
{ size_t const bitstreamSize = ZSTD_encodeSequences(
op, oend - op,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq,
longOffsets, bmi2);
if (ZSTD_isError(bitstreamSize)) return bitstreamSize;
op += bitstreamSize;
/* zstd versions <= 1.3.4 mistakenly report corruption when
* FSE_readNCount() recieves a buffer < 4 bytes.
* Fixed by https://github.com/facebook/zstd/pull/1146.
* This can happen when the last set_compressed table present is 2
* bytes and the bitstream is only one byte.
* In this exceedingly rare case, we will simply emit an uncompressed
* block, since it isn't worth optimizing.
*/
if (lastNCount && (op - lastNCount) < 4) {
/* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
assert(op - lastNCount == 3);
DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
"emitting an uncompressed block.");
return 0;
}
}
return op - ostart;
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static 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) {
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; cnt < shdr->sh_info && ((char *)defs + i < end); ++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)
vstart += verdef->vd_aux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
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 || vstart + sizeof(Elf_(Verdaux)) > end) {
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;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Pack<WebGLImageConversion::kDataFormatRGBA16_S,
WebGLImageConversion::kAlphaDoPremultiply,
int16_t,
int16_t>(const int16_t* source,
int16_t* destination,
unsigned pixels_per_row) {
for (unsigned i = 0; i < pixels_per_row; ++i) {
destination[3] = ClampMin(source[3]);
float scale_factor = static_cast<float>(destination[3]) / kMaxInt16Value;
destination[0] = static_cast<int16_t>(
static_cast<float>(ClampMin(source[0])) * scale_factor);
destination[1] = static_cast<int16_t>(
static_cast<float>(ClampMin(source[1])) * scale_factor);
destination[2] = static_cast<int16_t>(
static_cast<float>(ClampMin(source[2])) * scale_factor);
source += 4;
destination += 4;
}
}
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 WebContentsImpl::DidFailProvisionalLoadWithError(
RenderViewHost* render_view_host,
const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
<< ", error_code: " << params.error_code
<< ", error_description: " << params.error_description
<< ", is_main_frame: " << params.is_main_frame
<< ", showing_repost_interstitial: " <<
params.showing_repost_interstitial
<< ", frame_id: " << params.frame_id;
GURL validated_url(params.url);
RenderProcessHost* render_process_host =
render_view_host->GetProcess();
RenderViewHost::FilterURL(render_process_host, false, &validated_url);
if (net::ERR_ABORTED == params.error_code) {
if (ShowingInterstitialPage()) {
LOG(WARNING) << "Discarding message during interstitial.";
return;
}
render_manager_.RendererAbortedProvisionalLoad(render_view_host);
}
FOR_EACH_OBSERVER(WebContentsObserver,
observers_,
DidFailProvisionalLoad(params.frame_id,
params.is_main_frame,
validated_url,
params.error_code,
params.error_description,
render_view_host));
}
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: mobility_print(netdissect_options *ndo,
const u_char *bp, const u_char *bp2 _U_)
{
const struct ip6_mobility *mh;
const u_char *ep;
unsigned mhlen, hlen;
uint8_t type;
mh = (const struct ip6_mobility *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(mh->ip6m_len)) {
/*
* There's not enough captured data to include the
* mobility header length.
*
* Our caller expects us to return the length, however,
* so return a value that will run to the end of the
* captured data.
*
* XXX - "ip6_print()" doesn't do anything with the
* returned length, however, as it breaks out of the
* header-processing loop.
*/
mhlen = ep - bp;
goto trunc;
}
mhlen = (mh->ip6m_len + 1) << 3;
/* XXX ip6m_cksum */
ND_TCHECK(mh->ip6m_type);
type = mh->ip6m_type;
if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {
ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type));
goto trunc;
}
ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type)));
switch (type) {
case IP6M_BINDING_REQUEST:
hlen = IP6M_MINLEN;
break;
case IP6M_HOME_TEST_INIT:
case IP6M_CAREOF_TEST_INIT:
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_HOME_TEST:
case IP6M_CAREOF_TEST:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
if (ndo->ndo_vflag) {
ND_TCHECK2(*mh, hlen + 8);
ND_PRINT((ndo, " %s Keygen Token=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_BINDING_UPDATE:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 1);
if (bp[hlen] & 0xf0)
ND_PRINT((ndo, " "));
if (bp[hlen] & 0x80)
ND_PRINT((ndo, "A"));
if (bp[hlen] & 0x40)
ND_PRINT((ndo, "H"));
if (bp[hlen] & 0x20)
ND_PRINT((ndo, "L"));
if (bp[hlen] & 0x10)
ND_PRINT((ndo, "K"));
/* Reserved (4bits) */
hlen += 1;
/* Reserved (8bits) */
hlen += 1;
ND_TCHECK2(*mh, hlen + 2);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ACK:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
if (mh->ip6m_data8[1] & 0x80)
ND_PRINT((ndo, " K"));
/* Reserved (7bits) */
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 2);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen])));
hlen += 2;
ND_TCHECK2(*mh, hlen + 2);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ERROR:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
/* Reserved */
hlen = IP6M_MINLEN;
ND_TCHECK2(*mh, hlen + 16);
ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen])));
hlen += 16;
break;
default:
ND_PRINT((ndo, " len=%u", mh->ip6m_len));
return(mhlen);
break;
}
if (ndo->ndo_vflag)
if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen))
goto trunc;
return(mhlen);
trunc:
ND_PRINT((ndo, "%s", tstr));
return(mhlen);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
{
effect_descriptor_t desc = effect->desc();
uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
Mutex::Autolock _l(mLock);
effect->setChain(this);
sp<ThreadBase> thread = mThread.promote();
if (thread == 0) {
return NO_INIT;
}
effect->setThread(thread);
if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
mEffects.insertAt(effect, 0);
size_t numSamples = thread->frameCount();
int32_t *buffer = new int32_t[numSamples];
memset(buffer, 0, numSamples * sizeof(int32_t));
effect->setInBuffer((int16_t *)buffer);
effect->setOutBuffer(mInBuffer);
} else {
size_t size = mEffects.size();
size_t idx_insert = size;
ssize_t idx_insert_first = -1;
ssize_t idx_insert_last = -1;
for (size_t i = 0; i < size; i++) {
effect_descriptor_t d = mEffects[i]->desc();
uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
if (iMode == EFFECT_FLAG_TYPE_INSERT) {
if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s",
desc.name, d.name);
return INVALID_OPERATION;
}
if (idx_insert == size) {
idx_insert = i;
}
if (iPref == EFFECT_FLAG_INSERT_FIRST) {
idx_insert_first = i;
}
if (iPref == EFFECT_FLAG_INSERT_LAST &&
idx_insert_last == -1) {
idx_insert_last = i;
}
}
}
if (insertPref == EFFECT_FLAG_INSERT_LAST) {
if (idx_insert_last != -1) {
idx_insert = idx_insert_last;
} else {
idx_insert = size;
}
} else {
if (idx_insert_first != -1) {
idx_insert = idx_insert_first + 1;
}
}
effect->setInBuffer(mInBuffer);
if (idx_insert == size) {
if (idx_insert != 0) {
mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
mEffects[idx_insert-1]->configure();
}
effect->setOutBuffer(mOutBuffer);
} else {
effect->setOutBuffer(mInBuffer);
}
mEffects.insertAt(effect, idx_insert);
ALOGV("addEffect_l() effect %p, added in chain %p at rank %zu", effect.get(), this,
idx_insert);
}
effect->configure();
return NO_ERROR;
}
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: wiki_handle_rest_call(HttpRequest *req,
HttpResponse *res,
char *func)
{
if (func != NULL && *func != '\0')
{
if (!strcmp(func, "page/get"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && (access(page, R_OK) == 0))
{
http_response_printf(res, "%s", file_read(page));
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/set"))
{
char *wikitext = NULL, *page = NULL;
if( ( (wikitext = http_request_param_get(req, "text")) != NULL)
&& ( (page = http_request_param_get(req, "page")) != NULL))
{
file_write(page, wikitext);
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/delete"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && (unlink(page) > 0))
{
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "page/exists"))
{
char *page = http_request_param_get(req, "page");
if (page == NULL)
page = http_request_get_query_string(req);
if (page && (access(page, R_OK) == 0))
{
http_response_printf(res, "success");
http_response_send(res);
return;
}
}
else if (!strcmp(func, "pages") || !strcmp(func, "search"))
{
WikiPageList **pages = NULL;
int n_pages, i;
char *expr = http_request_param_get(req, "expr");
if (expr == NULL)
expr = http_request_get_query_string(req);
pages = wiki_get_pages(&n_pages, expr);
if (pages)
{
for (i=0; i<n_pages; i++)
{
struct tm *pTm;
char datebuf[64];
pTm = localtime(&pages[i]->mtime);
strftime(datebuf, sizeof(datebuf), "%Y-%m-%d %H:%M", pTm);
http_response_printf(res, "%s\t%s\n", pages[i]->name, datebuf);
}
http_response_send(res);
return;
}
}
}
http_response_set_status(res, 500, "Error");
http_response_printf(res, "<html><body>Failed</body></html>\n");
http_response_send(res);
return;
}
CWE ID: CWE-22
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void uverbs_user_mmap_disassociate(struct ib_uverbs_file *ufile)
{
struct rdma_umap_priv *priv, *next_priv;
lockdep_assert_held(&ufile->hw_destroy_rwsem);
while (1) {
struct mm_struct *mm = NULL;
/* Get an arbitrary mm pointer that hasn't been cleaned yet */
mutex_lock(&ufile->umap_lock);
while (!list_empty(&ufile->umaps)) {
int ret;
priv = list_first_entry(&ufile->umaps,
struct rdma_umap_priv, list);
mm = priv->vma->vm_mm;
ret = mmget_not_zero(mm);
if (!ret) {
list_del_init(&priv->list);
mm = NULL;
continue;
}
break;
}
mutex_unlock(&ufile->umap_lock);
if (!mm)
return;
/*
* The umap_lock is nested under mmap_sem since it used within
* the vma_ops callbacks, so we have to clean the list one mm
* at a time to get the lock ordering right. Typically there
* will only be one mm, so no big deal.
*/
down_write(&mm->mmap_sem);
mutex_lock(&ufile->umap_lock);
list_for_each_entry_safe (priv, next_priv, &ufile->umaps,
list) {
struct vm_area_struct *vma = priv->vma;
if (vma->vm_mm != mm)
continue;
list_del_init(&priv->list);
zap_vma_ptes(vma, vma->vm_start,
vma->vm_end - vma->vm_start);
vma->vm_flags &= ~(VM_SHARED | VM_MAYSHARE);
}
mutex_unlock(&ufile->umap_lock);
up_write(&mm->mmap_sem);
mmput(mm);
}
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static void crypto_cts_free(struct crypto_instance *inst)
{
crypto_drop_spawn(crypto_instance_ctx(inst));
kfree(inst);
}
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: png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
{
static PNG_CONST char short_months[12][4] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
if (png_ptr == NULL)
return (NULL);
if (png_ptr->time_buffer == NULL)
{
png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
png_sizeof(char)));
}
#ifdef _WIN32_WCE
{
wchar_t time_buf[29];
wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer,
29, NULL, NULL);
}
#else
#ifdef USE_FAR_KEYWORD
{
char near_time_buf[29];
png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
png_memcpy(png_ptr->time_buffer, near_time_buf,
29*png_sizeof(char));
}
#else
png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000",
ptime->day % 32, short_months[(ptime->month - 1) % 12],
ptime->year, ptime->hour % 24, ptime->minute % 60,
ptime->second % 61);
#endif
#endif /* _WIN32_WCE */
return ((png_charp)png_ptr->time_buffer);
}
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: const PPB_NaCl_Private* GetNaclInterface() {
pp::Module *module = pp::Module::Get();
CHECK(module);
return static_cast<const PPB_NaCl_Private*>(
module->GetBrowserInterface(PPB_NACL_PRIVATE_INTERFACE));
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void CWebServer::Cmd_UpdateDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights < 1)
{
session.reply_status = reply::forbidden;
return; //only user or higher allowed
}
std::string idx = request::findValue(&req, "idx");
if (!IsIdxForUser(&session, atoi(idx.c_str())))
{
_log.Log(LOG_ERROR, "User: %s tried to update an Unauthorized device!", session.username.c_str());
session.reply_status = reply::forbidden;
return;
}
std::string hid = request::findValue(&req, "hid");
std::string did = request::findValue(&req, "did");
std::string dunit = request::findValue(&req, "dunit");
std::string dtype = request::findValue(&req, "dtype");
std::string dsubtype = request::findValue(&req, "dsubtype");
std::string nvalue = request::findValue(&req, "nvalue");
std::string svalue = request::findValue(&req, "svalue");
if ((nvalue.empty() && svalue.empty()))
{
return;
}
int signallevel = 12;
int batterylevel = 255;
if (idx.empty())
{
if (
(hid.empty()) ||
(did.empty()) ||
(dunit.empty()) ||
(dtype.empty()) ||
(dsubtype.empty())
)
return;
}
else
{
std::vector<std::vector<std::string> > result;
result = m_sql.safe_query("SELECT HardwareID, DeviceID, Unit, Type, SubType FROM DeviceStatus WHERE (ID=='%q')",
idx.c_str());
if (result.empty())
return;
hid = result[0][0];
did = result[0][1];
dunit = result[0][2];
dtype = result[0][3];
dsubtype = result[0][4];
}
int HardwareID = atoi(hid.c_str());
std::string DeviceID = did;
int unit = atoi(dunit.c_str());
int devType = atoi(dtype.c_str());
int subType = atoi(dsubtype.c_str());
uint64_t ulIdx = std::strtoull(idx.c_str(), nullptr, 10);
int invalue = atoi(nvalue.c_str());
std::string sSignalLevel = request::findValue(&req, "rssi");
if (sSignalLevel != "")
{
signallevel = atoi(sSignalLevel.c_str());
}
std::string sBatteryLevel = request::findValue(&req, "battery");
if (sBatteryLevel != "")
{
batterylevel = atoi(sBatteryLevel.c_str());
}
if (m_mainworker.UpdateDevice(HardwareID, DeviceID, unit, devType, subType, invalue, svalue, signallevel, batterylevel))
{
root["status"] = "OK";
root["title"] = "Update Device";
}
}
CWE ID: CWE-89
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void bgp_packet_mpunreach_end(struct stream *s, size_t attrlen_pnt)
{
bgp_packet_mpattr_end(s, attrlen_pnt);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AXNodeObject::isChecked() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLInputElement(*node))
return toHTMLInputElement(*node).shouldAppearChecked();
switch (ariaRoleAttribute()) {
case CheckBoxRole:
case MenuItemCheckBoxRole:
case MenuItemRadioRole:
case RadioButtonRole:
case SwitchRole:
if (equalIgnoringCase(
getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked),
"true"))
return true;
return false;
default:
break;
}
return false;
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
{
if (avpkt->size < 0) {
av_log(avctx, AV_LOG_ERROR, "Invalid negative user packet size %d\n", avpkt->size);
return AVERROR(EINVAL);
}
if (size < 0 || size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n",
size, INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE);
return AVERROR(EINVAL);
}
if (avctx && 2*min_size < size) { // FIXME The factor needs to be finetuned
av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
if (!avpkt->data || avpkt->size < size) {
av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
avpkt->data = avctx->internal->byte_buffer;
avpkt->size = avctx->internal->byte_buffer_size;
}
}
if (avpkt->data) {
AVBufferRef *buf = avpkt->buf;
if (avpkt->size < size) {
av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %"PRId64")\n", avpkt->size, size);
return AVERROR(EINVAL);
}
av_init_packet(avpkt);
avpkt->buf = buf;
avpkt->size = size;
return 0;
} else {
int ret = av_new_packet(avpkt, size);
if (ret < 0)
av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size);
return ret;
}
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static VirtualKeyboardType convertStringToKeyboardType(const AtomicString& string)
{
DEFINE_STATIC_LOCAL(AtomicString, Default, ("default"));
DEFINE_STATIC_LOCAL(AtomicString, Url, ("url"));
DEFINE_STATIC_LOCAL(AtomicString, Email, ("email"));
DEFINE_STATIC_LOCAL(AtomicString, Password, ("password"));
DEFINE_STATIC_LOCAL(AtomicString, Web, ("web"));
DEFINE_STATIC_LOCAL(AtomicString, Number, ("number"));
DEFINE_STATIC_LOCAL(AtomicString, Symbol, ("symbol"));
DEFINE_STATIC_LOCAL(AtomicString, Phone, ("phone"));
DEFINE_STATIC_LOCAL(AtomicString, Pin, ("pin"));
DEFINE_STATIC_LOCAL(AtomicString, Hex, ("hexadecimal"));
if (string.isEmpty())
return VKBTypeNotSet;
if (equalIgnoringCase(string, Default))
return VKBTypeDefault;
if (equalIgnoringCase(string, Url))
return VKBTypeUrl;
if (equalIgnoringCase(string, Email))
return VKBTypeEmail;
if (equalIgnoringCase(string, Password))
return VKBTypePassword;
if (equalIgnoringCase(string, Web))
return VKBTypeWeb;
if (equalIgnoringCase(string, Number))
return VKBTypeNumPunc;
if (equalIgnoringCase(string, Symbol))
return VKBTypeSymbol;
if (equalIgnoringCase(string, Phone))
return VKBTypePhone;
if (equalIgnoringCase(string, Pin) || equalIgnoringCase(string, Hex))
return VKBTypePin;
return VKBTypeNotSet;
}
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: struct sock *inet_csk_clone_lock(const struct sock *sk,
const struct request_sock *req,
const gfp_t priority)
{
struct sock *newsk = sk_clone_lock(sk, priority);
if (newsk) {
struct inet_connection_sock *newicsk = inet_csk(newsk);
newsk->sk_state = TCP_SYN_RECV;
newicsk->icsk_bind_hash = NULL;
inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
newsk->sk_write_space = sk_stream_write_space;
/* listeners have SOCK_RCU_FREE, not the children */
sock_reset_flag(newsk, SOCK_RCU_FREE);
newsk->sk_mark = inet_rsk(req)->ir_mark;
atomic64_set(&newsk->sk_cookie,
atomic64_read(&inet_rsk(req)->ir_cookie));
newicsk->icsk_retransmits = 0;
newicsk->icsk_backoff = 0;
newicsk->icsk_probes_out = 0;
/* Deinitialize accept_queue to trap illegal accesses. */
memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
security_inet_csk_clone(newsk, req);
}
return newsk;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: BGD_DECLARE(int) gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_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: dump_xml_comment(xmlNode * data, int options, char **buffer, int *offset, int *max, int depth)
{
CRM_ASSERT(max != NULL);
CRM_ASSERT(offset != NULL);
CRM_ASSERT(buffer != NULL);
if (data == NULL) {
crm_trace("Nothing to dump");
return;
}
if (*buffer == NULL) {
*offset = 0;
*max = 0;
}
insert_prefix(options, buffer, offset, max, depth);
buffer_print(*buffer, *max, *offset, "<!--");
buffer_print(*buffer, *max, *offset, "%s", data->content);
buffer_print(*buffer, *max, *offset, "-->");
if (options & xml_log_option_formatted) {
buffer_print(*buffer, *max, *offset, "\n");
}
}
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 vapic_enter(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
struct page *page;
if (!apic || !apic->vapic_addr)
return 0;
page = gfn_to_page(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
if (is_error_page(page))
return -EFAULT;
vcpu->arch.apic->vapic_page = page;
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void *jsvGetNativeFunctionPtr(const JsVar *function) {
/* see descriptions in jsvar.h. If we have a child called JSPARSE_FUNCTION_CODE_NAME
* then we execute code straight from that */
JsVar *flatString = jsvFindChildFromString((JsVar*)function, JSPARSE_FUNCTION_CODE_NAME, 0);
if (flatString) {
flatString = jsvSkipNameAndUnLock(flatString);
void *v = (void*)((size_t)function->varData.native.ptr + (char*)jsvGetFlatStringPointer(flatString));
jsvUnLock(flatString);
return v;
} else
return (void *)function->varData.native.ptr;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int add_session(SSL *ssl, SSL_SESSION *session)
{
simple_ssl_session *sess;
unsigned char *p;
sess = OPENSSL_malloc(sizeof(simple_ssl_session));
if (!sess) {
BIO_printf(bio_err, "Out of memory adding session to external cache\n");
return 0;
}
SSL_SESSION_get_id(session, &sess->idlen);
sess->derlen = i2d_SSL_SESSION(session, NULL);
sess->id = BUF_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen);
sess->der = OPENSSL_malloc(sess->derlen);
if (!sess->id || !sess->der) {
BIO_printf(bio_err, "Out of memory adding session to external cache\n");
if (sess->id)
OPENSSL_free(sess->id);
if (sess->der)
OPENSSL_free(sess->der);
OPENSSL_free(sess);
return 0;
}
p = sess->der;
i2d_SSL_SESSION(session, &p);
sess->next = first;
first = sess;
BIO_printf(bio_err, "New session added to external cache\n");
return 0;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool CanCapture(const Extension& extension, const GURL& url) {
return extension.permissions_data()->CanCaptureVisiblePage(
url, kTabId, nullptr /*error*/);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: fst_tx_config(struct fst_port_info *port)
{
int i;
int pi;
unsigned int offset;
unsigned long flags;
struct fst_card_info *card;
pi = port->index;
card = port->card;
spin_lock_irqsave(&card->card_lock, flags);
for (i = 0; i < NUM_TX_BUFFER; i++) {
offset = BUF_OFFSET(txBuffer[pi][i][0]);
FST_WRW(card, txDescrRing[pi][i].ladr, (u16) offset);
FST_WRB(card, txDescrRing[pi][i].hadr, (u8) (offset >> 16));
FST_WRW(card, txDescrRing[pi][i].bcnt, 0);
FST_WRB(card, txDescrRing[pi][i].bits, 0);
}
port->txpos = 0;
port->txipos = 0;
port->start = 0;
spin_unlock_irqrestore(&card->card_lock, flags);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void JSFloat64Array::getOwnPropertyNames(JSObject* object, ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
{
JSFloat64Array* thisObject = jsCast<JSFloat64Array*>(object);
ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);
for (unsigned i = 0; i < static_cast<Float64Array*>(thisObject->impl())->length(); ++i)
propertyNames.add(Identifier::from(exec, i));
Base::getOwnPropertyNames(thisObject, exec, propertyNames, mode);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(SplFileInfo, getFilename)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
int path_len;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC);
if (path_len && path_len < intern->file_name_len) {
RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1);
} else {
RETURN_STRINGL(intern->file_name, intern->file_name_len, 1);
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void Document::ReportFeaturePolicyViolation(
mojom::FeaturePolicyFeature feature,
mojom::FeaturePolicyDisposition disposition,
const String& message) const {
if (!RuntimeEnabledFeatures::FeaturePolicyReportingEnabled())
return;
LocalFrame* frame = GetFrame();
if (!frame)
return;
const String& feature_name = GetNameForFeature(feature);
FeaturePolicyViolationReportBody* body =
MakeGarbageCollected<FeaturePolicyViolationReportBody>(
feature_name, "Feature policy violation",
(disposition == mojom::FeaturePolicyDisposition::kReport ? "report"
: "enforce"),
SourceLocation::Capture());
Report* report =
new Report("feature-policy-violation", Url().GetString(), body);
ReportingContext::From(this)->QueueReport(report);
bool is_null;
int line_number = body->lineNumber(is_null);
line_number = is_null ? 0 : line_number;
int column_number = body->columnNumber(is_null);
column_number = is_null ? 0 : column_number;
frame->GetReportingService()->QueueFeaturePolicyViolationReport(
Url(), feature_name,
(disposition == mojom::FeaturePolicyDisposition::kReport ? "report"
: "enforce"),
"Feature policy violation", body->sourceFile(), line_number,
column_number);
if (disposition == mojom::FeaturePolicyDisposition::kEnforce) {
frame->Console().AddMessage(ConsoleMessage::Create(
kViolationMessageSource, kErrorMessageLevel,
(message.IsEmpty() ? ("Feature policy violation: " + feature_name +
" is not allowed in this document.")
: message)));
}
}
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: FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) {
const DictionaryValue* dict = GetExtensionPref(extension_id);
std::string path;
if (!dict->GetString(kPrefPath, &path))
return FilePath();
return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path)));
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
unsigned x, y;
AVFilterContext *ctx = inlink->dst;
VignetteContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
if (s->eval_mode == EVAL_MODE_FRAME)
update_context(s, inlink, in);
if (s->desc->flags & AV_PIX_FMT_FLAG_RGB) {
uint8_t *dst = out->data[0];
const uint8_t *src = in ->data[0];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[0];
const int src_linesize = in ->linesize[0];
const int fmap_linesize = s->fmap_linesize;
for (y = 0; y < inlink->h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < inlink->w; x++, dstp += 3, srcp += 3) {
const float f = fmap[x];
dstp[0] = av_clip_uint8(srcp[0] * f + get_dither_value(s));
dstp[1] = av_clip_uint8(srcp[1] * f + get_dither_value(s));
dstp[2] = av_clip_uint8(srcp[2] * f + get_dither_value(s));
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize;
}
} else {
int plane;
for (plane = 0; plane < 4 && in->data[plane]; plane++) {
uint8_t *dst = out->data[plane];
const uint8_t *src = in ->data[plane];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[plane];
const int src_linesize = in ->linesize[plane];
const int fmap_linesize = s->fmap_linesize;
const int chroma = plane == 1 || plane == 2;
const int hsub = chroma ? s->desc->log2_chroma_w : 0;
const int vsub = chroma ? s->desc->log2_chroma_h : 0;
const int w = FF_CEIL_RSHIFT(inlink->w, hsub);
const int h = FF_CEIL_RSHIFT(inlink->h, vsub);
for (y = 0; y < h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < w; x++) {
const double dv = get_dither_value(s);
if (chroma) *dstp++ = av_clip_uint8(fmap[x << hsub] * (*srcp++ - 127) + 127 + dv);
else *dstp++ = av_clip_uint8(fmap[x ] * *srcp++ + dv);
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize << vsub;
}
}
}
return ff_filter_frame(outlink, out);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ne2000_reset(NE2000State *s)
{
int i;
s->isr = ENISR_RESET;
memcpy(s->mem, &s->c.macaddr, 6);
s->mem[14] = 0x57;
s->mem[15] = 0x57;
/* duplicate prom data */
for(i = 15;i >= 0; i--) {
s->mem[2 * i] = s->mem[i];
s->mem[2 * i + 1] = s->mem[i];
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void hashtable_clear(hashtable_t *hashtable)
{
size_t i;
hashtable_do_clear(hashtable);
for(i = 0; i < num_buckets(hashtable); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
}
list_init(&hashtable->list);
hashtable->size = 0;
}
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 AppListController::EnableAppList() {
PrefService* local_state = g_browser_process->local_state();
bool has_been_enabled = local_state->GetBoolean(
apps::prefs::kAppLauncherHasBeenEnabled);
if (!has_been_enabled) {
local_state->SetBoolean(apps::prefs::kAppLauncherHasBeenEnabled, true);
ShellIntegration::ShortcutLocations shortcut_locations;
shortcut_locations.on_desktop = true;
shortcut_locations.in_quick_launch_bar = true;
shortcut_locations.in_applications_menu = true;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
shortcut_locations.applications_menu_subdir = dist->GetAppShortCutName();
base::FilePath user_data_dir(
g_browser_process->profile_manager()->user_data_dir());
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&CreateAppListShortcuts,
user_data_dir, GetAppModelId(), shortcut_locations));
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void Range::detach(ExceptionCode& ec)
{
if (!m_start.container()) {
ec = INVALID_STATE_ERR;
return;
}
m_ownerDocument->detachRange(this);
m_start.clear();
m_end.clear();
}
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: image_PaintProc(const gs_client_color * pcolor, gs_gstate * pgs)
{
const pixmap_info *ppmap = gs_getpattern(pcolor)->client_data;
const gs_depth_bitmap *pbitmap = &(ppmap->bitmap);
gs_image_enum *pen =
gs_image_enum_alloc(gs_gstate_memory(pgs), "image_PaintProc");
gs_color_space *pcspace;
gx_image_enum_common_t *pie;
/*
* If the image is transparent then we want to do image type4 processing.
* Otherwise we want to use image type 1 processing.
*/
int transparent = ppmap->white_index < (1 << (pbitmap->num_comps * pbitmap->pix_depth));
/*
* Note: gs_image1_t and gs_image4_t sre nearly identical structure
* definitions. From our point of view, the only significant difference
* is MaskColor in gs_image4_t. The fields are generally loaded using
* the gs_image1_t version of the union and then used for either type
* of image processing.
*/
union {
gs_image1_t i1;
gs_image4_t i4;
} image;
int code;
if (pen == 0)
return_error(gs_error_VMerror);
if (ppmap->pcspace == 0) {
pcspace = gs_cspace_new_DeviceGray(pgs->memory);
if (pcspace == NULL)
return_error(gs_error_VMerror);
} else
pcspace = ppmap->pcspace;
code = gs_gsave(pgs);
if (code < 0)
goto fail;
code = gs_setcolorspace(pgs, pcspace);
if (code < 0)
return code;
if (transparent)
gs_image4_t_init( (gs_image4_t *) &image, pcspace);
else
gs_image_t_init_adjust( (gs_image_t *) &image, pcspace, 0);
image.i1.Width = pbitmap->size.x;
image.i1.Height = pbitmap->size.y;
if (transparent) {
image.i4.MaskColor_is_range = false;
image.i4.MaskColor[0] = ppmap->white_index;
}
image.i1.Decode[0] = 0.0;
image.i1.Decode[1] = (float)((1 << pbitmap->pix_depth) - 1);
image.i1.BitsPerComponent = pbitmap->pix_depth;
/* backwards compatibility */
if (ppmap->pcspace == 0) {
image.i1.Decode[0] = 1.0;
image.i1.Decode[1] = 0.0;
}
if ( (code = gs_image_begin_typed( (const gs_image_common_t *)&image,
pgs,
false,
false,
&pie )) >= 0 &&
(code = gs_image_enum_init( pen,
pie,
(gs_data_image_t *)&image,
pgs )) >= 0 &&
(code = bitmap_paint(pen, (gs_data_image_t *) & image, pbitmap, pgs)) >= 0) {
return gs_grestore(pgs);
}
fail:
gs_free_object(gs_gstate_memory(pgs), pen, "image_PaintProc");
return code;
}
CWE ID: CWE-704
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 commit_tree(struct mount *mnt, struct mount *shadows)
{
struct mount *parent = mnt->mnt_parent;
struct mount *m;
LIST_HEAD(head);
struct mnt_namespace *n = parent->mnt_ns;
BUG_ON(parent == mnt);
list_add_tail(&head, &mnt->mnt_list);
list_for_each_entry(m, &head, mnt_list)
m->mnt_ns = n;
list_splice(&head, n->list.prev);
attach_shadowed(mnt, parent, shadows);
touch_mnt_namespace(n);
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: bool TreeView::OnKeyDown(ui::KeyboardCode virtual_key_code) {
if (virtual_key_code == VK_F2) {
if (!GetEditingNode()) {
TreeModelNode* selected_node = GetSelectedNode();
if (selected_node)
StartEditing(selected_node);
}
return true;
} else if (virtual_key_code == ui::VKEY_RETURN && !process_enter_) {
Widget* widget = GetWidget();
DCHECK(widget);
Accelerator accelerator(Accelerator(virtual_key_code,
base::win::IsShiftPressed(),
base::win::IsCtrlPressed(),
base::win::IsAltPressed()));
GetFocusManager()->ProcessAccelerator(accelerator);
return true;
}
return false;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: name_len(netdissect_options *ndo,
const unsigned char *s, const unsigned char *maxbuf)
{
const unsigned char *s0 = s;
unsigned char c;
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
c = *s;
if ((c & 0xC0) == 0xC0)
return(2);
while (*s) {
if (s >= maxbuf)
return(-1); /* name goes past the end of the buffer */
ND_TCHECK2(*s, 1);
s += (*s) + 1;
}
return(PTR_DIFF(s, s0) + 1);
trunc:
return(-1); /* name goes past the end of the buffer */
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
ssize_t ret;
size_t count = iov_length(iov, nr_segs);
loff_t final_size = offset + count;
if (rw == WRITE && final_size <= inode->i_size) {
/*
* We could direct write to holes and fallocate.
*
* Allocated blocks to fill the hole are marked as uninitialized
* to prevent paralel buffered read to expose the stale data
* before DIO complete the data IO.
*
* As to previously fallocated extents, ext4 get_block
* will just simply mark the buffer mapped but still
* keep the extents uninitialized.
*
* for non AIO case, we will convert those unwritten extents
* to written after return back from blockdev_direct_IO.
*
* for async DIO, the conversion needs to be defered when
* the IO is completed. The ext4 end_io callback function
* will be called to take care of the conversion work.
* Here for async case, we allocate an io_end structure to
* hook to the iocb.
*/
iocb->private = NULL;
EXT4_I(inode)->cur_aio_dio = NULL;
if (!is_sync_kiocb(iocb)) {
iocb->private = ext4_init_io_end(inode);
if (!iocb->private)
return -ENOMEM;
/*
* we save the io structure for current async
* direct IO, so that later ext4_get_blocks()
* could flag the io structure whether there
* is a unwritten extents needs to be converted
* when IO is completed.
*/
EXT4_I(inode)->cur_aio_dio = iocb->private;
}
ret = blockdev_direct_IO(rw, iocb, inode,
inode->i_sb->s_bdev, iov,
offset, nr_segs,
ext4_get_block_write,
ext4_end_io_dio);
if (iocb->private)
EXT4_I(inode)->cur_aio_dio = NULL;
/*
* The io_end structure takes a reference to the inode,
* that structure needs to be destroyed and the
* reference to the inode need to be dropped, when IO is
* complete, even with 0 byte write, or failed.
*
* In the successful AIO DIO case, the io_end structure will be
* desctroyed and the reference to the inode will be dropped
* after the end_io call back function is called.
*
* In the case there is 0 byte write, or error case, since
* VFS direct IO won't invoke the end_io call back function,
* we need to free the end_io structure here.
*/
if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
ext4_free_io_end(iocb->private);
iocb->private = NULL;
} else if (ret > 0 && ext4_test_inode_state(inode,
EXT4_STATE_DIO_UNWRITTEN)) {
int err;
/*
* for non AIO case, since the IO is already
* completed, we could do the convertion right here
*/
err = ext4_convert_unwritten_extents(inode,
offset, ret);
if (err < 0)
ret = err;
ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
}
return ret;
}
/* for write the the end of file case, we fall back to old way */
return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
}
CWE ID:
Target: 1
Example 2:
Code: static TEE_Result get_prop_tee_sys_time_prot_level(
struct tee_ta_session *sess __unused,
void *buf, size_t *blen)
{
uint32_t prot;
if (*blen < sizeof(prot)) {
*blen = sizeof(prot);
return TEE_ERROR_SHORT_BUFFER;
}
*blen = sizeof(prot);
prot = tee_time_get_sys_time_protection_level();
return tee_svc_copy_to_user(buf, &prot, sizeof(prot));
}
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 RenderProcessHostImpl::RegisterProcessHostForSite(
BrowserContext* browser_context,
RenderProcessHost* process,
const GURL& url) {
SiteProcessMap* map =
GetSiteProcessMapForBrowserContext(browser_context);
std::string site = SiteInstance::GetSiteForURL(browser_context, url)
.possibly_invalid_spec();
map->RegisterProcess(site, process);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
const unsigned char *sess_id, int sesslen,
SSL_SESSION **psess)
{
SSL_SESSION *sess;
unsigned char *sdec;
const unsigned char *p;
int slen, mlen, renew_ticket = 0;
unsigned char tick_hmac[EVP_MAX_MD_SIZE];
HMAC_CTX hctx;
EVP_CIPHER_CTX ctx;
SSL_CTX *tctx = s->initial_ctx;
/* Need at least keyname + iv + some encrypted data */
if (eticklen < 48)
return 2;
/* Initialize session ticket encryption and HMAC contexts */
HMAC_CTX_init(&hctx);
EVP_CIPHER_CTX_init(&ctx);
if (tctx->tlsext_ticket_key_cb)
{
unsigned char *nctick = (unsigned char *)etick;
int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16,
&ctx, &hctx, 0);
if (rv < 0)
return -1;
if (rv == 0)
return 2;
if (rv == 2)
renew_ticket = 1;
}
else
{
/* Check key name matches */
if (memcmp(etick, tctx->tlsext_tick_key_name, 16))
return 2;
HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
tlsext_tick_md(), NULL);
EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
tctx->tlsext_tick_aes_key, etick + 16);
}
/* Attempt to process session ticket, first conduct sanity and
* integrity checks on ticket.
*/
mlen = HMAC_size(&hctx);
if (mlen < 0)
{
EVP_CIPHER_CTX_cleanup(&ctx);
return -1;
}
eticklen -= mlen;
/* Check HMAC of encrypted ticket */
HMAC_Update(&hctx, etick, eticklen);
HMAC_Final(&hctx, tick_hmac, NULL);
HMAC_CTX_cleanup(&hctx);
if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen))
return 2;
/* Attempt to decrypt session data */
/* Move p after IV to start of encrypted ticket, update length */
p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
{
EVP_CIPHER_CTX_cleanup(&ctx);
return -1;
}
EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen);
if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0)
{
EVP_CIPHER_CTX_cleanup(&ctx);
OPENSSL_free(sdec);
return 2;
}
slen += mlen;
EVP_CIPHER_CTX_cleanup(&ctx);
p = sdec;
sess = d2i_SSL_SESSION(NULL, &p, slen);
OPENSSL_free(sdec);
if (sess)
{
/* The session ID, if non-empty, is used by some clients to
* detect that the ticket has been accepted. So we copy it to
* the session structure. If it is empty set length to zero
* as required by standard.
*/
if (sesslen)
memcpy(sess->session_id, sess_id, sesslen);
sess->session_id_length = sesslen;
*psess = sess;
if (renew_ticket)
return 4;
else
return 3;
}
ERR_clear_error();
/* For session parse failure, indicate that we need to send a new
* ticket. */
return 2;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: WordAwareIterator::~WordAwareIterator()
{
}
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: radeon_atombios_get_primary_dac_info(struct radeon_encoder *encoder)
{
struct drm_device *dev = encoder->base.dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_mode_info *mode_info = &rdev->mode_info;
int index = GetIndexIntoMasterTable(DATA, CompassionateData);
uint16_t data_offset;
struct _COMPASSIONATE_DATA *dac_info;
uint8_t frev, crev;
uint8_t bg, dac;
struct radeon_encoder_primary_dac *p_dac = NULL;
if (atom_parse_data_header(mode_info->atom_context, index, NULL,
&frev, &crev, &data_offset)) {
dac_info = (struct _COMPASSIONATE_DATA *)
(mode_info->atom_context->bios + data_offset);
p_dac = kzalloc(sizeof(struct radeon_encoder_primary_dac), GFP_KERNEL);
if (!p_dac)
return NULL;
bg = dac_info->ucDAC1_BG_Adjustment;
dac = dac_info->ucDAC1_DAC_Adjustment;
p_dac->ps2_pdac_adj = (bg << 8) | (dac);
}
return p_dac;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void perform_gamma_sbit_tests(png_modifier *pm)
{
png_byte sbit;
/* The only interesting cases are colour and grayscale, alpha is ignored here
* for overall speed. Only bit depths where sbit is less than the bit depth
* are tested.
*/
for (sbit=pm->sbitlow; sbit<(1<<READ_BDHI); ++sbit)
{
png_byte colour_type = 0, bit_depth = 0;
unsigned int npalette = 0;
while (next_format(&colour_type, &bit_depth, &npalette, 1/*gamma*/))
if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 &&
((colour_type == 3 && sbit < 8) ||
(colour_type != 3 && sbit < bit_depth)))
{
unsigned int i;
for (i=0; i<pm->ngamma_tests; ++i)
{
unsigned int j;
for (j=0; j<pm->ngamma_tests; ++j) if (i != j)
{
gamma_transform_test(pm, colour_type, bit_depth, npalette,
pm->interlace_type, 1/pm->gammas[i], pm->gammas[j],
sbit, pm->use_input_precision_sbit, 0 /*scale16*/);
if (fail(pm))
return;
}
}
}
}
}
CWE ID:
Target: 1
Example 2:
Code: PHP_FUNCTION(pg_connection_busy)
{
php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_IS_BUSY);
}
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 encrypted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct encrypted_key_payload *epayload = key->payload.data[0];
struct encrypted_key_payload *new_epayload;
char *buf;
char *new_master_desc = NULL;
const char *format = NULL;
size_t datalen = prep->datalen;
int ret = 0;
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags))
return -ENOKEY;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
buf = kmalloc(datalen + 1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
buf[datalen] = 0;
memcpy(buf, prep->data, datalen);
ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);
if (ret < 0)
goto out;
ret = valid_master_desc(new_master_desc, epayload->master_desc);
if (ret < 0)
goto out;
new_epayload = encrypted_key_alloc(key, epayload->format,
new_master_desc, epayload->datalen);
if (IS_ERR(new_epayload)) {
ret = PTR_ERR(new_epayload);
goto out;
}
__ekey_init(new_epayload, epayload->format, new_master_desc,
epayload->datalen);
memcpy(new_epayload->iv, epayload->iv, ivsize);
memcpy(new_epayload->payload_data, epayload->payload_data,
epayload->payload_datalen);
rcu_assign_keypointer(key, new_epayload);
call_rcu(&epayload->rcu, encrypted_rcu_free);
out:
kzfree(buf);
return ret;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void free_huge_page(struct page *page)
{
/*
* Can't pass hstate in here because it is called from the
* compound page destructor.
*/
struct hstate *h = page_hstate(page);
int nid = page_to_nid(page);
struct address_space *mapping;
mapping = (struct address_space *) page_private(page);
set_page_private(page, 0);
page->mapping = NULL;
BUG_ON(page_count(page));
BUG_ON(page_mapcount(page));
INIT_LIST_HEAD(&page->lru);
spin_lock(&hugetlb_lock);
if (h->surplus_huge_pages_node[nid] && huge_page_order(h) < MAX_ORDER) {
update_and_free_page(h, page);
h->surplus_huge_pages--;
h->surplus_huge_pages_node[nid]--;
} else {
enqueue_huge_page(h, page);
}
spin_unlock(&hugetlb_lock);
if (mapping)
hugetlb_put_quota(mapping, 1);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: mainloop_del_fd(mainloop_io_t *client)
{
if(client != NULL) {
crm_trace("Removing client %s[%p] %d", client->name, client, mainloop_gio_refcount(client));
if (client->source) {
/* Results in mainloop_gio_destroy() being called just
* before the source is removed from mainloop
*/
g_source_remove(client->source);
}
}
}
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 RenderWidgetHostImpl::GetSnapshotFromBrowser(
const GetSnapshotFromBrowserCallback& callback,
bool from_surface) {
int id = next_browser_snapshot_id_++;
if (from_surface) {
pending_surface_browser_snapshots_.insert(std::make_pair(id, callback));
ui::LatencyInfo latency_info;
latency_info.AddLatencyNumber(ui::BROWSER_SNAPSHOT_FRAME_NUMBER_COMPONENT,
0, id);
Send(new ViewMsg_ForceRedraw(GetRoutingID(), latency_info));
return;
}
#if defined(OS_MACOSX)
if (pending_browser_snapshots_.empty())
GetWakeLock()->RequestWakeLock();
#endif
pending_browser_snapshots_.insert(std::make_pair(id, callback));
ui::LatencyInfo latency_info;
latency_info.AddLatencyNumber(ui::BROWSER_SNAPSHOT_FRAME_NUMBER_COMPONENT, 0,
id);
Send(new ViewMsg_ForceRedraw(GetRoutingID(), latency_info));
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ExtensionTtsPlatformImplWin::ExtensionTtsPlatformImplWin()
: speech_synthesizer_(NULL),
paused_(false) {
CoCreateInstance(
CLSID_SpVoice,
NULL,
CLSCTX_SERVER,
IID_ISpVoice,
reinterpret_cast<void**>(&speech_synthesizer_));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: ScopedResolvedFrameBufferBinder::~ScopedResolvedFrameBufferBinder() {
if (!resolve_and_bind_)
return;
ScopedGLErrorSuppressor suppressor(
"ScopedResolvedFrameBufferBinder::dtor", decoder_->GetErrorState());
decoder_->RestoreCurrentFramebufferBindings();
if (decoder_->state_.enable_flags.scissor_test) {
decoder_->state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, true);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: LockScreenMediaControlsView::LockScreenMediaControlsView(
service_manager::Connector* connector,
const Callbacks& callbacks)
: connector_(connector),
hide_controls_timer_(new base::OneShotTimer()),
media_controls_enabled_(callbacks.media_controls_enabled),
hide_media_controls_(callbacks.hide_media_controls),
show_media_controls_(callbacks.show_media_controls) {
DCHECK(callbacks.media_controls_enabled);
DCHECK(callbacks.hide_media_controls);
DCHECK(callbacks.show_media_controls);
Shell::Get()->media_controller()->SetMediaControlsDismissed(false);
middle_spacing_ = std::make_unique<NonAccessibleView>();
middle_spacing_->set_owned_by_client();
set_notify_enter_exit_on_child(true);
contents_view_ = AddChildView(std::make_unique<views::View>());
contents_view_->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical));
contents_view_->SetBackground(views::CreateRoundedRectBackground(
kMediaControlsBackground, kMediaControlsCornerRadius));
contents_view_->SetPaintToLayer(); // Needed for opacity animation.
contents_view_->layer()->SetFillsBoundsOpaquely(false);
auto close_button_row = std::make_unique<NonAccessibleView>();
views::GridLayout* close_button_layout =
close_button_row->SetLayoutManager(std::make_unique<views::GridLayout>());
views::ColumnSet* columns = close_button_layout->AddColumnSet(0);
columns->AddPaddingColumn(0, kCloseButtonOffset);
columns->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,
views::GridLayout::USE_PREF, 0, 0);
close_button_layout->StartRowWithPadding(
0, 0, 0, 5 /* padding between close button and top of view */);
auto close_button = CreateVectorImageButton(this);
SetImageFromVectorIcon(close_button.get(), vector_icons::kCloseRoundedIcon,
kCloseButtonIconSize, gfx::kGoogleGrey700);
close_button->SetPreferredSize(kCloseButtonSize);
close_button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
base::string16 close_button_label(
l10n_util::GetStringUTF16(IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_CLOSE));
close_button->SetAccessibleName(close_button_label);
close_button_ = close_button_layout->AddView(std::move(close_button));
close_button_->SetVisible(false);
contents_view_->AddChildView(std::move(close_button_row));
header_row_ =
contents_view_->AddChildView(std::make_unique<MediaControlsHeaderView>());
auto session_artwork = std::make_unique<views::ImageView>();
session_artwork->SetPreferredSize(
gfx::Size(kArtworkViewWidth, kArtworkViewHeight));
session_artwork->SetBorder(views::CreateEmptyBorder(kArtworkInsets));
session_artwork_ = contents_view_->AddChildView(std::move(session_artwork));
progress_ = contents_view_->AddChildView(
std::make_unique<media_message_center::MediaControlsProgressView>(
base::BindRepeating(&LockScreenMediaControlsView::SeekTo,
base::Unretained(this))));
auto button_row = std::make_unique<NonAccessibleView>();
auto* button_row_layout =
button_row->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, kButtonRowInsets,
kMediaButtonRowSeparator));
button_row_layout->set_cross_axis_alignment(
views::BoxLayout::CrossAxisAlignment::kCenter);
button_row_layout->set_main_axis_alignment(
views::BoxLayout::MainAxisAlignment::kCenter);
button_row->SetPreferredSize(kMediaControlsButtonRowSize);
button_row_ = contents_view_->AddChildView(std::move(button_row));
CreateMediaButton(
kChangeTrackIconSize, MediaSessionAction::kPreviousTrack,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PREVIOUS_TRACK));
CreateMediaButton(
kSeekingIconsSize, MediaSessionAction::kSeekBackward,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_BACKWARD));
auto play_pause_button = views::CreateVectorToggleImageButton(this);
play_pause_button->set_tag(static_cast<int>(MediaSessionAction::kPause));
play_pause_button->SetPreferredSize(kMediaButtonSize);
play_pause_button->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
play_pause_button->SetTooltipText(l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PAUSE));
play_pause_button->SetToggledTooltipText(l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PLAY));
play_pause_button_ = button_row_->AddChildView(std::move(play_pause_button));
views::SetImageFromVectorIcon(
play_pause_button_,
GetVectorIconForMediaAction(MediaSessionAction::kPause),
kPlayPauseIconSize, kMediaButtonColor);
views::SetToggledImageFromVectorIcon(
play_pause_button_,
GetVectorIconForMediaAction(MediaSessionAction::kPlay),
kPlayPauseIconSize, kMediaButtonColor);
CreateMediaButton(
kSeekingIconsSize, MediaSessionAction::kSeekForward,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_FORWARD));
CreateMediaButton(kChangeTrackIconSize, MediaSessionAction::kNextTrack,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_NEXT_TRACK));
MediaSessionMetadataChanged(base::nullopt);
MediaSessionPositionChanged(base::nullopt);
MediaControllerImageChanged(
media_session::mojom::MediaSessionImageType::kSourceIcon, SkBitmap());
SetArtwork(base::nullopt);
if (!connector_)
return;
mojo::Remote<media_session::mojom::MediaControllerManager>
controller_manager_remote;
connector_->Connect(media_session::mojom::kServiceName,
controller_manager_remote.BindNewPipeAndPassReceiver());
controller_manager_remote->CreateActiveMediaController(
media_controller_remote_.BindNewPipeAndPassReceiver());
media_controller_remote_->AddObserver(
observer_receiver_.BindNewPipeAndPassRemote());
media_controller_remote_->ObserveImages(
media_session::mojom::MediaSessionImageType::kArtwork,
kMinimumArtworkSize, kDesiredArtworkSize,
artwork_observer_receiver_.BindNewPipeAndPassRemote());
media_controller_remote_->ObserveImages(
media_session::mojom::MediaSessionImageType::kSourceIcon,
kMinimumIconSize, kDesiredIconSize,
icon_observer_receiver_.BindNewPipeAndPassRemote());
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
double
length,
maximum_length,
offset,
scale,
total_length;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register ssize_t
i;
register double
dx,
dy;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+1UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*(draw_info->dash_pattern[0]-0.5);
offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*(draw_info->dash_pattern[n]+0.5);
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; (i < number_vertices) && (length >= 0.0); i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot((double) dx,dy);
if (length == 0.0)
{
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
j=1;
}
else
{
if ((j+1) > (ssize_t) (2*number_vertices))
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length/maximum_length);
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length/maximum_length);
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
n++;
if (draw_info->dash_pattern[n] == 0.0)
n=0;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=MagickEpsilon;
dash_polygon[j].point.y+=MagickEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
if (cpu_has_secondary_exec_ctrls()) {
vmx_compute_secondary_exec_control(vmx);
vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
}
if (nested_vmx_allowed(vcpu))
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
else
to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
if (nested_vmx_allowed(vcpu))
nested_vmx_cr_fixed1_bits_update(vcpu);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const std::string& GetBuffer() {
if (!has_accept_header_) {
if (!buffer_.empty())
buffer_.append("\r\n");
buffer_.append("Accept: */*");
has_accept_header_ = true;
}
return buffer_;
}
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: spnego_gss_inquire_context(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
OM_uint32 ret = GSS_S_COMPLETE;
ret = gss_inquire_context(minor_status,
context_handle,
src_name,
targ_name,
lifetime_rec,
mech_type,
ctx_flags,
locally_initiated,
opened);
return (ret);
}
CWE ID: CWE-18
Target: 1
Example 2:
Code: void CreateDownloadFile(scoped_ptr<DownloadCreateInfo> info) {
download_file_manager_->CreateDownloadFile(
info.Pass(), scoped_ptr<content::ByteStreamReader>(),
download_manager_, true, net::BoundNetLog(),
base::Bind(&DownloadFileManagerTest::OnDownloadFileCreated,
base::Unretained(this)));
last_reason_ = content::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED;
ProcessAllPendingMessages();
EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE, last_reason_);
}
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: cib_remote_connection_destroy(gpointer user_data)
{
cib_client_t *client = user_data;
if (client == NULL) {
return;
}
crm_trace("Cleaning up after client disconnect: %s/%s",
crm_str(client->name), client->id);
if (client->id != NULL) {
if (!g_hash_table_remove(client_list, client->id)) {
crm_err("Client %s not found in the hashtable", client->name);
}
}
crm_trace("Destroying %s (%p)", client->name, user_data);
num_clients--;
crm_trace("Num unfree'd clients: %d", num_clients);
free(client->name);
free(client->callback_id);
free(client->id);
free(client->user);
free(client);
crm_trace("Freed the cib client");
if (cib_shutdown_flag) {
cib_shutdown(0);
}
return;
}
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: alloc_limit_assert (char *fn_name, size_t size)
{
if (alloc_limit && size > alloc_limit)
{
alloc_limit_failure (fn_name, size);
exit (-1);
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: int mk_vhost_open(struct session_request *sr)
{
int id;
int off;
unsigned int hash;
off = sr->host_conf->documentroot.len;
hash = mk_utils_gen_hash(sr->real_path.data + off,
sr->real_path.len - off);
id = (hash % VHOST_FDT_HASHTABLE_SIZE);
return mk_vhost_fdt_open(id, hash, sr);
}
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: crm_node_created(xmlNode *xml)
{
xmlNode *cIter = NULL;
xml_private_t *p = xml->_private;
if(p && TRACKING_CHANGES(xml)) {
if(is_not_set(p->flags, xpf_created)) {
p->flags |= xpf_created;
__xml_node_dirty(xml);
}
for (cIter = __xml_first_child(xml); cIter != NULL; cIter = __xml_next(cIter)) {
crm_node_created(cIter);
}
}
}
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 v8::Handle<v8::Value> uniformHelperi(const v8::Arguments& args,
FunctionToCall functionToCall) {
if (args.Length() != 2)
return V8Proxy::throwNotEnoughArgumentsError();
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
bool ok = false;
WebGLUniformLocation* location = toWebGLUniformLocation(args[0], ok);
if (V8Int32Array::HasInstance(args[1])) {
Int32Array* array = V8Int32Array::toNative(args[1]->ToObject());
ASSERT(array != NULL);
ExceptionCode ec = 0;
switch (functionToCall) {
case kUniform1v: context->uniform1iv(location, array, ec); break;
case kUniform2v: context->uniform2iv(location, array, ec); break;
case kUniform3v: context->uniform3iv(location, array, ec); break;
case kUniform4v: context->uniform4iv(location, array, ec); break;
default: ASSERT_NOT_REACHED(); break;
}
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
if (args[1].IsEmpty() || !args[1]->IsArray()) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
v8::Handle<v8::Array> array =
v8::Local<v8::Array>::Cast(args[1]);
uint32_t len = array->Length();
int* data = jsArrayToIntArray(array, len);
if (!data) {
V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate());
return notHandledByInterceptor();
}
ExceptionCode ec = 0;
switch (functionToCall) {
case kUniform1v: context->uniform1iv(location, data, len, ec); break;
case kUniform2v: context->uniform2iv(location, data, len, ec); break;
case kUniform3v: context->uniform3iv(location, data, len, ec); break;
case kUniform4v: context->uniform4iv(location, data, len, ec); break;
default: ASSERT_NOT_REACHED(); break;
}
fastFree(data);
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
CWE ID:
Target: 1
Example 2:
Code: GURL Extension::GetFullLaunchURL() const {
if (!launch_local_path().empty())
return url().Resolve(launch_local_path());
else
return GURL(launch_web_url());
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebPluginProxy::SetAcceleratedSurface(
gfx::PluginWindowHandle window,
const gfx::Size& size,
uint64 accelerated_surface_identifier) {
Send(new PluginHostMsg_AcceleratedSurfaceSetIOSurface(
route_id_, window, size.width(), size.height(),
accelerated_surface_identifier));
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ResourceDispatcherHostImpl::AcceptAuthRequest(
ResourceLoader* loader,
net::AuthChallengeInfo* auth_info) {
if (delegate_ && !delegate_->AcceptAuthRequest(loader->request(), auth_info))
return false;
if (!auth_info->is_proxy) {
HttpAuthResourceType resource_type =
HttpAuthResourceTypeOf(loader->request());
UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthResource",
resource_type,
HTTP_AUTH_RESOURCE_LAST);
if (resource_type == HTTP_AUTH_RESOURCE_BLOCKED_CROSS)
return false;
}
return true;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: poly_overlap(PG_FUNCTION_ARGS)
{
POLYGON *polya = PG_GETARG_POLYGON_P(0);
POLYGON *polyb = PG_GETARG_POLYGON_P(1);
bool result;
/* Quick check by bounding box */
result = (polya->npts > 0 && polyb->npts > 0 &&
box_ov(&polya->boundbox, &polyb->boundbox)) ? true : false;
/*
* Brute-force algorithm - try to find intersected edges, if so then
* polygons are overlapped else check is one polygon inside other or not
* by testing single point of them.
*/
if (result)
{
int ia,
ib;
LSEG sa,
sb;
/* Init first of polya's edge with last point */
sa.p[0] = polya->p[polya->npts - 1];
result = false;
for (ia = 0; ia < polya->npts && result == false; ia++)
{
/* Second point of polya's edge is a current one */
sa.p[1] = polya->p[ia];
/* Init first of polyb's edge with last point */
sb.p[0] = polyb->p[polyb->npts - 1];
for (ib = 0; ib < polyb->npts && result == false; ib++)
{
sb.p[1] = polyb->p[ib];
result = lseg_intersect_internal(&sa, &sb);
sb.p[0] = sb.p[1];
}
/*
* move current endpoint to the first point of next edge
*/
sa.p[0] = sa.p[1];
}
if (result == false)
{
result = (point_inside(polya->p, polyb->npts, polyb->p)
||
point_inside(polyb->p, polya->npts, polya->p));
}
}
/*
* Avoid leaking memory for toasted inputs ... needed for rtree indexes
*/
PG_FREE_IF_COPY(polya, 0);
PG_FREE_IF_COPY(polyb, 1);
PG_RETURN_BOOL(result);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: wkbConvGeometryToShape(wkbObj *w, shapeObj *shape)
{
int wkbtype = wkbType(w); /* Peak at the type number */
switch(wkbtype) {
/* Recurse into anonymous collections */
case WKB_GEOMETRYCOLLECTION:
return wkbConvCollectionToShape(w, shape);
/* Handle area types */
case WKB_POLYGON:
return wkbConvPolygonToShape(w, shape);
case WKB_MULTIPOLYGON:
return wkbConvCollectionToShape(w, shape);
case WKB_CURVEPOLYGON:
return wkbConvCurvePolygonToShape(w, shape);
case WKB_MULTISURFACE:
return wkbConvCollectionToShape(w, shape);
}
/* We can't convert any of the following types into polygons */
if ( shape->type == MS_SHAPE_POLYGON ) return MS_FAILURE;
/* Handle linear types */
switch(wkbtype) {
case WKB_LINESTRING:
return wkbConvLineStringToShape(w, shape);
case WKB_CIRCULARSTRING:
return wkbConvCircularStringToShape(w, shape);
case WKB_COMPOUNDCURVE:
return wkbConvCompoundCurveToShape(w, shape);
case WKB_MULTILINESTRING:
return wkbConvCollectionToShape(w, shape);
case WKB_MULTICURVE:
return wkbConvCollectionToShape(w, shape);
}
/* We can't convert any of the following types into lines */
if ( shape->type == MS_SHAPE_LINE ) return MS_FAILURE;
/* Handle point types */
switch(wkbtype) {
case WKB_POINT:
return wkbConvPointToShape(w, shape);
case WKB_MULTIPOINT:
return wkbConvCollectionToShape(w, shape);
}
/* This is a WKB type we don't know about! */
return MS_FAILURE;
}
CWE ID: CWE-89
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: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return (*field_rtrn != NULL);
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return true;
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: BrowserNonClientFrameViewAura::BrowserNonClientFrameViewAura(
BrowserFrame* frame, BrowserView* browser_view)
: BrowserNonClientFrameView(frame, browser_view),
maximize_button_(NULL),
close_button_(NULL),
window_icon_(NULL),
frame_painter_(new ash::FramePainter) {
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool TabStrip::NeedsTouchLayout() const {
if (!stacked_layout_)
return false;
const int pinned_tab_count = GetPinnedTabCount();
const int normal_count = tab_count() - pinned_tab_count;
if (normal_count <= 1)
return false;
const int tab_overlap = TabStyle::GetTabOverlap();
const int normal_width =
(GetStackableTabWidth() - tab_overlap) * normal_count + tab_overlap;
const int pinned_width =
std::max(0, pinned_tab_count * TabStyle::GetPinnedWidth() - tab_overlap);
return normal_width > (GetTabAreaWidth() - pinned_width);
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly)
{
ASSERT(&topResolver.runs() == &bidiRuns);
ASSERT(topResolver.position() != endOfRuns);
RenderObject* currentRoot = topResolver.position().root();
topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly);
while (!topResolver.isolatedRuns().isEmpty()) {
BidiRun* isolatedRun = topResolver.isolatedRuns().last();
topResolver.isolatedRuns().removeLast();
RenderObject* startObj = isolatedRun->object();
RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot));
InlineBidiResolver isolatedResolver;
EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();
TextDirection direction = isolatedInline->style()->direction();
if (unicodeBidi == Plaintext)
direction = determinePlaintextDirectionality(isolatedInline, startObj);
else {
ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride);
direction = isolatedInline->style()->direction();
}
isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi)));
setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj);
InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start);
isolatedResolver.setPositionIgnoringNestedIsolates(iter);
isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly);
if (isolatedResolver.runs().runCount())
bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs());
if (!isolatedResolver.isolatedRuns().isEmpty()) {
topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns());
isolatedResolver.isolatedRuns().clear();
currentRoot = isolatedInline;
}
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void analyzeDatabase(Parse *pParse, int iDb){
sqlite3 *db = pParse->db;
Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
HashElem *k;
int iStatCur;
int iMem;
int iTab;
sqlite3BeginWriteOperation(pParse, 0, iDb);
iStatCur = pParse->nTab;
pParse->nTab += 3;
openStatTable(pParse, iDb, iStatCur, 0, 0);
iMem = pParse->nMem+1;
iTab = pParse->nTab;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
Table *pTab = (Table*)sqliteHashData(k);
analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
}
loadAnalysis(pParse, iDb);
}
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: zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
struct zip_entry *rsrc)
{
struct zip *zip = (struct zip *)a->format->data;
unsigned char *metadata, *mp;
int64_t offset = archive_filter_bytes(&a->archive, 0);
size_t remaining_bytes, metadata_bytes;
ssize_t hsize;
int ret = ARCHIVE_OK, eof;
switch(rsrc->compression) {
case 0: /* No compression. */
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
#endif
break;
default: /* Unsupported compression. */
/* Return a warning. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported ZIP compression method (%s)",
compression_name(rsrc->compression));
/* We can't decompress this entry, but we will
* be able to skip() it and try the next entry. */
return (ARCHIVE_WARN);
}
if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Mac metadata is too large: %jd > 4M bytes",
(intmax_t)rsrc->uncompressed_size);
return (ARCHIVE_WARN);
}
metadata = malloc((size_t)rsrc->uncompressed_size);
if (metadata == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Mac metadata");
return (ARCHIVE_FATAL);
}
if (offset < rsrc->local_header_offset)
__archive_read_consume(a, rsrc->local_header_offset - offset);
else if (offset != rsrc->local_header_offset) {
__archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
}
hsize = zip_get_local_file_header_size(a, 0);
__archive_read_consume(a, hsize);
remaining_bytes = (size_t)rsrc->compressed_size;
metadata_bytes = (size_t)rsrc->uncompressed_size;
mp = metadata;
eof = 0;
while (!eof && remaining_bytes) {
const unsigned char *p;
ssize_t bytes_avail;
size_t bytes_used;
p = __archive_read_ahead(a, 1, &bytes_avail);
if (p == NULL) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
ret = ARCHIVE_WARN;
goto exit_mac_metadata;
}
if ((size_t)bytes_avail > remaining_bytes)
bytes_avail = remaining_bytes;
switch(rsrc->compression) {
case 0: /* No compression. */
memcpy(mp, p, bytes_avail);
bytes_used = (size_t)bytes_avail;
metadata_bytes -= bytes_used;
mp += bytes_used;
if (metadata_bytes == 0)
eof = 1;
break;
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
{
int r;
ret = zip_deflate_init(a, zip);
if (ret != ARCHIVE_OK)
goto exit_mac_metadata;
zip->stream.next_in =
(Bytef *)(uintptr_t)(const void *)p;
zip->stream.avail_in = (uInt)bytes_avail;
zip->stream.total_in = 0;
zip->stream.next_out = mp;
zip->stream.avail_out = (uInt)metadata_bytes;
zip->stream.total_out = 0;
r = inflate(&zip->stream, 0);
switch (r) {
case Z_OK:
break;
case Z_STREAM_END:
eof = 1;
break;
case Z_MEM_ERROR:
archive_set_error(&a->archive, ENOMEM,
"Out of memory for ZIP decompression");
ret = ARCHIVE_FATAL;
goto exit_mac_metadata;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"ZIP decompression failed (%d)", r);
ret = ARCHIVE_FATAL;
goto exit_mac_metadata;
}
bytes_used = zip->stream.total_in;
metadata_bytes -= zip->stream.total_out;
mp += zip->stream.total_out;
break;
}
#endif
default:
bytes_used = 0;
break;
}
__archive_read_consume(a, bytes_used);
remaining_bytes -= bytes_used;
}
archive_entry_copy_mac_metadata(entry, metadata,
(size_t)rsrc->uncompressed_size - metadata_bytes);
exit_mac_metadata:
__archive_read_seek(a, offset, SEEK_SET);
zip->decompress_init = 0;
free(metadata);
return (ret);
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
WebContentsImpl* old_contents = GetFocusedWebContents();
if (old_contents == this)
return;
GetOutermostWebContents()->node_.SetFocusedWebContents(this);
if (!GuestMode::IsCrossProcessFrameGuest(this) && browser_plugin_guest_)
return;
if (old_contents)
old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
if (GetRenderManager()->GetProxyToOuterDelegate())
GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
if (ShowingInterstitialPage()) {
static_cast<RenderFrameHostImpl*>(
GetRenderManager()->interstitial_page()->GetMainFrame())
->GetRenderWidgetHost()
->SetPageFocus(true);
} else {
GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: base::FilePath WebRunnerBrowserContext::GetPath() const {
return data_dir_path_;
}
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 int inotify_fasync(int fd, struct file *file, int on)
{
struct fsnotify_group *group = file->private_data;
return fasync_helper(fd, file, on, &group->inotify_data.fa) >= 0 ? 0 : -EIO;
}
CWE ID: CWE-399
Output: | 0 |
Subsets and Splits