prompt
stringlengths 799
20.4k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool SessionService::CreateTabsAndWindows(
const std::vector<SessionCommand*>& data,
std::map<int, SessionTab*>* tabs,
std::map<int, SessionWindow*>* windows) {
for (std::vector<SessionCommand*>::const_iterator i = data.begin();
i != data.end(); ++i) {
const SessionCommand::id_type kCommandSetWindowBounds2 = 10;
const SessionCommand* command = *i;
switch (command->id()) {
case kCommandSetTabWindow: {
SessionID::id_type payload[2];
if (!command->GetPayload(payload, sizeof(payload)))
return true;
GetTab(payload[1], tabs)->window_id.set_id(payload[0]);
break;
}
case kCommandSetWindowBounds2: {
WindowBoundsPayload2 payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x,
payload.y,
payload.w,
payload.h);
GetWindow(payload.window_id, windows)->show_state =
payload.is_maximized ?
ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL;
break;
}
case kCommandSetWindowBounds3: {
WindowBoundsPayload3 payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x,
payload.y,
payload.w,
payload.h);
ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL;
if (payload.show_state > ui::SHOW_STATE_DEFAULT &&
payload.show_state < ui::SHOW_STATE_END &&
payload.show_state != ui::SHOW_STATE_INACTIVE) {
show_state = static_cast<ui::WindowShowState>(payload.show_state);
} else {
NOTREACHED();
}
GetWindow(payload.window_id, windows)->show_state = show_state;
break;
}
case kCommandSetTabIndexInWindow: {
TabIndexInWindowPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetTab(payload.id, tabs)->tab_visual_index = payload.index;
break;
}
case kCommandTabClosed:
case kCommandWindowClosed: {
ClosedPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
if (command->id() == kCommandTabClosed) {
delete GetTab(payload.id, tabs);
tabs->erase(payload.id);
} else {
delete GetWindow(payload.id, windows);
windows->erase(payload.id);
}
break;
}
case kCommandTabNavigationPathPrunedFromBack: {
TabNavigationPathPrunedFromBackPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
SessionTab* tab = GetTab(payload.id, tabs);
tab->navigations.erase(
FindClosestNavigationWithIndex(&(tab->navigations), payload.index),
tab->navigations.end());
break;
}
case kCommandTabNavigationPathPrunedFromFront: {
TabNavigationPathPrunedFromFrontPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)) ||
payload.index <= 0) {
return true;
}
SessionTab* tab = GetTab(payload.id, tabs);
tab->current_navigation_index =
std::max(-1, tab->current_navigation_index - payload.index);
for (std::vector<TabNavigation>::iterator i = tab->navigations.begin();
i != tab->navigations.end();) {
i->set_index(i->index() - payload.index);
if (i->index() < 0)
i = tab->navigations.erase(i);
else
++i;
}
break;
}
case kCommandUpdateTabNavigation: {
TabNavigation navigation;
SessionID::id_type tab_id;
if (!RestoreUpdateTabNavigationCommand(*command, &navigation, &tab_id))
return true;
SessionTab* tab = GetTab(tab_id, tabs);
std::vector<TabNavigation>::iterator i =
FindClosestNavigationWithIndex(&(tab->navigations),
navigation.index());
if (i != tab->navigations.end() && i->index() == navigation.index())
*i = navigation;
else
tab->navigations.insert(i, navigation);
break;
}
case kCommandSetSelectedNavigationIndex: {
SelectedNavigationIndexPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetTab(payload.id, tabs)->current_navigation_index = payload.index;
break;
}
case kCommandSetSelectedTabInIndex: {
SelectedTabInIndexPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetWindow(payload.id, windows)->selected_tab_index = payload.index;
break;
}
case kCommandSetWindowType: {
WindowTypePayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetWindow(payload.id, windows)->is_constrained = false;
GetWindow(payload.id, windows)->type =
BrowserTypeForWindowType(
static_cast<WindowType>(payload.index));
break;
}
case kCommandSetPinnedState: {
PinnedStatePayload payload;
if (!command->GetPayload(&payload, sizeof(payload)))
return true;
GetTab(payload.tab_id, tabs)->pinned = payload.pinned_state;
break;
}
case kCommandSetExtensionAppID: {
SessionID::id_type tab_id;
std::string extension_app_id;
if (!RestoreSetTabExtensionAppIDCommand(
*command, &tab_id, &extension_app_id)) {
return true;
}
GetTab(tab_id, tabs)->extension_app_id.swap(extension_app_id);
break;
}
default:
return true;
}
}
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int ignore_interface_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: pdf_set_cmap_wmode(fz_context *ctx, pdf_cmap *cmap, int wmode)
{
cmap->wmode = wmode;
}
CWE ID: CWE-416
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PrintRenderFrameHelper::CopyMetafileDataToSharedMem(
const PdfMetafileSkia& metafile,
base::SharedMemoryHandle* shared_mem_handle) {
uint32_t buf_size = metafile.GetDataSize();
if (buf_size == 0)
return false;
std::unique_ptr<base::SharedMemory> shared_buf(
content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(buf_size));
if (!shared_buf)
return false;
if (!shared_buf->Map(buf_size))
return false;
if (!metafile.GetData(shared_buf->memory(), buf_size))
return false;
*shared_mem_handle =
base::SharedMemory::DuplicateHandle(shared_buf->handle());
return true;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: String AXObject::textFromAriaDescribedby(
AXRelatedObjectVector* relatedObjects) const {
AXObjectSet visited;
HeapVector<Member<Element>> elements;
elementsFromAttribute(elements, aria_describedbyAttr);
return textFromElements(true, visited, elements, relatedObjects);
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DownloadFileManager::CancelDownloadOnRename(
DownloadId global_id, net::Error rename_error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
DownloadFile* download_file = GetDownloadFile(global_id);
if (!download_file)
return;
DownloadManager* download_manager = download_file->GetDownloadManager();
DCHECK(download_manager);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&DownloadManager::OnDownloadInterrupted,
download_manager,
global_id.local(),
download_file->BytesSoFar(),
download_file->GetHashState(),
content::ConvertNetErrorToInterruptReason(
rename_error,
content::DOWNLOAD_INTERRUPT_FROM_DISK)));
}
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: WORD32 ih264d_end_of_pic(dec_struct_t *ps_dec,
UWORD8 u1_is_idr_slice,
UWORD16 u2_frame_num)
{
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
WORD32 ret;
ps_dec->u1_first_pb_nal_in_pic = 1;
ps_dec->u2_mbx = 0xffff;
ps_dec->u2_mby = 0;
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_err->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return ERROR_NEW_FRAME_EXPECTED;
}
}
H264_MUTEX_LOCK(&ps_dec->process_disp_mutex);
ret = ih264d_end_of_pic_processing(ps_dec);
if(ret != OK)
return ret;
ps_dec->u2_total_mbs_coded = 0;
/*--------------------------------------------------------------------*/
/* ih264d_decode_pic_order_cnt - calculate the Pic Order Cnt */
/* Needed to detect end of picture */
/*--------------------------------------------------------------------*/
{
pocstruct_t *ps_prev_poc = &ps_dec->s_prev_pic_poc;
pocstruct_t *ps_cur_poc = &ps_dec->s_cur_pic_poc;
if((0 == u1_is_idr_slice) && ps_cur_slice->u1_nal_ref_idc)
ps_dec->u2_prev_ref_frame_num = ps_cur_slice->u2_frame_num;
if(u1_is_idr_slice || ps_cur_slice->u1_mmco_equalto5)
ps_dec->u2_prev_ref_frame_num = 0;
if(ps_dec->ps_cur_sps->u1_gaps_in_frame_num_value_allowed_flag)
{
ret = ih264d_decode_gaps_in_frame_num(ps_dec, u2_frame_num);
if(ret != OK)
return ret;
}
ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst;
ps_prev_poc->u2_frame_num = ps_cur_poc->u2_frame_num;
ps_prev_poc->u1_mmco_equalto5 = ps_cur_slice->u1_mmco_equalto5;
if(ps_cur_slice->u1_nal_ref_idc)
{
ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb;
ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb;
ps_prev_poc->i4_delta_pic_order_cnt_bottom =
ps_cur_poc->i4_delta_pic_order_cnt_bottom;
ps_prev_poc->i4_delta_pic_order_cnt[0] =
ps_cur_poc->i4_delta_pic_order_cnt[0];
ps_prev_poc->i4_delta_pic_order_cnt[1] =
ps_cur_poc->i4_delta_pic_order_cnt[1];
ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field;
}
}
H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex);
return OK;
}
CWE ID: CWE-172
Target: 1
Example 2:
Code: GpuCommandBufferMemoryTracker(GpuChannel* channel) {
gpu_memory_manager_tracking_group_ = new GpuMemoryTrackingGroup(
channel->renderer_pid(),
this,
channel->gpu_channel_manager()->gpu_memory_manager());
}
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 MaybeRestoreIBusConfig() {
if (!ibus_) {
return;
}
MaybeDestroyIBusConfig();
if (!ibus_config_) {
GDBusConnection* ibus_connection = ibus_bus_get_connection(ibus_);
if (!ibus_connection) {
LOG(INFO) << "Couldn't create an ibus config object since "
<< "IBus connection is not ready.";
return;
}
const gboolean disconnected
= g_dbus_connection_is_closed(ibus_connection);
if (disconnected) {
LOG(ERROR) << "Couldn't create an ibus config object since "
<< "IBus connection is closed.";
return;
}
ibus_config_ = ibus_config_new(ibus_connection,
NULL /* do not cancel the operation */,
NULL /* do not get error information */);
if (!ibus_config_) {
LOG(ERROR) << "ibus_config_new() failed. ibus-memconf is not ready?";
return;
}
g_object_ref(ibus_config_);
LOG(INFO) << "ibus_config_ is ready.";
}
}
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: SimpleBlock::SimpleBlock(
Cluster* pCluster,
long idx,
long long start,
long long size) :
BlockEntry(pCluster, idx),
m_block(start, size, 0)
{
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: zdeletefile(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
gs_parsed_file_name_t pname;
int code = parse_real_file_name(op, &pname, imemory, "deletefile");
if (code < 0)
return code;
if (pname.iodev == iodev_default(imemory)) {
if ((code = check_file_permissions(i_ctx_p, pname.fname, pname.len,
"PermitFileControl")) < 0 &&
!file_is_tempfile(i_ctx_p, op->value.bytes, r_size(op))) {
return code;
}
}
code = (*pname.iodev->procs.delete_file)(pname.iodev, pname.fname);
gs_free_file_name(&pname, "deletefile");
if (code < 0)
return code;
pop(1);
return 0;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int DCTStream::readBit() {
int bit;
int c, c2;
if (inputBits == 0) {
if ((c = str->getChar()) == EOF)
return EOF;
if (c == 0xff) {
do {
c2 = str->getChar();
} while (c2 == 0xff);
if (c2 != 0x00) {
error(errSyntaxError, getPos(), "Bad DCT data: missing 00 after ff");
return EOF;
}
}
inputBuf = c;
inputBits = 8;
}
bit = (inputBuf >> (inputBits - 1)) & 1;
--inputBits;
return bit;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int g2m_init_buffers(G2MContext *c)
{
int aligned_height;
if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
c->framebuf_stride = FFALIGN(c->width * 3, 16);
aligned_height = FFALIGN(c->height, 16);
av_free(c->framebuf);
c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
if (!c->framebuf)
return AVERROR(ENOMEM);
}
if (!c->synth_tile || !c->jpeg_tile ||
c->old_tile_w < c->tile_width ||
c->old_tile_h < c->tile_height) {
c->tile_stride = FFALIGN(c->tile_width * 3, 16);
aligned_height = FFALIGN(c->tile_height, 16);
av_free(c->synth_tile);
av_free(c->jpeg_tile);
av_free(c->kempf_buf);
av_free(c->kempf_flags);
c->synth_tile = av_mallocz(c->tile_stride * aligned_height);
c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);
c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height
+ FF_INPUT_BUFFER_PADDING_SIZE);
c->kempf_flags = av_mallocz( c->tile_width * aligned_height);
if (!c->synth_tile || !c->jpeg_tile ||
!c->kempf_buf || !c->kempf_flags)
return AVERROR(ENOMEM);
}
return 0;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static int __init aes_s390_init(void)
{
int ret;
if (crypt_s390_func_available(KM_AES_128_ENCRYPT, CRYPT_S390_MSA))
keylen_flag |= AES_KEYLEN_128;
if (crypt_s390_func_available(KM_AES_192_ENCRYPT, CRYPT_S390_MSA))
keylen_flag |= AES_KEYLEN_192;
if (crypt_s390_func_available(KM_AES_256_ENCRYPT, CRYPT_S390_MSA))
keylen_flag |= AES_KEYLEN_256;
if (!keylen_flag)
return -EOPNOTSUPP;
/* z9 109 and z9 BC/EC only support 128 bit key length */
if (keylen_flag == AES_KEYLEN_128)
pr_info("AES hardware acceleration is only available for"
" 128-bit keys\n");
ret = crypto_register_alg(&aes_alg);
if (ret)
goto aes_err;
ret = crypto_register_alg(&ecb_aes_alg);
if (ret)
goto ecb_aes_err;
ret = crypto_register_alg(&cbc_aes_alg);
if (ret)
goto cbc_aes_err;
if (crypt_s390_func_available(KM_XTS_128_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4) &&
crypt_s390_func_available(KM_XTS_256_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4)) {
ret = crypto_register_alg(&xts_aes_alg);
if (ret)
goto xts_aes_err;
xts_aes_alg_reg = 1;
}
if (crypt_s390_func_available(KMCTR_AES_128_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4) &&
crypt_s390_func_available(KMCTR_AES_192_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4) &&
crypt_s390_func_available(KMCTR_AES_256_ENCRYPT,
CRYPT_S390_MSA | CRYPT_S390_MSA4)) {
ctrblk = (u8 *) __get_free_page(GFP_KERNEL);
if (!ctrblk) {
ret = -ENOMEM;
goto ctr_aes_err;
}
ret = crypto_register_alg(&ctr_aes_alg);
if (ret) {
free_page((unsigned long) ctrblk);
goto ctr_aes_err;
}
ctr_aes_alg_reg = 1;
}
out:
return ret;
ctr_aes_err:
crypto_unregister_alg(&xts_aes_alg);
xts_aes_err:
crypto_unregister_alg(&cbc_aes_alg);
cbc_aes_err:
crypto_unregister_alg(&ecb_aes_alg);
ecb_aes_err:
crypto_unregister_alg(&aes_alg);
aes_err:
goto out;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE)
{
searchpath_t *search;
long len;
if(!fs_searchpaths)
Com_Error(ERR_FATAL, "Filesystem call made without initialization");
for(search = fs_searchpaths; search; search = search->next)
{
len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse);
if(file == NULL)
{
if(len > 0)
return len;
}
else
{
if(len >= 0 && *file)
return len;
}
}
#ifdef FS_MISSING
if(missingFiles)
fprintf(missingFiles, "%s\n", filename);
#endif
if(file)
{
*file = 0;
return -1;
}
else
{
return 0;
}
}
CWE ID: CWE-269
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: psf_fwrite (const void *ptr, sf_count_t bytes, sf_count_t items, SF_PRIVATE *psf)
{ sf_count_t total = 0 ;
ssize_t count ;
if (psf->virtual_io)
return psf->vio.write (ptr, bytes*items, psf->vio_user_data) / bytes ;
items *= bytes ;
/* Do this check after the multiplication above. */
if (items <= 0)
return 0 ;
while (items > 0)
{ /* Break the writes down to a sensible size. */
count = (items > SENSIBLE_SIZE) ? SENSIBLE_SIZE : items ;
count = write (psf->file.filedes, ((const char*) ptr) + total, count) ;
if (count == -1)
{ if (errno == EINTR)
continue ;
psf_log_syserr (psf, errno) ;
break ;
} ;
if (count == 0)
break ;
total += count ;
items -= count ;
} ;
if (psf->is_pipe)
psf->pipeoffset += total ;
return total / bytes ;
} /* psf_fwrite */
CWE ID: CWE-189
Target: 1
Example 2:
Code: iperf_got_sigend(struct iperf_test *test)
{
/*
* If we're the client, or if we're a server and running a test,
* then dump out the accumulated stats so far.
*/
if (test->role == 'c' ||
(test->role == 's' && test->state == TEST_RUNNING)) {
test->done = 1;
cpu_util(test->cpu_util);
test->stats_callback(test);
test->state = DISPLAY_RESULTS; /* change local state only */
if (test->on_test_finish)
test->on_test_finish(test);
test->reporter_callback(test);
}
if (test->ctrl_sck >= 0) {
test->state = (test->role == 'c') ? CLIENT_TERMINATE : SERVER_TERMINATE;
(void) Nwrite(test->ctrl_sck, (char*) &test->state, sizeof(signed char), Ptcp);
}
i_errno = (test->role == 'c') ? IECLIENTTERM : IESERVERTERM;
iperf_errexit(test, "interrupt - %s", iperf_strerror(i_errno));
}
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 u32 apic_get_tmcct(struct kvm_lapic *apic)
{
ktime_t remaining;
s64 ns;
u32 tmcct;
ASSERT(apic != NULL);
/* if initial count is 0, current count should also be 0 */
if (kvm_apic_get_reg(apic, APIC_TMICT) == 0)
return 0;
remaining = hrtimer_get_remaining(&apic->lapic_timer.timer);
if (ktime_to_ns(remaining) < 0)
remaining = ktime_set(0, 0);
ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
tmcct = div64_u64(ns,
(APIC_BUS_CYCLE_NS * apic->divide_count));
return tmcct;
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AddExpectationsForSimulatedAttrib0(
GLsizei num_vertices, GLuint buffer_id) {
EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER,
num_vertices * sizeof(GLfloat) * 4,
_, GL_DYNAMIC_DRAW))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl_, BufferSubData(
GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id))
.Times(1)
.RetiresOnSaturation();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void LayerTreeHostImpl::PinchGestureUpdate(float magnify_delta,
const gfx::Point& anchor) {
TRACE_EVENT0("cc", "LayerTreeHostImpl::PinchGestureUpdate");
if (!InnerViewportScrollLayer())
return;
viewport()->PinchUpdate(magnify_delta, anchor);
client_->SetNeedsCommitOnImplThread();
SetNeedsRedraw();
client_->RenewTreePriority();
UpdateRootLayerStateForSynchronousInputHandler();
}
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: PHPAPI char *php_escape_shell_arg(char *str)
{
int x, y = 0, l = strlen(str);
char *cmd;
size_t estimate = (4 * l) + 3;
TSRMLS_FETCH();
cmd = safe_emalloc(4, l, 3); /* worst case */
#ifdef PHP_WIN32
cmd[y++] = '"';
#else
cmd[y++] = '\'';
#endif
for (x = 0; x < l; x++) {
int mb_len = php_mblen(str + x, (l - x));
/* skip non-valid multibyte characters */
if (mb_len < 0) {
continue;
} else if (mb_len > 1) {
memcpy(cmd + y, str + x, mb_len);
y += mb_len;
x += mb_len - 1;
continue;
}
switch (str[x]) {
#ifdef PHP_WIN32
case '"':
case '%':
cmd[y++] = ' ';
break;
#else
case '\'':
cmd[y++] = '\'';
cmd[y++] = '\\';
cmd[y++] = '\'';
#endif
/* fall-through */
default:
cmd[y++] = str[x];
}
}
#ifdef PHP_WIN32
cmd[y++] = '"';
#else
cmd[y++] = '\'';
return cmd;
}
CWE ID: CWE-78
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 MostVisitedSitesBridge::JavaObserver::OnMostVisitedURLsAvailable(
const NTPTilesVector& tiles) {
JNIEnv* env = AttachCurrentThread();
std::vector<base::string16> titles;
std::vector<std::string> urls;
std::vector<std::string> whitelist_icon_paths;
std::vector<int> sources;
titles.reserve(tiles.size());
urls.reserve(tiles.size());
whitelist_icon_paths.reserve(tiles.size());
sources.reserve(tiles.size());
for (const auto& tile : tiles) {
titles.emplace_back(tile.title);
urls.emplace_back(tile.url.spec());
whitelist_icon_paths.emplace_back(tile.whitelist_icon_path.value());
sources.emplace_back(static_cast<int>(tile.source));
}
Java_MostVisitedURLsObserver_onMostVisitedURLsAvailable(
env, observer_, ToJavaArrayOfStrings(env, titles),
ToJavaArrayOfStrings(env, urls),
ToJavaArrayOfStrings(env, whitelist_icon_paths),
ToJavaIntArray(env, sources));
}
CWE ID: CWE-17
Target: 1
Example 2:
Code: int test_gf2m_mod_div(BIO *bp,BN_CTX *ctx)
{
BIGNUM *a,*b[2],*c,*d,*e,*f;
int i, j, ret = 0;
int p0[] = {163,7,6,3,0,-1};
int p1[] = {193,15,0,-1};
a=BN_new();
b[0]=BN_new();
b[1]=BN_new();
c=BN_new();
d=BN_new();
e=BN_new();
f=BN_new();
BN_GF2m_arr2poly(p0, b[0]);
BN_GF2m_arr2poly(p1, b[1]);
for (i=0; i<num0; i++)
{
BN_bntest_rand(a, 512, 0, 0);
BN_bntest_rand(c, 512, 0, 0);
for (j=0; j < 2; j++)
{
BN_GF2m_mod_div(d, a, c, b[j], ctx);
BN_GF2m_mod_mul(e, d, c, b[j], ctx);
BN_GF2m_mod_div(f, a, e, b[j], ctx);
#if 0 /* make test uses ouput in bc but bc can't handle GF(2^m) arithmetic */
if (bp != NULL)
{
if (!results)
{
BN_print(bp,a);
BIO_puts(bp, " = ");
BN_print(bp,c);
BIO_puts(bp," * ");
BN_print(bp,d);
BIO_puts(bp, " % ");
BN_print(bp,b[j]);
BIO_puts(bp,"\n");
}
}
#endif
/* Test that ((a/c)*c)/a = 1. */
if(!BN_is_one(f))
{
fprintf(stderr,"GF(2^m) modular division test failed!\n");
goto err;
}
}
}
ret = 1;
err:
BN_free(a);
BN_free(b[0]);
BN_free(b[1]);
BN_free(c);
BN_free(d);
BN_free(e);
BN_free(f);
return ret;
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: decode_pathname(__be32 *p, char **namp, unsigned int *lenp)
{
char *name;
unsigned int i;
if ((p = xdr_decode_string_inplace(p, namp, lenp, NFS_MAXPATHLEN)) != NULL) {
for (i = 0, name = *namp; i < *lenp; i++, name++) {
if (*name == '\0')
return NULL;
}
}
return p;
}
CWE ID: CWE-404
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebGL2RenderingContextBase::texSubImage3D(GLenum target,
GLint level,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLsizei width,
GLsizei height,
GLsizei depth,
GLenum format,
GLenum type,
GLintptr offset) {
if (isContextLost())
return;
if (!ValidateTexture3DBinding("texSubImage3D", target))
return;
if (!bound_pixel_unpack_buffer_) {
SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage3D",
"no bound PIXEL_UNPACK_BUFFER");
return;
}
if (!ValidateTexFunc("texSubImage3D", kTexSubImage, kSourceUnpackBuffer,
target, level, 0, width, height, depth, 0, format, type,
xoffset, yoffset, zoffset))
return;
if (!ValidateValueFitNonNegInt32("texSubImage3D", "offset", offset))
return;
ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width,
height, depth, format, type,
reinterpret_cast<const void*>(offset));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void V8Proxy::clearForClose()
{
resetIsolatedWorlds();
windowShell()->clearForClose();
}
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 RenderFrameHostImpl::SetNetworkFactoryForTesting(
const CreateNetworkFactoryCallback& url_loader_factory_callback) {
DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(url_loader_factory_callback.is_null() ||
g_url_loader_factory_callback_for_test.Get().is_null())
<< "It is not expected that this is called with non-null callback when "
<< "another overriding callback is already set.";
g_url_loader_factory_callback_for_test.Get() = url_loader_factory_callback;
}
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 PrintRenderFrameHelper::PrintPagesNative(blink::WebLocalFrame* frame,
int page_count) {
const PrintMsg_PrintPages_Params& params = *print_pages_params_;
const PrintMsg_Print_Params& print_params = params.params;
std::vector<int> printed_pages = GetPrintedPages(params, page_count);
if (printed_pages.empty())
return false;
PdfMetafileSkia metafile(print_params.printed_doc_type);
CHECK(metafile.Init());
PrintHostMsg_DidPrintDocument_Params page_params;
PrintPageInternal(print_params, printed_pages[0], page_count, frame,
&metafile, &page_params.page_size,
&page_params.content_area);
for (size_t i = 1; i < printed_pages.size(); ++i) {
PrintPageInternal(print_params, printed_pages[i], page_count, frame,
&metafile, nullptr, nullptr);
}
FinishFramePrinting();
metafile.FinishDocument();
if (!CopyMetafileDataToSharedMem(metafile,
&page_params.metafile_data_handle)) {
return false;
}
page_params.data_size = metafile.GetDataSize();
page_params.document_cookie = print_params.document_cookie;
#if defined(OS_WIN)
page_params.physical_offsets = printer_printable_area_.origin();
#endif
Send(new PrintHostMsg_DidPrintDocument(routing_id(), page_params));
return true;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void initialise_threads(int fragment_buffer_size, int data_buffer_size)
{
struct rlimit rlim;
int i, max_files, res;
sigset_t sigmask, old_mask;
/* block SIGQUIT and SIGHUP, these are handled by the info thread */
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGQUIT);
sigaddset(&sigmask, SIGHUP);
if(pthread_sigmask(SIG_BLOCK, &sigmask, NULL) != 0)
EXIT_UNSQUASH("Failed to set signal mask in initialise_threads"
"\n");
/*
* temporarily block these signals so the created sub-threads will
* ignore them, ensuring the main thread handles them
*/
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGINT);
sigaddset(&sigmask, SIGTERM);
if(pthread_sigmask(SIG_BLOCK, &sigmask, &old_mask) != 0)
EXIT_UNSQUASH("Failed to set signal mask in initialise_threads"
"\n");
if(processors == -1) {
#ifndef linux
int mib[2];
size_t len = sizeof(processors);
mib[0] = CTL_HW;
#ifdef HW_AVAILCPU
mib[1] = HW_AVAILCPU;
#else
mib[1] = HW_NCPU;
#endif
if(sysctl(mib, 2, &processors, &len, NULL, 0) == -1) {
ERROR("Failed to get number of available processors. "
"Defaulting to 1\n");
processors = 1;
}
#else
processors = sysconf(_SC_NPROCESSORS_ONLN);
#endif
}
if(add_overflow(processors, 3) ||
multiply_overflow(processors + 3, sizeof(pthread_t)))
EXIT_UNSQUASH("Processors too large\n");
thread = malloc((3 + processors) * sizeof(pthread_t));
if(thread == NULL)
EXIT_UNSQUASH("Out of memory allocating thread descriptors\n");
inflator_thread = &thread[3];
/*
* dimensioning the to_reader and to_inflate queues. The size of
* these queues is directly related to the amount of block
* read-ahead possible. To_reader queues block read requests to
* the reader thread and to_inflate queues block decompression
* requests to the inflate thread(s) (once the block has been read by
* the reader thread). The amount of read-ahead is determined by
* the combined size of the data_block and fragment caches which
* determine the total number of blocks which can be "in flight"
* at any one time (either being read or being decompressed)
*
* The maximum file open limit, however, affects the read-ahead
* possible, in that for normal sizes of the fragment and data block
* caches, where the incoming files have few data blocks or one fragment
* only, the file open limit is likely to be reached before the
* caches are full. This means the worst case sizing of the combined
* sizes of the caches is unlikely to ever be necessary. However, is is
* obvious read-ahead up to the data block cache size is always possible
* irrespective of the file open limit, because a single file could
* contain that number of blocks.
*
* Choosing the size as "file open limit + data block cache size" seems
* to be a reasonable estimate. We can reasonably assume the maximum
* likely read-ahead possible is data block cache size + one fragment
* per open file.
*
* dimensioning the to_writer queue. The size of this queue is
* directly related to the amount of block read-ahead possible.
* However, unlike the to_reader and to_inflate queues, this is
* complicated by the fact the to_writer queue not only contains
* entries for fragments and data_blocks but it also contains
* file entries, one per open file in the read-ahead.
*
* Choosing the size as "2 * (file open limit) +
* data block cache size" seems to be a reasonable estimate.
* We can reasonably assume the maximum likely read-ahead possible
* is data block cache size + one fragment per open file, and then
* we will have a file_entry for each open file.
*/
res = getrlimit(RLIMIT_NOFILE, &rlim);
if (res == -1) {
ERROR("failed to get open file limit! Defaulting to 1\n");
rlim.rlim_cur = 1;
}
if (rlim.rlim_cur != RLIM_INFINITY) {
/*
* leave OPEN_FILE_MARGIN free (rlim_cur includes fds used by
* stdin, stdout, stderr and filesystem fd
*/
if (rlim.rlim_cur <= OPEN_FILE_MARGIN)
/* no margin, use minimum possible */
max_files = 1;
else
max_files = rlim.rlim_cur - OPEN_FILE_MARGIN;
} else
max_files = -1;
/* set amount of available files for use by open_wait and close_wake */
open_init(max_files);
/*
* allocate to_reader, to_inflate and to_writer queues. Set based on
* open file limit and cache size, unless open file limit is unlimited,
* in which case set purely based on cache limits
*
* In doing so, check that the user supplied values do not overflow
* a signed int
*/
if (max_files != -1) {
if(add_overflow(data_buffer_size, max_files) ||
add_overflow(data_buffer_size, max_files * 2))
EXIT_UNSQUASH("Data queue size is too large\n");
to_reader = queue_init(max_files + data_buffer_size);
to_inflate = queue_init(max_files + data_buffer_size);
to_writer = queue_init(max_files * 2 + data_buffer_size);
} else {
int all_buffers_size;
if(add_overflow(fragment_buffer_size, data_buffer_size))
EXIT_UNSQUASH("Data and fragment queues combined are"
" too large\n");
all_buffers_size = fragment_buffer_size + data_buffer_size;
if(add_overflow(all_buffers_size, all_buffers_size))
EXIT_UNSQUASH("Data and fragment queues combined are"
" too large\n");
to_reader = queue_init(all_buffers_size);
to_inflate = queue_init(all_buffers_size);
to_writer = queue_init(all_buffers_size * 2);
}
from_writer = queue_init(1);
fragment_cache = cache_init(block_size, fragment_buffer_size);
data_cache = cache_init(block_size, data_buffer_size);
pthread_create(&thread[0], NULL, reader, NULL);
pthread_create(&thread[1], NULL, writer, NULL);
pthread_create(&thread[2], NULL, progress_thread, NULL);
init_info();
pthread_mutex_init(&fragment_mutex, NULL);
for(i = 0; i < processors; i++) {
if(pthread_create(&inflator_thread[i], NULL, inflator, NULL) !=
0)
EXIT_UNSQUASH("Failed to create thread\n");
}
printf("Parallel unsquashfs: Using %d processor%s\n", processors,
processors == 1 ? "" : "s");
if(pthread_sigmask(SIG_SETMASK, &old_mask, NULL) != 0)
EXIT_UNSQUASH("Failed to set signal mask in initialise_threads"
"\n");
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool AppCacheBackendImpl::SelectCacheForWorker(
int host_id, int parent_process_id, int parent_host_id) {
AppCacheHost* host = GetHost(host_id);
if (!host || host->was_select_cache_called())
return false;
host->SelectCacheForWorker(parent_process_id, parent_host_id);
return true;
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: _gnutls_recv_handshake_header (gnutls_session_t session,
gnutls_handshake_description_t type,
gnutls_handshake_description_t * recv_type)
{
int ret;
uint32_t length32 = 0;
uint8_t *dataptr = NULL; /* for realloc */
size_t handshake_header_size = HANDSHAKE_HEADER_SIZE;
/* if we have data into the buffer then return them, do not read the next packet.
* In order to return we need a full TLS handshake header, or in case of a version 2
* packet, then we return the first byte.
*/
if (session->internals.handshake_header_buffer.header_size ==
handshake_header_size || (session->internals.v2_hello != 0
&& type == GNUTLS_HANDSHAKE_CLIENT_HELLO
&& session->internals.
handshake_header_buffer.packet_length > 0))
{
*recv_type = session->internals.handshake_header_buffer.recv_type;
return session->internals.handshake_header_buffer.packet_length;
}
ret =
_gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE,
type, dataptr, SSL2_HEADERS);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
/* The case ret==0 is caught here.
*/
if (ret != SSL2_HEADERS)
{
gnutls_assert ();
return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
}
session->internals.handshake_header_buffer.header_size = SSL2_HEADERS;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void ListAttributeTargetObserver::IdTargetChanged() {
element_->ListAttributeTargetChanged();
}
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 nfs4_xdr_dec_create(struct rpc_rqst *rqstp, struct xdr_stream *xdr,
struct nfs4_create_res *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_sequence(xdr, &res->seq_res, rqstp);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_savefh(xdr);
if (status)
goto out;
status = decode_create(xdr, &res->dir_cinfo);
if (status)
goto out;
status = decode_getfh(xdr, res->fh);
if (status)
goto out;
if (decode_getfattr(xdr, res->fattr, res->server,
!RPC_IS_ASYNC(rqstp->rq_task)) != 0)
goto out;
status = decode_restorefh(xdr);
if (status)
goto out;
decode_getfattr(xdr, res->dir_fattr, res->server,
!RPC_IS_ASYNC(rqstp->rq_task));
out:
return status;
}
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: init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
#ifdef AUTOKEY
filegen_register(statsdir, "cryptostats", &cryptostats);
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
filegen_register(statsdir, "timingstats", &timingstats);
#endif /* DEBUG_TIMING */
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void setup_new_vc_session(void)
{
char addr[INET6_ADDRSTRLEN];
DEBUG(2,("setup_new_vc_session: New VC == 0, if NT4.x "
"compatible we would close all old resources.\n"));
#if 0
conn_close_all();
invalidate_all_vuids();
#endif
if (lp_reset_on_zero_vc()) {
connections_forall(shutdown_other_smbds,
CONST_DISCARD(void *,
client_addr(get_client_fd(),addr,sizeof(addr))));
}
}
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 do_exec(smart_str *querystr, int expect, PGconn *pg_link, ulong opt TSRMLS_DC)
{
if (opt & PGSQL_DML_ASYNC) {
if (PQsendQuery(pg_link, querystr->c)) {
return 0;
}
}
else {
PGresult *pg_result;
pg_result = PQexec(pg_link, querystr->c);
if (PQresultStatus(pg_result) == expect) {
PQclear(pg_result);
return 0;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", PQresultErrorMessage(pg_result));
PQclear(pg_result);
}
}
return -1;
}
CWE ID: CWE-254
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CloseTabsAndExpectNotifications(
TabStripModel* tab_strip_model,
std::vector<LifecycleUnit*> lifecycle_units) {
std::vector<std::unique_ptr<testing::StrictMock<MockLifecycleUnitObserver>>>
observers;
for (LifecycleUnit* lifecycle_unit : lifecycle_units) {
observers.emplace_back(
std::make_unique<testing::StrictMock<MockLifecycleUnitObserver>>());
lifecycle_unit->AddObserver(observers.back().get());
EXPECT_CALL(*observers.back().get(),
OnLifecycleUnitDestroyed(lifecycle_unit));
}
tab_strip_model->CloseAllTabs();
}
CWE ID:
Target: 1
Example 2:
Code: vrrp_gna_interval_handler(vector_t *strvec)
{
double interval;
if (!read_double_strvec(strvec, 1, &interval, 1.0 / TIMER_HZ, UINT_MAX / TIMER_HZ, true))
report_config_error(CONFIG_GENERAL_ERROR, "vrrp_gna_interval '%s' is invalid", FMT_STR_VSLOT(strvec, 1));
else
global_data->vrrp_gna_interval = (unsigned)(interval * TIMER_HZ);
if (global_data->vrrp_gna_interval >= 1 * TIMER_HZ)
log_message(LOG_INFO, "The vrrp_gna_interval is very large - %s seconds", FMT_STR_VSLOT(strvec, 1));
}
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: wb_print(netdissect_options *ndo,
register const void *hdr, register u_int len)
{
register const struct pkt_hdr *ph;
ph = (const struct pkt_hdr *)hdr;
if (len < sizeof(*ph) || !ND_TTEST(*ph)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
len -= sizeof(*ph);
if (ph->ph_flags)
ND_PRINT((ndo, "*"));
switch (ph->ph_type) {
case PT_KILL:
ND_PRINT((ndo, " wb-kill"));
return;
case PT_ID:
if (wb_id(ndo, (const struct pkt_id *)(ph + 1), len) >= 0)
return;
break;
case PT_RREQ:
if (wb_rreq(ndo, (const struct pkt_rreq *)(ph + 1), len) >= 0)
return;
break;
case PT_RREP:
if (wb_rrep(ndo, (const struct pkt_rrep *)(ph + 1), len) >= 0)
return;
break;
case PT_DRAWOP:
if (wb_drawop(ndo, (const struct pkt_dop *)(ph + 1), len) >= 0)
return;
break;
case PT_PREQ:
if (wb_preq(ndo, (const struct pkt_preq *)(ph + 1), len) >= 0)
return;
break;
case PT_PREP:
if (wb_prep(ndo, (const struct pkt_prep *)(ph + 1), len) >= 0)
return;
break;
default:
ND_PRINT((ndo, " wb-%d!", ph->ph_type));
return;
}
}
CWE ID: CWE-125
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: RuntimeCustomBindings::RuntimeCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetManifest",
base::Bind(&RuntimeCustomBindings::GetManifest, base::Unretained(this)));
RouteFunction("OpenChannelToExtension",
base::Bind(&RuntimeCustomBindings::OpenChannelToExtension,
base::Unretained(this)));
RouteFunction("OpenChannelToNativeApp",
base::Bind(&RuntimeCustomBindings::OpenChannelToNativeApp,
base::Unretained(this)));
RouteFunction("GetExtensionViews",
base::Bind(&RuntimeCustomBindings::GetExtensionViews,
base::Unretained(this)));
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: ftrace_snapshot_free(struct ftrace_probe_ops *ops, struct trace_array *tr,
unsigned long ip, void *data)
{
struct ftrace_func_mapper *mapper = data;
if (!ip) {
if (!mapper)
return;
free_ftrace_func_mapper(mapper, NULL);
return;
}
ftrace_func_mapper_remove_ip(mapper, ip);
}
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: findoprnd(ITEM *ptr, int32 *pos)
{
if (ptr[*pos].type == VAL || ptr[*pos].type == VALTRUE)
{
ptr[*pos].left = 0;
(*pos)++;
}
else if (ptr[*pos].val == (int32) '!')
{
ptr[*pos].left = 1;
(*pos)++;
findoprnd(ptr, pos);
}
else
{
ITEM *curitem = &ptr[*pos];
int32 tmp = *pos;
(*pos)++;
findoprnd(ptr, pos);
curitem->left = *pos - tmp;
findoprnd(ptr, pos);
}
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int verify_source_vc(char **ret_path, const char *src_vc) {
_cleanup_close_ int fd = -1;
char *path;
int r;
fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (fd < 0)
return log_error_errno(fd, "Failed to open %s: %m", src_vc);
r = verify_vc_device(fd);
if (r < 0)
return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc);
r = verify_vc_allocation_byfd(fd);
if (r < 0)
return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc);
r = verify_vc_kbmode(fd);
if (r < 0)
return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc);
path = strdup(src_vc);
if (!path)
return log_oom();
*ret_path = path;
return TAKE_FD(fd);
}
CWE ID: CWE-255
Target: 1
Example 2:
Code: static int ipgre_tap_validate(struct nlattr *tb[], struct nlattr *data[])
{
__be32 daddr;
if (tb[IFLA_ADDRESS]) {
if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
return -EINVAL;
if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
return -EADDRNOTAVAIL;
}
if (!data)
goto out;
if (data[IFLA_GRE_REMOTE]) {
memcpy(&daddr, nla_data(data[IFLA_GRE_REMOTE]), 4);
if (!daddr)
return -EINVAL;
}
out:
return ipgre_tunnel_validate(tb, data);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ZEND_API void* ZEND_FASTCALL _safe_realloc(void *ptr, size_t nmemb, size_t size, size_t offset)
{
return perealloc(ptr, safe_address(nmemb, size, offset), 1);
}
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: CURLcode Curl_auth_create_plain_message(struct Curl_easy *data,
const char *userp,
const char *passwdp,
char **outptr, size_t *outlen)
{
CURLcode result;
char *plainauth;
size_t ulen;
size_t plen;
size_t plainlen;
*outlen = 0;
*outptr = NULL;
ulen = strlen(userp);
plen = strlen(passwdp);
/* Compute binary message length. Check for overflows. */
if((ulen > SIZE_T_MAX/2) || (plen > (SIZE_T_MAX/2 - 2)))
return CURLE_OUT_OF_MEMORY;
plainlen = 2 * ulen + plen + 2;
plainauth = malloc(plainlen);
if(!plainauth)
return CURLE_OUT_OF_MEMORY;
/* Calculate the reply */
memcpy(plainauth, userp, ulen);
plainauth[ulen] = '\0';
memcpy(plainauth + ulen + 1, userp, ulen);
plainauth[2 * ulen + 1] = '\0';
memcpy(plainauth + 2 * ulen + 2, passwdp, plen);
/* Base64 encode the reply */
result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen);
free(plainauth);
return result;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static ssize_t uart_mode_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
return sprintf(buf, "%d\n", edge_port->bUartMode);
}
CWE ID: CWE-191
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: mm_sshpam_init_ctx(Authctxt *authctxt)
{
Buffer m;
int success;
debug3("%s", __func__);
buffer_init(&m);
buffer_put_cstring(&m, authctxt->user);
mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_PAM_INIT_CTX, &m);
debug3("%s: waiting for MONITOR_ANS_PAM_INIT_CTX", __func__);
mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_PAM_INIT_CTX, &m);
success = buffer_get_int(&m);
if (success == 0) {
debug3("%s: pam_init_ctx failed", __func__);
buffer_free(&m);
return (NULL);
}
buffer_free(&m);
return (authctxt);
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PaintArtifactCompositor::MightOverlap(const PendingLayer& layer_a,
const PendingLayer& layer_b) {
PropertyTreeState root_property_tree_state(TransformPaintPropertyNode::Root(),
ClipPaintPropertyNode::Root(),
EffectPaintPropertyNode::Root());
FloatClipRect bounds_a(layer_a.bounds);
GeometryMapper::LocalToAncestorVisualRect(layer_a.property_tree_state,
root_property_tree_state, bounds_a);
FloatClipRect bounds_b(layer_b.bounds);
GeometryMapper::LocalToAncestorVisualRect(layer_b.property_tree_state,
root_property_tree_state, bounds_b);
return bounds_a.Rect().Intersects(bounds_b.Rect());
}
CWE ID:
Target: 1
Example 2:
Code: static struct buffer_head *udf_getblk(struct inode *inode, long block,
int create, int *err)
{
struct buffer_head *bh;
struct buffer_head dummy;
dummy.b_state = 0;
dummy.b_blocknr = -1000;
*err = udf_get_block(inode, block, &dummy, create);
if (!*err && buffer_mapped(&dummy)) {
bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
if (buffer_new(&dummy)) {
lock_buffer(bh);
memset(bh->b_data, 0x00, inode->i_sb->s_blocksize);
set_buffer_uptodate(bh);
unlock_buffer(bh);
mark_buffer_dirty_inode(bh, inode);
}
return bh;
}
return NULL;
}
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: jbig2_word_stream_buf_get_next_word(Jbig2WordStream *self, int offset, uint32_t *word)
{
Jbig2WordStreamBuf *z = (Jbig2WordStreamBuf *) self;
const byte *data = z->data;
uint32_t result;
if (offset + 4 < z->size)
result = (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3];
else if (offset > z->size)
return -1;
else {
int i;
result = 0;
for (i = 0; i < z->size - offset; i++)
result |= data[offset + i] << ((3 - i) << 3);
}
*word = result;
return 0;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
char __user *optval,
int __user *optlen)
{
struct sctp_assoc_stats sas;
struct sctp_association *asoc = NULL;
/* User must provide at least the assoc id */
if (len < sizeof(sctp_assoc_t))
return -EINVAL;
if (copy_from_user(&sas, optval, len))
return -EFAULT;
asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
if (!asoc)
return -EINVAL;
sas.sas_rtxchunks = asoc->stats.rtxchunks;
sas.sas_gapcnt = asoc->stats.gapcnt;
sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
sas.sas_osacks = asoc->stats.osacks;
sas.sas_isacks = asoc->stats.isacks;
sas.sas_octrlchunks = asoc->stats.octrlchunks;
sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
sas.sas_oodchunks = asoc->stats.oodchunks;
sas.sas_iodchunks = asoc->stats.iodchunks;
sas.sas_ouodchunks = asoc->stats.ouodchunks;
sas.sas_iuodchunks = asoc->stats.iuodchunks;
sas.sas_idupchunks = asoc->stats.idupchunks;
sas.sas_opackets = asoc->stats.opackets;
sas.sas_ipackets = asoc->stats.ipackets;
/* New high max rto observed, will return 0 if not a single
* RTO update took place. obs_rto_ipaddr will be bogus
* in such a case
*/
sas.sas_maxrto = asoc->stats.max_obs_rto;
memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
sizeof(struct sockaddr_storage));
/* Mark beginning of a new observation period */
asoc->stats.max_obs_rto = asoc->rto_min;
/* Allow the struct to grow and fill in as much as possible */
len = min_t(size_t, len, sizeof(sas));
if (put_user(len, optlen))
return -EFAULT;
SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n",
len, sas.sas_assoc_id);
if (copy_to_user(optval, &sas, len))
return -EFAULT;
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: base::Time DiscardableSharedMemoryManager::Now() const {
return base::Time::Now();
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void queue_push(register Queue *qp, size_t extra_length, char const *info)
{
register char *cp;
size_t memory_length;
size_t available_length;
size_t begin_length;
size_t n_begin;
size_t q_length;
if (!extra_length)
return;
memory_length = qp->d_memory_end - qp->d_memory;
q_length =
qp->d_read <= qp->d_write ?
(size_t)(qp->d_write - qp->d_read)
:
memory_length - (qp->d_read - qp->d_write);
available_length = memory_length - q_length - 1;
/* -1, as the Q cannot completely fill up all */
/* available memory in the buffer */
if (message_show(MSG_INFO))
message("push_front %u bytes in `%s'", (unsigned)extra_length, info);
if (extra_length > available_length)
{
/* enlarge the buffer: */
memory_length += extra_length - available_length + BLOCK_QUEUE;
cp = new_memory(memory_length, sizeof(char));
if (message_show(MSG_INFO))
message("Reallocating queue at %p to %p", qp->d_memory, cp);
if (qp->d_read > qp->d_write) /* q wraps around end */
{
size_t tail_len = qp->d_memory_end - qp->d_read;
memcpy(cp, qp->d_read, tail_len); /* first part -> begin */
/* 2nd part beyond */
memcpy(cp + tail_len, qp->d_memory,
(size_t)(qp->d_write - qp->d_memory));
qp->d_write = cp + q_length;
qp->d_read = cp;
}
else /* q as one block */
{
memcpy(cp, qp->d_memory, memory_length);/* cp existing buffer */
qp->d_read = cp + (qp->d_read - qp->d_memory);
qp->d_write = cp + (qp->d_write - qp->d_memory);
}
free(qp->d_memory); /* free old memory */
qp->d_memory_end = cp + memory_length; /* update d_memory_end */
qp->d_memory = cp; /* update d_memory */
}
/*
Write as much as possible at the begin of the buffer, then write
the remaining chars at the end.
q_length is increased by the length of the info string
The first chars to write are at the end of info, and the 2nd part to
write are the initial chars of info, since the initial part of info
is then read first.
*/
/* # chars available at the */
begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */
n_begin = extra_length <= begin_length ? /* determine # to write at */
extra_length /* the begin of the buffer */
:
begin_length;
memcpy /* write trailing part of */
( /* info first */
qp->d_read -= n_begin,
info + extra_length - n_begin,
n_begin
);
if (extra_length > begin_length) /* not yet all chars written*/
{
/* continue with the remaining number of characters. Insert these at*/
/* the end of the buffer */
extra_length -= begin_length; /* reduce # to write */
memcpy /* d_read wraps to the end */
( /* write info's rest */
qp->d_read = qp->d_memory_end - extra_length,
info,
extra_length
);
}
}
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: ImageTransportClientTexture(
WebKit::WebGraphicsContext3D* host_context,
const gfx::Size& size,
float device_scale_factor,
uint64 surface_id)
: ui::Texture(true, size, device_scale_factor),
host_context_(host_context),
texture_id_(surface_id) {
}
CWE ID:
Target: 1
Example 2:
Code: bool CardUnmaskPromptViews::ShouldDefaultButtonBeBlue() const {
return true;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostViewAura::WasHidden() {
if (host_->is_hidden())
return;
host_->WasHidden();
released_front_lock_ = NULL;
if (ShouldReleaseFrontSurface() &&
host_->is_accelerated_compositing_active()) {
current_surface_ = 0;
UpdateExternalTexture();
}
AdjustSurfaceProtection();
#if defined(OS_WIN)
aura::RootWindow* root_window = window_->GetRootWindow();
if (root_window) {
HWND parent = root_window->GetAcceleratedWidget();
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(parent, HideWindowsCallback, lparam);
}
#endif
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PixarLogDecode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "PixarLogDecode";
TIFFDirectory *td = &tif->tif_dir;
PixarLogState* sp = DecoderState(tif);
tmsize_t i;
tmsize_t nsamples;
int llen;
uint16 *up;
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
nsamples = occ / sizeof(float); /* XXX float == 32 bits */
break;
case PIXARLOGDATAFMT_16BIT:
case PIXARLOGDATAFMT_12BITPICIO:
case PIXARLOGDATAFMT_11BITLOG:
nsamples = occ / sizeof(uint16); /* XXX uint16 == 16 bits */
break;
case PIXARLOGDATAFMT_8BIT:
case PIXARLOGDATAFMT_8BITABGR:
nsamples = occ;
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"%d bit input not supported in PixarLog",
td->td_bitspersample);
return 0;
}
llen = sp->stride * td->td_imagewidth;
(void) s;
assert(sp != NULL);
sp->stream.next_out = (unsigned char *) sp->tbuf;
assert(sizeof(sp->stream.avail_out)==4); /* if this assert gets raised,
we need to simplify this code to reflect a ZLib that is likely updated
to deal with 8byte memory sizes, though this code will respond
appropriately even before we simplify it */
sp->stream.avail_out = (uInt) (nsamples * sizeof(uint16));
if (sp->stream.avail_out != nsamples * sizeof(uint16))
{
TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
return (0);
}
do {
int state = inflate(&sp->stream, Z_PARTIAL_FLUSH);
if (state == Z_STREAM_END) {
break; /* XXX */
}
if (state == Z_DATA_ERROR) {
TIFFErrorExt(tif->tif_clientdata, module,
"Decoding error at scanline %lu, %s",
(unsigned long) tif->tif_row, sp->stream.msg ? sp->stream.msg : "(null)");
if (inflateSync(&sp->stream) != Z_OK)
return (0);
continue;
}
if (state != Z_OK) {
TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
sp->stream.msg ? sp->stream.msg : "(null)");
return (0);
}
} while (sp->stream.avail_out > 0);
/* hopefully, we got all the bytes we needed */
if (sp->stream.avail_out != 0) {
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at scanline %lu (short " TIFF_UINT64_FORMAT " bytes)",
(unsigned long) tif->tif_row, (TIFF_UINT64_T) sp->stream.avail_out);
return (0);
}
up = sp->tbuf;
/* Swap bytes in the data if from a different endian machine. */
if (tif->tif_flags & TIFF_SWAB)
TIFFSwabArrayOfShort(up, nsamples);
/*
* if llen is not an exact multiple of nsamples, the decode operation
* may overflow the output buffer, so truncate it enough to prevent
* that but still salvage as much data as possible.
*/
if (nsamples % llen) {
TIFFWarningExt(tif->tif_clientdata, module,
"stride %lu is not a multiple of sample count, "
"%lu, data truncated.", (unsigned long) llen, (unsigned long) nsamples);
nsamples -= nsamples % llen;
}
for (i = 0; i < nsamples; i += llen, up += llen) {
switch (sp->user_datafmt) {
case PIXARLOGDATAFMT_FLOAT:
horizontalAccumulateF(up, llen, sp->stride,
(float *)op, sp->ToLinearF);
op += llen * sizeof(float);
break;
case PIXARLOGDATAFMT_16BIT:
horizontalAccumulate16(up, llen, sp->stride,
(uint16 *)op, sp->ToLinear16);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_12BITPICIO:
horizontalAccumulate12(up, llen, sp->stride,
(int16 *)op, sp->ToLinearF);
op += llen * sizeof(int16);
break;
case PIXARLOGDATAFMT_11BITLOG:
horizontalAccumulate11(up, llen, sp->stride,
(uint16 *)op);
op += llen * sizeof(uint16);
break;
case PIXARLOGDATAFMT_8BIT:
horizontalAccumulate8(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
case PIXARLOGDATAFMT_8BITABGR:
horizontalAccumulate8abgr(up, llen, sp->stride,
(unsigned char *)op, sp->ToLinear8);
op += llen * sizeof(unsigned char);
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Unsupported bits/sample: %d",
td->td_bitspersample);
return (0);
}
}
return (1);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static rsRetVal createContext() {
if (s_context == NULL) {
DBGPRINTF("imzmq3: creating zctx...");
zsys_handler_set(NULL);
s_context = zctx_new();
if (s_context == NULL) {
errmsg.LogError(0, RS_RET_INVALID_PARAMS,
"zctx_new failed: %s",
zmq_strerror(errno));
/* DK: really should do better than invalid params...*/
return RS_RET_INVALID_PARAMS;
}
DBGPRINTF("success!\n");
if (runModConf->io_threads > 1) {
DBGPRINTF("setting io worker threads to %d\n", runModConf->io_threads);
zctx_set_iothreads(s_context, runModConf->io_threads);
}
}
return RS_RET_OK;
}
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Track::EOSBlock::EOSBlock() :
BlockEntry(NULL, LONG_MIN)
{
}
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 PrintWebViewHelper::OnPrintingDone(bool success) {
notify_browser_of_print_failure_ = false;
if (!success)
LOG(ERROR) << "Failure in OnPrintingDone";
DidFinishPrinting(success ? OK : FAIL_PRINT);
}
CWE ID:
Target: 1
Example 2:
Code: static void __iomem *hns_ppe_get_iobase(struct ppe_common_cb *ppe_common,
int ppe_idx)
{
return ppe_common->dsaf_dev->ppe_base + ppe_idx * PPE_REG_OFFSET;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int GetFreeFrameBuffer(size_t min_size, vpx_codec_frame_buffer_t *fb) {
EXPECT_TRUE(fb != NULL);
const int idx = FindFreeBufferIndex();
if (idx == num_buffers_)
return -1;
if (ext_fb_list_[idx].size < min_size) {
delete [] ext_fb_list_[idx].data;
ext_fb_list_[idx].data = new uint8_t[min_size];
ext_fb_list_[idx].size = min_size;
}
SetFrameBuffer(idx, fb);
return 0;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintViewManager::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == print_preview_rfh_)
print_preview_state_ = NOT_PREVIEWING;
PrintViewManagerBase::RenderFrameDeleted(render_frame_host);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void sigterm_handler(int s) {
int parent=0;
g_hash_table_foreach(children, killchild, &parent);
if(parent) {
unlink(pidfname);
}
exit(EXIT_SUCCESS);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int move_to_new_page(struct page *newpage, struct page *page,
enum migrate_mode mode)
{
struct address_space *mapping;
int rc = -EAGAIN;
bool is_lru = !__PageMovable(page);
VM_BUG_ON_PAGE(!PageLocked(page), page);
VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
mapping = page_mapping(page);
if (likely(is_lru)) {
if (!mapping)
rc = migrate_page(mapping, newpage, page, mode);
else if (mapping->a_ops->migratepage)
/*
* Most pages have a mapping and most filesystems
* provide a migratepage callback. Anonymous pages
* are part of swap space which also has its own
* migratepage callback. This is the most common path
* for page migration.
*/
rc = mapping->a_ops->migratepage(mapping, newpage,
page, mode);
else
rc = fallback_migrate_page(mapping, newpage,
page, mode);
} else {
/*
* In case of non-lru page, it could be released after
* isolation step. In that case, we shouldn't try migration.
*/
VM_BUG_ON_PAGE(!PageIsolated(page), page);
if (!PageMovable(page)) {
rc = MIGRATEPAGE_SUCCESS;
__ClearPageIsolated(page);
goto out;
}
rc = mapping->a_ops->migratepage(mapping, newpage,
page, mode);
WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS &&
!PageIsolated(page));
}
/*
* When successful, old pagecache page->mapping must be cleared before
* page is freed; but stats require that PageAnon be left as PageAnon.
*/
if (rc == MIGRATEPAGE_SUCCESS) {
if (__PageMovable(page)) {
VM_BUG_ON_PAGE(!PageIsolated(page), page);
/*
* We clear PG_movable under page_lock so any compactor
* cannot try to migrate this page.
*/
__ClearPageIsolated(page);
}
/*
* Anonymous and movable page->mapping will be cleard by
* free_pages_prepare so don't reset it here for keeping
* the type to work PageAnon, for example.
*/
if (!PageMappingFlags(page))
page->mapping = NULL;
}
out:
return rc;
}
CWE ID: CWE-200
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void mincore_pmd_range(struct vm_area_struct *vma, pud_t *pud,
unsigned long addr, unsigned long end,
unsigned char *vec)
{
unsigned long next;
pmd_t *pmd;
pmd = pmd_offset(pud, addr);
do {
next = pmd_addr_end(addr, end);
if (pmd_trans_huge(*pmd)) {
if (mincore_huge_pmd(vma, pmd, addr, next, vec)) {
vec += (next - addr) >> PAGE_SHIFT;
continue;
}
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
mincore_unmapped_range(vma, addr, next, vec);
else
mincore_pte_range(vma, pmd, addr, next, vec);
vec += (next - addr) >> PAGE_SHIFT;
} while (pmd++, addr = next, addr != end);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool AutolaunchInfoBarDelegate::Accept() {
action_taken_ = true;
auto_launch_trial::UpdateInfobarResponseMetric(
auto_launch_trial::INFOBAR_OK);
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 WebPage::dispatchInspectorMessage(const BlackBerry::Platform::String& message)
{
d->m_page->inspectorController()->dispatchMessageFromFrontend(message);
}
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 SVGFEColorMatrixElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
{
FEColorMatrix* colorMatrix = static_cast<FEColorMatrix*>(effect);
if (attrName == SVGNames::typeAttr)
return colorMatrix->setType(m_type->currentValue()->enumValue());
if (attrName == SVGNames::valuesAttr)
return colorMatrix->setValues(m_values->currentValue()->toFloatVector());
ASSERT_NOT_REACHED();
return false;
}
CWE ID:
Target: 1
Example 2:
Code: void unregister_netdev(struct net_device *dev)
{
rtnl_lock();
unregister_netdevice(dev);
rtnl_unlock();
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ChromeOSChangeInputMethod(
InputMethodStatusConnection* connection, const char* name) {
DCHECK(name);
DLOG(INFO) << "ChangeInputMethod: " << name;
g_return_val_if_fail(connection, false);
return connection->ChangeInputMethod(name);
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: TestPaintArtifact& TestPaintArtifact::Chunk(
scoped_refptr<const TransformPaintPropertyNode> transform,
scoped_refptr<const ClipPaintPropertyNode> clip,
scoped_refptr<const EffectPaintPropertyNode> effect) {
return Chunk(NewClient(), transform, clip, effect);
}
CWE ID:
Target: 1
Example 2:
Code: void __init mmap_init(void)
{
int ret;
ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
VM_BUG_ON(ret);
}
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: gray_line_to( const FT_Vector* to,
PWorker worker )
{
gray_render_line( RAS_VAR_ UPSCALE( to->x ), UPSCALE( to->y ) );
return 0;
}
CWE ID: CWE-189
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: XGetDeviceControl(
register Display *dpy,
XDevice *dev,
int control)
{
XDeviceControl *Device = NULL;
XDeviceControl *Sav = NULL;
xDeviceState *d = NULL;
xDeviceState *sav = NULL;
xGetDeviceControlReq *req;
xGetDeviceControlReply rep;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Add_XChangeDeviceControl, info) == -1)
return NULL;
GetReq(GetDeviceControl, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetDeviceControl;
req->deviceid = dev->device_id;
req->control = control;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
goto out;
if (rep.length > 0) {
unsigned long nbytes;
size_t size = 0;
if (rep.length < (INT_MAX >> 2)) {
nbytes = (unsigned long) rep.length << 2;
d = Xmalloc(nbytes);
}
_XEatDataWords(dpy, rep.length);
goto out;
}
sav = d;
_XRead(dpy, (char *)d, nbytes);
/* In theory, we should just be able to use d->length to get the size.
* Turns out that a number of X servers (up to and including server
* 1.4) sent the wrong length value down the wire. So to not break
* apps that run against older servers, we have to calculate the size
* manually.
*/
switch (d->control) {
case DEVICE_RESOLUTION:
{
xDeviceResolutionState *r;
size_t val_size;
size_t val_size;
r = (xDeviceResolutionState *) d;
if (r->num_valuators >= (INT_MAX / (3 * sizeof(int))))
goto out;
val_size = 3 * sizeof(int) * r->num_valuators;
if ((sizeof(xDeviceResolutionState) + val_size) > nbytes)
break;
}
case DEVICE_ABS_CALIB:
{
if (sizeof(xDeviceAbsCalibState) > nbytes)
goto out;
size = sizeof(XDeviceAbsCalibState);
break;
}
case DEVICE_ABS_AREA:
{
if (sizeof(xDeviceAbsAreaState) > nbytes)
goto out;
size = sizeof(XDeviceAbsAreaState);
break;
}
case DEVICE_CORE:
{
if (sizeof(xDeviceCoreState) > nbytes)
goto out;
size = sizeof(XDeviceCoreState);
break;
}
default:
if (d->length > nbytes)
goto out;
size = d->length;
break;
}
Device = Xmalloc(size);
if (!Device)
goto out;
Sav = Device;
d = sav;
switch (control) {
case DEVICE_RESOLUTION:
{
int *iptr, *iptr2;
xDeviceResolutionState *r;
XDeviceResolutionState *R;
unsigned int i;
r = (xDeviceResolutionState *) d;
R = (XDeviceResolutionState *) Device;
R->control = DEVICE_RESOLUTION;
R->length = sizeof(XDeviceResolutionState);
R->num_valuators = r->num_valuators;
iptr = (int *)(R + 1);
iptr2 = (int *)(r + 1);
R->resolutions = iptr;
R->min_resolutions = iptr + R->num_valuators;
R->max_resolutions = iptr + (2 * R->num_valuators);
for (i = 0; i < (3 * R->num_valuators); i++)
*iptr++ = *iptr2++;
break;
}
case DEVICE_ABS_CALIB:
{
xDeviceAbsCalibState *c = (xDeviceAbsCalibState *) d;
XDeviceAbsCalibState *C = (XDeviceAbsCalibState *) Device;
C->control = DEVICE_ABS_CALIB;
C->length = sizeof(XDeviceAbsCalibState);
C->min_x = c->min_x;
C->max_x = c->max_x;
C->min_y = c->min_y;
C->max_y = c->max_y;
C->flip_x = c->flip_x;
C->flip_y = c->flip_y;
C->rotation = c->rotation;
C->button_threshold = c->button_threshold;
break;
}
case DEVICE_ABS_AREA:
{
xDeviceAbsAreaState *a = (xDeviceAbsAreaState *) d;
XDeviceAbsAreaState *A = (XDeviceAbsAreaState *) Device;
A->control = DEVICE_ABS_AREA;
A->length = sizeof(XDeviceAbsAreaState);
A->offset_x = a->offset_x;
A->offset_y = a->offset_y;
A->width = a->width;
A->height = a->height;
A->screen = a->screen;
A->following = a->following;
break;
}
case DEVICE_CORE:
{
xDeviceCoreState *c = (xDeviceCoreState *) d;
XDeviceCoreState *C = (XDeviceCoreState *) Device;
C->control = DEVICE_CORE;
C->length = sizeof(XDeviceCoreState);
C->status = c->status;
C->iscore = c->iscore;
break;
}
case DEVICE_ENABLE:
{
xDeviceEnableState *e = (xDeviceEnableState *) d;
XDeviceEnableState *E = (XDeviceEnableState *) Device;
E->control = DEVICE_ENABLE;
E->length = sizeof(E);
E->enable = e->enable;
break;
}
default:
break;
}
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: zsetfillcolorspace(i_ctx_t * i_ctx_p)
{
return zsetcolorspace(i_ctx_p);
}
CWE ID: CWE-704
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void TIFFWarnings(const char *module,const char *format,va_list warning)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent,format,warning);
#else
(void) vsprintf(message,format,warning);
#endif
message[MaxTextExtent-2]='\0';
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'",module);
}
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 Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
CWE ID: CWE-269
Target: 1
Example 2:
Code: MagickExport ClassType GetPixelCacheStorageClass(const Cache cache)
{
CacheInfo
*restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
return(cache_info->storage_class);
}
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: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){
static char base_address;
xmlNodePtr cur = NULL;
xmlXPathObjectPtr obj = NULL;
long val;
xmlChar str[30];
xmlDocPtr doc;
if (nargs == 0) {
cur = ctxt->context->node;
} else if (nargs == 1) {
xmlNodeSetPtr nodelist;
int i, ret;
if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) {
ctxt->error = XPATH_INVALID_TYPE;
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"generate-id() : invalid arg expecting a node-set\n");
return;
}
obj = valuePop(ctxt);
nodelist = obj->nodesetval;
if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) {
xmlXPathFreeObject(obj);
valuePush(ctxt, xmlXPathNewCString(""));
return;
}
cur = nodelist->nodeTab[0];
for (i = 1;i < nodelist->nodeNr;i++) {
ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]);
if (ret == -1)
cur = nodelist->nodeTab[i];
}
} else {
xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,
"generate-id() : invalid number of args %d\n", nargs);
ctxt->error = XPATH_INVALID_ARITY;
return;
}
/*
* Okay this is ugly but should work, use the NodePtr address
* to forge the ID
*/
if (cur->type != XML_NAMESPACE_DECL)
doc = cur->doc;
else {
xmlNsPtr ns = (xmlNsPtr) cur;
if (ns->context != NULL)
doc = ns->context;
else
doc = ctxt->context->doc;
}
if (obj)
xmlXPathFreeObject(obj);
val = (long)((char *)cur - (char *)&base_address);
if (val >= 0) {
sprintf((char *)str, "idp%ld", val);
} else {
sprintf((char *)str, "idm%ld", -val);
}
valuePush(ctxt, xmlXPathNewString(str));
}
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: gss_delete_sec_context (minor_status,
context_handle,
output_token)
OM_uint32 * minor_status;
gss_ctx_id_t * context_handle;
gss_buffer_t output_token;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
status = val_del_sec_ctx_args(minor_status, context_handle, output_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;
if (GSSINT_CHK_LOOP(ctx))
return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);
status = gssint_delete_internal_sec_context(minor_status,
ctx->mech_type,
&ctx->internal_ctx_id,
output_token);
if (status)
return status;
/* now free up the space for the union context structure */
free(ctx->mech_type->elements);
free(ctx->mech_type);
free(*context_handle);
*context_handle = GSS_C_NO_CONTEXT;
return (GSS_S_COMPLETE);
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
{
if (ssh->queueing)
ssh2_pkt_queue(ssh, pkt);
else
ssh2_pkt_defer_noqueue(ssh, pkt, 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: bool UnprivilegedProcessDelegate::LaunchProcess(
IPC::Listener* delegate,
ScopedHandle* process_exit_event_out) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
std::string channel_name = GenerateIpcChannelName(this);
ScopedHandle client;
scoped_ptr<IPC::ChannelProxy> server;
if (!CreateConnectedIpcChannel(channel_name, delegate, &client, &server))
return false;
std::string pipe_handle = base::StringPrintf(
"%d", reinterpret_cast<ULONG_PTR>(client.Get()));
CommandLine command_line(binary_path_);
command_line.AppendSwitchASCII(kDaemonPipeSwitchName, pipe_handle);
command_line.CopySwitchesFrom(*CommandLine::ForCurrentProcess(),
kCopiedSwitchNames,
arraysize(kCopiedSwitchNames));
ScopedHandle worker_thread;
worker_process_.Close();
if (!LaunchProcessWithToken(command_line.GetProgram(),
command_line.GetCommandLineString(),
NULL,
true,
0,
&worker_process_,
&worker_thread)) {
return false;
}
ScopedHandle process_exit_event;
if (!DuplicateHandle(GetCurrentProcess(),
worker_process_,
GetCurrentProcess(),
process_exit_event.Receive(),
SYNCHRONIZE,
FALSE,
0)) {
LOG_GETLASTERROR(ERROR) << "Failed to duplicate a handle";
KillProcess(CONTROL_C_EXIT);
return false;
}
channel_ = server.Pass();
*process_exit_event_out = process_exit_event.Pass();
return true;
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
{
struct key *keyring;
int bucket;
if (!name)
return ERR_PTR(-EINVAL);
bucket = keyring_hash(name);
read_lock(&keyring_name_lock);
if (keyring_name_hash[bucket].next) {
/* search this hash bucket for a keyring with a matching name
* that's readable and that hasn't been revoked */
list_for_each_entry(keyring,
&keyring_name_hash[bucket],
name_link
) {
if (!kuid_has_mapping(current_user_ns(), keyring->user->uid))
continue;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
continue;
if (strcmp(keyring->description, name) != 0)
continue;
if (!skip_perm_check &&
key_permission(make_key_ref(keyring, 0),
KEY_NEED_SEARCH) < 0)
continue;
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!refcount_inc_not_zero(&keyring->usage))
continue;
keyring->last_used_at = current_kernel_time().tv_sec;
goto out;
}
}
keyring = ERR_PTR(-ENOKEY);
out:
read_unlock(&keyring_name_lock);
return keyring;
}
CWE ID:
Target: 1
Example 2:
Code: int vrend_create_sampler_view(struct vrend_context *ctx,
uint32_t handle,
uint32_t res_handle, uint32_t format,
uint32_t val0, uint32_t val1, uint32_t swizzle_packed)
{
struct vrend_sampler_view *view;
struct vrend_resource *res;
int ret_handle;
res = vrend_renderer_ctx_res_lookup(ctx, res_handle);
if (!res) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_RESOURCE, res_handle);
return EINVAL;
}
view = CALLOC_STRUCT(vrend_sampler_view);
if (!view)
return ENOMEM;
pipe_reference_init(&view->reference, 1);
view->format = format;
view->val0 = val0;
view->val1 = val1;
view->swizzle_r = swizzle_packed & 0x7;
view->swizzle_g = (swizzle_packed >> 3) & 0x7;
view->swizzle_b = (swizzle_packed >> 6) & 0x7;
view->swizzle_a = (swizzle_packed >> 9) & 0x7;
view->cur_base = -1;
view->cur_max = 10000;
vrend_resource_reference(&view->texture, res);
view->srgb_decode = GL_DECODE_EXT;
if (view->format != view->texture->base.format) {
if (util_format_is_srgb(view->texture->base.format) &&
!util_format_is_srgb(view->format))
view->srgb_decode = GL_SKIP_DECODE_EXT;
}
view->gl_swizzle_a = to_gl_swizzle(view->swizzle_a);
view->gl_swizzle_r = to_gl_swizzle(view->swizzle_r);
view->gl_swizzle_g = to_gl_swizzle(view->swizzle_g);
view->gl_swizzle_b = to_gl_swizzle(view->swizzle_b);
if (!(util_format_has_alpha(format) || util_format_is_depth_or_stencil(format))) {
if (view->gl_swizzle_a == GL_ALPHA)
view->gl_swizzle_a = GL_ONE;
if (view->gl_swizzle_r == GL_ALPHA)
view->gl_swizzle_r = GL_ONE;
if (view->gl_swizzle_g == GL_ALPHA)
view->gl_swizzle_g = GL_ONE;
if (view->gl_swizzle_b == GL_ALPHA)
view->gl_swizzle_b = GL_ONE;
}
if (tex_conv_table[format].flags & VREND_BIND_NEED_SWIZZLE) {
view->gl_swizzle_r = to_gl_swizzle(tex_conv_table[format].swizzle[0]);
view->gl_swizzle_g = to_gl_swizzle(tex_conv_table[format].swizzle[1]);
view->gl_swizzle_b = to_gl_swizzle(tex_conv_table[format].swizzle[2]);
view->gl_swizzle_a = to_gl_swizzle(tex_conv_table[format].swizzle[3]);
}
ret_handle = vrend_renderer_object_insert(ctx, view, sizeof(*view), handle, VIRGL_OBJECT_SAMPLER_VIEW);
if (ret_handle == 0) {
FREE(view);
return ENOMEM;
}
return 0;
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool DataReductionProxySettings::IsDataReductionProxyEnabled() const {
if (base::FeatureList::IsEnabled(network::features::kNetworkService) &&
!params::IsEnabledWithNetworkService()) {
return false;
}
return IsDataSaverEnabledByUser();
}
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: unsigned paravirt_patch_call(void *insnbuf,
const void *target, u16 tgt_clobbers,
unsigned long addr, u16 site_clobbers,
unsigned len)
{
struct branch *b = insnbuf;
unsigned long delta = (unsigned long)target - (addr+5);
if (tgt_clobbers & ~site_clobbers)
return len; /* target would clobber too much for this site */
if (len < 5)
return len; /* call too long for patch site */
b->opcode = 0xe8; /* call */
b->delta = delta;
BUILD_BUG_ON(sizeof(*b) != 5);
return 5;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static HB_Error Load_PosRule( HB_PosRule* pr,
HB_Stream stream )
{
HB_Error error;
HB_UShort n, count;
HB_UShort* i;
HB_PosLookupRecord* plr;
if ( ACCESS_Frame( 4L ) )
return error;
pr->GlyphCount = GET_UShort();
pr->PosCount = GET_UShort();
FORGET_Frame();
pr->Input = NULL;
count = pr->GlyphCount - 1; /* only GlyphCount - 1 elements */
if ( ALLOC_ARRAY( pr->Input, count, HB_UShort ) )
return error;
i = pr->Input;
if ( ACCESS_Frame( count * 2L ) )
goto Fail2;
for ( n = 0; n < count; n++ )
i[n] = GET_UShort();
FORGET_Frame();
pr->PosLookupRecord = NULL;
count = pr->PosCount;
if ( ALLOC_ARRAY( pr->PosLookupRecord, count, HB_PosLookupRecord ) )
goto Fail2;
plr = pr->PosLookupRecord;
if ( ACCESS_Frame( count * 4L ) )
goto Fail1;
for ( n = 0; n < count; n++ )
{
plr[n].SequenceIndex = GET_UShort();
plr[n].LookupListIndex = GET_UShort();
}
FORGET_Frame();
return HB_Err_Ok;
Fail1:
FREE( plr );
Fail2:
FREE( i );
return error;
}
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 handle_emulation_failure(struct kvm_vcpu *vcpu)
{
int r = EMULATE_DONE;
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
if (!is_guest_mode(vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
r = EMULATE_FAIL;
}
kvm_queue_exception(vcpu, UD_VECTOR);
return r;
}
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 int tomoyo_mount_acl(struct tomoyo_request_info *r, char *dev_name,
struct path *dir, char *type, unsigned long flags)
{
struct path path;
struct file_system_type *fstype = NULL;
const char *requested_type = NULL;
const char *requested_dir_name = NULL;
const char *requested_dev_name = NULL;
struct tomoyo_path_info rtype;
struct tomoyo_path_info rdev;
struct tomoyo_path_info rdir;
int need_dev = 0;
int error = -ENOMEM;
/* Get fstype. */
requested_type = tomoyo_encode(type);
if (!requested_type)
goto out;
rtype.name = requested_type;
tomoyo_fill_path_info(&rtype);
/* Get mount point. */
requested_dir_name = tomoyo_realpath_from_path(dir);
if (!requested_dir_name) {
error = -ENOMEM;
goto out;
}
rdir.name = requested_dir_name;
tomoyo_fill_path_info(&rdir);
/* Compare fs name. */
if (!strcmp(type, TOMOYO_MOUNT_REMOUNT_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_MAKE_UNBINDABLE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_PRIVATE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SLAVE_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MAKE_SHARED_KEYWORD)) {
/* dev_name is ignored. */
} else if (!strcmp(type, TOMOYO_MOUNT_BIND_KEYWORD) ||
!strcmp(type, TOMOYO_MOUNT_MOVE_KEYWORD)) {
need_dev = -1; /* dev_name is a directory */
} else {
fstype = get_fs_type(type);
if (!fstype) {
error = -ENODEV;
goto out;
}
if (fstype->fs_flags & FS_REQUIRES_DEV)
/* dev_name is a block device file. */
need_dev = 1;
}
if (need_dev) {
/* Get mount point or device file. */
if (kern_path(dev_name, LOOKUP_FOLLOW, &path)) {
error = -ENOENT;
goto out;
}
requested_dev_name = tomoyo_realpath_from_path(&path);
path_put(&path);
if (!requested_dev_name) {
error = -ENOENT;
goto out;
}
} else {
/* Map dev_name to "<NULL>" if no dev_name given. */
if (!dev_name)
dev_name = "<NULL>";
requested_dev_name = tomoyo_encode(dev_name);
if (!requested_dev_name) {
error = -ENOMEM;
goto out;
}
}
rdev.name = requested_dev_name;
tomoyo_fill_path_info(&rdev);
r->param_type = TOMOYO_TYPE_MOUNT_ACL;
r->param.mount.need_dev = need_dev;
r->param.mount.dev = &rdev;
r->param.mount.dir = &rdir;
r->param.mount.type = &rtype;
r->param.mount.flags = flags;
do {
tomoyo_check_acl(r, tomoyo_check_mount_acl);
error = tomoyo_audit_mount_log(r);
} while (error == TOMOYO_RETRY_REQUEST);
out:
kfree(requested_dev_name);
kfree(requested_dir_name);
if (fstype)
put_filesystem(fstype);
kfree(requested_type);
return error;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: reset_peer_stats(peer_t *p, double offset)
{
int i;
bool small_ofs = fabs(offset) < STEP_THRESHOLD;
/* Used to set p->filter_datapoint[i].d_dispersion = MAXDISP
* and clear reachable bits, but this proved to be too agressive:
* after step (tested with suspending laptop for ~30 secs),
* this caused all previous data to be considered invalid,
* making us needing to collect full ~8 datapoins per peer
* after step in order to start trusting them.
* In turn, this was making poll interval decrease even after
* step was done. (Poll interval decreases already before step
* in this scenario, because we see large offsets and end up with
* no good peer to select).
*/
for (i = 0; i < NUM_DATAPOINTS; i++) {
if (small_ofs) {
p->filter_datapoint[i].d_recv_time += offset;
if (p->filter_datapoint[i].d_offset != 0) {
p->filter_datapoint[i].d_offset -= offset;
}
} else {
p->filter_datapoint[i].d_recv_time = G.cur_time;
p->filter_datapoint[i].d_offset = 0;
/*p->filter_datapoint[i].d_dispersion = MAXDISP;*/
}
}
if (small_ofs) {
p->lastpkt_recv_time += offset;
} else {
/*p->reachable_bits = 0;*/
p->lastpkt_recv_time = G.cur_time;
}
filter_datapoints(p); /* recalc p->filter_xxx */
VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
}
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: virDomainIsActive(virDomainPtr dom)
{
VIR_DEBUG("dom=%p", dom);
virResetLastError();
virCheckDomainReturn(dom, -1);
if (dom->conn->driver->domainIsActive) {
int ret;
ret = dom->conn->driver->domainIsActive(dom);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(dom->conn);
return -1;
}
CWE ID: CWE-254
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ChunkedUploadDataStream::AppendData(
const char* data, int data_len, bool is_done) {
DCHECK(!all_data_appended_);
DCHECK(data_len > 0 || is_done);
if (data_len > 0) {
DCHECK(data);
upload_data_.push_back(
base::MakeUnique<std::vector<char>>(data, data + data_len));
}
all_data_appended_ = is_done;
if (!read_buffer_.get())
return;
int result = ReadChunk(read_buffer_.get(), read_buffer_len_);
DCHECK_GE(result, 0);
read_buffer_ = NULL;
read_buffer_len_ = 0;
OnReadCompleted(result);
}
CWE ID: CWE-311
Target: 1
Example 2:
Code: check_secret_key( RSA_secret_key *sk )
{
int rc;
gcry_mpi_t temp = mpi_alloc( mpi_get_nlimbs(sk->p)*2 );
mpi_mul(temp, sk->p, sk->q );
rc = mpi_cmp( temp, sk->n );
mpi_free(temp);
return !rc;
}
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: static void process_blob(struct rev_info *revs,
struct blob *blob,
show_object_fn show,
struct strbuf *path,
const char *name,
void *cb_data)
{
struct object *obj = &blob->object;
if (!revs->blob_objects)
return;
if (!obj)
die("bad blob object");
if (obj->flags & (UNINTERESTING | SEEN))
return;
obj->flags |= SEEN;
show(obj, path, name, cb_data);
}
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 _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type )
{
char *f_org, *f_dest;
int f_org_len, f_dest_len;
long height, width, threshold;
gdImagePtr im_org, im_dest, im_tmp;
char *fn_org = NULL;
char *fn_dest = NULL;
FILE *org, *dest;
int dest_height = -1;
int dest_width = -1;
int org_height, org_width;
int white, black;
int color, color_org, median;
int int_threshold;
int x, y;
float x_ratio, y_ratio;
long ignore_warning;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pplll", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) {
return;
}
fn_org = f_org;
fn_dest = f_dest;
dest_height = height;
dest_width = width;
int_threshold = threshold;
/* Check threshold value */
if (int_threshold < 0 || int_threshold > 8) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid threshold value '%d'", int_threshold);
RETURN_FALSE;
}
/* Check origin file */
PHP_GD_CHECK_OPEN_BASEDIR(fn_org, "Invalid origin filename");
/* Check destination file */
PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, "Invalid destination filename");
/* Open origin file */
org = VCWD_FOPEN(fn_org, "rb");
if (!org) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for reading", fn_org);
RETURN_FALSE;
}
/* Open destination file */
dest = VCWD_FOPEN(fn_dest, "wb");
if (!dest) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' for writing", fn_dest);
RETURN_FALSE;
}
switch (image_type) {
case PHP_GDIMG_TYPE_GIF:
im_org = gdImageCreateFromGif(org);
if (im_org == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid GIF file", fn_dest);
RETURN_FALSE;
}
break;
#ifdef HAVE_GD_JPG
case PHP_GDIMG_TYPE_JPG:
ignore_warning = INI_INT("gd.jpeg_ignore_warning");
im_org = gdImageCreateFromJpegEx(org, ignore_warning);
if (im_org == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid JPEG file", fn_dest);
RETURN_FALSE;
}
break;
#endif /* HAVE_GD_JPG */
#ifdef HAVE_GD_PNG
case PHP_GDIMG_TYPE_PNG:
im_org = gdImageCreateFromPng(org);
if (im_org == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open '%s' Not a valid PNG file", fn_dest);
RETURN_FALSE;
}
break;
#endif /* HAVE_GD_PNG */
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Format not supported");
RETURN_FALSE;
break;
}
org_width = gdImageSX (im_org);
org_height = gdImageSY (im_org);
x_ratio = (float) org_width / (float) dest_width;
y_ratio = (float) org_height / (float) dest_height;
if (x_ratio > 1 && y_ratio > 1) {
if (y_ratio > x_ratio) {
x_ratio = y_ratio;
} else {
y_ratio = x_ratio;
}
dest_width = (int) (org_width / x_ratio);
dest_height = (int) (org_height / y_ratio);
} else {
x_ratio = (float) dest_width / (float) org_width;
y_ratio = (float) dest_height / (float) org_height;
if (y_ratio < x_ratio) {
x_ratio = y_ratio;
} else {
y_ratio = x_ratio;
}
dest_width = (int) (org_width * x_ratio);
dest_height = (int) (org_height * y_ratio);
}
im_tmp = gdImageCreate (dest_width, dest_height);
if (im_tmp == NULL ) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate temporary buffer");
RETURN_FALSE;
}
gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height);
gdImageDestroy(im_org);
fclose(org);
im_dest = gdImageCreate(dest_width, dest_height);
if (im_dest == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate destination buffer");
RETURN_FALSE;
}
white = gdImageColorAllocate(im_dest, 255, 255, 255);
if (white == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer");
RETURN_FALSE;
}
black = gdImageColorAllocate(im_dest, 0, 0, 0);
if (black == -1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to allocate the colors for the destination buffer");
RETURN_FALSE;
}
int_threshold = int_threshold * 32;
for (y = 0; y < dest_height; y++) {
for (x = 0; x < dest_width; x++) {
color_org = gdImageGetPixel (im_tmp, x, y);
median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3;
if (median < int_threshold) {
color = black;
} else {
color = white;
}
gdImageSetPixel (im_dest, x, y, color);
}
}
gdImageDestroy (im_tmp );
gdImageWBMP(im_dest, black , dest);
fflush(dest);
fclose(dest);
gdImageDestroy(im_dest);
RETURN_TRUE;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: virtual void TearDown() {
download_manager_ = NULL;
ui_thread_.message_loop()->RunAllPending();
}
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 Cues::PreloadCuePoint(
long& cue_points_size,
long long pos) const
{
assert(m_count == 0);
if (m_preload_count >= cue_points_size)
{
const long n = (cue_points_size <= 0) ? 2048 : 2*cue_points_size;
CuePoint** const qq = new CuePoint*[n];
CuePoint** q = qq; //beginning of target
CuePoint** p = m_cue_points; //beginning of source
CuePoint** const pp = p + m_preload_count; //end of source
while (p != pp)
*q++ = *p++;
delete[] m_cue_points;
m_cue_points = qq;
cue_points_size = n;
}
CuePoint* const pCP = new CuePoint(m_preload_count, pos);
m_cue_points[m_preload_count++] = pCP;
}
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 sched_read_attr(struct sched_attr __user *uattr,
struct sched_attr *attr,
unsigned int usize)
{
int ret;
if (!access_ok(VERIFY_WRITE, uattr, usize))
return -EFAULT;
/*
* If we're handed a smaller struct than we know of,
* ensure all the unknown bits are 0 - i.e. old
* user-space does not get uncomplete information.
*/
if (usize < sizeof(*attr)) {
unsigned char *addr;
unsigned char *end;
addr = (void *)attr + usize;
end = (void *)attr + sizeof(*attr);
for (; addr < end; addr++) {
if (*addr)
goto err_size;
}
attr->size = usize;
}
ret = copy_to_user(uattr, attr, usize);
if (ret)
return -EFAULT;
out:
return ret;
err_size:
ret = -E2BIG;
goto out;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void randomdelay(void)
{
usleep(rand() % 15000UL); /* dummy... no need for arc4 */
}
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 LiveSyncTest::SetupMockGaiaResponses() {
username_ = "[email protected]";
password_ = "password";
factory_.reset(new FakeURLFetcherFactory());
factory_->SetFakeResponse(kClientLoginUrl, "SID=sid\nLSID=lsid", true);
factory_->SetFakeResponse(kGetUserInfoUrl, "[email protected]", true);
factory_->SetFakeResponse(kIssueAuthTokenUrl, "auth", true);
factory_->SetFakeResponse(kSearchDomainCheckUrl, ".google.com", true);
URLFetcher::set_factory(factory_.get());
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void __svc_rdma_free(struct work_struct *work)
{
struct svcxprt_rdma *rdma =
container_of(work, struct svcxprt_rdma, sc_work);
struct svc_xprt *xprt = &rdma->sc_xprt;
dprintk("svcrdma: %s(%p)\n", __func__, rdma);
if (rdma->sc_qp && !IS_ERR(rdma->sc_qp))
ib_drain_qp(rdma->sc_qp);
/* We should only be called from kref_put */
if (kref_read(&xprt->xpt_ref) != 0)
pr_err("svcrdma: sc_xprt still in use? (%d)\n",
kref_read(&xprt->xpt_ref));
/*
* Destroy queued, but not processed read completions. Note
* that this cleanup has to be done before destroying the
* cm_id because the device ptr is needed to unmap the dma in
* svc_rdma_put_context.
*/
while (!list_empty(&rdma->sc_read_complete_q)) {
struct svc_rdma_op_ctxt *ctxt;
ctxt = list_first_entry(&rdma->sc_read_complete_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
svc_rdma_put_context(ctxt, 1);
}
/* Destroy queued, but not processed recv completions */
while (!list_empty(&rdma->sc_rq_dto_q)) {
struct svc_rdma_op_ctxt *ctxt;
ctxt = list_first_entry(&rdma->sc_rq_dto_q,
struct svc_rdma_op_ctxt, list);
list_del(&ctxt->list);
svc_rdma_put_context(ctxt, 1);
}
/* Warn if we leaked a resource or under-referenced */
if (rdma->sc_ctxt_used != 0)
pr_err("svcrdma: ctxt still in use? (%d)\n",
rdma->sc_ctxt_used);
/* Final put of backchannel client transport */
if (xprt->xpt_bc_xprt) {
xprt_put(xprt->xpt_bc_xprt);
xprt->xpt_bc_xprt = NULL;
}
rdma_dealloc_frmr_q(rdma);
svc_rdma_destroy_ctxts(rdma);
svc_rdma_destroy_maps(rdma);
/* Destroy the QP if present (not a listener) */
if (rdma->sc_qp && !IS_ERR(rdma->sc_qp))
ib_destroy_qp(rdma->sc_qp);
if (rdma->sc_sq_cq && !IS_ERR(rdma->sc_sq_cq))
ib_free_cq(rdma->sc_sq_cq);
if (rdma->sc_rq_cq && !IS_ERR(rdma->sc_rq_cq))
ib_free_cq(rdma->sc_rq_cq);
if (rdma->sc_pd && !IS_ERR(rdma->sc_pd))
ib_dealloc_pd(rdma->sc_pd);
/* Destroy the CM ID */
rdma_destroy_id(rdma->sc_cm_id);
kfree(rdma);
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: static void session_get_config(struct session_s *session, effect_config_t *config)
{
memcpy(config, &session->config, sizeof(effect_config_t));
config->inputCfg.mask = config->outputCfg.mask =
(EFFECT_CONFIG_SMP_RATE | EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_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: rpc_xdr_encode(struct rpc_task *task)
{
struct rpc_rqst *req = task->tk_rqstp;
kxdreproc_t encode;
__be32 *p;
dprint_status(task);
rpc_xdr_buf_init(&req->rq_snd_buf,
req->rq_buffer,
req->rq_callsize);
rpc_xdr_buf_init(&req->rq_rcv_buf,
(char *)req->rq_buffer + req->rq_callsize,
req->rq_rcvsize);
p = rpc_encode_header(task);
if (p == NULL) {
printk(KERN_INFO "RPC: couldn't encode RPC header, exit EIO\n");
rpc_exit(task, -EIO);
return;
}
encode = task->tk_msg.rpc_proc->p_encode;
if (encode == NULL)
return;
task->tk_status = rpcauth_wrap_req(task, encode, req, p,
task->tk_msg.rpc_argp);
}
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: forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
if (q >= end) return 0; /* fail */
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: void RenderViewImpl::OnImeConfirmComposition(
const string16& text, const ui::Range& replacement_range) {
if (pepper_delegate_.IsPluginFocused()) {
pepper_delegate_.OnImeConfirmComposition(text);
} else {
#if defined(OS_WIN)
if (focused_plugin_id_ >= 0) {
std::set<WebPluginDelegateProxy*>::iterator it;
for (it = plugin_delegates_.begin();
it != plugin_delegates_.end(); ++it) {
(*it)->ImeCompositionCompleted(text, focused_plugin_id_);
}
return;
}
#endif
if (replacement_range.IsValid() && webview()) {
if (WebFrame* frame = webview()->focusedFrame()) {
WebRange webrange = WebRange::fromDocumentRange(
frame, replacement_range.start(), replacement_range.length());
if (!webrange.isNull())
frame->setSelectionToRange(webrange);
}
}
RenderWidget::OnImeConfirmComposition(text, replacement_range);
}
}
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 RenderFrameHostManager::CreateSpeculativeRenderFrameHost(
SiteInstance* old_instance,
SiteInstance* new_instance) {
CHECK(new_instance);
CHECK_NE(old_instance, new_instance);
if (!new_instance->GetProcess()->Init())
return false;
CreateProxiesForNewRenderFrameHost(old_instance, new_instance);
speculative_render_frame_host_ =
CreateRenderFrame(new_instance, delegate_->IsHidden(), nullptr);
return !!speculative_render_frame_host_;
}
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: perform_gamma_threshold_tests(png_modifier *pm)
{
png_byte colour_type = 0;
png_byte bit_depth = 0;
unsigned int palette_number = 0;
/* Don't test more than one instance of each palette - it's pointless, in
* fact this test is somewhat excessive since libpng doesn't make this
* decision based on colour type or bit depth!
*/
while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/))
if (palette_number == 0)
{
double test_gamma = 1.0;
while (test_gamma >= .4)
{
/* There's little point testing the interlacing vs non-interlacing,
* but this can be set from the command line.
*/
gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
test_gamma, 1/test_gamma);
test_gamma *= .95;
}
/* And a special test for sRGB */
gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type,
.45455, 2.2);
if (fail(pm))
return;
}
}
CWE ID:
Target: 1
Example 2:
Code: EventFilteringInfo ParseFromObject(v8::Local<v8::Object> object,
v8::Isolate* isolate) {
EventFilteringInfo info;
v8::Local<v8::String> url(v8::String::NewFromUtf8(isolate, "url"));
if (object->Has(url)) {
v8::Local<v8::Value> url_value(object->Get(url));
info.SetURL(GURL(*v8::String::Utf8Value(url_value)));
}
v8::Local<v8::String> instance_id(
v8::String::NewFromUtf8(isolate, "instanceId"));
if (object->Has(instance_id)) {
v8::Local<v8::Value> instance_id_value(object->Get(instance_id));
info.SetInstanceID(instance_id_value->IntegerValue());
}
v8::Local<v8::String> service_type(
v8::String::NewFromUtf8(isolate, "serviceType"));
if (object->Has(service_type)) {
v8::Local<v8::Value> service_type_value(object->Get(service_type));
info.SetServiceType(*v8::String::Utf8Value(service_type_value));
}
v8::Local<v8::String> window_types(
v8::String::NewFromUtf8(isolate, "windowType"));
if (object->Has(window_types)) {
v8::Local<v8::Value> window_types_value(object->Get(window_types));
info.SetWindowType(*v8::String::Utf8Value(window_types_value));
}
v8::Local<v8::String> window_exposed(
v8::String::NewFromUtf8(isolate, "windowExposedByDefault"));
if (object->Has(window_exposed)) {
v8::Local<v8::Value> window_exposed_value(object->Get(window_exposed));
info.SetWindowExposedByDefault(
window_exposed_value.As<v8::Boolean>()->Value());
}
return info;
}
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 ClosestColor(const Image *image,CubeInfo *cube_info,
const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
ClosestColor(image,cube_info,node_info->child[i]);
if (node_info->number_unique != 0)
{
MagickRealType
pixel;
register DoublePixelPacket
*magick_restrict q;
register MagickRealType
alpha,
beta,
distance;
register PixelPacket
*magick_restrict p;
/*
Determine if this color is "closest".
*/
p=image->colormap+node_info->color_number;
q=(&cube_info->target);
alpha=1.0;
beta=1.0;
if (cube_info->associate_alpha != MagickFalse)
{
alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p));
beta=(MagickRealType) (QuantumScale*GetPixelAlpha(q));
}
pixel=alpha*GetPixelRed(p)-beta*GetPixelRed(q);
distance=pixel*pixel;
if (distance <= cube_info->distance)
{
pixel=alpha*GetPixelGreen(p)-beta*GetPixelGreen(q);
distance+=pixel*pixel;
if (distance <= cube_info->distance)
{
pixel=alpha*GetPixelBlue(p)-beta*GetPixelBlue(q);
distance+=pixel*pixel;
if (distance <= cube_info->distance)
{
if (cube_info->associate_alpha != MagickFalse)
{
pixel=GetPixelAlpha(p)-GetPixelAlpha(q);
distance+=pixel*pixel;
}
if (distance <= cube_info->distance)
{
cube_info->distance=distance;
cube_info->color_number=node_info->color_number;
}
}
}
}
}
}
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 SeekHead::ParseEntry(IMkvReader* pReader, long long start, long long size_,
Entry* pEntry) {
if (size_ <= 0)
return false;
long long pos = start;
const long long stop = start + size_;
long len;
const long long seekIdId = ReadUInt(pReader, pos, len);
if (seekIdId != 0x13AB) // SeekID ID
return false;
if ((pos + len) > stop)
return false;
pos += len; // consume SeekID id
const long long seekIdSize = ReadUInt(pReader, pos, len);
if (seekIdSize <= 0)
return false;
if ((pos + len) > stop)
return false;
pos += len; // consume size of field
if ((pos + seekIdSize) > stop)
return false;
pEntry->id = ReadUInt(pReader, pos, len); // payload
if (pEntry->id <= 0)
return false;
if (len != seekIdSize)
return false;
pos += seekIdSize; // consume SeekID payload
const long long seekPosId = ReadUInt(pReader, pos, len);
if (seekPosId != 0x13AC) // SeekPos ID
return false;
if ((pos + len) > stop)
return false;
pos += len; // consume id
const long long seekPosSize = ReadUInt(pReader, pos, len);
if (seekPosSize <= 0)
return false;
if ((pos + len) > stop)
return false;
pos += len; // consume size
if ((pos + seekPosSize) > stop)
return false;
pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize);
if (pEntry->pos < 0)
return false;
pos += seekPosSize; // consume payload
if (pos != stop)
return false;
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: AXObject::AXRange AXLayoutObject::selection() const {
AXRange textSelection = textControlSelection();
if (textSelection.isValid())
return textSelection;
if (!getLayoutObject() || !getLayoutObject()->frame())
return AXRange();
VisibleSelection selection =
getLayoutObject()
->frame()
->selection()
.computeVisibleSelectionInDOMTreeDeprecated();
if (selection.isNone())
return AXRange();
VisiblePosition visibleStart = selection.visibleStart();
Position start = visibleStart.toParentAnchoredPosition();
TextAffinity startAffinity = visibleStart.affinity();
VisiblePosition visibleEnd = selection.visibleEnd();
Position end = visibleEnd.toParentAnchoredPosition();
TextAffinity endAffinity = visibleEnd.affinity();
Node* anchorNode = start.anchorNode();
ASSERT(anchorNode);
AXLayoutObject* anchorObject = nullptr;
while (anchorNode) {
anchorObject = getUnignoredObjectFromNode(*anchorNode);
if (anchorObject)
break;
if (anchorNode->nextSibling())
anchorNode = anchorNode->nextSibling();
else
anchorNode = anchorNode->parentNode();
}
Node* focusNode = end.anchorNode();
ASSERT(focusNode);
AXLayoutObject* focusObject = nullptr;
while (focusNode) {
focusObject = getUnignoredObjectFromNode(*focusNode);
if (focusObject)
break;
if (focusNode->previousSibling())
focusNode = focusNode->previousSibling();
else
focusNode = focusNode->parentNode();
}
if (!anchorObject || !focusObject)
return AXRange();
int anchorOffset = anchorObject->indexForVisiblePosition(visibleStart);
ASSERT(anchorOffset >= 0);
int focusOffset = focusObject->indexForVisiblePosition(visibleEnd);
ASSERT(focusOffset >= 0);
return AXRange(anchorObject, anchorOffset, startAffinity, focusObject,
focusOffset, endAffinity);
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int sctp6_rcv(struct sk_buff *skb)
{
return sctp_rcv(skb) ? -1 : 0;
}
CWE ID: CWE-310
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: IndexedDBTransaction::IndexedDBTransaction(
int64_t id,
IndexedDBConnection* connection,
const std::set<int64_t>& object_store_ids,
blink::WebIDBTransactionMode mode,
IndexedDBBackingStore::Transaction* backing_store_transaction)
: id_(id),
object_store_ids_(object_store_ids),
mode_(mode),
connection_(connection),
transaction_(backing_store_transaction),
ptr_factory_(this) {
IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this);
callbacks_ = connection_->callbacks();
database_ = connection_->database();
diagnostics_.tasks_scheduled = 0;
diagnostics_.tasks_completed = 0;
diagnostics_.creation_time = base::Time::Now();
}
CWE ID:
Target: 1
Example 2:
Code: int sm_looptest_fast_mode_start(p_fm_config_conx_hdlt hdl, fm_mgr_type_t mgr, int argc, char *argv[]) {
fm_mgr_config_errno_t res;
fm_msg_ret_code_t ret_code;
int numpkts=4;
uint8_t data[BUF_SZ];
if (argc > 1) {
printf("Error: only 1 argument expected\n");
return 0;
}
if (argc == 1) {
numpkts = atol(argv[0]);
if (numpkts < 0 || numpkts > 10) {
printf("Error: number of packets must be from 0 to 10\n");
return 0;
}
}
*(int*)data = numpkts;
if((res = fm_mgr_simple_query(hdl, FM_ACT_GET, FM_DT_SM_LOOP_TEST_FAST_MODE_START, mgr,
BUF_SZ, data, &ret_code)) != FM_CONF_OK)
{
fprintf(stderr, "sm_looptest_fast_mode_start: Failed to retrieve data: \n"
"\tError:(%d) %s \n\tRet code:(%d) %s\n",
res, fm_mgr_get_error_str(res),ret_code,
fm_mgr_get_resp_error_str(ret_code));
} else {
printf("Successfully sent Loop Test Fast Mode START control (%d inject packets) to local SM instance\n", numpkts);
data[BUF_SZ-1]=0;
printf("%s", (char*) data);
}
return 0;
}
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 JSValue getDataViewMember(ExecState* exec, DataView* imp, DataViewAccessType type)
{
if (exec->argumentCount() < 1)
return throwError(exec, createTypeError(exec, "Not enough arguments"));
ExceptionCode ec = 0;
unsigned byteOffset = exec->argument(0).toUInt32(exec);
if (exec->hadException())
return jsUndefined();
bool littleEndian = false;
if (exec->argumentCount() > 1 && (type == AccessDataViewMemberAsFloat32 || type == AccessDataViewMemberAsFloat64)) {
littleEndian = exec->argument(1).toBoolean(exec);
if (exec->hadException())
return jsUndefined();
}
JSC::JSValue result;
switch (type) {
case AccessDataViewMemberAsInt8:
result = jsNumber(imp->getInt8(byteOffset, ec));
break;
case AccessDataViewMemberAsUint8:
result = jsNumber(imp->getUint8(byteOffset, ec));
break;
case AccessDataViewMemberAsFloat32:
case AccessDataViewMemberAsFloat64: {
double value = (type == AccessDataViewMemberAsFloat32) ? imp->getFloat32(byteOffset, littleEndian, ec) : imp->getFloat64(byteOffset, littleEndian, ec);
result = isnan(value) ? jsNaN() : jsNumber(value);
break;
} default:
ASSERT_NOT_REACHED();
break;
}
setDOMException(exec, ec);
return result;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct rds_connection *__rds_conn_create(struct net *net,
__be32 laddr, __be32 faddr,
struct rds_transport *trans, gfp_t gfp,
int is_outgoing)
{
struct rds_connection *conn, *parent = NULL;
struct hlist_head *head = rds_conn_bucket(laddr, faddr);
struct rds_transport *loop_trans;
unsigned long flags;
int ret;
rcu_read_lock();
conn = rds_conn_lookup(net, head, laddr, faddr, trans);
if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport &&
laddr == faddr && !is_outgoing) {
/* This is a looped back IB connection, and we're
* called by the code handling the incoming connect.
* We need a second connection object into which we
* can stick the other QP. */
parent = conn;
conn = parent->c_passive;
}
rcu_read_unlock();
if (conn)
goto out;
conn = kmem_cache_zalloc(rds_conn_slab, gfp);
if (!conn) {
conn = ERR_PTR(-ENOMEM);
goto out;
}
INIT_HLIST_NODE(&conn->c_hash_node);
conn->c_laddr = laddr;
conn->c_faddr = faddr;
spin_lock_init(&conn->c_lock);
conn->c_next_tx_seq = 1;
rds_conn_net_set(conn, net);
init_waitqueue_head(&conn->c_waitq);
INIT_LIST_HEAD(&conn->c_send_queue);
INIT_LIST_HEAD(&conn->c_retrans);
ret = rds_cong_get_maps(conn);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
/*
* This is where a connection becomes loopback. If *any* RDS sockets
* can bind to the destination address then we'd rather the messages
* flow through loopback rather than either transport.
*/
loop_trans = rds_trans_get_preferred(net, faddr);
if (loop_trans) {
rds_trans_put(loop_trans);
conn->c_loopback = 1;
if (is_outgoing && trans->t_prefer_loopback) {
/* "outgoing" connection - and the transport
* says it wants the connection handled by the
* loopback transport. This is what TCP does.
*/
trans = &rds_loop_transport;
}
}
if (trans == NULL) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(-ENODEV);
goto out;
}
conn->c_trans = trans;
ret = trans->conn_alloc(conn, gfp);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
atomic_set(&conn->c_state, RDS_CONN_DOWN);
conn->c_send_gen = 0;
conn->c_outgoing = (is_outgoing ? 1 : 0);
conn->c_reconnect_jiffies = 0;
INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker);
INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker);
INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker);
INIT_WORK(&conn->c_down_w, rds_shutdown_worker);
mutex_init(&conn->c_cm_lock);
conn->c_flags = 0;
rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n",
conn, &laddr, &faddr,
trans->t_name ? trans->t_name : "[unknown]",
is_outgoing ? "(outgoing)" : "");
/*
* Since we ran without holding the conn lock, someone could
* have created the same conn (either normal or passive) in the
* interim. We check while holding the lock. If we won, we complete
* init and return our conn. If we lost, we rollback and return the
* other one.
*/
spin_lock_irqsave(&rds_conn_lock, flags);
if (parent) {
/* Creating passive conn */
if (parent->c_passive) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = parent->c_passive;
} else {
parent->c_passive = conn;
rds_cong_add_conn(conn);
rds_conn_count++;
}
} else {
/* Creating normal conn */
struct rds_connection *found;
found = rds_conn_lookup(net, head, laddr, faddr, trans);
if (found) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = found;
} else {
hlist_add_head_rcu(&conn->c_hash_node, head);
rds_cong_add_conn(conn);
rds_conn_count++;
}
}
spin_unlock_irqrestore(&rds_conn_lock, flags);
out:
return conn;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int has_item(char *ary[], const char *item)
{
char **p;
for (p = ary; *p != NULL; p++)
if (!strcmp(item, *p))
return 1;
return 0;
}
CWE ID: CWE-77
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 NavigationControllerImpl::NeedsReload() const {
return needs_reload_;
}
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 PrintRenderFrameHelper::PreviewPageRendered(int page_number,
PdfMetafileSkia* metafile) {
DCHECK_GE(page_number, FIRST_PAGE_INDEX);
if (!print_preview_context_.IsModifiable() ||
!print_preview_context_.generate_draft_pages()) {
DCHECK(!metafile);
return true;
}
if (!metafile) {
NOTREACHED();
print_preview_context_.set_error(
PREVIEW_ERROR_PAGE_RENDERED_WITHOUT_METAFILE);
return false;
}
PrintHostMsg_DidPreviewPage_Params preview_page_params;
if (!CopyMetafileDataToSharedMem(*metafile,
&preview_page_params.metafile_data_handle)) {
LOG(ERROR) << "CopyMetafileDataToSharedMem failed";
print_preview_context_.set_error(PREVIEW_ERROR_METAFILE_COPY_FAILED);
return false;
}
preview_page_params.data_size = metafile->GetDataSize();
preview_page_params.page_number = page_number;
preview_page_params.preview_request_id =
print_pages_params_->params.preview_request_id;
Send(new PrintHostMsg_DidPreviewPage(routing_id(), preview_page_params));
return true;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int atl2_check_link(struct atl2_adapter *adapter)
{
struct atl2_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
int ret_val;
u16 speed, duplex, phy_data;
int reconfig = 0;
/* MII_BMSR must read twise */
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
atl2_read_phy_reg(hw, MII_BMSR, &phy_data);
if (!(phy_data&BMSR_LSTATUS)) { /* link down */
if (netif_carrier_ok(netdev)) { /* old link state: Up */
u32 value;
/* disable rx */
value = ATL2_READ_REG(hw, REG_MAC_CTRL);
value &= ~MAC_CTRL_RX_EN;
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
return 0;
}
/* Link Up */
ret_val = atl2_get_speed_and_duplex(hw, &speed, &duplex);
if (ret_val)
return ret_val;
switch (hw->MediaType) {
case MEDIA_TYPE_100M_FULL:
if (speed != SPEED_100 || duplex != FULL_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_100M_HALF:
if (speed != SPEED_100 || duplex != HALF_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_10M_FULL:
if (speed != SPEED_10 || duplex != FULL_DUPLEX)
reconfig = 1;
break;
case MEDIA_TYPE_10M_HALF:
if (speed != SPEED_10 || duplex != HALF_DUPLEX)
reconfig = 1;
break;
}
/* link result is our setting */
if (reconfig == 0) {
if (adapter->link_speed != speed ||
adapter->link_duplex != duplex) {
adapter->link_speed = speed;
adapter->link_duplex = duplex;
atl2_setup_mac_ctrl(adapter);
printk(KERN_INFO "%s: %s NIC Link is Up<%d Mbps %s>\n",
atl2_driver_name, netdev->name,
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ?
"Full Duplex" : "Half Duplex");
}
if (!netif_carrier_ok(netdev)) { /* Link down -> Up */
netif_carrier_on(netdev);
netif_wake_queue(netdev);
}
return 0;
}
/* change original link status */
if (netif_carrier_ok(netdev)) {
u32 value;
/* disable rx */
value = ATL2_READ_REG(hw, REG_MAC_CTRL);
value &= ~MAC_CTRL_RX_EN;
ATL2_WRITE_REG(hw, REG_MAC_CTRL, value);
adapter->link_speed = SPEED_0;
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
/* auto-neg, insert timer to re-config phy
* (if interval smaller than 5 seconds, something strange) */
if (!test_bit(__ATL2_DOWN, &adapter->flags)) {
if (!test_and_set_bit(0, &adapter->cfg_phy))
mod_timer(&adapter->phy_config_timer,
round_jiffies(jiffies + 5 * HZ));
}
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 WebURLLoaderImpl::Context::OnReceivedResponse(
const ResourceResponseInfo& info) {
if (!client_)
return;
WebURLResponse response;
response.initialize();
PopulateURLResponse(request_.url(), info, &response);
bool show_raw_listing = (GURL(request_.url()).query() == "raw");
if (info.mime_type == "text/vnd.chromium.ftp-dir") {
if (show_raw_listing) {
response.setMIMEType("text/plain");
} else {
response.setMIMEType("text/html");
}
}
client_->didReceiveResponse(loader_, response);
if (!client_)
return;
DCHECK(!ftp_listing_delegate_.get());
DCHECK(!multipart_delegate_.get());
if (info.headers && info.mime_type == "multipart/x-mixed-replace") {
std::string content_type;
info.headers->EnumerateHeader(NULL, "content-type", &content_type);
std::string mime_type;
std::string charset;
bool had_charset = false;
std::string boundary;
net::HttpUtil::ParseContentType(content_type, &mime_type, &charset,
&had_charset, &boundary);
TrimString(boundary, " \"", &boundary);
if (!boundary.empty()) {
multipart_delegate_.reset(
new MultipartResponseDelegate(client_, loader_, response, boundary));
}
} else if (info.mime_type == "text/vnd.chromium.ftp-dir" &&
!show_raw_listing) {
ftp_listing_delegate_.reset(
new FtpDirectoryListingResponseDelegate(client_, loader_, response));
}
}
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: static plist_t parse_string_node(const char **bnode, uint64_t size)
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_STRING;
data->strval = (char *) malloc(sizeof(char) * (size + 1));
memcpy(data->strval, *bnode, size);
data->strval[size] = '\0';
data->length = strlen(data->strval);
return node_create(NULL, data);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static HB_Error Load_PosClassSet( HB_ContextPosFormat2* cpf2,
HB_PosClassSet* pcs,
HB_Stream stream )
{
HB_Error error;
HB_UShort n, m, count;
HB_UInt cur_offset, new_offset, base_offset;
HB_PosClassRule* pcr;
base_offset = FILE_Pos();
if ( ACCESS_Frame( 2L ) )
return error;
count = pcs->PosClassRuleCount = GET_UShort();
FORGET_Frame();
pcs->PosClassRule = NULL;
if ( ALLOC_ARRAY( pcs->PosClassRule, count, HB_PosClassRule ) )
return error;
pcr = pcs->PosClassRule;
for ( n = 0; n < count; n++ )
{
if ( ACCESS_Frame( 2L ) )
goto Fail;
new_offset = GET_UShort() + base_offset;
FORGET_Frame();
cur_offset = FILE_Pos();
if ( FILE_Seek( new_offset ) ||
( error = Load_PosClassRule( cpf2, &pcr[n],
stream ) ) != HB_Err_Ok )
goto Fail;
(void)FILE_Seek( cur_offset );
}
return HB_Err_Ok;
Fail:
for ( m = 0; m < n; m++ )
Free_PosClassRule( &pcr[m] );
FREE( pcr );
return error;
}
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: explicit LogoDelegateImpl(
std::unique_ptr<image_fetcher::ImageDecoder> image_decoder)
: image_decoder_(std::move(image_decoder)) {}
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 set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data)
{
int ret;
ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0),
PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0,
indx, data, size, 100);
if (ret < 0)
netif_dbg(pegasus, drv, pegasus->net,
"%s returned %d\n", __func__, ret);
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,
char *data, EVP_PKEY *pkey)
{
EVP_MD_CTX ctx;
const EVP_MD *type;
unsigned char *p,*buf_in=NULL;
int ret= -1,i,inl;
EVP_MD_CTX_init(&ctx);
i=OBJ_obj2nid(a->algorithm);
type=EVP_get_digestbyname(OBJ_nid2sn(i));
if (type == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
inl=i2d(data,NULL);
buf_in=OPENSSL_malloc((unsigned int)inl);
if (buf_in == NULL)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE);
goto err;
}
p=buf_in;
i2d(data,&p);
if (!EVP_VerifyInit_ex(&ctx,type, NULL))
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl);
OPENSSL_cleanse(buf_in,(unsigned int)inl);
OPENSSL_free(buf_in);
if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data,
(unsigned int)signature->length,pkey) <= 0)
{
ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB);
ret=0;
goto err;
}
/* we don't need to zero the 'ctx' because we just checked
* public information */
/* memset(&ctx,0,sizeof(ctx)); */
ret=1;
err:
EVP_MD_CTX_cleanup(&ctx);
return(ret);
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void collapse_huge_page(struct mm_struct *mm,
unsigned long address,
struct page **hpage,
struct vm_area_struct *vma,
int node)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd, _pmd;
pte_t *pte;
pgtable_t pgtable;
struct page *new_page;
spinlock_t *ptl;
int isolated;
unsigned long hstart, hend;
VM_BUG_ON(address & ~HPAGE_PMD_MASK);
#ifndef CONFIG_NUMA
VM_BUG_ON(!*hpage);
new_page = *hpage;
if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
up_read(&mm->mmap_sem);
return;
}
#else
VM_BUG_ON(*hpage);
/*
* Allocate the page while the vma is still valid and under
* the mmap_sem read mode so there is no memory allocation
* later when we take the mmap_sem in write mode. This is more
* friendly behavior (OTOH it may actually hide bugs) to
* filesystems in userland with daemons allocating memory in
* the userland I/O paths. Allocating memory with the
* mmap_sem in read mode is good idea also to allow greater
* scalability.
*/
new_page = alloc_hugepage_vma(khugepaged_defrag(), vma, address,
node, __GFP_OTHER_NODE);
if (unlikely(!new_page)) {
up_read(&mm->mmap_sem);
count_vm_event(THP_COLLAPSE_ALLOC_FAILED);
*hpage = ERR_PTR(-ENOMEM);
return;
}
count_vm_event(THP_COLLAPSE_ALLOC);
if (unlikely(mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))) {
up_read(&mm->mmap_sem);
put_page(new_page);
return;
}
#endif
/* after allocating the hugepage upgrade to mmap_sem write mode */
up_read(&mm->mmap_sem);
/*
* Prevent all access to pagetables with the exception of
* gup_fast later hanlded by the ptep_clear_flush and the VM
* handled by the anon_vma lock + PG_lock.
*/
down_write(&mm->mmap_sem);
if (unlikely(khugepaged_test_exit(mm)))
goto out;
vma = find_vma(mm, address);
hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
hend = vma->vm_end & HPAGE_PMD_MASK;
if (address < hstart || address + HPAGE_PMD_SIZE > hend)
goto out;
if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) ||
(vma->vm_flags & VM_NOHUGEPAGE))
goto out;
/* VM_PFNMAP vmas may have vm_ops null but vm_file set */
if (!vma->anon_vma || vma->vm_ops || vma->vm_file)
goto out;
if (is_vma_temporary_stack(vma))
goto out;
VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
goto out;
pud = pud_offset(pgd, address);
if (!pud_present(*pud))
goto out;
pmd = pmd_offset(pud, address);
/* pmd can't go away or become huge under us */
if (!pmd_present(*pmd) || pmd_trans_huge(*pmd))
goto out;
anon_vma_lock(vma->anon_vma);
pte = pte_offset_map(pmd, address);
ptl = pte_lockptr(mm, pmd);
spin_lock(&mm->page_table_lock); /* probably unnecessary */
/*
* After this gup_fast can't run anymore. This also removes
* any huge TLB entry from the CPU so we won't allow
* huge and small TLB entries for the same virtual address
* to avoid the risk of CPU bugs in that area.
*/
_pmd = pmdp_clear_flush_notify(vma, address, pmd);
spin_unlock(&mm->page_table_lock);
spin_lock(ptl);
isolated = __collapse_huge_page_isolate(vma, address, pte);
spin_unlock(ptl);
if (unlikely(!isolated)) {
pte_unmap(pte);
spin_lock(&mm->page_table_lock);
BUG_ON(!pmd_none(*pmd));
set_pmd_at(mm, address, pmd, _pmd);
spin_unlock(&mm->page_table_lock);
anon_vma_unlock(vma->anon_vma);
goto out;
}
/*
* All pages are isolated and locked so anon_vma rmap
* can't run anymore.
*/
anon_vma_unlock(vma->anon_vma);
__collapse_huge_page_copy(pte, new_page, vma, address, ptl);
pte_unmap(pte);
__SetPageUptodate(new_page);
pgtable = pmd_pgtable(_pmd);
VM_BUG_ON(page_count(pgtable) != 1);
VM_BUG_ON(page_mapcount(pgtable) != 0);
_pmd = mk_pmd(new_page, vma->vm_page_prot);
_pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma);
_pmd = pmd_mkhuge(_pmd);
/*
* spin_lock() below is not the equivalent of smp_wmb(), so
* this is needed to avoid the copy_huge_page writes to become
* visible after the set_pmd_at() write.
*/
smp_wmb();
spin_lock(&mm->page_table_lock);
BUG_ON(!pmd_none(*pmd));
page_add_new_anon_rmap(new_page, vma, address);
set_pmd_at(mm, address, pmd, _pmd);
update_mmu_cache(vma, address, entry);
prepare_pmd_huge_pte(pgtable, mm);
mm->nr_ptes--;
spin_unlock(&mm->page_table_lock);
#ifndef CONFIG_NUMA
*hpage = NULL;
#endif
khugepaged_pages_collapsed++;
out_up_write:
up_write(&mm->mmap_sem);
return;
out:
mem_cgroup_uncharge_page(new_page);
#ifdef CONFIG_NUMA
put_page(new_page);
#endif
goto out_up_write;
}
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: cJSON *cJSON_GetObjectItem( cJSON *object, const char *string )
{
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) )
c = c->next;
return c;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int ssl3_send_change_cipher_spec(SSL *s, int a, int b)
{
unsigned char *p;
if (s->state == a)
{
p=(unsigned char *)s->init_buf->data;
*p=SSL3_MT_CCS;
s->init_num=1;
s->init_off=0;
s->state=b;
}
/* SSL3_ST_CW_CHANGE_B */
return(ssl3_do_write(s,SSL3_RT_CHANGE_CIPHER_SPEC));
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ParamTraits<gfx::Transform>::Read(const base::Pickle* m,
base::PickleIterator* iter,
param_type* r) {
const char* column_major_data;
if (!iter->ReadBytes(&column_major_data, sizeof(SkMScalar) * 16))
return false;
r->matrix().setColMajor(
reinterpret_cast<const SkMScalar*>(column_major_data));
return true;
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: mapi_attr_read (size_t len, unsigned char *buf)
{
size_t idx = 0;
uint32 i,j;
assert(len > 4);
uint32 num_properties = GETINT32(buf+idx);
MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1));
idx += 4;
if (!attrs) return NULL;
for (i = 0; i < num_properties; i++)
{
MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1);
MAPI_Value* v = NULL;
CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2;
CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2;
/* handle special case of GUID prefixed properties */
if (a->name & GUID_EXISTS_FLAG)
{
/* copy GUID */
a->guid = CHECKED_XMALLOC(GUID, 1);
copy_guid_from_buf(a->guid, buf+idx, len);
idx += sizeof (GUID);
CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4;
if (a->num_names > 0)
{
/* FIXME: do something useful here! */
size_t i;
a->names = CHECKED_XCALLOC(VarLenData, a->num_names);
for (i = 0; i < a->num_names; i++)
{
size_t j;
CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4;
/* read the data into a buffer */
a->names[i].data
= CHECKED_XMALLOC(unsigned char, a->names[i].len);
for (j = 0; j < (a->names[i].len >> 1); j++)
a->names[i].data[j] = (buf+idx)[j*2];
/* But what are we going to do with it? */
idx += pad_to_4byte(a->names[i].len);
}
}
else
{
/* get the 'real' name */
CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4;
}
}
/*
* Multi-value types and string/object/binary types have
* multiple values
*/
if (a->type & MULTI_VALUE_FLAG ||
a->type == szMAPI_STRING ||
a->type == szMAPI_UNICODE_STRING ||
a->type == szMAPI_OBJECT ||
a->type == szMAPI_BINARY)
{
CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx);
idx += 4;
}
else
{
a->num_values = 1;
}
/* Amend the type in case of multi-value type */
if (a->type & MULTI_VALUE_FLAG)
{
a->type -= MULTI_VALUE_FLAG;
}
v = alloc_mapi_values (a);
for (j = 0; j < a->num_values; j++)
{
switch (a->type)
{
case szMAPI_SHORT: /* 2 bytes */
v->len = 2;
CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx);
idx += 4; /* assume padding of 2, advance by 4! */
break;
case szMAPI_INT: /* 4 bytes */
v->len = 4;
CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
idx += 4;
v++;
break;
case szMAPI_FLOAT: /* 4 bytes */
case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */
v->len = 4;
CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
idx += v->len;
break;
case szMAPI_SYSTIME: /* 8 bytes */
v->len = 8;
CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
idx += 8;
v++;
break;
case szMAPI_DOUBLE: /* 8 bytes */
case szMAPI_APPTIME:
case szMAPI_CURRENCY:
case szMAPI_INT8BYTE:
v->len = 8;
CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
idx += v->len;
break;
case szMAPI_CLSID:
v->len = sizeof (GUID);
copy_guid_from_buf(&v->data.guid, buf+idx, len);
idx += v->len;
break;
case szMAPI_STRING:
case szMAPI_UNICODE_STRING:
case szMAPI_OBJECT:
case szMAPI_BINARY:
CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4;
if (a->type == szMAPI_UNICODE_STRING)
{
v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx);
}
else
{
v->data.buf = CHECKED_XMALLOC(unsigned char, v->len);
memmove (v->data.buf, buf+idx, v->len);
}
idx += pad_to_4byte(v->len);
v++;
break;
case szMAPI_NULL: /* illegal in input tnef streams */
case szMAPI_ERROR:
case szMAPI_UNSPECIFIED:
fprintf (stderr,
"Invalid attribute, input file may be corrupted\n");
if (!ENCODE_SKIP) exit (1);
return NULL;
default: /* should never get here */
fprintf (stderr,
"Undefined attribute, input file may be corrupted\n");
if (!ENCODE_SKIP) exit (1);
return NULL;
}
if (DEBUG_ON) mapi_attr_dump (attrs[i]);
}
}
attrs[i] = NULL;
return attrs;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: double BaseRenderingContext2D::miterLimit() const {
return GetState().MiterLimit();
}
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 WebGL2RenderingContextBase::deleteVertexArray(
WebGLVertexArrayObject* vertex_array) {
if (isContextLost() || !vertex_array)
return;
if (!vertex_array->IsDefaultObject() &&
vertex_array == bound_vertex_array_object_)
SetBoundVertexArrayObject(nullptr);
vertex_array->DeleteObject(ContextGL());
}
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: long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info)
{
/* This is only valid for single tasks */
if (pid <= 0 || tgid <= 0)
return -EINVAL;
/* Not even root can pretend to send signals from the kernel.
Nor can they impersonate a kill(), which adds source info. */
if (info->si_code >= 0)
return -EPERM;
info->si_signo = sig;
return do_send_specific(tgid, pid, sig, info);
}
CWE ID:
Target: 1
Example 2:
Code: static void srpt_recv_done(struct ib_cq *cq, struct ib_wc *wc)
{
struct srpt_rdma_ch *ch = cq->cq_context;
struct srpt_recv_ioctx *ioctx =
container_of(wc->wr_cqe, struct srpt_recv_ioctx, ioctx.cqe);
if (wc->status == IB_WC_SUCCESS) {
int req_lim;
req_lim = atomic_dec_return(&ch->req_lim);
if (unlikely(req_lim < 0))
pr_err("req_lim = %d < 0\n", req_lim);
srpt_handle_new_iu(ch, ioctx, NULL);
} else {
pr_info("receiving failed for ioctx %p with status %d\n",
ioctx, wc->status);
}
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void set_test_case_name(const std::string& name) { test_case_name_ = name; }
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 _xml_unparsedEntityDeclHandler(void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName)
{
xml_parser *parser = (xml_parser *)userData;
if (parser && parser->unparsedEntityDeclHandler) {
zval *retval, *args[6];
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding);
args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding);
args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding);
args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding);
args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) {
zval_ptr_dtor(&retval);
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebGL2RenderingContextBase::bindSampler(GLuint unit,
WebGLSampler* sampler) {
if (isContextLost())
return;
bool deleted;
if (!CheckObjectToBeBound("bindSampler", sampler, deleted))
return;
if (deleted) {
SynthesizeGLError(GL_INVALID_OPERATION, "bindSampler",
"attempted to bind a deleted sampler");
return;
}
if (unit >= sampler_units_.size()) {
SynthesizeGLError(GL_INVALID_VALUE, "bindSampler",
"texture unit out of range");
return;
}
sampler_units_[unit] = sampler;
ContextGL()->BindSampler(unit, ObjectOrZero(sampler));
}
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 __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)
{
struct mmu_gather tlb;
struct vm_area_struct *vma;
bool ret = true;
/*
* We have to make sure to not race with the victim exit path
* and cause premature new oom victim selection:
* __oom_reap_task_mm exit_mm
* mmget_not_zero
* mmput
* atomic_dec_and_test
* exit_oom_victim
* [...]
* out_of_memory
* select_bad_process
* # no TIF_MEMDIE task selects new victim
* unmap_page_range # frees some memory
*/
mutex_lock(&oom_lock);
if (!down_read_trylock(&mm->mmap_sem)) {
ret = false;
trace_skip_task_reaping(tsk->pid);
goto unlock_oom;
}
/*
* If the mm has notifiers then we would need to invalidate them around
* unmap_page_range and that is risky because notifiers can sleep and
* what they do is basically undeterministic. So let's have a short
* sleep to give the oom victim some more time.
* TODO: we really want to get rid of this ugly hack and make sure that
* notifiers cannot block for unbounded amount of time and add
* mmu_notifier_invalidate_range_{start,end} around unmap_page_range
*/
if (mm_has_notifiers(mm)) {
up_read(&mm->mmap_sem);
schedule_timeout_idle(HZ);
goto unlock_oom;
}
/*
* MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't
* work on the mm anymore. The check for MMF_OOM_SKIP must run
* under mmap_sem for reading because it serializes against the
* down_write();up_write() cycle in exit_mmap().
*/
if (test_bit(MMF_OOM_SKIP, &mm->flags)) {
up_read(&mm->mmap_sem);
trace_skip_task_reaping(tsk->pid);
goto unlock_oom;
}
trace_start_task_reaping(tsk->pid);
/*
* Tell all users of get_user/copy_from_user etc... that the content
* is no longer stable. No barriers really needed because unmapping
* should imply barriers already and the reader would hit a page fault
* if it stumbled over a reaped memory.
*/
set_bit(MMF_UNSTABLE, &mm->flags);
tlb_gather_mmu(&tlb, mm, 0, -1);
for (vma = mm->mmap ; vma; vma = vma->vm_next) {
if (!can_madv_dontneed_vma(vma))
continue;
/*
* Only anonymous pages have a good chance to be dropped
* without additional steps which we cannot afford as we
* are OOM already.
*
* We do not even care about fs backed pages because all
* which are reclaimable have already been reclaimed and
* we do not want to block exit_mmap by keeping mm ref
* count elevated without a good reason.
*/
if (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED))
unmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end,
NULL);
}
tlb_finish_mmu(&tlb, 0, -1);
pr_info("oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\n",
task_pid_nr(tsk), tsk->comm,
K(get_mm_counter(mm, MM_ANONPAGES)),
K(get_mm_counter(mm, MM_FILEPAGES)),
K(get_mm_counter(mm, MM_SHMEMPAGES)));
up_read(&mm->mmap_sem);
trace_finish_task_reaping(tsk->pid);
unlock_oom:
mutex_unlock(&oom_lock);
return ret;
}
CWE ID: CWE-416
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void NetworkHandler::DeleteCookies(
const std::string& name,
Maybe<std::string> url,
Maybe<std::string> domain,
Maybe<std::string> path,
std::unique_ptr<DeleteCookiesCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
if (!url.isJust() && !domain.isJust()) {
callback->sendFailure(Response::InvalidParams(
"At least one of the url and domain needs to be specified"));
}
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&DeleteCookiesOnIO,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext()),
name, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""),
base::BindOnce(&DeleteCookiesCallback::sendSuccess,
std::move(callback))));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static tBTM_SEC_SERV_REC *btm_sec_find_next_serv (tBTM_SEC_SERV_REC *p_cur)
{
tBTM_SEC_SERV_REC *p_serv_rec = &btm_cb.sec_serv_rec[0];
int i;
for (i = 0; i < BTM_SEC_MAX_SERVICE_RECORDS; i++, p_serv_rec++)
{
if ((p_serv_rec->security_flags & BTM_SEC_IN_USE)
&& (p_serv_rec->psm == p_cur->psm) )
{
if (p_cur != p_serv_rec)
{
return(p_serv_rec);
}
}
}
return(NULL);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void setattr_copy(struct inode *inode, const struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
if (ia_valid & ATTR_UID)
inode->i_uid = attr->ia_uid;
if (ia_valid & ATTR_GID)
inode->i_gid = attr->ia_gid;
if (ia_valid & ATTR_ATIME)
inode->i_atime = timespec_trunc(attr->ia_atime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_MTIME)
inode->i_mtime = timespec_trunc(attr->ia_mtime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_CTIME)
inode->i_ctime = timespec_trunc(attr->ia_ctime,
inode->i_sb->s_time_gran);
if (ia_valid & ATTR_MODE) {
umode_t mode = attr->ia_mode;
if (!in_group_p(inode->i_gid) &&
!inode_capable(inode, CAP_FSETID))
mode &= ~S_ISGID;
inode->i_mode = mode;
}
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AppModalDialog::~AppModalDialog() {
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int fail(png_modifier *pm)
{
return !pm->log && !pm->this.verbose && (pm->this.nerrors > 0 ||
(pm->this.treat_warnings_as_errors && pm->this.nwarnings > 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: CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item)
{
if (item == NULL)
{
return false;
}
return (item->type & 0xff) == cJSON_True;
}
CWE ID: CWE-754
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct sk_buff *udp6_ufo_fragment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
unsigned int mss;
unsigned int unfrag_ip6hlen, unfrag_len;
struct frag_hdr *fptr;
u8 *packet_start, *prevhdr;
u8 nexthdr;
u8 frag_hdr_sz = sizeof(struct frag_hdr);
__wsum csum;
int tnl_hlen;
mss = skb_shinfo(skb)->gso_size;
if (unlikely(skb->len <= mss))
goto out;
if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) {
/* Packet is from an untrusted source, reset gso_segs. */
skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss);
/* Set the IPv6 fragment id if not set yet */
if (!skb_shinfo(skb)->ip6_frag_id)
ipv6_proxy_select_ident(dev_net(skb->dev), skb);
segs = NULL;
goto out;
}
if (skb->encapsulation && skb_shinfo(skb)->gso_type &
(SKB_GSO_UDP_TUNNEL|SKB_GSO_UDP_TUNNEL_CSUM))
segs = skb_udp_tunnel_segment(skb, features, true);
else {
const struct ipv6hdr *ipv6h;
struct udphdr *uh;
if (!pskb_may_pull(skb, sizeof(struct udphdr)))
goto out;
/* Do software UFO. Complete and fill in the UDP checksum as HW cannot
* do checksum of UDP packets sent as multiple IP fragments.
*/
uh = udp_hdr(skb);
ipv6h = ipv6_hdr(skb);
uh->check = 0;
csum = skb_checksum(skb, 0, skb->len, 0);
uh->check = udp_v6_check(skb->len, &ipv6h->saddr,
&ipv6h->daddr, csum);
if (uh->check == 0)
uh->check = CSUM_MANGLED_0;
skb->ip_summed = CHECKSUM_NONE;
/* If there is no outer header we can fake a checksum offload
* due to the fact that we have already done the checksum in
* software prior to segmenting the frame.
*/
if (!skb->encap_hdr_csum)
features |= NETIF_F_HW_CSUM;
/* Check if there is enough headroom to insert fragment header. */
tnl_hlen = skb_tnl_header_len(skb);
if (skb->mac_header < (tnl_hlen + frag_hdr_sz)) {
if (gso_pskb_expand_head(skb, tnl_hlen + frag_hdr_sz))
goto out;
}
/* Find the unfragmentable header and shift it left by frag_hdr_sz
* bytes to insert fragment header.
*/
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
*prevhdr = NEXTHDR_FRAGMENT;
unfrag_len = (skb_network_header(skb) - skb_mac_header(skb)) +
unfrag_ip6hlen + tnl_hlen;
packet_start = (u8 *) skb->head + SKB_GSO_CB(skb)->mac_offset;
memmove(packet_start-frag_hdr_sz, packet_start, unfrag_len);
SKB_GSO_CB(skb)->mac_offset -= frag_hdr_sz;
skb->mac_header -= frag_hdr_sz;
skb->network_header -= frag_hdr_sz;
fptr = (struct frag_hdr *)(skb_network_header(skb) + unfrag_ip6hlen);
fptr->nexthdr = nexthdr;
fptr->reserved = 0;
if (!skb_shinfo(skb)->ip6_frag_id)
ipv6_proxy_select_ident(dev_net(skb->dev), skb);
fptr->identification = skb_shinfo(skb)->ip6_frag_id;
/* Fragment the skb. ipv6 header and the remaining fields of the
* fragment header are updated in ipv6_gso_segment()
*/
segs = skb_segment(skb, features);
}
out:
return segs;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void DatabaseMessageFilter::OnDatabaseGetSpaceAvailable(
const string16& origin_identifier, IPC::Message* reply_msg) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(db_tracker_->quota_manager_proxy());
QuotaManager* quota_manager =
db_tracker_->quota_manager_proxy()->quota_manager();
if (!quota_manager) {
NOTREACHED(); // The system is shutting down, messages are unexpected.
DatabaseHostMsg_GetSpaceAvailable::WriteReplyParams(
reply_msg, static_cast<int64>(0));
Send(reply_msg);
return;
}
quota_manager->GetUsageAndQuota(
DatabaseUtil::GetOriginFromIdentifier(origin_identifier),
quota::kStorageTypeTemporary,
base::Bind(&DatabaseMessageFilter::OnDatabaseGetUsageAndQuota,
this, reply_msg));
}
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: static void *ax25_info_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_hlist_next(v, &ax25_list, pos);
}
CWE ID: CWE-200
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static __always_inline int __do_follow_link(struct path *path, struct nameidata *nd)
{
int error;
void *cookie;
struct dentry *dentry = path->dentry;
touch_atime(path->mnt, dentry);
nd_set_link(nd, NULL);
if (path->mnt != nd->path.mnt) {
path_to_nameidata(path, nd);
dget(dentry);
}
mntget(path->mnt);
cookie = dentry->d_inode->i_op->follow_link(dentry, nd);
error = PTR_ERR(cookie);
if (!IS_ERR(cookie)) {
char *s = nd_get_link(nd);
error = 0;
if (s)
error = __vfs_follow_link(nd, s);
else if (nd->last_type == LAST_BIND) {
error = force_reval_path(&nd->path, nd);
if (error)
path_put(&nd->path);
}
if (dentry->d_inode->i_op->put_link)
dentry->d_inode->i_op->put_link(dentry, nd, cookie);
}
return error;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: copy_file (char const *from, char const *to, struct stat *tost,
int to_flags, mode_t mode, bool to_dir_known_to_exist)
{
int tofd;
if (debug & 4)
say ("Copying %s %s to %s\n",
S_ISLNK (mode) ? "symbolic link" : "file",
quotearg_n (0, from), quotearg_n (1, to));
if (S_ISLNK (mode))
{
char *buffer = xmalloc (PATH_MAX);
if (readlink (from, buffer, PATH_MAX) < 0)
pfatal ("Can't read %s %s", "symbolic link", from);
if (symlink (buffer, to) != 0)
pfatal ("Can't create %s %s", "symbolic link", to);
if (tost && lstat (to, tost) != 0)
pfatal ("Can't get file attributes of %s %s", "symbolic link", to);
free (buffer);
}
else
{
assert (S_ISREG (mode));
tofd = create_file (to, O_WRONLY | O_BINARY | to_flags, mode,
to_dir_known_to_exist);
copy_to_fd (from, tofd);
if (tost && fstat (tofd, tost) != 0)
pfatal ("Can't get file attributes of %s %s", "file", to);
if (close (tofd) != 0)
write_fatal ();
}
}
CWE ID: CWE-22
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderViewHostManager::SetWebUIPostCommit(WebUIImpl* web_ui) {
DCHECK(!web_ui_.get());
web_ui_.reset(web_ui);
}
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: batadv_frag_merge_packets(struct hlist_head *chain, struct sk_buff *skb)
{
struct batadv_frag_packet *packet;
struct batadv_frag_list_entry *entry;
struct sk_buff *skb_out = NULL;
int size, hdr_size = sizeof(struct batadv_frag_packet);
/* Make sure incoming skb has non-bogus data. */
packet = (struct batadv_frag_packet *)skb->data;
size = ntohs(packet->total_size);
if (size > batadv_frag_size_limit())
goto free;
/* Remove first entry, as this is the destination for the rest of the
* fragments.
*/
entry = hlist_entry(chain->first, struct batadv_frag_list_entry, list);
hlist_del(&entry->list);
skb_out = entry->skb;
kfree(entry);
/* Make room for the rest of the fragments. */
if (pskb_expand_head(skb_out, 0, size - skb->len, GFP_ATOMIC) < 0) {
kfree_skb(skb_out);
skb_out = NULL;
goto free;
}
/* Move the existing MAC header to just before the payload. (Override
* the fragment header.)
*/
skb_pull_rcsum(skb_out, hdr_size);
memmove(skb_out->data - ETH_HLEN, skb_mac_header(skb_out), ETH_HLEN);
skb_set_mac_header(skb_out, -ETH_HLEN);
skb_reset_network_header(skb_out);
skb_reset_transport_header(skb_out);
/* Copy the payload of the each fragment into the last skb */
hlist_for_each_entry(entry, chain, list) {
size = entry->skb->len - hdr_size;
memcpy(skb_put(skb_out, size), entry->skb->data + hdr_size,
size);
}
free:
/* Locking is not needed, because 'chain' is not part of any orig. */
batadv_frag_clear_chain(chain);
return skb_out;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void reflectedCustomIntegralAttrAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectV8Internal::reflectedCustomIntegralAttrAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok)
#if !defined(DISABLE_NACL)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_LaunchNaCl, OnLaunchNaCl)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetReadonlyPnaclFD,
OnGetReadonlyPnaclFd)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_NaClCreateTemporaryFile,
OnNaClCreateTemporaryFile)
#endif
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DnsPrefetch, OnDnsPrefetch)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_ResourceTypeStats,
OnResourceTypeStats)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdatedCacheStats,
OnUpdatedCacheStats)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FPS, OnFPS)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_V8HeapStats, OnV8HeapStats)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension,
OnOpenChannelToExtension)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle,
OnGetExtensionMessageBundle)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddListener, OnExtensionAddListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveListener,
OnExtensionRemoveListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddLazyListener,
OnExtensionAddLazyListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveLazyListener,
OnExtensionRemoveLazyListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddFilteredListener,
OnExtensionAddFilteredListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveFilteredListener,
OnExtensionRemoveFilteredListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_CloseChannel, OnExtensionCloseChannel)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread,
OnExtensionRequestForIOThread)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_ShouldUnloadAck,
OnExtensionShouldUnloadAck)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID,
OnExtensionGenerateUniqueID)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests,
OnExtensionResumeRequests);
#if defined(USE_TCMALLOC)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK,
OnWriteTcmallocHeapProfile)
#endif
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowIndexedDB, OnAllowIndexedDB)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardRead,
OnCanTriggerClipboardRead)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardWrite,
OnCanTriggerClipboardWrite)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
#if defined(ENABLE_AUTOMATION)
if ((message.type() == ChromeViewHostMsg_GetCookies::ID ||
message.type() == ChromeViewHostMsg_SetCookie::ID) &&
AutomationResourceMessageFilter::ShouldFilterCookieMessages(
render_process_id_, message.routing_id())) {
IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message,
*message_was_ok)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetCookies,
OnGetCookies)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetCookie, OnSetCookie)
IPC_END_MESSAGE_MAP()
handled = true;
}
#endif
return handled;
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(Phar, offsetExists)
{
char *fname;
size_t fname_len;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_FALSE;
}
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
/* none of these are real files, so they don't exist */
RETURN_FALSE;
}
RETURN_TRUE;
} else {
if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int ext4_block_truncate_page(handle_t *handle,
struct address_space *mapping, loff_t from)
{
unsigned offset = from & (PAGE_SIZE-1);
unsigned length;
unsigned blocksize;
struct inode *inode = mapping->host;
blocksize = inode->i_sb->s_blocksize;
length = blocksize - (offset & (blocksize - 1));
return ext4_block_zero_page_range(handle, mapping, from, length);
}
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 MoveTouchPoint(int index, int x, int y) {
touch_event_.MovePoint(index, x, y);
}
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 v8::Handle<v8::Value> overloadedMethod5Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod5");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
if (args.Length() <= 0 || !args[0]->IsFunction())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
RefPtr<TestCallback> callback = V8TestCallback::create(args[0], getScriptExecutionContext());
imp->overloadedMethod(callback);
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: void FindFallbackPatternMatchInWorkingSet() {
FindFallbackPatternMatch(false);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nfs_ctime_need_update(const struct inode *inode, const struct nfs_fattr *fattr)
{
return timespec_compare(&fattr->ctime, &inode->i_ctime) > 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: set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth,
png_uint_32 value, png_const_bytep gamma_table, double conv)
{
unsigned int mask = (1U << bit_depth)-1;
x *= bit_depth; /* Maximum x is 4*1024, maximum bit_depth is 16 */
if (value <= mask)
{
png_uint_32 offset = x >> 3;
if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes))
{
row += offset;
switch (bit_depth)
{
case 1:
case 2:
case 4:
/* Don't gamma correct - values get smashed */
{
unsigned int shift = (8 - bit_depth) - (x & 0x7U);
mask <<= shift;
value = (value << shift) & mask;
*row = (png_byte)((*row & ~mask) | value);
}
return;
default:
fprintf(stderr, "makepng: bad bit depth (internal error)\n");
exit(1);
case 16:
value = (unsigned int)floor(65535*pow(value/65535.,conv)+.5);
*row++ = (png_byte)(value >> 8);
*row = (png_byte)value;
return;
case 8:
*row = gamma_table[value];
return;
}
}
else
{
fprintf(stderr, "makepng: row buffer overflow (internal error)\n");
exit(1);
}
}
else
{
fprintf(stderr, "makepng: component overflow (internal error)\n");
exit(1);
}
}
CWE ID:
Target: 1
Example 2:
Code: void DataPipeProducerDispatcher::UpdateSignalsStateNoLock() {
lock_.AssertAcquired();
const bool was_peer_closed = peer_closed_;
const bool was_peer_remote = peer_remote_;
size_t previous_capacity = available_capacity_;
ports::PortStatus port_status;
int rv = node_controller_->node()->GetStatus(control_port_, &port_status);
peer_remote_ = rv == ports::OK && port_status.peer_remote;
if (rv != ports::OK || !port_status.receiving_messages) {
DVLOG(1) << "Data pipe producer " << pipe_id_ << " is aware of peer closure"
<< " [control_port=" << control_port_.name() << "]";
peer_closed_ = true;
} else if (rv == ports::OK && port_status.has_messages && !in_transit_) {
std::unique_ptr<ports::UserMessageEvent> message_event;
do {
int rv = node_controller_->node()->GetMessage(control_port_,
&message_event, nullptr);
if (rv != ports::OK)
peer_closed_ = true;
if (message_event) {
auto* message = message_event->GetMessage<UserMessageImpl>();
if (message->user_payload_size() < sizeof(DataPipeControlMessage)) {
peer_closed_ = true;
break;
}
const DataPipeControlMessage* m =
static_cast<const DataPipeControlMessage*>(message->user_payload());
if (m->command != DataPipeCommand::DATA_WAS_READ) {
DLOG(ERROR) << "Unexpected message from consumer.";
peer_closed_ = true;
break;
}
if (static_cast<size_t>(available_capacity_) + m->num_bytes >
options_.capacity_num_bytes) {
DLOG(ERROR) << "Consumer claims to have read too many bytes.";
break;
}
DVLOG(1) << "Data pipe producer " << pipe_id_ << " is aware that "
<< m->num_bytes
<< " bytes were read. [control_port=" << control_port_.name()
<< "]";
available_capacity_ += m->num_bytes;
}
} while (message_event);
}
if (peer_closed_ != was_peer_closed ||
available_capacity_ != previous_capacity ||
was_peer_remote != peer_remote_) {
watchers_.NotifyState(GetHandleSignalsStateNoLock());
}
}
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 RenderFrameImpl::HandleAccessibilityFindInPageResult(
int identifier,
int match_index,
const blink::WebNode& start_node,
int start_offset,
const blink::WebNode& end_node,
int end_offset) {
if (render_accessibility_) {
render_accessibility_->HandleAccessibilityFindInPageResult(
identifier, match_index, blink::WebAXObject::FromWebNode(start_node),
start_offset, blink::WebAXObject::FromWebNode(end_node), end_offset);
}
}
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 u64 __skb_get_nlattr_nest(u64 ctx, u64 A, u64 X, u64 r4, u64 r5)
{
struct sk_buff *skb = (struct sk_buff *)(long) ctx;
struct nlattr *nla;
if (skb_is_nonlinear(skb))
return 0;
if (A > skb->len - sizeof(struct nlattr))
return 0;
nla = (struct nlattr *) &skb->data[A];
if (nla->nla_len > A - skb->len)
return 0;
nla = nla_find_nested(nla, X);
if (nla)
return (void *) nla - (void *) skb->data;
return 0;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: bool CameraClient::previewEnabled() {
LOG1("previewEnabled (pid %d)", getCallingPid());
Mutex::Autolock lock(mLock);
if (checkPidAndHardware() != NO_ERROR) return false;
return mHardware->previewEnabled();
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MediaStreamDispatcherHost::DoOpenDevice(
int32_t page_request_id,
const std::string& device_id,
MediaStreamType type,
OpenDeviceCallback callback,
MediaDeviceSaltAndOrigin salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!MediaStreamManager::IsOriginAllowed(render_process_id_,
salt_and_origin.origin)) {
std::move(callback).Run(false /* success */, std::string(),
MediaStreamDevice());
return;
}
media_stream_manager_->OpenDevice(
render_process_id_, render_frame_id_, page_request_id, device_id, type,
std::move(salt_and_origin), std::move(callback),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped,
weak_factory_.GetWeakPtr()));
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PluginModule::InitAsProxiedNaCl(
scoped_ptr<PluginDelegate::OutOfProcessProxy> out_of_process_proxy,
PP_Instance instance) {
nacl_ipc_proxy_ = true;
InitAsProxied(out_of_process_proxy.release());
out_of_process_proxy_->AddInstance(instance);
PluginInstance* plugin_instance = host_globals->GetInstance(instance);
if (!plugin_instance)
return;
plugin_instance->ResetAsProxied();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: R_API RList *r_bin_get_imports(RBin *bin) {
RBinObject *o = r_bin_cur_object (bin);
return o? o->imports: NULL;
}
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 int __submit_flush_wait(struct f2fs_sb_info *sbi,
struct block_device *bdev)
{
struct bio *bio = f2fs_bio_alloc(0);
int ret;
bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
bio_set_dev(bio, bdev);
ret = submit_bio_wait(bio);
bio_put(bio);
trace_f2fs_issue_flush(bdev, test_opt(sbi, NOBARRIER),
test_opt(sbi, FLUSH_MERGE), ret);
return ret;
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RunInvTxfm(int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, tx_type_);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ScriptController::installFunctionsForPagePopup(Frame* frame, PagePopupClient* popupClient)
{
ASSERT(frame);
ASSERT(popupClient);
v8::HandleScope handleScope;
v8::Handle<v8::Context> context = V8Proxy::mainWorldContext(frame);
if (context.IsEmpty()) {
ASSERT_NOT_REACHED();
return;
}
v8::Context::Scope scope(context);
DOMWindowPagePopup::install(frame->existingDOMWindow(), popupClient);
v8::Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(setValueAndClosePopupCallback, V8DOMWindow::wrap(frame->existingDOMWindow()));
context->Global()->Set(v8::String::New("setValueAndClosePopup"), v8::Handle<v8::Function>(templ->GetFunction()));
}
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 AppCacheHost::NotifyMainResourceBlocked(const GURL& manifest_url) {
main_resource_blocked_ = true;
blocked_manifest_url_ = manifest_url;
}
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 webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget)
{
WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container);
WebKitWebViewBasePrivate* priv = webView->priv;
if (WEBKIT_IS_WEB_VIEW_BASE(widget)
&& WebInspectorProxy::isInspectorPage(WEBKIT_WEB_VIEW_BASE(widget)->priv->pageProxy.get())) {
ASSERT(!priv->inspectorView);
priv->inspectorView = widget;
priv->inspectorViewHeight = gMinimumAttachedInspectorHeight;
} else {
GtkAllocation childAllocation;
gtk_widget_get_allocation(widget, &childAllocation);
priv->children.set(widget, childAllocation);
}
gtk_widget_set_parent(widget, GTK_WIDGET(container));
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: BGD_DECLARE(void *) gdImageGd2Ptr (gdImagePtr im, int cs, int fmt, int *size)
{
_noLibzError();
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rds_rm_size(struct msghdr *msg, int data_len)
{
struct cmsghdr *cmsg;
int size = 0;
int cmsg_groups = 0;
int retval;
for_each_cmsghdr(cmsg, msg) {
if (!CMSG_OK(msg, cmsg))
return -EINVAL;
if (cmsg->cmsg_level != SOL_RDS)
continue;
switch (cmsg->cmsg_type) {
case RDS_CMSG_RDMA_ARGS:
cmsg_groups |= 1;
retval = rds_rdma_extra_size(CMSG_DATA(cmsg));
if (retval < 0)
return retval;
size += retval;
break;
case RDS_CMSG_RDMA_DEST:
case RDS_CMSG_RDMA_MAP:
cmsg_groups |= 2;
/* these are valid but do no add any size */
break;
case RDS_CMSG_ATOMIC_CSWP:
case RDS_CMSG_ATOMIC_FADD:
case RDS_CMSG_MASKED_ATOMIC_CSWP:
case RDS_CMSG_MASKED_ATOMIC_FADD:
cmsg_groups |= 1;
size += sizeof(struct scatterlist);
break;
default:
return -EINVAL;
}
}
size += ceil(data_len, PAGE_SIZE) * sizeof(struct scatterlist);
/* Ensure (DEST, MAP) are never used with (ARGS, ATOMIC) */
if (cmsg_groups == 3)
return -EINVAL;
return size;
}
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 int br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb,
struct net_device *dev)
{
struct net_bridge *br = netdev_priv(dev);
struct net_bridge_mdb_htable *mdb;
struct nlattr *nest, *nest2;
int i, err = 0;
int idx = 0, s_idx = cb->args[1];
if (br->multicast_disabled)
return 0;
mdb = rcu_dereference(br->mdb);
if (!mdb)
return 0;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
return -EMSGSIZE;
for (i = 0; i < mdb->max; i++) {
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p, **pp;
struct net_bridge_port *port;
hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) {
if (idx < s_idx)
goto skip;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL) {
err = -EMSGSIZE;
goto out;
}
for (pp = &mp->ports;
(p = rcu_dereference(*pp)) != NULL;
pp = &p->next) {
port = p->port;
if (port) {
struct br_mdb_entry e;
e.ifindex = port->dev->ifindex;
e.state = p->state;
if (p->addr.proto == htons(ETH_P_IP))
e.addr.u.ip4 = p->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
if (p->addr.proto == htons(ETH_P_IPV6))
e.addr.u.ip6 = p->addr.u.ip6;
#endif
e.addr.proto = p->addr.proto;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) {
nla_nest_cancel(skb, nest2);
err = -EMSGSIZE;
goto out;
}
}
}
nla_nest_end(skb, nest2);
skip:
idx++;
}
}
out:
cb->args[1] = idx;
nla_nest_end(skb, nest);
return err;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool omx_video::execute_output_flush(void)
{
unsigned long p1 = 0; // Parameter - 1
unsigned long p2 = 0; // Parameter - 2
unsigned long ident = 0;
bool bRet = true;
/*Generate FBD for all Buffers in the FTBq*/
DEBUG_PRINT_LOW("execute_output_flush");
pthread_mutex_lock(&m_lock);
while (m_ftb_q.m_size) {
m_ftb_q.pop_entry(&p1,&p2,&ident);
if (ident == OMX_COMPONENT_GENERATE_FTB ) {
pending_output_buffers++;
fill_buffer_done(&m_cmp,(OMX_BUFFERHEADERTYPE *)p2);
} else if (ident == OMX_COMPONENT_GENERATE_FBD) {
fill_buffer_done(&m_cmp,(OMX_BUFFERHEADERTYPE *)p1);
}
}
pthread_mutex_unlock(&m_lock);
/*Check if there are buffers with the Driver*/
if (dev_flush(PORT_INDEX_OUT)) {
DEBUG_PRINT_ERROR("ERROR: o/p dev_flush() Failed");
return false;
}
return bRet;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4],
const DVprofile *sys)
{
int size, chan, i, j, d, of, smpls, freq, quant, half_ch;
uint16_t lc, rc;
const uint8_t* as_pack;
uint8_t *pcm, ipcm;
as_pack = dv_extract_pack(frame, dv_audio_source);
if (!as_pack) /* No audio ? */
return 0;
smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */
freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */
if (quant > 1)
return -1; /* unsupported quantization */
size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */
half_ch = sys->difseg_size / 2;
/* We work with 720p frames split in half, thus even frames have
* channels 0,1 and odd 2,3. */
ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0;
pcm = ppcm[ipcm++];
/* for each DIF channel */
for (chan = 0; chan < sys->n_difchan; chan++) {
/* for each DIF segment */
for (i = 0; i < sys->difseg_size; i++) {
frame += 6 * 80; /* skip DIF segment header */
break;
}
/* for each AV sequence */
for (j = 0; j < 9; j++) {
for (d = 8; d < 80; d += 2) {
if (quant == 0) { /* 16bit quantization */
of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride;
if (of*2 >= size)
continue;
pcm[of*2] = frame[d+1]; // FIXME: maybe we have to admit
pcm[of*2+1] = frame[d]; // that DV is a big-endian PCM
if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00)
pcm[of*2+1] = 0;
} else { /* 12bit quantization */
lc = ((uint16_t)frame[d] << 4) |
((uint16_t)frame[d+2] >> 4);
rc = ((uint16_t)frame[d+1] << 4) |
((uint16_t)frame[d+2] & 0x0f);
lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));
rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));
of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride;
if (of*2 >= size)
continue;
pcm[of*2] = lc & 0xff; // FIXME: maybe we have to admit
pcm[of*2+1] = lc >> 8; // that DV is a big-endian PCM
of = sys->audio_shuffle[i%half_ch+half_ch][j] +
(d - 8) / 3 * sys->audio_stride;
pcm[of*2] = rc & 0xff; // FIXME: maybe we have to admit
pcm[of*2+1] = rc >> 8; // that DV is a big-endian PCM
++d;
}
}
frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
}
}
frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */
}
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: download::DownloadItemImpl* DownloadManagerImpl::CreateActiveItem(
uint32_t id,
const download::DownloadCreateInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!base::ContainsKey(downloads_, id));
download::DownloadItemImpl* download =
item_factory_->CreateActiveItem(this, id, info);
downloads_[id] = base::WrapUnique(download);
downloads_by_guid_[download->GetGuid()] = download;
DownloadItemUtils::AttachInfo(
download, GetBrowserContext(),
WebContentsImpl::FromRenderFrameHostID(info.render_process_id,
info.render_frame_id));
return download;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int ati_remote2_reset_resume(struct usb_interface *interface)
{
struct ati_remote2 *ar2;
struct usb_host_interface *alt = interface->cur_altsetting;
int r = 0;
if (alt->desc.bInterfaceNumber)
return 0;
ar2 = usb_get_intfdata(interface);
dev_dbg(&ar2->intf[0]->dev, "%s()\n", __func__);
mutex_lock(&ati_remote2_mutex);
r = ati_remote2_setup(ar2, ar2->channel_mask);
if (r)
goto out;
if (ar2->flags & ATI_REMOTE2_OPENED)
r = ati_remote2_submit_urbs(ar2);
if (!r)
ar2->flags &= ~ATI_REMOTE2_SUSPENDED;
out:
mutex_unlock(&ati_remote2_mutex);
return r;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void start_auth_request(PgSocket *client, const char *username)
{
int res;
PktBuf *buf;
client->auth_user = client->db->auth_user;
/* have to fetch user info from db */
client->pool = get_pool(client->db, client->db->auth_user);
if (!find_server(client)) {
client->wait_for_user_conn = true;
return;
}
slog_noise(client, "Doing auth_conn query");
client->wait_for_user_conn = false;
client->wait_for_user = true;
if (!sbuf_pause(&client->sbuf)) {
release_server(client->link);
disconnect_client(client, true, "pause failed");
return;
}
client->link->ready = 0;
res = 0;
buf = pktbuf_dynamic(512);
if (buf) {
pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
res = pktbuf_send_immediate(buf, client->link);
pktbuf_free(buf);
/*
* Should do instead:
* res = pktbuf_send_queued(buf, client->link);
* but that needs better integration with SBuf.
*/
}
if (!res)
disconnect_server(client->link, false, "unable to send login query");
}
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: BaseRenderingContext2D::BaseRenderingContext2D()
: clip_antialiasing_(kNotAntiAliased) {
state_stack_.push_back(CanvasRenderingContext2DState::Create());
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void activate_path(struct work_struct *work)
{
struct pgpath *pgpath =
container_of(work, struct pgpath, activate_path.work);
scsi_dh_activate(bdev_get_queue(pgpath->path.dev->bdev),
pg_init_done, pgpath);
}
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 read_tfra(MOVContext *mov, AVIOContext *f)
{
MOVFragmentIndex* index = NULL;
int version, fieldlength, i, j;
int64_t pos = avio_tell(f);
uint32_t size = avio_rb32(f);
void *tmp;
if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {
return 1;
}
av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");
index = av_mallocz(sizeof(MOVFragmentIndex));
if (!index) {
return AVERROR(ENOMEM);
}
tmp = av_realloc_array(mov->fragment_index_data,
mov->fragment_index_count + 1,
sizeof(MOVFragmentIndex*));
if (!tmp) {
av_freep(&index);
return AVERROR(ENOMEM);
}
mov->fragment_index_data = tmp;
mov->fragment_index_data[mov->fragment_index_count++] = index;
version = avio_r8(f);
avio_rb24(f);
index->track_id = avio_rb32(f);
fieldlength = avio_rb32(f);
index->item_count = avio_rb32(f);
index->items = av_mallocz_array(
index->item_count, sizeof(MOVFragmentIndexItem));
if (!index->items) {
index->item_count = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < index->item_count; i++) {
int64_t time, offset;
if (version == 1) {
time = avio_rb64(f);
offset = avio_rb64(f);
} else {
time = avio_rb32(f);
offset = avio_rb32(f);
}
index->items[i].time = time;
index->items[i].moof_offset = offset;
for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)
avio_r8(f);
for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)
avio_r8(f);
for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)
avio_r8(f);
}
avio_seek(f, pos + size, SEEK_SET);
return 0;
}
CWE ID: CWE-834
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 DevToolsAgentHostImpl::AttachClient(DevToolsAgentHostClient* client) {
if (SessionByClient(client))
return;
InnerAttachClient(client);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: set_pwd ()
{
SHELL_VAR *temp_var, *home_var;
char *temp_string, *home_string;
home_var = find_variable ("HOME");
home_string = home_var ? value_cell (home_var) : (char *)NULL;
temp_var = find_variable ("PWD");
if (temp_var && imported_p (temp_var) &&
(temp_string = value_cell (temp_var)) &&
same_file (temp_string, ".", (struct stat *)NULL, (struct stat *)NULL))
set_working_directory (temp_string);
else if (home_string && interactive_shell && login_shell &&
same_file (home_string, ".", (struct stat *)NULL, (struct stat *)NULL))
{
set_working_directory (home_string);
temp_var = bind_variable ("PWD", home_string, 0);
set_auto_export (temp_var);
}
else
{
temp_string = get_working_directory ("shell-init");
if (temp_string)
{
temp_var = bind_variable ("PWD", temp_string, 0);
set_auto_export (temp_var);
free (temp_string);
}
}
/* According to the Single Unix Specification, v2, $OLDPWD is an
`environment variable' and therefore should be auto-exported.
Make a dummy invisible variable for OLDPWD, and mark it as exported. */
temp_var = bind_variable ("OLDPWD", (char *)NULL, 0);
VSETATTR (temp_var, (att_exported | att_invisible));
}
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 ssize_t aio_setup_single_vector(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
size_t len,
struct iovec *iovec)
{
if (unlikely(!access_ok(!rw, buf, len)))
return -EFAULT;
iovec->iov_base = buf;
iovec->iov_len = len;
*nr_segs = 1;
return 0;
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: UserSelectionScreen::UpdateAndReturnUserListForMojo() {
std::vector<ash::mojom::LoginUserInfoPtr> user_info_list;
const AccountId owner = GetOwnerAccountId();
const bool is_signin_to_add = IsSigninToAdd();
users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add);
user_auth_type_map_.clear();
for (user_manager::UserList::const_iterator it = users_to_send_.begin();
it != users_to_send_.end(); ++it) {
const AccountId& account_id = (*it)->GetAccountId();
bool is_owner = owner == account_id;
const bool is_public_account =
((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT);
const proximity_auth::mojom::AuthType initial_auth_type =
is_public_account
? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK
: (ShouldForceOnlineSignIn(*it)
? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN
: proximity_auth::mojom::AuthType::OFFLINE_PASSWORD);
user_auth_type_map_[account_id] = initial_auth_type;
ash::mojom::LoginUserInfoPtr login_user_info =
ash::mojom::LoginUserInfo::New();
const std::vector<std::string>* public_session_recommended_locales =
public_session_recommended_locales_.find(account_id) ==
public_session_recommended_locales_.end()
? nullptr
: &public_session_recommended_locales_[account_id];
FillUserMojoStruct(*it, is_owner, is_signin_to_add, initial_auth_type,
public_session_recommended_locales,
login_user_info.get());
login_user_info->can_remove = CanRemoveUser(*it);
if (is_public_account && LoginScreenClient::HasInstance()) {
LoginScreenClient::Get()->RequestPublicSessionKeyboardLayouts(
account_id, login_user_info->public_account_info->default_locale);
}
user_info_list.push_back(std::move(login_user_info));
}
return user_info_list;
}
CWE ID:
Target: 1
Example 2:
Code: static void __report_tpr_access(struct kvm_lapic *apic, bool write)
{
struct kvm_vcpu *vcpu = apic->vcpu;
struct kvm_run *run = vcpu->run;
kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
run->tpr_access.rip = kvm_rip_read(vcpu);
run->tpr_access.is_write = write;
}
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 SecureProxyChecker::CheckIfSecureProxyIsAllowed(
SecureProxyCheckerCallback fetcher_callback) {
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation(
"data_reduction_proxy_secure_proxy_check", R"(
semantics {
sender: "Data Reduction Proxy"
description:
"Sends a request to the Data Reduction Proxy server. Proceeds "
"with using a secure connection to the proxy only if the "
"response is not blocked or modified by an intermediary."
trigger:
"A request can be sent whenever the browser is determining how "
"to configure its connection to the data reduction proxy. This "
"happens on startup and network changes."
data: "A specific URL, not related to user data."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Data Saver on Android via the 'Data Saver' "
"setting. Data Saver is not available on iOS, and on desktop "
"it is enabled by installing the Data Saver extension."
policy_exception_justification: "Not implemented."
})");
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = params::GetSecureProxyCheckURL();
resource_request->load_flags =
net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_PROXY;
resource_request->allow_credentials = false;
url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
traffic_annotation);
static const int kMaxRetries = 5;
url_loader_->SetRetryOptions(
kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE |
network::SimpleURLLoader::RETRY_ON_5XX);
url_loader_->SetOnRedirectCallback(base::BindRepeating(
&SecureProxyChecker::OnURLLoaderRedirect, base::Unretained(this)));
fetcher_callback_ = fetcher_callback;
secure_proxy_check_start_time_ = base::Time::Now();
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
url_loader_factory_.get(),
base::BindOnce(&SecureProxyChecker::OnURLLoadComplete,
base::Unretained(this)));
}
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: gnutls_session_get_data (gnutls_session_t session,
void *session_data, size_t * session_data_size)
{
gnutls_datum_t psession;
int ret;
if (session->internals.resumable == RESUME_FALSE)
return GNUTLS_E_INVALID_SESSION;
psession.data = session_data;
ret = _gnutls_session_pack (session, &psession);
if (ret < 0)
{
gnutls_assert ();
return ret;
}
*session_data_size = psession.size;
if (psession.size > *session_data_size)
{
ret = GNUTLS_E_SHORT_MEMORY_BUFFER;
goto error;
}
if (session_data != NULL)
memcpy (session_data, psession.data, psession.size);
ret = 0;
error:
_gnutls_free_datum (&psession);
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: R_API int r_bin_file_deref(RBin *bin, RBinFile *a) {
RBinObject *o = r_bin_cur_object (bin);
int res = false;
if (a && !o) {
res = true;
} else if (a && o->referenced - 1 < 1) {
res = true;
} else if (o) {
o->referenced--;
}
if (bin) bin->cur = NULL;
return res;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static v8::Handle<v8::Value> convert4Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.convert4");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(d*, , V8d::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8d::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->convert4();
return v8::Handle<v8::Value>();
}
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: flatpak_proxy_client_finalize (GObject *object)
{
FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);
client->proxy->clients = g_list_remove (client->proxy->clients, client);
g_clear_object (&client->proxy);
g_hash_table_destroy (client->rewrite_reply);
g_hash_table_destroy (client->get_owner_reply);
g_hash_table_destroy (client->unique_id_policy);
free_side (&client->client_side);
free_side (&client->bus_side);
G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);
}
CWE ID: CWE-436
Target: 1
Example 2:
Code: void VirtualKeyboardController::SetKeyboardEnabled(bool enabled) {
keyboard::SetTouchKeyboardEnabled(enabled);
if (enabled) {
Shell::GetInstance()->CreateKeyboard();
} else {
if (!keyboard::IsKeyboardEnabled())
Shell::GetInstance()->DeactivateKeyboard();
}
}
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 char *eol(char *s)
{
char *p = strend(s);
if (p - s > 1 && p[-1] != 10) {
*p++ = 10;
*p = 0;
}
return p;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void sas_revalidate_domain(struct work_struct *work)
{
int res = 0;
struct sas_discovery_event *ev = to_sas_discovery_event(work);
struct asd_sas_port *port = ev->port;
struct sas_ha_struct *ha = port->ha;
struct domain_device *ddev = port->port_dev;
/* prevent revalidation from finding sata links in recovery */
mutex_lock(&ha->disco_mutex);
if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) {
SAS_DPRINTK("REVALIDATION DEFERRED on port %d, pid:%d\n",
port->id, task_pid_nr(current));
goto out;
}
clear_bit(DISCE_REVALIDATE_DOMAIN, &port->disc.pending);
SAS_DPRINTK("REVALIDATING DOMAIN on port %d, pid:%d\n", port->id,
task_pid_nr(current));
if (ddev && (ddev->dev_type == SAS_FANOUT_EXPANDER_DEVICE ||
ddev->dev_type == SAS_EDGE_EXPANDER_DEVICE))
res = sas_ex_revalidate_domain(ddev);
SAS_DPRINTK("done REVALIDATING DOMAIN on port %d, pid:%d, res 0x%x\n",
port->id, task_pid_nr(current), res);
out:
mutex_unlock(&ha->disco_mutex);
}
CWE ID:
Target: 1
Example 2:
Code: static void set_acl_from_sec_attr(sc_card_t *card, sc_file_t *file)
{
unsigned int method;
unsigned long key_ref;
assert(card && card->ctx && file);
assert(file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE);
assert(1 + 6 < SC_RTECP_SEC_ATTR_SIZE);
sc_file_add_acl_entry(file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE);
if (file->sec_attr[0] & 0x40) /* if AccessMode.6 */
{
method = sec_attr_to_method(file->sec_attr[1 + 6]);
key_ref = sec_attr_to_key_ref(file->sec_attr[1 + 6]);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"SC_AC_OP_DELETE %i %lu\n",
(int)method, key_ref);
sc_file_add_acl_entry(file, SC_AC_OP_DELETE, method, key_ref);
}
if (file->sec_attr[0] & 0x01) /* if AccessMode.0 */
{
method = sec_attr_to_method(file->sec_attr[1 + 0]);
key_ref = sec_attr_to_key_ref(file->sec_attr[1 + 0]);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
(file->type == SC_FILE_TYPE_DF) ?
"SC_AC_OP_CREATE %i %lu\n"
: "SC_AC_OP_READ %i %lu\n",
(int)method, key_ref);
sc_file_add_acl_entry(file, (file->type == SC_FILE_TYPE_DF) ?
SC_AC_OP_CREATE : SC_AC_OP_READ, method, key_ref);
}
if (file->type == SC_FILE_TYPE_DF)
{
sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else
if (file->sec_attr[0] & 0x02) /* if AccessMode.1 */
{
method = sec_attr_to_method(file->sec_attr[1 + 1]);
key_ref = sec_attr_to_key_ref(file->sec_attr[1 + 1]);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"SC_AC_OP_UPDATE %i %lu\n",
(int)method, key_ref);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, method, key_ref);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"SC_AC_OP_WRITE %i %lu\n",
(int)method, key_ref);
sc_file_add_acl_entry(file, SC_AC_OP_WRITE, method, key_ref);
}
}
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 int mv_read_header(AVFormatContext *avctx)
{
MvContext *mv = avctx->priv_data;
AVIOContext *pb = avctx->pb;
AVStream *ast = NULL, *vst = NULL; //initialization to suppress warning
int version, i;
int ret;
avio_skip(pb, 4);
version = avio_rb16(pb);
if (version == 2) {
uint64_t timestamp;
int v;
avio_skip(pb, 22);
/* allocate audio track first to prevent unnecessary seeking
* (audio packet always precede video packet for a given frame) */
ast = avformat_new_stream(avctx, NULL);
if (!ast)
return AVERROR(ENOMEM);
vst = avformat_new_stream(avctx, NULL);
if (!vst)
return AVERROR(ENOMEM);
avpriv_set_pts_info(vst, 64, 1, 15);
vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
vst->avg_frame_rate = av_inv_q(vst->time_base);
vst->nb_frames = avio_rb32(pb);
v = avio_rb32(pb);
switch (v) {
case 1:
vst->codecpar->codec_id = AV_CODEC_ID_MVC1;
break;
case 2:
vst->codecpar->format = AV_PIX_FMT_ARGB;
vst->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
break;
default:
avpriv_request_sample(avctx, "Video compression %i", v);
break;
}
vst->codecpar->codec_tag = 0;
vst->codecpar->width = avio_rb32(pb);
vst->codecpar->height = avio_rb32(pb);
avio_skip(pb, 12);
ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
ast->nb_frames = vst->nb_frames;
ast->codecpar->sample_rate = avio_rb32(pb);
if (ast->codecpar->sample_rate <= 0) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample rate %d\n", ast->codecpar->sample_rate);
return AVERROR_INVALIDDATA;
}
avpriv_set_pts_info(ast, 33, 1, ast->codecpar->sample_rate);
if (set_channels(avctx, ast, avio_rb32(pb)) < 0)
return AVERROR_INVALIDDATA;
v = avio_rb32(pb);
if (v == AUDIO_FORMAT_SIGNED) {
ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
} else {
avpriv_request_sample(avctx, "Audio compression (format %i)", v);
}
avio_skip(pb, 12);
var_read_metadata(avctx, "title", 0x80);
var_read_metadata(avctx, "comment", 0x100);
avio_skip(pb, 0x80);
timestamp = 0;
for (i = 0; i < vst->nb_frames; i++) {
uint32_t pos = avio_rb32(pb);
uint32_t asize = avio_rb32(pb);
uint32_t vsize = avio_rb32(pb);
avio_skip(pb, 8);
av_add_index_entry(ast, pos, timestamp, asize, 0, AVINDEX_KEYFRAME);
av_add_index_entry(vst, pos + asize, i, vsize, 0, AVINDEX_KEYFRAME);
timestamp += asize / (ast->codecpar->channels * 2);
}
} else if (!version && avio_rb16(pb) == 3) {
avio_skip(pb, 4);
if ((ret = read_table(avctx, NULL, parse_global_var)) < 0)
return ret;
if (mv->nb_audio_tracks > 1) {
avpriv_request_sample(avctx, "Multiple audio streams support");
return AVERROR_PATCHWELCOME;
} else if (mv->nb_audio_tracks) {
ast = avformat_new_stream(avctx, NULL);
if (!ast)
return AVERROR(ENOMEM);
ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
if ((read_table(avctx, ast, parse_audio_var)) < 0)
return ret;
if (mv->acompression == 100 &&
mv->aformat == AUDIO_FORMAT_SIGNED &&
ast->codecpar->bits_per_coded_sample == 16) {
ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE;
} else {
avpriv_request_sample(avctx,
"Audio compression %i (format %i, sr %i)",
mv->acompression, mv->aformat,
ast->codecpar->bits_per_coded_sample);
ast->codecpar->codec_id = AV_CODEC_ID_NONE;
}
if (ast->codecpar->channels <= 0) {
av_log(avctx, AV_LOG_ERROR, "No valid channel count found.\n");
return AVERROR_INVALIDDATA;
}
}
if (mv->nb_video_tracks > 1) {
avpriv_request_sample(avctx, "Multiple video streams support");
return AVERROR_PATCHWELCOME;
} else if (mv->nb_video_tracks) {
vst = avformat_new_stream(avctx, NULL);
if (!vst)
return AVERROR(ENOMEM);
vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
if ((ret = read_table(avctx, vst, parse_video_var))<0)
return ret;
}
if (mv->nb_audio_tracks)
read_index(pb, ast);
if (mv->nb_video_tracks)
read_index(pb, vst);
} else {
avpriv_request_sample(avctx, "Version %i", version);
return AVERROR_PATCHWELCOME;
}
return 0;
}
CWE ID: CWE-834
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: dwarf_elf_object_access_load_section(void* obj_in,
Dwarf_Half section_index,
Dwarf_Small** section_data,
int* error)
{
dwarf_elf_object_access_internals_t*obj =
(dwarf_elf_object_access_internals_t*)obj_in;
if (section_index == 0) {
return DW_DLV_NO_ENTRY;
}
{
Elf_Scn *scn = 0;
Elf_Data *data = 0;
scn = elf_getscn(obj->elf, section_index);
if (scn == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
/* When using libelf as a producer, section data may be stored
in multiple buffers. In libdwarf however, we only use libelf
as a consumer (there is a dwarf producer API, but it doesn't
use libelf). Because of this, this single call to elf_getdata
will retrieve the entire section in a single contiguous
buffer. */
data = elf_getdata(scn, NULL);
if (data == NULL) {
*error = DW_DLE_MDE;
return DW_DLV_ERROR;
}
*section_data = data->d_buf;
}
return DW_DLV_OK;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: TabLifecycleUnitTest() : scoped_set_tick_clock_for_testing_(&test_clock_) {
observers_.AddObserver(&observer_);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete)
{
res.flags.IpOK = FALSE;
res.flags.IpFailed = TRUE;
return res;
}
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
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: PHP_FUNCTION(imagepsencodefont)
{
zval *fnt;
char *enc, **enc_vector;
int enc_len, *f_ind;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &fnt, &enc, &enc_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, "Type 1 font", le_ps_font);
if ((enc_vector = T1_LoadEncoding(enc)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't load encoding vector from %s", enc);
RETURN_FALSE;
}
T1_DeleteAllSizes(*f_ind);
if (T1_ReencodeFont(*f_ind, enc_vector)) {
T1_DeleteEncoding(enc_vector);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Couldn't re-encode font");
RETURN_FALSE;
}
zend_list_insert(enc_vector, le_ps_enc TSRMLS_CC);
RETURN_TRUE;
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static inline int __ldsem_down_write_nested(struct ld_semaphore *sem,
int subclass, long timeout)
{
long count;
lockdep_acquire(sem, subclass, 0, _RET_IP_);
count = ldsem_atomic_update(LDSEM_WRITE_BIAS, sem);
if ((count & LDSEM_ACTIVE_MASK) != LDSEM_ACTIVE_BIAS) {
lock_stat(sem, contended);
if (!down_write_failed(sem, count, timeout)) {
lockdep_release(sem, 1, _RET_IP_);
return 0;
}
}
lock_stat(sem, acquired);
return 1;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool PermissionsRemoveFunction::RunImpl() {
scoped_ptr<Remove::Params> params(Remove::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
scoped_refptr<PermissionSet> permissions =
helpers::UnpackPermissionSet(params->permissions, &error_);
if (!permissions.get())
return false;
const extensions::Extension* extension = GetExtension();
APIPermissionSet apis = permissions->apis();
for (APIPermissionSet::const_iterator i = apis.begin();
i != apis.end(); ++i) {
if (!i->info()->supports_optional()) {
error_ = ErrorUtils::FormatErrorMessage(
kNotWhitelistedError, i->name());
return false;
}
}
const PermissionSet* required = extension->required_permission_set();
scoped_refptr<PermissionSet> intersection(
PermissionSet::CreateIntersection(permissions.get(), required));
if (!intersection->IsEmpty()) {
error_ = kCantRemoveRequiredPermissionsError;
results_ = Remove::Results::Create(false);
return false;
}
PermissionsUpdater(profile()).RemovePermissions(extension, permissions.get());
results_ = Remove::Results::Create(true);
return true;
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int snd_ctl_replace(struct snd_card *card, struct snd_kcontrol *kcontrol,
bool add_on_replace)
{
struct snd_ctl_elem_id id;
unsigned int idx;
struct snd_kcontrol *old;
int ret;
if (!kcontrol)
return -EINVAL;
if (snd_BUG_ON(!card || !kcontrol->info)) {
ret = -EINVAL;
goto error;
}
id = kcontrol->id;
down_write(&card->controls_rwsem);
old = snd_ctl_find_id(card, &id);
if (!old) {
if (add_on_replace)
goto add;
up_write(&card->controls_rwsem);
ret = -EINVAL;
goto error;
}
ret = snd_ctl_remove(card, old);
if (ret < 0) {
up_write(&card->controls_rwsem);
goto error;
}
add:
if (snd_ctl_find_hole(card, kcontrol->count) < 0) {
up_write(&card->controls_rwsem);
ret = -ENOMEM;
goto error;
}
list_add_tail(&kcontrol->list, &card->controls);
card->controls_count += kcontrol->count;
kcontrol->id.numid = card->last_numid + 1;
card->last_numid += kcontrol->count;
up_write(&card->controls_rwsem);
for (idx = 0; idx < kcontrol->count; idx++, id.index++, id.numid++)
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id);
return 0;
error:
snd_ctl_free_one(kcontrol);
return ret;
}
CWE ID:
Target: 1
Example 2:
Code: MagickExport const char *GetLocaleValue(const LocaleInfo *locale_info)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(locale_info != (LocaleInfo *) NULL);
assert(locale_info->signature == MagickCoreSignature);
return(locale_info->message);
}
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: GURL PPAPITestBase::GetTestFileUrl(const std::string& test_case) {
FilePath test_path;
EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &test_path));
test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));
EXPECT_TRUE(file_util::PathExists(test_path));
GURL test_url = net::FilePathToFileURL(test_path);
GURL::Replacements replacements;
std::string query = BuildQuery("", test_case);
replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size()));
return test_url.ReplaceComponents(replacements);
}
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: static ssize_t environ_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *page;
unsigned long src = *ppos;
int ret = 0;
struct mm_struct *mm = file->private_data;
unsigned long env_start, env_end;
if (!mm)
return 0;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
ret = 0;
if (!atomic_inc_not_zero(&mm->mm_users))
goto free;
down_read(&mm->mmap_sem);
env_start = mm->env_start;
env_end = mm->env_end;
up_read(&mm->mmap_sem);
while (count > 0) {
size_t this_len, max_len;
int retval;
if (src >= (env_end - env_start))
break;
this_len = env_end - (env_start + src);
max_len = min_t(size_t, PAGE_SIZE, count);
this_len = min(max_len, this_len);
retval = access_remote_vm(mm, (env_start + src),
page, this_len, 0);
if (retval <= 0) {
ret = retval;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
mmput(mm);
free:
free_page((unsigned long) page);
return ret;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: bool TestBrowserWindow::IsToolbarShowing() const {
return false;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
{
update_rq_clock(rq);
sched_info_dequeued(rq, p);
p->sched_class->dequeue_task(rq, p, flags);
}
CWE ID: CWE-200
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin,
int off_pitch, int bytesperline,
int lines)
{
int y;
int off_cur;
int off_cur_end;
for (y = 0; y < lines; y++) {
off_cur = off_begin;
off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask;
memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur);
off_begin += off_pitch;
}
uint8_t *dst;
dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask);
if (blit_is_unsafe(s, false))
return 0;
(*s->cirrus_rop) (s, dst, src,
s->cirrus_blt_dstpitch, 0,
s->cirrus_blt_width, s->cirrus_blt_height);
cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,
s->cirrus_blt_dstpitch, s->cirrus_blt_width,
s->cirrus_blt_height);
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void HTMLInputElement::setType(const String& type)
{
if (type.isEmpty())
removeAttribute(typeAttr);
else
setAttribute(typeAttr, type);
}
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 parseVorbisComment(
const sp<MetaData> &fileMeta, const char *comment, size_t commentLength)
{
struct {
const char *const mTag;
uint32_t mKey;
} kMap[] = {
{ "TITLE", kKeyTitle },
{ "ARTIST", kKeyArtist },
{ "ALBUMARTIST", kKeyAlbumArtist },
{ "ALBUM ARTIST", kKeyAlbumArtist },
{ "COMPILATION", kKeyCompilation },
{ "ALBUM", kKeyAlbum },
{ "COMPOSER", kKeyComposer },
{ "GENRE", kKeyGenre },
{ "AUTHOR", kKeyAuthor },
{ "TRACKNUMBER", kKeyCDTrackNumber },
{ "DISCNUMBER", kKeyDiscNumber },
{ "DATE", kKeyDate },
{ "YEAR", kKeyYear },
{ "LYRICIST", kKeyWriter },
{ "METADATA_BLOCK_PICTURE", kKeyAlbumArt },
{ "ANDROID_LOOP", kKeyAutoLoop },
};
for (size_t j = 0; j < sizeof(kMap) / sizeof(kMap[0]); ++j) {
size_t tagLen = strlen(kMap[j].mTag);
if (!strncasecmp(kMap[j].mTag, comment, tagLen)
&& comment[tagLen] == '=') {
if (kMap[j].mKey == kKeyAlbumArt) {
extractAlbumArt(
fileMeta,
&comment[tagLen + 1],
commentLength - tagLen - 1);
} else if (kMap[j].mKey == kKeyAutoLoop) {
if (!strcasecmp(&comment[tagLen + 1], "true")) {
fileMeta->setInt32(kKeyAutoLoop, true);
}
} else {
fileMeta->setCString(kMap[j].mKey, &comment[tagLen + 1]);
}
}
}
}
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: static int hfsplus_readdir(struct file *filp, void *dirent, filldir_t filldir)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct super_block *sb = inode->i_sb;
int len, err;
char strbuf[HFSPLUS_MAX_STRLEN + 1];
hfsplus_cat_entry entry;
struct hfs_find_data fd;
struct hfsplus_readdir_data *rd;
u16 type;
if (filp->f_pos >= inode->i_size)
return 0;
err = hfs_find_init(HFSPLUS_SB(sb)->cat_tree, &fd);
if (err)
return err;
hfsplus_cat_build_key(sb, fd.search_key, inode->i_ino, NULL);
err = hfs_brec_find(&fd);
if (err)
goto out;
switch ((u32)filp->f_pos) {
case 0:
/* This is completely artificial... */
if (filldir(dirent, ".", 1, 0, inode->i_ino, DT_DIR))
goto out;
filp->f_pos++;
/* fall through */
case 1:
hfs_bnode_read(fd.bnode, &entry, fd.entryoffset,
fd.entrylength);
if (be16_to_cpu(entry.type) != HFSPLUS_FOLDER_THREAD) {
printk(KERN_ERR "hfs: bad catalog folder thread\n");
err = -EIO;
goto out;
}
if (fd.entrylength < HFSPLUS_MIN_THREAD_SZ) {
printk(KERN_ERR "hfs: truncated catalog thread\n");
err = -EIO;
goto out;
}
if (filldir(dirent, "..", 2, 1,
be32_to_cpu(entry.thread.parentID), DT_DIR))
goto out;
filp->f_pos++;
/* fall through */
default:
if (filp->f_pos >= inode->i_size)
goto out;
err = hfs_brec_goto(&fd, filp->f_pos - 1);
if (err)
goto out;
}
for (;;) {
if (be32_to_cpu(fd.key->cat.parent) != inode->i_ino) {
printk(KERN_ERR "hfs: walked past end of dir\n");
err = -EIO;
goto out;
}
hfs_bnode_read(fd.bnode, &entry, fd.entryoffset,
fd.entrylength);
type = be16_to_cpu(entry.type);
len = HFSPLUS_MAX_STRLEN;
err = hfsplus_uni2asc(sb, &fd.key->cat.name, strbuf, &len);
if (err)
goto out;
if (type == HFSPLUS_FOLDER) {
if (fd.entrylength <
sizeof(struct hfsplus_cat_folder)) {
printk(KERN_ERR "hfs: small dir entry\n");
err = -EIO;
goto out;
}
if (HFSPLUS_SB(sb)->hidden_dir &&
HFSPLUS_SB(sb)->hidden_dir->i_ino ==
be32_to_cpu(entry.folder.id))
goto next;
if (filldir(dirent, strbuf, len, filp->f_pos,
be32_to_cpu(entry.folder.id), DT_DIR))
break;
} else if (type == HFSPLUS_FILE) {
if (fd.entrylength < sizeof(struct hfsplus_cat_file)) {
printk(KERN_ERR "hfs: small file entry\n");
err = -EIO;
goto out;
}
if (filldir(dirent, strbuf, len, filp->f_pos,
be32_to_cpu(entry.file.id), DT_REG))
break;
} else {
printk(KERN_ERR "hfs: bad catalog entry type\n");
err = -EIO;
goto out;
}
next:
filp->f_pos++;
if (filp->f_pos >= inode->i_size)
goto out;
err = hfs_brec_goto(&fd, 1);
if (err)
goto out;
}
rd = filp->private_data;
if (!rd) {
rd = kmalloc(sizeof(struct hfsplus_readdir_data), GFP_KERNEL);
if (!rd) {
err = -ENOMEM;
goto out;
}
filp->private_data = rd;
rd->file = filp;
list_add(&rd->list, &HFSPLUS_I(inode)->open_dir_list);
}
memcpy(&rd->key, fd.key, sizeof(struct hfsplus_cat_key));
out:
hfs_find_exit(&fd);
return err;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){
tsize_t written=0;
int i=0;
written += t2pWriteFile(output, (tdata_t) "/Decode [ ", 10);
for (i=0;i<t2p->tiff_samplesperpixel;i++){
written += t2pWriteFile(output, (tdata_t) "1 0 ", 4);
}
written += t2pWriteFile(output, (tdata_t) "]\n", 2);
return(written);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: INST_HANDLER (lds) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
CWE ID: CWE-125
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static char *print_object( cJSON *item, int depth, int fmt )
{
char **entries = 0, **names = 0;
char *out = 0, *ptr, *ret, *str;
int len = 7, i = 0, j;
cJSON *child = item->child;
int numentries = 0, fail = 0;
/* Count the number of entries. */
while ( child ) {
++numentries;
child = child->next;
}
/* Allocate space for the names and the objects. */
if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) )
return 0;
if ( ! ( names = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) ) {
cJSON_free( entries );
return 0;
}
memset( entries, 0, sizeof(char*) * numentries );
memset( names, 0, sizeof(char*) * numentries );
/* Collect all the results into our arrays. */
child = item->child;
++depth;
if ( fmt )
len += depth;
while ( child ) {
names[i] = str = print_string_ptr( child->string );
entries[i++] = ret = print_value( child, depth, fmt );
if ( str && ret )
len += strlen( ret ) + strlen( str ) + 2 + ( fmt ? 2 + depth : 0 );
else
fail = 1;
child = child->next;
}
/* Try to allocate the output string. */
if ( ! fail ) {
out = (char*) cJSON_malloc( len );
if ( ! out )
fail = 1;
}
/* Handle failure. */
if ( fail ) {
for ( i = 0; i < numentries; ++i ) {
if ( names[i] )
cJSON_free( names[i] );
if ( entries[i] )
cJSON_free( entries[i] );
}
cJSON_free( names );
cJSON_free( entries );
return 0;
}
/* Compose the output. */
*out = '{';
ptr = out + 1;
if ( fmt )
*ptr++ = '\n';
*ptr = 0;
for ( i = 0; i < numentries; ++i ) {
if ( fmt )
for ( j = 0; j < depth; ++j )
*ptr++ = '\t';
strcpy( ptr, names[i] );
ptr += strlen( names[i] );
*ptr++ = ':';
if ( fmt )
*ptr++ = '\t';
strcpy( ptr, entries[i] );
ptr += strlen( entries[i] );
if ( i != numentries - 1 )
*ptr++ = ',';
if ( fmt )
*ptr++ = '\n';
*ptr = 0;
cJSON_free( names[i] );
cJSON_free( entries[i] );
}
cJSON_free( names );
cJSON_free( entries );
if ( fmt )
for ( i = 0; i < depth - 1; ++i )
*ptr++ = '\t';
*ptr++ = '}';
*ptr++ = 0;
return out;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderBox::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
{
ASSERT(!view() || !view()->layoutStateEnabled());
bool isFixedPos = style()->position() == FixedPosition;
bool hasTransform = hasLayer() && layer()->transform();
if (hasTransform && !isFixedPos) {
mode &= ~IsFixed;
} else if (isFixedPos)
mode |= IsFixed;
RenderBoxModelObject::mapAbsoluteToLocalPoint(mode, transformState);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: get_linux_shareopts(const char *shareopts, char **plinux_opts)
{
int rc;
assert(plinux_opts != NULL);
*plinux_opts = NULL;
/* default options for Solaris shares */
(void) add_linux_shareopt(plinux_opts, "no_subtree_check", NULL);
(void) add_linux_shareopt(plinux_opts, "no_root_squash", NULL);
(void) add_linux_shareopt(plinux_opts, "mountpoint", NULL);
rc = foreach_nfs_shareopt(shareopts, get_linux_shareopts_cb,
plinux_opts);
if (rc != SA_OK) {
free(*plinux_opts);
*plinux_opts = NULL;
}
return (rc);
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GpuProcessHostUIShim::OnAcceleratedSurfaceRelease(
const GpuHostMsg_AcceleratedSurfaceRelease_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
view->AcceleratedSurfaceRelease(params.identifier);
}
CWE ID:
Target: 1
Example 2:
Code: DevToolsDomainHandler::~DevToolsDomainHandler() {
}
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: uint32_t ReverbGetDecayTime(ReverbContext *pContext){
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "ReverbGetDecayTime")
if(ActiveParams.T60 != pContext->SavedDecayTime){
ALOGV("\tLVM_ERROR : ReverbGetDecayTime() has wrong level -> %d %d\n",
ActiveParams.T60, pContext->SavedDecayTime);
}
return (uint32_t)ActiveParams.T60;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool WebContentsImpl::ShowingInterstitialPage() const {
return GetRenderManager()->interstitial_page() != NULL;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool PDFShouldDisableScalingBasedOnPreset(
const blink::WebPrintPresetOptions& options,
const PrintMsg_Print_Params& params,
bool ignore_page_size) {
if (options.is_scaling_disabled)
return true;
if (!options.is_page_size_uniform)
return false;
int dpi = GetDPI(¶ms);
if (!dpi) {
return true;
}
if (ignore_page_size)
return false;
blink::WebSize page_size(
ConvertUnit(params.page_size.width(), dpi, kPointsPerInch),
ConvertUnit(params.page_size.height(), dpi, kPointsPerInch));
return options.uniform_page_size == page_size;
}
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: JSValue jsTestObjIntAttr(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(slotBase));
UNUSED_PARAM(exec);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
JSValue result = jsNumber(impl->intAttr());
return result;
}
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 MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
header[MagickPathExtent];
const char
*property;
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
length;
ssize_t
count,
y;
unsigned char
pixel[4],
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if (IsRGBColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,RGBColorspace,exception);
/*
Write header.
*/
(void) ResetMagickMemory(header,' ',MagickPathExtent);
length=CopyMagickString(header,"#?RGBE\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
property=GetImageProperty(image,"comment",exception);
if ((property != (const char *) NULL) &&
(strchr(property,'\n') == (char *) NULL))
{
count=FormatLocaleString(header,MagickPathExtent,"#%s\n",property);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
property=GetImageProperty(image,"hdr:exposure",exception);
if (property != (const char *) NULL)
{
count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n",
strtod(property,(char **) NULL));
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
if (image->gamma != 0.0)
{
count=FormatLocaleString(header,MagickPathExtent,"GAMMA=%g\n",image->gamma);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
count=FormatLocaleString(header,MagickPathExtent,
"PRIMARIES=%g %g %g %g %g %g %g %g\n",
image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,
image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,
image->chromaticity.white_point.x,image->chromaticity.white_point.y);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
count=FormatLocaleString(header,MagickPathExtent,"-Y %.20g +X %.20g\n",
(double) image->rows,(double) image->columns);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
/*
Write HDR pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixel[0]=2;
pixel[1]=2;
pixel[2]=(unsigned char) (image->columns >> 8);
pixel[3]=(unsigned char) (image->columns & 0xff);
count=WriteBlob(image,4*sizeof(*pixel),pixel);
if (count != (ssize_t) (4*sizeof(*pixel)))
break;
}
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
pixel[0]=0;
pixel[1]=0;
pixel[2]=0;
pixel[3]=0;
gamma=QuantumScale*GetPixelRed(image,p);
if ((QuantumScale*GetPixelGreen(image,p)) > gamma)
gamma=QuantumScale*GetPixelGreen(image,p);
if ((QuantumScale*GetPixelBlue(image,p)) > gamma)
gamma=QuantumScale*GetPixelBlue(image,p);
if (gamma > MagickEpsilon)
{
int
exponent;
gamma=frexp(gamma,&exponent)*256.0/gamma;
pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));
pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));
pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));
pixel[3]=(unsigned char) (exponent+128);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixels[x]=pixel[0];
pixels[x+image->columns]=pixel[1];
pixels[x+2*image->columns]=pixel[2];
pixels[x+3*image->columns]=pixel[3];
}
else
{
pixels[i++]=pixel[0];
pixels[i++]=pixel[1];
pixels[i++]=pixel[2];
pixels[i++]=pixel[3];
}
p+=GetPixelChannels(image);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
for (i=0; i < 4; i++)
length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);
}
else
{
count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(MagickTrue);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int kvp_key_add_or_modify(int pool, __u8 *key, int key_size, __u8 *value,
int value_size)
{
int i;
int num_records;
struct kvp_record *record;
int num_blocks;
if ((key_size > HV_KVP_EXCHANGE_MAX_KEY_SIZE) ||
(value_size > HV_KVP_EXCHANGE_MAX_VALUE_SIZE))
return 1;
/*
* First update the in-memory state.
*/
kvp_update_mem_state(pool);
num_records = kvp_file_info[pool].num_records;
record = kvp_file_info[pool].records;
num_blocks = kvp_file_info[pool].num_blocks;
for (i = 0; i < num_records; i++) {
if (memcmp(key, record[i].key, key_size))
continue;
/*
* Found a match; just update the value -
* this is the modify case.
*/
memcpy(record[i].value, value, value_size);
kvp_update_file(pool);
return 0;
}
/*
* Need to add a new entry;
*/
if (num_records == (ENTRIES_PER_BLOCK * num_blocks)) {
/* Need to allocate a larger array for reg entries. */
record = realloc(record, sizeof(struct kvp_record) *
ENTRIES_PER_BLOCK * (num_blocks + 1));
if (record == NULL)
return 1;
kvp_file_info[pool].num_blocks++;
}
memcpy(record[i].value, value, value_size);
memcpy(record[i].key, key, key_size);
kvp_file_info[pool].records = record;
kvp_file_info[pool].num_records++;
kvp_update_file(pool);
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int Downmix_Reset(downmix_object_t *pDownmixer, bool init) {
return 0;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WebNotificationData ToWebNotificationData(
const PlatformNotificationData& platform_data) {
WebNotificationData web_data;
web_data.title = platform_data.title;
switch (platform_data.direction) {
case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT:
web_data.direction = WebNotificationData::DirectionLeftToRight;
break;
case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT:
web_data.direction = WebNotificationData::DirectionRightToLeft;
break;
case PlatformNotificationData::DIRECTION_AUTO:
web_data.direction = WebNotificationData::DirectionAuto;
break;
}
web_data.lang = blink::WebString::fromUTF8(platform_data.lang);
web_data.body = platform_data.body;
web_data.tag = blink::WebString::fromUTF8(platform_data.tag);
web_data.icon = blink::WebURL(platform_data.icon);
web_data.vibrate = platform_data.vibration_pattern;
web_data.timestamp = platform_data.timestamp.ToJsTime();
web_data.silent = platform_data.silent;
web_data.requireInteraction = platform_data.require_interaction;
web_data.data = platform_data.data;
blink::WebVector<blink::WebNotificationAction> resized(
platform_data.actions.size());
web_data.actions.swap(resized);
for (size_t i = 0; i < platform_data.actions.size(); ++i) {
web_data.actions[i].action =
blink::WebString::fromUTF8(platform_data.actions[i].action);
web_data.actions[i].title = platform_data.actions[i].title;
}
return web_data;
}
CWE ID:
Target: 1
Example 2:
Code: process_update_pdu(STREAM s)
{
uint16 update_type, count;
in_uint16_le(s, update_type);
ui_begin_update();
switch (update_type)
{
case RDP_UPDATE_ORDERS:
logger(Protocol, Debug, "%s(), RDP_UPDATE_ORDERS", __func__);
in_uint8s(s, 2); /* pad */
in_uint16_le(s, count);
in_uint8s(s, 2); /* pad */
process_orders(s, count);
break;
case RDP_UPDATE_BITMAP:
logger(Protocol, Debug, "%s(), RDP_UPDATE_BITMAP", __func__);
process_bitmap_updates(s);
break;
case RDP_UPDATE_PALETTE:
logger(Protocol, Debug, "%s(), RDP_UPDATE_PALETTE", __func__);
process_palette(s);
break;
case RDP_UPDATE_SYNCHRONIZE:
logger(Protocol, Debug, "%s(), RDP_UPDATE_SYNCHRONIZE", __func__);
break;
default:
logger(Protocol, Warning, "process_update_pdu(), unhandled update type %d",
update_type);
}
ui_end_update();
}
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 ip_rt_bug(struct sock *sk, struct sk_buff *skb)
{
pr_debug("%s: %pI4 -> %pI4, %s\n",
__func__, &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr,
skb->dev ? skb->dev->name : "?");
kfree_skb(skb);
WARN_ON(1);
return 0;
}
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: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::AllocateHistogram(
HistogramType histogram_type,
const std::string& name,
int minimum,
int maximum,
const BucketRanges* bucket_ranges,
int32_t flags,
Reference* ref_ptr) {
if (memory_allocator_->IsCorrupt()) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_CORRUPT);
return nullptr;
}
PersistentHistogramData* histogram_data =
memory_allocator_->New<PersistentHistogramData>(
offsetof(PersistentHistogramData, name) + name.length() + 1);
if (histogram_data) {
memcpy(histogram_data->name, name.c_str(), name.size() + 1);
histogram_data->histogram_type = histogram_type;
histogram_data->flags = flags | HistogramBase::kIsPersistent;
}
if (histogram_type != SPARSE_HISTOGRAM) {
size_t bucket_count = bucket_ranges->bucket_count();
size_t counts_bytes = CalculateRequiredCountsBytes(bucket_count);
if (counts_bytes == 0) {
NOTREACHED();
return nullptr;
}
DCHECK_EQ(this, GlobalHistogramAllocator::Get());
PersistentMemoryAllocator::Reference ranges_ref =
bucket_ranges->persistent_reference();
if (!ranges_ref) {
size_t ranges_count = bucket_count + 1;
size_t ranges_bytes = ranges_count * sizeof(HistogramBase::Sample);
ranges_ref =
memory_allocator_->Allocate(ranges_bytes, kTypeIdRangesArray);
if (ranges_ref) {
HistogramBase::Sample* ranges_data =
memory_allocator_->GetAsArray<HistogramBase::Sample>(
ranges_ref, kTypeIdRangesArray, ranges_count);
if (ranges_data) {
for (size_t i = 0; i < bucket_ranges->size(); ++i)
ranges_data[i] = bucket_ranges->range(i);
bucket_ranges->set_persistent_reference(ranges_ref);
} else {
NOTREACHED();
ranges_ref = PersistentMemoryAllocator::kReferenceNull;
}
}
} else {
DCHECK_EQ(kTypeIdRangesArray, memory_allocator_->GetType(ranges_ref));
}
if (ranges_ref && histogram_data) {
histogram_data->minimum = minimum;
histogram_data->maximum = maximum;
histogram_data->bucket_count = static_cast<uint32_t>(bucket_count);
histogram_data->ranges_ref = ranges_ref;
histogram_data->ranges_checksum = bucket_ranges->checksum();
} else {
histogram_data = nullptr; // Clear this for proper handling below.
}
}
if (histogram_data) {
std::unique_ptr<HistogramBase> histogram = CreateHistogram(histogram_data);
DCHECK(histogram);
DCHECK_NE(0U, histogram_data->samples_metadata.id);
DCHECK_NE(0U, histogram_data->logged_metadata.id);
PersistentMemoryAllocator::Reference histogram_ref =
memory_allocator_->GetAsReference(histogram_data);
if (ref_ptr != nullptr)
*ref_ptr = histogram_ref;
subtle::NoBarrier_Store(&last_created_, histogram_ref);
return histogram;
}
CreateHistogramResultType result;
if (memory_allocator_->IsCorrupt()) {
RecordCreateHistogramResult(CREATE_HISTOGRAM_ALLOCATOR_NEWLY_CORRUPT);
result = CREATE_HISTOGRAM_ALLOCATOR_CORRUPT;
} else if (memory_allocator_->IsFull()) {
result = CREATE_HISTOGRAM_ALLOCATOR_FULL;
} else {
result = CREATE_HISTOGRAM_ALLOCATOR_ERROR;
}
RecordCreateHistogramResult(result);
if (result != CREATE_HISTOGRAM_ALLOCATOR_FULL)
NOTREACHED() << memory_allocator_->Name() << ", error=" << result;
return nullptr;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void GDataEntry::FromProto(const GDataEntryProto& proto) {
ConvertProtoToPlatformFileInfo(proto.file_info(), &file_info_);
title_ = proto.title();
resource_id_ = proto.resource_id();
parent_resource_id_ = proto.parent_resource_id();
edit_url_ = GURL(proto.edit_url());
content_url_ = GURL(proto.content_url());
SetFileNameFromTitle();
}
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: store_freenew(png_store *ps)
{
store_freebuffer(&ps->new);
ps->writepos = 0;
if (ps->palette != NULL)
{
free(ps->palette);
ps->palette = NULL;
ps->npalette = 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: fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32 bps = tif->tif_dir.td_bitspersample / 8;
tmsize_t wc = cc / bps;
tmsize_t count = cc;
uint8 *cp = (uint8 *) cp0;
uint8 *tmp = (uint8 *)_TIFFmalloc(cc);
if(cc%(bps*stride)!=0)
{
TIFFErrorExt(tif->tif_clientdata, "fpAcc",
"%s", "cc%(bps*stride))!=0");
return 0;
}
if (!tmp)
return 0;
while (count > stride) {
REPEAT4(stride, cp[stride] =
(unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
count -= stride;
}
_TIFFmemcpy(tmp, cp0, cc);
cp = (uint8 *) cp0;
for (count = 0; count < wc; count++) {
uint32 byte;
for (byte = 0; byte < bps; byte++) {
#if WORDS_BIGENDIAN
cp[bps * count + byte] = tmp[byte * wc + count];
#else
cp[bps * count + byte] =
tmp[(bps - byte - 1) * wc + count];
#endif
}
}
_TIFFfree(tmp);
return 1;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ExtensionReadyNotificationObserver::~ExtensionReadyNotificationObserver() {
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int pdo_stmt_setup_fetch_mode(INTERNAL_FUNCTION_PARAMETERS, pdo_stmt_t *stmt, int skip)
{
long mode = PDO_FETCH_BOTH;
int flags = 0, argc = ZEND_NUM_ARGS() - skip;
zval ***args;
zend_class_entry **cep;
int retval;
do_fetch_opt_finish(stmt, 1 TSRMLS_CC);
switch (stmt->default_fetch_type) {
case PDO_FETCH_INTO:
if (stmt->fetch.into) {
zval_ptr_dtor(&stmt->fetch.into);
stmt->fetch.into = NULL;
}
break;
default:
;
}
stmt->default_fetch_type = PDO_FETCH_BOTH;
if (argc == 0) {
return SUCCESS;
}
args = safe_emalloc(ZEND_NUM_ARGS(), sizeof(zval*), 0);
retval = zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args);
if (SUCCESS == retval) {
if (Z_TYPE_PP(args[skip]) != IS_LONG) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "mode must be an integer" TSRMLS_CC);
retval = FAILURE;
} else {
mode = Z_LVAL_PP(args[skip]);
flags = mode & PDO_FETCH_FLAGS;
retval = pdo_stmt_verify_mode(stmt, mode, 0 TSRMLS_CC);
}
}
if (FAILURE == retval) {
PDO_STMT_CLEAR_ERR();
efree(args);
return FAILURE;
}
retval = FAILURE;
switch (mode & ~PDO_FETCH_FLAGS) {
case PDO_FETCH_USE_DEFAULT:
case PDO_FETCH_LAZY:
case PDO_FETCH_ASSOC:
case PDO_FETCH_NUM:
case PDO_FETCH_BOTH:
case PDO_FETCH_OBJ:
case PDO_FETCH_BOUND:
case PDO_FETCH_NAMED:
case PDO_FETCH_KEY_PAIR:
if (argc != 1) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode doesn't allow any extra arguments" TSRMLS_CC);
} else {
retval = SUCCESS;
}
break;
case PDO_FETCH_COLUMN:
if (argc != 2) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode requires the colno argument" TSRMLS_CC);
} else if (Z_TYPE_PP(args[skip+1]) != IS_LONG) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "colno must be an integer" TSRMLS_CC);
} else {
stmt->fetch.column = Z_LVAL_PP(args[skip+1]);
retval = SUCCESS;
}
break;
case PDO_FETCH_CLASS:
/* Gets its class name from 1st column */
if ((flags & PDO_FETCH_CLASSTYPE) == PDO_FETCH_CLASSTYPE) {
if (argc != 1) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode doesn't allow any extra arguments" TSRMLS_CC);
} else {
stmt->fetch.cls.ce = NULL;
retval = SUCCESS;
}
} else {
if (argc < 2) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode requires the classname argument" TSRMLS_CC);
} else if (argc > 3) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "too many arguments" TSRMLS_CC);
} else if (Z_TYPE_PP(args[skip+1]) != IS_STRING) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "classname must be a string" TSRMLS_CC);
} else {
retval = zend_lookup_class(Z_STRVAL_PP(args[skip+1]),
Z_STRLEN_PP(args[skip+1]), &cep TSRMLS_CC);
if (SUCCESS == retval && cep && *cep) {
stmt->fetch.cls.ce = *cep;
}
}
}
if (SUCCESS == retval) {
stmt->fetch.cls.ctor_args = NULL;
#ifdef ilia_0 /* we'll only need this when we have persistent statements, if ever */
if (stmt->dbh->is_persistent) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "PHP might crash if you don't call $stmt->setFetchMode() to reset to defaults on this persistent statement. This will be fixed in a later release");
}
#endif
if (argc == 3) {
if (Z_TYPE_PP(args[skip+2]) != IS_NULL && Z_TYPE_PP(args[skip+2]) != IS_ARRAY) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "ctor_args must be either NULL or an array" TSRMLS_CC);
retval = FAILURE;
} else if (Z_TYPE_PP(args[skip+2]) == IS_ARRAY && zend_hash_num_elements(Z_ARRVAL_PP(args[skip+2]))) {
ALLOC_ZVAL(stmt->fetch.cls.ctor_args);
*stmt->fetch.cls.ctor_args = **args[skip+2];
zval_copy_ctor(stmt->fetch.cls.ctor_args);
}
}
if (SUCCESS == retval) {
do_fetch_class_prepare(stmt TSRMLS_CC);
}
}
break;
case PDO_FETCH_INTO:
if (argc != 2) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "fetch mode requires the object parameter" TSRMLS_CC);
} else if (Z_TYPE_PP(args[skip+1]) != IS_OBJECT) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY000", "object must be an object" TSRMLS_CC);
} else {
retval = SUCCESS;
}
if (SUCCESS == retval) {
#ifdef ilia_0 /* we'll only need this when we have persistent statements, if ever */
if (stmt->dbh->is_persistent) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "PHP might crash if you don't call $stmt->setFetchMode() to reset to defaults on this persistent statement. This will be fixed in a later release");
}
#endif
MAKE_STD_ZVAL(stmt->fetch.into);
Z_TYPE_P(stmt->fetch.into) = IS_OBJECT;
Z_OBJ_HANDLE_P(stmt->fetch.into) = Z_OBJ_HANDLE_PP(args[skip+1]);
Z_OBJ_HT_P(stmt->fetch.into) = Z_OBJ_HT_PP(args[skip+1]);
zend_objects_store_add_ref(stmt->fetch.into TSRMLS_CC);
}
break;
default:
pdo_raise_impl_error(stmt->dbh, stmt, "22003", "Invalid fetch mode specified" TSRMLS_CC);
}
if (SUCCESS == retval) {
stmt->default_fetch_type = mode;
}
/*
* PDO error (if any) has already been raised at this point.
*
* The error_code is cleared, otherwise the caller will read the
* last error message from the driver.
*
*/
PDO_STMT_CLEAR_ERR();
efree(args);
return retval;
}
CWE ID: CWE-476
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int l2cap_parse_conf_req(struct sock *sk, void *data)
{
struct l2cap_pinfo *pi = l2cap_pi(sk);
struct l2cap_conf_rsp *rsp = data;
void *ptr = rsp->data;
void *req = pi->conf_req;
int len = pi->conf_len;
int type, hint, olen;
unsigned long val;
struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };
u16 mtu = L2CAP_DEFAULT_MTU;
u16 result = L2CAP_CONF_SUCCESS;
BT_DBG("sk %p", sk);
while (len >= L2CAP_CONF_OPT_SIZE) {
len -= l2cap_get_conf_opt(&req, &type, &olen, &val);
hint = type & L2CAP_CONF_HINT;
type &= L2CAP_CONF_MASK;
switch (type) {
case L2CAP_CONF_MTU:
mtu = val;
break;
case L2CAP_CONF_FLUSH_TO:
pi->flush_to = val;
break;
case L2CAP_CONF_QOS:
break;
case L2CAP_CONF_RFC:
if (olen == sizeof(rfc))
memcpy(&rfc, (void *) val, olen);
break;
default:
if (hint)
break;
result = L2CAP_CONF_UNKNOWN;
*((u8 *) ptr++) = type;
break;
}
}
if (result == L2CAP_CONF_SUCCESS) {
/* Configure output options and let the other side know
* which ones we don't like. */
if (rfc.mode == L2CAP_MODE_BASIC) {
if (mtu < pi->omtu)
result = L2CAP_CONF_UNACCEPT;
else {
pi->omtu = mtu;
pi->conf_state |= L2CAP_CONF_OUTPUT_DONE;
}
l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu);
} else {
result = L2CAP_CONF_UNACCEPT;
memset(&rfc, 0, sizeof(rfc));
rfc.mode = L2CAP_MODE_BASIC;
l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,
sizeof(rfc), (unsigned long) &rfc);
}
}
rsp->scid = cpu_to_le16(pi->dcid);
rsp->result = cpu_to_le16(result);
rsp->flags = cpu_to_le16(0x0000);
return ptr - data;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
preferred_size_ = pref_size;
if (delegate_)
delegate_->UpdatePreferredSize(this, pref_size);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
const uint8_t *name, uint8_t *dst, int dst_size)
{
int namelen = strlen(name);
int len;
while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) {
len = ff_amf_tag_size(data, data_end);
if (len < 0)
len = data_end - data;
data += len;
}
if (data_end - data < 3)
return -1;
data++;
for (;;) {
int size = bytestream_get_be16(&data);
if (!size)
break;
if (size < 0 || size >= data_end - data)
return -1;
data += size;
if (size == namelen && !memcmp(data-size, name, namelen)) {
switch (*data++) {
case AMF_DATA_TYPE_NUMBER:
snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data)));
break;
case AMF_DATA_TYPE_BOOL:
snprintf(dst, dst_size, "%s", *data ? "true" : "false");
break;
case AMF_DATA_TYPE_STRING:
len = bytestream_get_be16(&data);
av_strlcpy(dst, data, FFMIN(len+1, dst_size));
break;
default:
return -1;
}
return 0;
}
len = ff_amf_tag_size(data, data_end);
if (len < 0 || len >= data_end - data)
return -1;
data += len;
}
return -1;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: CSSStyleSheet* CSSStyleSheet::CreateInline(Node& owner_node,
const KURL& base_url,
const TextPosition& start_position,
const WTF::TextEncoding& encoding) {
CSSParserContext* parser_context = CSSParserContext::Create(
owner_node.GetDocument(), owner_node.GetDocument().BaseURL(),
owner_node.GetDocument().GetReferrerPolicy(), encoding);
StyleSheetContents* sheet =
StyleSheetContents::Create(base_url.GetString(), parser_context);
return new CSSStyleSheet(sheet, owner_node, true, start_position);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: mm_destroy(struct mm_master *mm)
{
mm_freelist(mm->mmalloc, &mm->rb_free);
mm_freelist(mm->mmalloc, &mm->rb_allocated);
if (munmap(mm->address, mm->size) == -1)
fatal("munmap(%p, %zu): %s", mm->address, mm->size,
strerror(errno));
if (mm->mmalloc == NULL)
free(mm);
else
mm_free(mm->mmalloc, mm);
}
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: initCropMasks (struct crop_mask *cps)
{
int i;
cps->crop_mode = CROP_NONE;
cps->res_unit = RESUNIT_NONE;
cps->edge_ref = EDGE_TOP;
cps->width = 0;
cps->length = 0;
for (i = 0; i < 4; i++)
cps->margins[i] = 0.0;
cps->bufftotal = (uint32)0;
cps->combined_width = (uint32)0;
cps->combined_length = (uint32)0;
cps->rotation = (uint16)0;
cps->photometric = INVERT_DATA_AND_TAG;
cps->mirror = (uint16)0;
cps->invert = (uint16)0;
cps->zones = (uint32)0;
cps->regions = (uint32)0;
for (i = 0; i < MAX_REGIONS; i++)
{
cps->corners[i].X1 = 0.0;
cps->corners[i].X2 = 0.0;
cps->corners[i].Y1 = 0.0;
cps->corners[i].Y2 = 0.0;
cps->regionlist[i].x1 = 0;
cps->regionlist[i].x2 = 0;
cps->regionlist[i].y1 = 0;
cps->regionlist[i].y2 = 0;
cps->regionlist[i].width = 0;
cps->regionlist[i].length = 0;
cps->regionlist[i].buffsize = 0;
cps->regionlist[i].buffptr = NULL;
cps->zonelist[i].position = 0;
cps->zonelist[i].total = 0;
}
cps->exp_mode = ONE_FILE_COMPOSITE;
cps->img_mode = COMPOSITE_IMAGES;
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int pagemap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma;
struct pagemapread *pm = walk->private;
pte_t *pte;
int err = 0;
split_huge_page_pmd(walk->mm, pmd);
/* find the first VMA at or above 'addr' */
vma = find_vma(walk->mm, addr);
for (; addr != end; addr += PAGE_SIZE) {
u64 pfn = PM_NOT_PRESENT;
/* check to see if we've left 'vma' behind
* and need a new, higher one */
if (vma && (addr >= vma->vm_end))
vma = find_vma(walk->mm, addr);
/* check that 'vma' actually covers this address,
* and that it isn't a huge page vma */
if (vma && (vma->vm_start <= addr) &&
!is_vm_hugetlb_page(vma)) {
pte = pte_offset_map(pmd, addr);
pfn = pte_to_pagemap_entry(*pte);
/* unmap before userspace copy */
pte_unmap(pte);
}
err = add_to_pagemap(addr, pfn, pm);
if (err)
return err;
}
cond_resched();
return err;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: rb_num_of_entries(struct ring_buffer_per_cpu *cpu_buffer)
{
return local_read(&cpu_buffer->entries) -
(local_read(&cpu_buffer->overrun) + cpu_buffer->read);
}
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 HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) {
WaitableEvent done(false, false);
scoped_refptr<WorkerTask> task(new WorkerTask(work, &done));
history_service_->ScheduleDBTask(task.get(), this);
done.Wait();
}
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: cJSON *cJSON_CreateString( const char *string )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_String;
item->valuestring = cJSON_strdup( string );
}
return item;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool SyncManager::ReceivedExperimentalTypes(syncable::ModelTypeSet* to_add)
const {
ReadTransaction trans(FROM_HERE, GetUserShare());
ReadNode node(&trans);
if (!node.InitByTagLookup(kNigoriTag)) {
DVLOG(1) << "Couldn't find Nigori node.";
return false;
}
if (node.GetNigoriSpecifics().sync_tabs()) {
to_add->Put(syncable::SESSIONS);
return true;
}
return false;
}
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 GDataCacheMetadataMap::Initialize(
const std::vector<FilePath>& cache_paths) {
AssertOnSequencedWorkerPool();
if (cache_paths.size() < GDataCache::NUM_CACHE_TYPES) {
LOG(ERROR) << "Size of cache_paths is invalid.";
return;
}
if (!GDataCache::CreateCacheDirectories(cache_paths))
return;
if (!ChangeFilePermissions(cache_paths[GDataCache::CACHE_TYPE_PERSISTENT],
S_IRWXU | S_IXGRP | S_IXOTH))
return;
DVLOG(1) << "Scanning directories";
ResourceIdToFilePathMap persistent_file_map;
ScanCacheDirectory(cache_paths,
GDataCache::CACHE_TYPE_PERSISTENT,
&cache_map_,
&persistent_file_map);
ResourceIdToFilePathMap tmp_file_map;
ScanCacheDirectory(cache_paths,
GDataCache::CACHE_TYPE_TMP,
&cache_map_,
&tmp_file_map);
ResourceIdToFilePathMap pinned_file_map;
ScanCacheDirectory(cache_paths,
GDataCache::CACHE_TYPE_PINNED,
&cache_map_,
&pinned_file_map);
ResourceIdToFilePathMap outgoing_file_map;
ScanCacheDirectory(cache_paths,
GDataCache::CACHE_TYPE_OUTGOING,
&cache_map_,
&outgoing_file_map);
RemoveInvalidFilesFromPersistentDirectory(persistent_file_map,
outgoing_file_map,
&cache_map_);
DVLOG(1) << "Directory scan finished";
}
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: MagickExport const char *GetMagickFeatures(void)
{
return "DPC"
#if defined(MAGICKCORE_BUILD_MODULES) || defined(_DLL)
" Modules"
#endif
#if defined(MAGICKCORE_HDRI_SUPPORT)
" HDRI"
#endif
#if defined(MAGICKCORE_OPENCL_SUPPORT)
" OpenCL"
#endif
#if defined(MAGICKCORE_OPENMP_SUPPORT)
" OpenMP"
#endif
;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: v8::Handle<v8::Value> deserialize()
{
v8::Isolate* isolate = m_reader.scriptState()->isolate();
if (!m_reader.readVersion(m_version) || m_version > SerializedScriptValue::wireFormatVersion)
return v8::Null(isolate);
m_reader.setVersion(m_version);
v8::EscapableHandleScope scope(isolate);
while (!m_reader.isEof()) {
if (!doDeserialize())
return v8::Null(isolate);
}
if (stackDepth() != 1 || m_openCompositeReferenceStack.size())
return v8::Null(isolate);
v8::Handle<v8::Value> result = scope.Escape(element(0));
return result;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Editor::replaceSelectionWithText(const String& text,
bool selectReplacement,
bool smartReplace,
InputEvent::InputType inputType) {
replaceSelectionWithFragment(createFragmentFromText(selectedRange(), text),
selectReplacement, smartReplace, true,
inputType);
}
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 RenderFrameDevToolsAgentHost::UpdateFrameHost(
RenderFrameHostImpl* frame_host) {
if (frame_host == frame_host_) {
if (frame_host && !render_frame_alive_) {
render_frame_alive_ = true;
MaybeReattachToRenderFrame();
}
return;
}
if (frame_host && !ShouldCreateDevToolsForHost(frame_host)) {
DestroyOnRenderFrameGone();
return;
}
if (IsAttached())
RevokePolicy();
frame_host_ = frame_host;
agent_ptr_.reset();
render_frame_alive_ = true;
if (IsAttached()) {
GrantPolicy();
for (DevToolsSession* session : sessions()) {
session->SetRenderer(frame_host ? frame_host->GetProcess() : nullptr,
frame_host);
}
MaybeReattachToRenderFrame();
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void GpuCommandBufferStub::OnAsyncFlush(int32 put_offset,
uint32 flush_count) {
TRACE_EVENT1("gpu", "GpuCommandBufferStub::OnAsyncFlush",
"put_offset", put_offset);
DCHECK(command_buffer_.get());
if (flush_count - last_flush_count_ < 0x8000000U) {
last_flush_count_ = flush_count;
command_buffer_->Flush(put_offset);
} else {
NOTREACHED() << "Received a Flush message out-of-order";
}
ReportState();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole,
OnDidAddMessageToConsole)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoad,
OnDidStartProvisionalLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
OnDocumentOnLoadCompleted)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
OnJavaScriptExecuteResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_RunFileChooser, OnRunFileChooser)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SerializeAsMHTMLResponse,
OnSerializeAsMHTMLResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGesture,
OnSetHasReceivedUserGesture)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_MESSAGE_HANDLER(FrameHostMsg_StreamHandleConsumed,
OnStreamHandleConsumed)
IPC_END_MESSAGE_MAP()
return handled;
}
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: Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict, Catalog *catalogA,
double hDPI, double vDPI, PDFRectangle *box,
PDFRectangle *cropBox, int rotate,
GBool (*abortCheckCbkA)(void *data),
void *abortCheckCbkDataA)
#ifdef USE_CMS
: iccColorSpaceCache(5)
#endif
{
int i;
xref = xrefA;
catalog = catalogA;
subPage = gFalse;
printCommands = globalParams->getPrintCommands();
profileCommands = globalParams->getProfileCommands();
textHaveCSPattern = gFalse;
drawText = gFalse;
maskHaveCSPattern = gFalse;
mcStack = NULL;
res = new GfxResources(xref, resDict, NULL);
out = outA;
state = new GfxState(hDPI, vDPI, box, rotate, out->upsideDown());
stackHeight = 1;
pushStateGuard();
fontChanged = gFalse;
clip = clipNone;
ignoreUndef = 0;
out->startPage(pageNum, state);
out->setDefaultCTM(state->getCTM());
out->updateAll(state);
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
formDepth = 0;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int ext4_da_write_end(struct file *file,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct inode *inode = mapping->host;
int ret = 0, ret2;
handle_t *handle = ext4_journal_current_handle();
loff_t new_i_size;
unsigned long start, end;
int write_mode = (int)(unsigned long)fsdata;
if (write_mode == FALL_BACK_TO_NONDELALLOC) {
if (ext4_should_order_data(inode)) {
return ext4_ordered_write_end(file, mapping, pos,
len, copied, page, fsdata);
} else if (ext4_should_writeback_data(inode)) {
return ext4_writeback_write_end(file, mapping, pos,
len, copied, page, fsdata);
} else {
BUG();
}
}
trace_ext4_da_write_end(inode, pos, len, copied);
start = pos & (PAGE_CACHE_SIZE - 1);
end = start + copied - 1;
/*
* generic_write_end() will run mark_inode_dirty() if i_size
* changes. So let's piggyback the i_disksize mark_inode_dirty
* into that.
*/
new_i_size = pos + copied;
if (new_i_size > EXT4_I(inode)->i_disksize) {
if (ext4_da_should_update_i_disksize(page, end)) {
down_write(&EXT4_I(inode)->i_data_sem);
if (new_i_size > EXT4_I(inode)->i_disksize) {
/*
* Updating i_disksize when extending file
* without needing block allocation
*/
if (ext4_should_order_data(inode))
ret = ext4_jbd2_file_inode(handle,
inode);
EXT4_I(inode)->i_disksize = new_i_size;
}
up_write(&EXT4_I(inode)->i_data_sem);
/* We need to mark inode dirty even if
* new_i_size is less that inode->i_size
* bu greater than i_disksize.(hint delalloc)
*/
ext4_mark_inode_dirty(handle, inode);
}
}
ret2 = generic_write_end(file, mapping, pos, len, copied,
page, fsdata);
copied = ret2;
if (ret2 < 0)
ret = ret2;
ret2 = ext4_journal_stop(handle);
if (!ret)
ret = ret2;
return ret ? ret : copied;
}
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 nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride)
{
nsc_encode_argb_to_aycocg(context, bmpdata, rowstride);
if (context->ChromaSubsamplingLevel)
{
nsc_encode_subsampling(context);
}
}
CWE ID: CWE-787
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Chapters::Atom::ShallowCopy(Atom& rhs) const
{
rhs.m_string_uid = m_string_uid;
rhs.m_uid = m_uid;
rhs.m_start_timecode = m_start_timecode;
rhs.m_stop_timecode = m_stop_timecode;
rhs.m_displays = m_displays;
rhs.m_displays_size = m_displays_size;
rhs.m_displays_count = m_displays_count;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void FS_Rename( const char *from, const char *to ) {
char *from_ospath, *to_ospath;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
}
S_ClearSoundBuffer();
from_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, from );
to_ospath = FS_BuildOSPath( fs_homepath->string, fs_gamedir, to );
if ( fs_debug->integer ) {
Com_Printf( "FS_Rename: %s --> %s\n", from_ospath, to_ospath );
}
FS_CheckFilenameIsMutable( to_ospath, __func__ );
rename(from_ospath, to_ospath);
}
CWE ID: CWE-269
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: dtls1_hm_fragment_free(hm_fragment *frag)
{
if (frag->fragment) OPENSSL_free(frag->fragment);
if (frag->reassembly) OPENSSL_free(frag->reassembly);
OPENSSL_free(frag);
int curr_mtu;
unsigned int len, frag_off, mac_size, blocksize;
/* AHA! Figure out the MTU, and stick to the right size */
if (s->d1->mtu < dtls1_min_mtu() && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU))
{
s->d1->mtu =
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
/* I've seen the kernel return bogus numbers when it doesn't know
* (initial write), so just make sure we have a reasonable number */
if (s->d1->mtu < dtls1_min_mtu())
{
s->d1->mtu = 0;
s->d1->mtu = dtls1_guess_mtu(s->d1->mtu);
BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
s->d1->mtu, NULL);
}
}
#if 0
mtu = s->d1->mtu;
fprintf(stderr, "using MTU = %d\n", mtu);
mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s));
if ( curr_mtu > 0)
mtu = curr_mtu;
else if ( ( ret = BIO_flush(SSL_get_wbio(s))) <= 0)
return ret;
if ( BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu)
{
ret = BIO_flush(SSL_get_wbio(s));
if ( ret <= 0)
return ret;
mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
}
#endif
OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu()); /* should have something reasonable now */
if ( s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
OPENSSL_assert(s->init_num ==
(int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
if (s->write_hash)
mac_size = EVP_MD_CTX_size(s->write_hash);
else
mac_size = 0;
if (s->enc_write_ctx &&
(EVP_CIPHER_mode( s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
else
blocksize = 0;
frag_off = 0;
while( s->init_num)
{
curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
if ( curr_mtu <= DTLS1_HM_HEADER_LENGTH)
{
/* grr.. we could get an error if MTU picked was wrong */
ret = BIO_flush(SSL_get_wbio(s));
if ( ret <= 0)
return ret;
curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH -
mac_size - blocksize;
}
if ( s->init_num > curr_mtu)
len = curr_mtu;
else
len = s->init_num;
/* XDTLS: this function is too long. split out the CCS part */
if ( type == SSL3_RT_HANDSHAKE)
{
if ( s->init_off != 0)
{
OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
s->init_off -= DTLS1_HM_HEADER_LENGTH;
s->init_num += DTLS1_HM_HEADER_LENGTH;
if ( s->init_num > curr_mtu)
len = curr_mtu;
else
len = s->init_num;
}
dtls1_fix_message_header(s, frag_off,
len - DTLS1_HM_HEADER_LENGTH);
dtls1_write_message_header(s, (unsigned char *)&s->init_buf->data[s->init_off]);
OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
}
ret=dtls1_write_bytes(s,type,&s->init_buf->data[s->init_off],
len);
if (ret < 0)
{
/* might need to update MTU here, but we don't know
* which previous packet caused the failure -- so can't
* really retransmit anything. continue as if everything
* is fine and wait for an alert to handle the
* retransmit
*/
if ( BIO_ctrl(SSL_get_wbio(s),
BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0 )
s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
else
return(-1);
}
else
{
/* bad if this assert fails, only part of the handshake
* message got sent. but why would this happen? */
OPENSSL_assert(len == (unsigned int)ret);
if (type == SSL3_RT_HANDSHAKE && ! s->d1->retransmitting)
{
/* should not be done for 'Hello Request's, but in that case
* we'll ignore the result anyway */
unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];
const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
int xlen;
if (frag_off == 0 && s->version != DTLS1_BAD_VER)
{
/* reconstruct message header is if it
* is being sent in single fragment */
*p++ = msg_hdr->type;
l2n3(msg_hdr->msg_len,p);
s2n (msg_hdr->seq,p);
l2n3(0,p);
l2n3(msg_hdr->msg_len,p);
p -= DTLS1_HM_HEADER_LENGTH;
xlen = ret;
}
else
{
p += DTLS1_HM_HEADER_LENGTH;
xlen = ret - DTLS1_HM_HEADER_LENGTH;
}
ssl3_finish_mac(s, p, xlen);
}
if (ret == s->init_num)
{
if (s->msg_callback)
s->msg_callback(1, s->version, type, s->init_buf->data,
(size_t)(s->init_off + s->init_num), s,
s->msg_callback_arg);
s->init_off = 0; /* done writing this message */
s->init_num = 0;
return(1);
}
s->init_off+=ret;
s->init_num-=ret;
frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
}
}
return(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: static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, int idx) {
int i, j, sym, wordsize;
ut32 stype;
wordsize = MACH0_(get_bits)(bin) / 8;
if (idx < 0 || idx >= bin->nsymtab) {
return 0;
}
if ((bin->symtab[idx].n_desc & REFERENCE_TYPE) == REFERENCE_FLAG_UNDEFINED_LAZY) {
stype = S_LAZY_SYMBOL_POINTERS;
} else {
stype = S_NON_LAZY_SYMBOL_POINTERS;
}
reloc->offset = 0;
reloc->addr = 0;
reloc->addend = 0;
#define CASE(T) case (T / 8): reloc->type = R_BIN_RELOC_ ## T; break
switch (wordsize) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
default: return false;
}
#undef CASE
for (i = 0; i < bin->nsects; i++) {
if ((bin->sects[i].flags & SECTION_TYPE) == stype) {
for (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++)
if (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) {
sym = j;
break;
}
reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize;
reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize;
return true;
}
}
return false;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: GetCommonLinkProperties(struct upnphttp * h, const char * action, const char * ns)
{
/* WANAccessType : set depending on the hardware :
* DSL, POTS (plain old Telephone service), Cable, Ethernet */
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<NewWANAccessType>%s</NewWANAccessType>"
"<NewLayer1UpstreamMaxBitRate>%lu</NewLayer1UpstreamMaxBitRate>"
"<NewLayer1DownstreamMaxBitRate>%lu</NewLayer1DownstreamMaxBitRate>"
"<NewPhysicalLinkStatus>%s</NewPhysicalLinkStatus>"
"</u:%sResponse>";
char body[2048];
int bodylen;
struct ifdata data;
const char * status = "Up"; /* Up, Down (Required),
* Initializing, Unavailable (Optional) */
const char * wan_access_type = "Cable"; /* DSL, POTS, Cable, Ethernet */
char ext_ip_addr[INET_ADDRSTRLEN];
if((downstream_bitrate == 0) || (upstream_bitrate == 0))
{
if(getifstats(ext_if_name, &data) >= 0)
{
if(downstream_bitrate == 0) downstream_bitrate = data.baudrate;
if(upstream_bitrate == 0) upstream_bitrate = data.baudrate;
}
}
if(getifaddr(ext_if_name, ext_ip_addr, INET_ADDRSTRLEN, NULL, NULL) < 0) {
status = "Down";
}
bodylen = snprintf(body, sizeof(body), resp,
action, ns, /* was "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" */
wan_access_type,
upstream_bitrate, downstream_bitrate,
status, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void reset_pmcr(struct kvm_vcpu *vcpu, const struct sys_reg_desc *r)
{
u64 pmcr, val;
pmcr = read_sysreg(pmcr_el0);
/*
* Writable bits of PMCR_EL0 (ARMV8_PMU_PMCR_MASK) are reset to UNKNOWN
* except PMCR.E resetting to zero.
*/
val = ((pmcr & ~ARMV8_PMU_PMCR_MASK)
| (ARMV8_PMU_PMCR_MASK & 0xdecafbad)) & (~ARMV8_PMU_PMCR_E);
vcpu_sys_reg(vcpu, PMCR_EL0) = val;
}
CWE ID: CWE-617
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch(
const ScoredHistoryMatch& history_match,
int score) {
const history::URLRow& info = history_match.url_info;
AutocompleteMatch match(this, score, !!info.visit_count(),
history_match.url_matches.empty() ?
AutocompleteMatch::HISTORY_URL : AutocompleteMatch::HISTORY_TITLE);
match.destination_url = info.url();
DCHECK(match.destination_url.is_valid());
std::vector<size_t> offsets =
OffsetsFromTermMatches(history_match.url_matches);
const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP);
match.fill_into_edit =
AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
net::FormatUrlWithOffsets(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, &offsets));
history::TermMatches new_matches =
ReplaceOffsetsInTermMatches(history_match.url_matches, offsets);
match.contents = net::FormatUrl(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, NULL);
match.contents_class =
SpansFromTermMatch(new_matches, match.contents.length(), true);
if (!history_match.can_inline) {
match.inline_autocomplete_offset = string16::npos;
} else {
DCHECK(!new_matches.empty());
match.inline_autocomplete_offset = new_matches[0].offset +
new_matches[0].length;
if (match.inline_autocomplete_offset > match.fill_into_edit.length())
match.inline_autocomplete_offset = match.fill_into_edit.length();
}
match.description = info.title();
match.description_class = SpansFromTermMatch(
history_match.title_matches, match.description.length(), false);
return match;
}
CWE ID:
Target: 1
Example 2:
Code: static char *r_bin_wasm_type_entry_to_string (RBinWasmTypeEntry *ptr) {
if (!ptr || ptr->to_str) {
return NULL;
}
char *ret;
int p, i = 0, sz;
sz = (ptr->param_count + ptr->return_count) * 5 + 9;
if (!(ret = (char*) malloc (sz * sizeof(char)))) {
return NULL;
}
strcpy (ret + i, "(");
i++;
for (p = 0; p < ptr->param_count; p++ ) {
R_BIN_WASM_VALUETYPETOSTRING (ret+i, ptr->param_types[p], i); // i+=3
if (p < ptr->param_count - 1) {
strcpy (ret+i, ", ");
i += 2;
}
}
strcpy (ret + i, ") -> (");
i += 6;
if (ptr->return_count == 1) {
R_BIN_WASM_VALUETYPETOSTRING (ret + i, ptr->return_type, i);
}
strcpy (ret + i, ")");
return ret;
}
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 RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
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 char *__filterQuotedShell(const char *arg) {
r_return_val_if_fail (arg, NULL);
char *a = malloc (strlen (arg) + 1);
if (!a) {
return NULL;
}
char *b = a;
while (*arg) {
switch (*arg) {
case ' ':
case '=':
case '\r':
case '\n':
break;
default:
*b++ = *arg;
break;
}
arg++;
}
*b = 0;
return a;
}
CWE ID: CWE-78
Target: 1
Example 2:
Code: Document* Document::ParentDocument() const {
if (!frame_)
return nullptr;
Frame* parent = frame_->Tree().Parent();
if (!parent || !parent->IsLocalFrame())
return nullptr;
return ToLocalFrame(parent)->GetDocument();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
if( profile == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
*flags = 0;
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
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: v8::Handle<v8::Value> V8DirectoryEntry::getDirectoryCallback(const v8::Arguments& args)
{
INC_STATS("DOM.DirectoryEntry.getDirectory");
DirectoryEntry* imp = V8DirectoryEntry::toNative(args.Holder());
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<WithUndefinedOrNullCheck>, path, args[0]);
if (args.Length() <= 1) {
imp->getDirectory(path);
return v8::Handle<v8::Value>();
}
RefPtr<WebKitFlags> flags;
if (!isUndefinedOrNull(args[1]) && args[1]->IsObject()) {
EXCEPTION_BLOCK(v8::Handle<v8::Object>, object, v8::Handle<v8::Object>::Cast(args[1]));
flags = WebKitFlags::create();
v8::Local<v8::Value> v8Create = object->Get(v8::String::New("create"));
if (!v8Create.IsEmpty() && !isUndefinedOrNull(v8Create)) {
EXCEPTION_BLOCK(bool, isCreate, v8Create->BooleanValue());
flags->setCreate(isCreate);
}
v8::Local<v8::Value> v8Exclusive = object->Get(v8::String::New("exclusive"));
if (!v8Exclusive.IsEmpty() && !isUndefinedOrNull(v8Exclusive)) {
EXCEPTION_BLOCK(bool, isExclusive, v8Exclusive->BooleanValue());
flags->setExclusive(isExclusive);
}
}
RefPtr<EntryCallback> successCallback;
if (args.Length() > 2 && !args[2]->IsNull() && !args[2]->IsUndefined()) {
if (!args[2]->IsObject())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
successCallback = V8EntryCallback::create(args[2], getScriptExecutionContext());
}
RefPtr<ErrorCallback> errorCallback;
if (args.Length() > 3 && !args[3]->IsNull() && !args[3]->IsUndefined()) {
if (!args[3]->IsObject())
return throwError(TYPE_MISMATCH_ERR, args.GetIsolate());
errorCallback = V8ErrorCallback::create(args[3], getScriptExecutionContext());
}
imp->getDirectory(path, flags, successCallback, errorCallback);
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: static void GIFAnimEncode(gdIOCtxPtr fp, int IWidth, int IHeight, int LeftOfs, int TopOfs, int GInterlace, int Transparent, int Delay, int Disposal, int BitsPerPixel, int *Red, int *Green, int *Blue, gdImagePtr im)
{
int B;
int ColorMapSize;
int InitCodeSize;
int i;
GifCtx ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.Interlace = GInterlace;
ctx.in_count = 1;
ColorMapSize = 1 << BitsPerPixel;
if(LeftOfs < 0) {
LeftOfs = 0;
}
if(TopOfs < 0) {
TopOfs = 0;
}
if(Delay < 0) {
Delay = 100;
}
if(Disposal < 0) {
Disposal = 1;
}
ctx.Width = IWidth;
ctx.Height = IHeight;
/* Calculate number of bits we are expecting */
ctx.CountDown = (long)ctx.Width * (long)ctx.Height;
/* Indicate which pass we are on (if interlace) */
ctx.Pass = 0;
/* The initial code size */
if(BitsPerPixel <= 1) {
InitCodeSize = 2;
} else {
InitCodeSize = BitsPerPixel;
}
/* Set up the current x and y position */
ctx.curx = ctx.cury = 0;
/* Write out extension for image animation and looping */
gdPutC('!', fp);
gdPutC(0xf9, fp);
gdPutC(4, fp);
gdPutC((Transparent >= 0 ? 1 : 0) | (Disposal << 2), fp);
gdPutC((unsigned char)(Delay & 255), fp);
gdPutC((unsigned char)((Delay >> 8) & 255), fp);
gdPutC((unsigned char) Transparent, fp);
gdPutC(0, fp);
/* Write an Image separator */
gdPutC(',', fp);
/* Write out the Image header */
gifPutWord(LeftOfs, fp);
gifPutWord(TopOfs, fp);
gifPutWord(ctx.Width, fp);
gifPutWord(ctx.Height, fp);
/* Indicate that there is a local colour map */
B = (Red && Green && Blue) ? 0x80 : 0;
/* OR in the interlacing */
B |= ctx.Interlace ? 0x40 : 0;
/* OR in the Bits per Pixel */
B |= (Red && Green && Blue) ? (BitsPerPixel - 1) : 0;
/* Write it out */
gdPutC(B, fp);
/* Write out the Local Colour Map */
if(Red && Green && Blue) {
for(i = 0; i < ColorMapSize; ++i) {
gdPutC(Red[i], fp);
gdPutC(Green[i], fp);
gdPutC(Blue[i], fp);
}
}
/* Write out the initial code size */
gdPutC(InitCodeSize, fp);
/* Go and actually compress the data */
compress(InitCodeSize + 1, fp, im, &ctx);
/* Write out a Zero-length packet (to end the series) */
gdPutC(0, fp);
}
CWE ID: CWE-415
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */
{
struct _store_object *obj;
int failure = 0;
if (!EG(objects_store).object_buckets) {
return;
}
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
/* Make sure we hold a reference count during the destructor call
otherwise, when the destructor ends the storage might be freed
when the refcount reaches 0 a second time
*/
if (EG(objects_store).object_buckets[handle].valid) {
if (obj->refcount == 1) {
if (!EG(objects_store).object_buckets[handle].destructor_called) {
EG(objects_store).object_buckets[handle].destructor_called = 1;
if (obj->dtor) {
if (handlers && !obj->handlers) {
obj->handlers = handlers;
}
zend_try {
obj->dtor(obj->object, handle TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
}
/* re-read the object from the object store as the store might have been reallocated in the dtor */
obj = &EG(objects_store).object_buckets[handle].bucket.obj;
if (obj->refcount == 1) {
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
if (obj->free_storage) {
zend_try {
obj->free_storage(obj->object TSRMLS_CC);
} zend_catch {
failure = 1;
} zend_end_try();
}
ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();
}
}
}
obj->refcount--;
#if ZEND_DEBUG_OBJECTS
if (obj->refcount == 0) {
fprintf(stderr, "Deallocated object id #%d\n", handle);
} else {
fprintf(stderr, "Decreased refcount of object id #%d\n", handle);
}
#endif
if (failure) {
zend_bailout();
}
}
/* }}} */
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: NavigateToAboutBlank() {
GURL about_blank(url::kAboutBlankURL);
content::NavigationController::LoadURLParams params(about_blank);
params.frame_tree_node_id = frame_tree_node_id_;
params.source_site_instance = parent_site_instance_;
params.is_renderer_initiated = true;
web_contents()->GetController().LoadURLWithParams(params);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int decode_attr_bitmap(struct xdr_stream *xdr, uint32_t *bitmap)
{
uint32_t bmlen;
__be32 *p;
READ_BUF(4);
READ32(bmlen);
bitmap[0] = bitmap[1] = 0;
READ_BUF((bmlen << 2));
if (bmlen > 0) {
READ32(bitmap[0]);
if (bmlen > 1)
READ32(bitmap[1]);
}
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: HandleFlushNeighborsMessage(flush_neighbors_message_t *msg)
{
if (msg->family == AF_INET)
{
return FlushIpNetTable(msg->iface.index);
}
return FlushIpNetTable2(msg->family, msg->iface.index);
}
CWE ID: CWE-415
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xsltFreeTemplateHashes(xsltStylesheetPtr style) {
if (style->templatesHash != NULL)
xmlHashFree((xmlHashTablePtr) style->templatesHash,
(xmlHashDeallocator) xsltFreeCompMatchList);
if (style->rootMatch != NULL)
xsltFreeCompMatchList(style->rootMatch);
if (style->keyMatch != NULL)
xsltFreeCompMatchList(style->keyMatch);
if (style->elemMatch != NULL)
xsltFreeCompMatchList(style->elemMatch);
if (style->attrMatch != NULL)
xsltFreeCompMatchList(style->attrMatch);
if (style->parentMatch != NULL)
xsltFreeCompMatchList(style->parentMatch);
if (style->textMatch != NULL)
xsltFreeCompMatchList(style->textMatch);
if (style->piMatch != NULL)
xsltFreeCompMatchList(style->piMatch);
if (style->commentMatch != NULL)
xsltFreeCompMatchList(style->commentMatch);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: struct tty_struct *tty_init_dev(struct tty_driver *driver, int idx,
int first_ok)
{
struct tty_struct *tty;
int retval;
/* Check if pty master is being opened multiple times */
if (driver->subtype == PTY_TYPE_MASTER &&
(driver->flags & TTY_DRIVER_DEVPTS_MEM) && !first_ok) {
return ERR_PTR(-EIO);
}
/*
* First time open is complex, especially for PTY devices.
* This code guarantees that either everything succeeds and the
* TTY is ready for operation, or else the table slots are vacated
* and the allocated memory released. (Except that the termios
* and locked termios may be retained.)
*/
if (!try_module_get(driver->owner))
return ERR_PTR(-ENODEV);
tty = alloc_tty_struct();
if (!tty) {
retval = -ENOMEM;
goto err_module_put;
}
initialize_tty_struct(tty, driver, idx);
retval = tty_driver_install_tty(driver, tty);
if (retval < 0)
goto err_deinit_tty;
/*
* Structures all installed ... call the ldisc open routines.
* If we fail here just call release_tty to clean up. No need
* to decrement the use counts, as release_tty doesn't care.
*/
retval = tty_ldisc_setup(tty, tty->link);
if (retval)
goto err_release_tty;
return tty;
err_deinit_tty:
deinitialize_tty_struct(tty);
free_tty_struct(tty);
err_module_put:
module_put(driver->owner);
return ERR_PTR(retval);
/* call the tty release_tty routine to clean out this slot */
err_release_tty:
printk_ratelimited(KERN_INFO "tty_init_dev: ldisc open failed, "
"clearing slot %d\n", idx);
release_tty(tty, idx);
return ERR_PTR(retval);
}
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: juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
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: AppCacheDispatcherHost::AppCacheDispatcherHost(
ChromeAppCacheService* appcache_service,
int process_id)
: BrowserMessageFilter(AppCacheMsgStart),
appcache_service_(appcache_service),
frontend_proxy_(this),
process_id_(process_id) {
}
CWE ID:
Target: 1
Example 2:
Code: PersistentSparseHistogramDataManager::UseSampleMapRecords(uint64_t id,
const void* user) {
base::AutoLock auto_lock(lock_);
return GetSampleMapRecordsWhileLocked(id)->Acquire(user);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void opl3_setup_voice(int dev, int voice, int chn)
{
struct channel_info *info =
&synth_devs[dev]->chn_info[chn];
opl3_set_instr(dev, voice, info->pgm_num);
devc->voc[voice].bender = 0;
devc->voc[voice].bender_range = info->bender_range;
devc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME];
devc->voc[voice].panning = (info->controllers[CTL_PAN] * 2) - 128;
}
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: v8::Handle<v8::Value> V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebGLRenderingContext.getFramebufferAttachmentParameter()");
if (args.Length() != 3)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
unsigned target = toInt32(args[0]);
unsigned attachment = toInt32(args[1]);
unsigned pname = toInt32(args[2]);
WebGLGetInfo info = context->getFramebufferAttachmentParameter(target, attachment, pname, ec);
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
return toV8Object(info, args.GetIsolate());
}
CWE ID:
Target: 1
Example 2:
Code: void CloseSession() {
if (opened_device_label_.empty())
return;
media_stream_manager_->CancelRequest(opened_device_label_);
opened_device_label_.clear();
opened_session_id_ = kInvalidMediaCaptureSessionId;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int handle_vcpu_debug(struct kvm_vcpu *vcpu,
struct kvm_run *kvm_run)
{
printk("VMM: %s", vcpu->arch.log_buf);
return 1;
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void print_value(int output, int num, const char *devname,
const char *value, const char *name, size_t valsz)
{
if (output & OUTPUT_VALUE_ONLY) {
fputs(value, stdout);
fputc('\n', stdout);
} else if (output & OUTPUT_UDEV_LIST) {
print_udev_format(name, value);
} else if (output & OUTPUT_EXPORT_LIST) {
if (num == 1 && devname)
printf("DEVNAME=%s\n", devname);
fputs(name, stdout);
fputs("=", stdout);
safe_print(value, valsz, NULL);
fputs("\n", stdout);
} else {
if (num == 1 && devname)
printf("%s:", devname);
fputs(" ", stdout);
fputs(name, stdout);
fputs("=\"", stdout);
safe_print(value, valsz, "\"");
fputs("\"", stdout);
}
}
CWE ID: CWE-77
Target: 1
Example 2:
Code: static void airo_set_promisc(struct airo_info *ai) {
Cmd cmd;
Resp rsp;
memset(&cmd, 0, sizeof(cmd));
cmd.cmd=CMD_SETMODE;
clear_bit(JOB_PROMISC, &ai->jobs);
cmd.parm0=(ai->flags&IFF_PROMISC) ? PROMISC : NOPROMISC;
issuecommand(ai, &cmd, &rsp);
up(&ai->sem);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
assert(pCluster);
assert(pCluster->m_index < 0);
assert(idx >= m_clusterCount);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new Cluster* [n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AXNodeObject::isMultiSelectable() const {
const AtomicString& ariaMultiSelectable =
getAttribute(aria_multiselectableAttr);
if (equalIgnoringCase(ariaMultiSelectable, "true"))
return true;
if (equalIgnoringCase(ariaMultiSelectable, "false"))
return false;
return isHTMLSelectElement(getNode()) &&
toHTMLSelectElement(*getNode()).isMultiple();
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: ui::MenuSourceType context_menu_source_type() const {
return context_menu_params_.source_type;
}
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 common_timer_get(struct k_itimer *timr, struct itimerspec64 *cur_setting)
{
const struct k_clock *kc = timr->kclock;
ktime_t now, remaining, iv;
struct timespec64 ts64;
bool sig_none;
sig_none = (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE;
iv = timr->it_interval;
/* interval timer ? */
if (iv) {
cur_setting->it_interval = ktime_to_timespec64(iv);
} else if (!timr->it_active) {
/*
* SIGEV_NONE oneshot timers are never queued. Check them
* below.
*/
if (!sig_none)
return;
}
/*
* The timespec64 based conversion is suboptimal, but it's not
* worth to implement yet another callback.
*/
kc->clock_get(timr->it_clock, &ts64);
now = timespec64_to_ktime(ts64);
/*
* When a requeue is pending or this is a SIGEV_NONE timer move the
* expiry time forward by intervals, so expiry is > now.
*/
if (iv && (timr->it_requeue_pending & REQUEUE_PENDING || sig_none))
timr->it_overrun += kc->timer_forward(timr, now);
remaining = kc->timer_remaining(timr, now);
/* Return 0 only, when the timer is expired and not pending */
if (remaining <= 0) {
/*
* A single shot SIGEV_NONE timer must return 0, when
* it is expired !
*/
if (!sig_none)
cur_setting->it_value.tv_nsec = 1;
} else {
cur_setting->it_value = ktime_to_timespec64(remaining);
}
}
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: long ContentEncoding::ParseContentEncAESSettingsEntry(
long long start,
long long size,
IMkvReader* pReader,
ContentEncAESSettings* aes) {
assert(pReader);
assert(aes);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x7E8) {
aes->cipher_mode = UnserializeUInt(pReader, pos, size);
if (aes->cipher_mode != 1)
return E_FILE_FORMAT_INVALID;
}
pos += size; //consume payload
assert(pos <= stop);
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void MetricsLog::RecordCurrentSessionData(
DelegatingProvider* delegating_provider,
base::TimeDelta incremental_uptime,
base::TimeDelta uptime) {
DCHECK(!closed_);
DCHECK(has_environment_);
WriteRealtimeStabilityAttributes(incremental_uptime, uptime);
delegating_provider->ProvideCurrentSessionData(uma_proto());
}
CWE ID: CWE-79
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IndexedDBTransaction::TaskQueue::TaskQueue() {}
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 ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
ssize_t size, void *private)
{
ext4_io_end_t *io_end = iocb->private;
struct workqueue_struct *wq;
/* if not async direct IO or dio with 0 bytes write, just return */
if (!io_end || !size)
return;
ext_debug("ext4_end_io_dio(): io_end 0x%p"
"for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
iocb->private, io_end->inode->i_ino, iocb, offset,
size);
/* if not aio dio with unwritten extents, just free io and return */
if (io_end->flag != EXT4_IO_UNWRITTEN){
ext4_free_io_end(io_end);
iocb->private = NULL;
return;
}
io_end->offset = offset;
io_end->size = size;
wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
/* queue the work to convert unwritten extents to written */
queue_work(wq, &io_end->work);
/* Add the io_end to per-inode completed aio dio list*/
list_add_tail(&io_end->list,
&EXT4_I(io_end->inode)->i_completed_io_list);
iocb->private = NULL;
}
CWE ID:
Target: 1
Example 2:
Code: void AutocompleteInput::UpdateText(const string16& text,
const url_parse::Parsed& parts) {
text_ = text;
parts_ = parts;
}
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 add_chan(struct pppox_sock *sock)
{
static int call_id;
spin_lock(&chan_lock);
if (!sock->proto.pptp.src_addr.call_id) {
call_id = find_next_zero_bit(callid_bitmap, MAX_CALLID, call_id + 1);
if (call_id == MAX_CALLID) {
call_id = find_next_zero_bit(callid_bitmap, MAX_CALLID, 1);
if (call_id == MAX_CALLID)
goto out_err;
}
sock->proto.pptp.src_addr.call_id = call_id;
} else if (test_bit(sock->proto.pptp.src_addr.call_id, callid_bitmap))
goto out_err;
set_bit(sock->proto.pptp.src_addr.call_id, callid_bitmap);
rcu_assign_pointer(callid_sock[sock->proto.pptp.src_addr.call_id], sock);
spin_unlock(&chan_lock);
return 0;
out_err:
spin_unlock(&chan_lock);
return -1;
}
CWE ID: CWE-200
Output:
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.