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: long Segment::ParseCues(
long long off,
long long& pos,
long& len)
{
if (m_pCues)
return 0; //success
if (off < 0)
return -1;
long long total, avail;
const int status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
pos = m_start + off;
if ((total < 0) || (pos >= total))
return 1; //don't bother parsing cues
const long long element_start = pos;
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id != 0x0C53BB6B) //Cues ID
return E_FILE_FORMAT_INVALID;
pos += len; //consume ID
assert((segment_stop < 0) || (pos <= segment_stop));
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
if (size == 0) //weird, although technically not illegal
return 1; //done
pos += len; //consume length of size of element
assert((segment_stop < 0) || (pos <= segment_stop));
const long long element_stop = pos + size;
if ((segment_stop >= 0) && (element_stop > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && (element_stop > total))
return 1; //don't bother parsing anymore
len = static_cast<long>(size);
if (element_stop > avail)
return E_BUFFER_NOT_FULL;
const long long element_size = element_stop - element_start;
m_pCues = new (std::nothrow) Cues(
this,
pos,
size,
element_start,
element_size);
assert(m_pCues); //TODO
return 0; //success
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool CustomButton::OnMousePressed(const ui::MouseEvent& event) {
if (state_ != STATE_DISABLED) {
if (ShouldEnterPushedState(event) && HitTestPoint(event.location()))
SetState(STATE_PRESSED);
if (request_focus_on_press_)
RequestFocus();
if (IsTriggerableEvent(event) && notify_action_ == NOTIFY_ON_PRESS) {
NotifyClick(event);
}
}
return true;
}
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 MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void coroutine_fn v9fs_xattrcreate(void *opaque)
{
int flags;
int32_t fid;
int64_t size;
ssize_t err = 0;
V9fsString name;
size_t offset = 7;
V9fsFidState *file_fidp;
V9fsFidState *xattr_fidp;
V9fsPDU *pdu = opaque;
v9fs_string_init(&name);
err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags);
if (err < 0) {
goto out_nofid;
}
trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);
file_fidp = get_fid(pdu, fid);
if (file_fidp == NULL) {
err = -EINVAL;
goto out_nofid;
}
/* Make the file fid point to xattr */
xattr_fidp = file_fidp;
xattr_fidp->fid_type = P9_FID_XATTR;
xattr_fidp->fs.xattr.copied_len = 0;
xattr_fidp->fs.xattr.len = size;
xattr_fidp->fs.xattr.flags = flags;
v9fs_string_init(&xattr_fidp->fs.xattr.name);
v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);
xattr_fidp->fs.xattr.value = g_malloc(size);
err = offset;
put_fid(pdu, file_fidp);
out_nofid:
pdu_complete(pdu, err);
v9fs_string_free(&name);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct bmc_device *ipmi_find_bmc_guid(struct device_driver *drv,
guid_t *guid)
{
struct device *dev;
struct bmc_device *bmc = NULL;
dev = driver_find_device(drv, NULL, guid, __find_bmc_guid);
if (dev) {
bmc = to_bmc_device(dev);
put_device(dev);
}
return bmc;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int v9fs_xattr_set_acl(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *name, const void *value,
size_t size, int flags)
{
int retval;
struct posix_acl *acl;
struct v9fs_session_info *v9ses;
v9ses = v9fs_dentry2v9ses(dentry);
/*
* set the attribute on the remote. Without even looking at the
* xattr value. We leave it to the server to validate
*/
if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT)
return v9fs_xattr_set(dentry, handler->name, value, size,
flags);
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (value) {
/* update the cached acl value */
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
return PTR_ERR(acl);
else if (acl) {
retval = posix_acl_valid(inode->i_sb->s_user_ns, acl);
if (retval)
goto err_out;
}
} else
acl = NULL;
switch (handler->flags) {
case ACL_TYPE_ACCESS:
if (acl) {
umode_t mode = inode->i_mode;
retval = posix_acl_equiv_mode(acl, &mode);
if (retval < 0)
goto err_out;
else {
struct iattr iattr;
if (retval == 0) {
/*
* ACL can be represented
* by the mode bits. So don't
* update ACL.
*/
acl = NULL;
value = NULL;
size = 0;
}
/* Updte the mode bits */
iattr.ia_mode = ((mode & S_IALLUGO) |
(inode->i_mode & ~S_IALLUGO));
iattr.ia_valid = ATTR_MODE;
/* FIXME should we update ctime ?
* What is the following setxattr update the
* mode ?
*/
v9fs_vfs_setattr_dotl(dentry, &iattr);
}
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
retval = acl ? -EINVAL : 0;
goto err_out;
}
break;
default:
BUG();
}
retval = v9fs_xattr_set(dentry, handler->name, value, size, flags);
if (!retval)
set_cached_acl(inode, handler->flags, acl);
err_out:
posix_acl_release(acl);
return retval;
}
CWE ID: CWE-285
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DoTest(ExternalProtocolHandler::BlockState block_state,
shell_integration::DefaultWebClientState os_state,
Action expected_action) {
GURL url("mailto:[email protected]");
EXPECT_FALSE(delegate_.has_prompted());
EXPECT_FALSE(delegate_.has_launched());
EXPECT_FALSE(delegate_.has_blocked());
delegate_.set_block_state(block_state);
delegate_.set_os_state(os_state);
ExternalProtocolHandler::LaunchUrlWithDelegate(
url, 0, 0, ui::PAGE_TRANSITION_LINK, true, &delegate_);
content::RunAllTasksUntilIdle();
EXPECT_EQ(expected_action == Action::PROMPT, delegate_.has_prompted());
EXPECT_EQ(expected_action == Action::LAUNCH, delegate_.has_launched());
EXPECT_EQ(expected_action == Action::BLOCK, delegate_.has_blocked());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static const char *special_mapping_name(struct vm_area_struct *vma)
{
return ((struct vm_special_mapping *)vma->vm_private_data)->name;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void get_global(u_int cmd, struct au1200_lcd_global_regs_t *pdata)
{
unsigned int hi1, divider;
pdata->xsize = ((lcd->screen & LCD_SCREEN_SX) >> 19) + 1;
pdata->ysize = ((lcd->screen & LCD_SCREEN_SY) >> 8) + 1;
pdata->backcolor = lcd->backcolor;
pdata->colorkey = lcd->colorkey;
pdata->mask = lcd->colorkeymsk;
hi1 = (lcd->pwmhi >> 16) + 1;
divider = (lcd->pwmdiv & 0x3FFFF) + 1;
pdata->brightness = ((hi1 << 8) / divider) - 1;
au_sync();
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int perf_event_task_disable(void)
{
struct perf_event *event;
mutex_lock(¤t->perf_event_mutex);
list_for_each_entry(event, ¤t->perf_event_list, owner_entry)
perf_event_for_each_child(event, perf_event_disable);
mutex_unlock(¤t->perf_event_mutex);
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static inline int pageblock_free(struct page *page)
{
return PageBuddy(page) && page_order(page) >= pageblock_order;
}
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 UINT drdynvc_order_recv(drdynvcPlugin* drdynvc, wStream* s)
{
int value;
int Cmd;
int Sp;
int cbChId;
Stream_Read_UINT8(s, value);
Cmd = (value & 0xf0) >> 4;
Sp = (value & 0x0c) >> 2;
cbChId = (value & 0x03) >> 0;
WLog_Print(drdynvc->log, WLOG_DEBUG, "order_recv: Cmd=0x%x, Sp=%d cbChId=%d", Cmd, Sp, cbChId);
switch (Cmd)
{
case CAPABILITY_REQUEST_PDU:
return drdynvc_process_capability_request(drdynvc, Sp, cbChId, s);
case CREATE_REQUEST_PDU:
return drdynvc_process_create_request(drdynvc, Sp, cbChId, s);
case DATA_FIRST_PDU:
return drdynvc_process_data_first(drdynvc, Sp, cbChId, s);
case DATA_PDU:
return drdynvc_process_data(drdynvc, Sp, cbChId, s);
case CLOSE_REQUEST_PDU:
return drdynvc_process_close_request(drdynvc, Sp, cbChId, s);
default:
WLog_Print(drdynvc->log, WLOG_ERROR, "unknown drdynvc cmd 0x%x", Cmd);
return ERROR_INTERNAL_ERROR;
}
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int http_buf_read(URLContext *h, uint8_t *buf, int size)
{
HTTPContext *s = h->priv_data;
int len;
/* read bytes from input buffer first */
len = s->buf_end - s->buf_ptr;
if (len > 0) {
if (len > size)
len = size;
memcpy(buf, s->buf_ptr, len);
s->buf_ptr += len;
} else {
int64_t target_end = s->end_off ? s->end_off : s->filesize;
if ((!s->willclose || s->chunksize < 0) &&
target_end >= 0 && s->off >= target_end)
return AVERROR_EOF;
len = ffurl_read(s->hd, buf, size);
if (!len && (!s->willclose || s->chunksize < 0) &&
target_end >= 0 && s->off < target_end) {
av_log(h, AV_LOG_ERROR,
"Stream ends prematurely at %"PRId64", should be %"PRId64"\n",
s->off, target_end
);
return AVERROR(EIO);
}
}
if (len > 0) {
s->off += len;
if (s->chunksize > 0)
s->chunksize -= len;
}
return len;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: const AtomicString& TextTrack::HiddenKeyword() {
DEFINE_STATIC_LOCAL(const AtomicString, hidden, ("hidden"));
return hidden;
}
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: GC_INNER void * GC_generic_malloc_ignore_off_page(size_t lb, int k)
{
void *result;
size_t lg;
size_t lb_rounded;
word n_blocks;
GC_bool init;
DCL_LOCK_STATE;
if (SMALL_OBJ(lb))
return(GC_generic_malloc((word)lb, k));
lg = ROUNDED_UP_GRANULES(lb);
lb_rounded = GRANULES_TO_BYTES(lg);
n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded);
init = GC_obj_kinds[k].ok_init;
if (EXPECT(GC_have_errors, FALSE))
GC_print_all_errors();
GC_INVOKE_FINALIZERS();
LOCK();
result = (ptr_t)GC_alloc_large(ADD_SLOP(lb), k, IGNORE_OFF_PAGE);
if (0 != result) {
if (GC_debugging_started) {
BZERO(result, n_blocks * HBLKSIZE);
} else {
# ifdef THREADS
/* Clear any memory that might be used for GC descriptors */
/* before we release the lock. */
((word *)result)[0] = 0;
((word *)result)[1] = 0;
((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0;
((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0;
# endif
}
}
GC_bytes_allocd += lb_rounded;
if (0 == result) {
GC_oom_func oom_fn = GC_oom_fn;
UNLOCK();
return((*oom_fn)(lb));
} else {
UNLOCK();
if (init && !GC_debugging_started) {
BZERO(result, n_blocks * HBLKSIZE);
}
return(result);
}
}
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: int sas_discover_end_dev(struct domain_device *dev)
{
int res;
res = sas_notify_lldd_dev_found(dev);
if (res)
return res;
sas_discover_event(dev->port, DISCE_PROBE);
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: explicit VaapiVP9Picture(
scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> surface)
: dec_surface_(surface) {}
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: EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionAddEventListener(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestEventTarget::s_info))
return throwVMTypeError(exec);
JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info);
TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl());
if (exec->argumentCount() < 2)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
JSValue listener = exec->argument(1);
if (!listener.isObject())
return JSValue::encode(jsUndefined());
impl->addEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)), exec->argument(2).toBoolean(exec));
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) {
ipfix_template_record_t *ipfix_template_record;
while ( size_left ) {
uint32_t id;
ipfix_template_record = (ipfix_template_record_t *)DataPtr;
size_left -= 4;
id = ntohs(ipfix_template_record->TemplateID);
if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) {
remove_all_translation_tables(exporter);
ReInitExtensionMapList(fs);
} else {
remove_translation_table(fs, exporter, id);
}
DataPtr = DataPtr + 4;
if ( size_left < 4 ) {
dbg_printf("Skip %u bytes padding\n", size_left);
size_left = 0;
}
}
} // End of Process_ipfix_template_withdraw
CWE ID: CWE-190
Target: 1
Example 2:
Code: test_bson_visit_unsupported_type_bad_key (void)
{
/* key is invalid utf-8 char, '\x80' */
const char data[] = "\x0c\x00\x00\x00\x33\x80\x00\x01\x00\x00\x00\x00";
bson_t b;
bson_iter_t iter;
unsupported_type_test_data_t context = {0};
bson_visitor_t visitor = {0};
visitor.visit_unsupported_type = visit_unsupported_type;
BSON_ASSERT (bson_init_static (&b, (const uint8_t *) data, sizeof data - 1));
BSON_ASSERT (bson_iter_init (&iter, &b));
BSON_ASSERT (!bson_iter_visit_all (&iter, &visitor, (void *) &context));
BSON_ASSERT (!bson_iter_next (&iter));
/* unsupported type error wasn't reported, because the bson is corrupt */
BSON_ASSERT (!context.visited);
}
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: InputBuffer(uint32_t id,
std::unique_ptr<SharedMemoryRegion> shm,
base::OnceCallback<void(int32_t id)> release_cb)
: id_(id), shm_(std::move(shm)), release_cb_(std::move(release_cb)) {}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void add_probe(const char *name)
{
struct module_entry *m;
m = get_or_add_modentry(name);
if (!(option_mask32 & (OPT_REMOVE | OPT_SHOW_DEPS))
&& (m->flags & MODULE_FLAG_LOADED)
&& strncmp(m->modname, "symbol:", 7) == 0
) {
G.need_symbols = 1;
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void auth_exit_ev(const void *event_data, void *user_data) {
pr_auth_cache_clear();
/* Close the scoreboard descriptor that we opened. */
(void) pr_close_scoreboard(FALSE);
}
CWE ID: CWE-59
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static v8::Handle<v8::Value> idbKeyCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.idbKey");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(RefPtr<IDBKey>, key, createIDBKeyFromValue(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
imp->idbKey(key.get());
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: gss_unwrap_iov (minor_status,
context_handle,
conf_state,
qop_state,
iov,
iov_count)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
int * conf_state;
gss_qop_t *qop_state;
gss_iov_buffer_desc * iov;
int iov_count;
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
status = val_unwrap_iov_args(minor_status, context_handle,
conf_state, qop_state, iov, iov_count);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_unwrap_iov) {
status = mech->gss_unwrap_iov(
minor_status,
ctx->internal_ctx_id,
conf_state,
qop_state,
iov,
iov_count);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: static void voidMethodUnsignedShortArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "voidMethodUnsignedShortArg", "TestObjectPython", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(1, info.Length()));
exceptionState.throwIfNeeded();
return;
}
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
V8TRYCATCH_EXCEPTION_VOID(unsigned, unsignedShortArg, toUInt16(info[0], exceptionState), exceptionState);
imp->voidMethodUnsignedShortArg(unsignedShortArg);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int php_stream_temp_close(php_stream *stream, int close_handle TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
int ret;
assert(ts != NULL);
if (ts->innerstream) {
ret = php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE | (close_handle ? 0 : PHP_STREAM_FREE_PRESERVE_HANDLE));
} else {
ret = 0;
}
if (ts->meta) {
zval_ptr_dtor(&ts->meta);
}
efree(ts);
return ret;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool TaskService::UnbindInstance() {
{
base::AutoLock lock(lock_);
if (bound_instance_id_ == kInvalidInstanceId)
return false;
bound_instance_id_ = kInvalidInstanceId;
DCHECK(default_task_runner_);
default_task_runner_ = nullptr;
}
base::subtle::AutoWriteLock task_lock(task_lock_);
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int imap_create_mailbox(struct ImapData *idata, char *mailbox)
{
char buf[LONG_STRING], mbox[LONG_STRING];
imap_munge_mbox_name(idata, mbox, sizeof(mbox), mailbox);
snprintf(buf, sizeof(buf), "CREATE %s", mbox);
if (imap_exec(idata, buf, 0) != 0)
{
mutt_error(_("CREATE failed: %s"), imap_cmd_trailer(idata));
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: int SeekHead::GetCount() const
{
return m_entry_count;
}
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 vlan_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags |= IFF_802_1Q_VLAN;
dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
dev->tx_queue_len = 0;
dev->netdev_ops = &vlan_netdev_ops;
dev->destructor = free_netdev;
dev->ethtool_ops = &vlan_ethtool_ops;
memset(dev->broadcast, 0, ETH_ALEN);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void FileStream::reset() {
#if HAVE_FSEEKO
savePos = (Guint)ftello(f);
fseeko(f, start, SEEK_SET);
#elif HAVE_FSEEK64
savePos = (Guint)ftell64(f);
fseek64(f, start, SEEK_SET);
#else
savePos = (Guint)ftell(f);
fseek(f, start, SEEK_SET);
#endif
saved = gTrue;
bufPtr = bufEnd = buf;
bufPos = start;
}
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: LoadWatcher(ScriptContext* context,
content::RenderFrame* frame,
v8::Local<v8::Function> cb)
: content::RenderFrameObserver(frame),
context_(context),
callback_(context->isolate(), cb) {
if (ExtensionFrameHelper::Get(frame)->
did_create_current_document_element()) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&LoadWatcher::CallbackAndDie, base::Unretained(this),
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: bool ChromeRenderProcessObserver::OnControlMessageReceived(
const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeRenderProcessObserver, message)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetIsIncognitoProcess,
OnSetIsIncognitoProcess)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetCacheCapacities, OnSetCacheCapacities)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ClearCache, OnClearCache)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetFieldTrialGroup, OnSetFieldTrialGroup)
#if defined(USE_TCMALLOC)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetTcmallocHeapProfiling,
OnSetTcmallocHeapProfiling)
IPC_MESSAGE_HANDLER(ChromeViewMsg_WriteTcmallocHeapProfile,
OnWriteTcmallocHeapProfile)
#endif
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetV8HeapStats, OnGetV8HeapStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_GetCacheResourceStats,
OnGetCacheResourceStats)
IPC_MESSAGE_HANDLER(ChromeViewMsg_PurgeMemory, OnPurgeMemory)
IPC_MESSAGE_HANDLER(ChromeViewMsg_SetContentSettingRules,
OnSetContentSettingRules)
IPC_MESSAGE_HANDLER(ChromeViewMsg_ToggleWebKitSharedTimer,
OnToggleWebKitSharedTimer)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: virtual status_t allowAllocation(bool allow) {
Parcel data, reply;
data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
data.writeInt32(static_cast<int32_t>(allow));
status_t result = remote()->transact(ALLOW_ALLOCATION, data, &reply);
if (result != NO_ERROR) {
return result;
}
result = reply.readInt32();
return result;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void AddImpl(Handle<JSObject> object, uint32_t index,
Handle<Object> value, PropertyAttributes attributes,
uint32_t new_capacity) {
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()));
Handle<FixedArrayBase> old_elements(
FixedArrayBase::cast(parameter_map->get(1)));
Handle<SeededNumberDictionary> dictionary =
old_elements->IsSeededNumberDictionary()
? Handle<SeededNumberDictionary>::cast(old_elements)
: JSObject::NormalizeElements(object);
PropertyDetails details(kData, attributes, 0, PropertyCellType::kNoCell);
Handle<SeededNumberDictionary> new_dictionary =
SeededNumberDictionary::AddNumberEntry(dictionary, index, value,
details, object);
if (attributes != NONE) object->RequireSlowElements(*new_dictionary);
if (*dictionary != *new_dictionary) {
FixedArray::cast(object->elements())->set(1, *new_dictionary);
}
}
CWE ID: CWE-704
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: get_strings_2_svc(gstrings_arg *arg, struct svc_req *rqstp)
{
static gstrings_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_gstrings_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (! cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_INQUIRE,
arg->princ,
NULL))) {
ret.code = KADM5_AUTH_GET;
log_unauth("kadm5_get_strings", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_get_strings((void *)handle, arg->princ, &ret.strings,
&ret.count);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_get_strings", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void raisesExceptionLongAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectPythonV8Internal::raisesExceptionLongAttributeAttributeGetter(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: void UniqueElementData::removeAttribute(size_t index)
{
ASSERT_WITH_SECURITY_IMPLICATION(index < length());
m_attributeVector.remove(index);
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int do_fault(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long address, pte_t *page_table, pmd_t *pmd,
unsigned int flags, pte_t orig_pte)
{
pgoff_t pgoff = (((address & PAGE_MASK)
- vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
pte_unmap(page_table);
if (!(flags & FAULT_FLAG_WRITE))
return do_read_fault(mm, vma, address, pmd, pgoff, flags,
orig_pte);
if (!(vma->vm_flags & VM_SHARED))
return do_cow_fault(mm, vma, address, pmd, pgoff, flags,
orig_pte);
return do_shared_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void LayerTreeHostImpl::RequestUpdateForSynchronousInputHandler() {
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: static int http_receivepack(
http_subtransport *t,
git_smart_subtransport_stream **stream)
{
http_stream *s;
if (http_stream_alloc(t, stream) < 0)
return -1;
s = (http_stream *)*stream;
/* Use Transfer-Encoding: chunked for this request */
s->chunked = 1;
s->parent.write = http_stream_write_chunked;
s->service = receive_pack_service;
s->service_url = receive_pack_service_url;
s->verb = post_verb;
return 0;
}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
unsigned int flags)
{
struct ext4_extent_header *neh;
struct buffer_head *bh;
ext4_fsblk_t newblock, goal = 0;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
int err = 0;
/* Try to prepend new index to old one */
if (ext_depth(inode))
goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode)));
if (goal > le32_to_cpu(es->s_first_data_block)) {
flags |= EXT4_MB_HINT_TRY_GOAL;
goal--;
} else
goal = ext4_inode_to_goal_block(inode);
newblock = ext4_new_meta_blocks(handle, inode, goal, flags,
NULL, &err);
if (newblock == 0)
return err;
bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS);
if (unlikely(!bh))
return -ENOMEM;
lock_buffer(bh);
err = ext4_journal_get_create_access(handle, bh);
if (err) {
unlock_buffer(bh);
goto out;
}
/* move top-level index/leaf into new block */
memmove(bh->b_data, EXT4_I(inode)->i_data,
sizeof(EXT4_I(inode)->i_data));
/* set size of new block */
neh = ext_block_hdr(bh);
/* old root could have indexes or leaves
* so calculate e_max right way */
if (ext_depth(inode))
neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));
else
neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));
neh->eh_magic = EXT4_EXT_MAGIC;
ext4_extent_block_csum_set(inode, neh);
set_buffer_uptodate(bh);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, inode, bh);
if (err)
goto out;
/* Update top-level index: num,max,pointer */
neh = ext_inode_hdr(inode);
neh->eh_entries = cpu_to_le16(1);
ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);
if (neh->eh_depth == 0) {
/* Root extent block becomes index block */
neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));
EXT_FIRST_INDEX(neh)->ei_block =
EXT_FIRST_EXTENT(neh)->ee_block;
}
ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n",
le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),
le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),
ext4_idx_pblock(EXT_FIRST_INDEX(neh)));
le16_add_cpu(&neh->eh_depth, 1);
ext4_mark_inode_dirty(handle, inode);
out:
brelse(bh);
return err;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool ShouldTreatNavigationAsReload(const NavigationEntry* entry) {
if (!entry)
return false;
if ((ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
ui::PAGE_TRANSITION_RELOAD) &&
(entry->GetTransitionType() & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR))) {
return true;
}
if (ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
ui::PAGE_TRANSITION_TYPED)) {
return true;
}
if (ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
ui::PAGE_TRANSITION_LINK)) {
return true;
}
return false;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void h2_session_ev_pre_close(h2_session *session, int arg, const char *msg)
{
h2_session_shutdown(session, arg, msg, 1);
}
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 int process_line(URLContext *h, char *line, int line_count,
int *new_location)
{
HTTPContext *s = h->priv_data;
const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
char *tag, *p, *end, *method, *resource, *version;
int ret;
/* end of header */
if (line[0] == '\0') {
s->end_header = 1;
return 0;
}
p = line;
if (line_count == 0) {
if (s->is_connected_server) {
method = p;
while (*p && !av_isspace(*p))
p++;
*(p++) = '\0';
av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
if (s->method) {
if (av_strcasecmp(s->method, method)) {
av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
s->method, method);
return ff_http_averror(400, AVERROR(EIO));
}
} else {
av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
if (av_strcasecmp(auto_method, method)) {
av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
"(%s autodetected %s received)\n", auto_method, method);
return ff_http_averror(400, AVERROR(EIO));
}
if (!(s->method = av_strdup(method)))
return AVERROR(ENOMEM);
}
while (av_isspace(*p))
p++;
resource = p;
while (!av_isspace(*p))
p++;
*(p++) = '\0';
av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
if (!(s->resource = av_strdup(resource)))
return AVERROR(ENOMEM);
while (av_isspace(*p))
p++;
version = p;
while (*p && !av_isspace(*p))
p++;
*p = '\0';
if (av_strncasecmp(version, "HTTP/", 5)) {
av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
return ff_http_averror(400, AVERROR(EIO));
}
av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
} else {
while (!av_isspace(*p) && *p != '\0')
p++;
while (av_isspace(*p))
p++;
s->http_code = strtol(p, &end, 10);
av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
if ((ret = check_http_code(h, s->http_code, end)) < 0)
return ret;
}
} else {
while (*p != '\0' && *p != ':')
p++;
if (*p != ':')
return 1;
*p = '\0';
tag = line;
p++;
while (av_isspace(*p))
p++;
if (!av_strcasecmp(tag, "Location")) {
if ((ret = parse_location(s, p)) < 0)
return ret;
*new_location = 1;
} else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
s->filesize = strtoll(p, NULL, 10);
} else if (!av_strcasecmp(tag, "Content-Range")) {
parse_content_range(h, p);
} else if (!av_strcasecmp(tag, "Accept-Ranges") &&
!strncmp(p, "bytes", 5) &&
s->seekable == -1) {
h->is_streamed = 0;
} else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
!av_strncasecmp(p, "chunked", 7)) {
s->filesize = -1;
s->chunksize = 0;
} else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
ff_http_auth_handle_header(&s->auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Authentication-Info")) {
ff_http_auth_handle_header(&s->auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
} else if (!av_strcasecmp(tag, "Connection")) {
if (!strcmp(p, "close"))
s->willclose = 1;
} else if (!av_strcasecmp(tag, "Server")) {
if (!av_strcasecmp(p, "AkamaiGHost")) {
s->is_akamai = 1;
} else if (!av_strncasecmp(p, "MediaGateway", 12)) {
s->is_mediagateway = 1;
}
} else if (!av_strcasecmp(tag, "Content-Type")) {
av_free(s->mime_type);
s->mime_type = av_strdup(p);
} else if (!av_strcasecmp(tag, "Set-Cookie")) {
if (parse_cookie(s, p, &s->cookie_dict))
av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
} else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
s->icy_metaint = strtoll(p, NULL, 10);
} else if (!av_strncasecmp(tag, "Icy-", 4)) {
if ((ret = parse_icy(s, tag, p)) < 0)
return ret;
} else if (!av_strcasecmp(tag, "Content-Encoding")) {
if ((ret = parse_content_encoding(h, p)) < 0)
return ret;
}
}
return 1;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: xmlParseBalancedChunkMemory(xmlDocPtr doc, xmlSAXHandlerPtr sax,
void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst) {
return xmlParseBalancedChunkMemoryRecover( doc, sax, user_data,
depth, string, lst, 0 );
}
CWE ID: CWE-611
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: safecat_color_encoding(char *buffer, size_t bufsize, size_t pos,
PNG_CONST color_encoding *e, double encoding_gamma)
{
if (e != 0)
{
if (encoding_gamma != 0)
pos = safecat(buffer, bufsize, pos, "(");
pos = safecat(buffer, bufsize, pos, "R(");
pos = safecatd(buffer, bufsize, pos, e->red.X, 4);
pos = safecat(buffer, bufsize, pos, ",");
pos = safecatd(buffer, bufsize, pos, e->red.Y, 4);
pos = safecat(buffer, bufsize, pos, ",");
pos = safecatd(buffer, bufsize, pos, e->red.Z, 4);
pos = safecat(buffer, bufsize, pos, "),G(");
pos = safecatd(buffer, bufsize, pos, e->green.X, 4);
pos = safecat(buffer, bufsize, pos, ",");
pos = safecatd(buffer, bufsize, pos, e->green.Y, 4);
pos = safecat(buffer, bufsize, pos, ",");
pos = safecatd(buffer, bufsize, pos, e->green.Z, 4);
pos = safecat(buffer, bufsize, pos, "),B(");
pos = safecatd(buffer, bufsize, pos, e->blue.X, 4);
pos = safecat(buffer, bufsize, pos, ",");
pos = safecatd(buffer, bufsize, pos, e->blue.Y, 4);
pos = safecat(buffer, bufsize, pos, ",");
pos = safecatd(buffer, bufsize, pos, e->blue.Z, 4);
pos = safecat(buffer, bufsize, pos, ")");
if (encoding_gamma != 0)
pos = safecat(buffer, bufsize, pos, ")");
}
if (encoding_gamma != 0)
{
pos = safecat(buffer, bufsize, pos, "^");
pos = safecatd(buffer, bufsize, pos, encoding_gamma, 5);
}
return pos;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void OMXNodeInstance::onEvent(
OMX_EVENTTYPE event, OMX_U32 arg1, OMX_U32 arg2) {
const char *arg1String = "??";
const char *arg2String = "??";
ADebug::Level level = ADebug::kDebugInternalState;
switch (event) {
case OMX_EventCmdComplete:
arg1String = asString((OMX_COMMANDTYPE)arg1);
switch (arg1) {
case OMX_CommandStateSet:
arg2String = asString((OMX_STATETYPE)arg2);
level = ADebug::kDebugState;
break;
case OMX_CommandFlush:
case OMX_CommandPortEnable:
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
default:
arg2String = portString(arg2);
}
break;
case OMX_EventError:
arg1String = asString((OMX_ERRORTYPE)arg1);
level = ADebug::kDebugLifeCycle;
break;
case OMX_EventPortSettingsChanged:
arg2String = asString((OMX_INDEXEXTTYPE)arg2);
default:
arg1String = portString(arg1);
}
CLOGI_(level, onEvent, "%s(%x), %s(%x), %s(%x)",
asString(event), event, arg1String, arg1, arg2String, arg2);
const sp<GraphicBufferSource>& bufferSource(getGraphicBufferSource());
if (bufferSource != NULL
&& event == OMX_EventCmdComplete
&& arg1 == OMX_CommandStateSet
&& arg2 == OMX_StateExecuting) {
bufferSource->omxExecuting();
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: GLES2CmdHelper* GLES2Implementation::helper() const {
return helper_;
}
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 nfs_set_pageerror(struct page *page)
{
nfs_zap_mapping(page_file_mapping(page)->host, page_file_mapping(page));
}
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: UWORD32 ihevcd_cabac_decode_bypass_bins_egk(cab_ctxt_t *ps_cabac,
bitstrm_t *ps_bitstrm,
WORD32 k)
{
UWORD32 u4_sym;
WORD32 numones;
WORD32 bin;
/* Sanity checks */
ASSERT((k >= 0));
numones = k;
bin = 1;
u4_sym = 0;
while(bin)
{
IHEVCD_CABAC_DECODE_BYPASS_BIN(bin, ps_cabac, ps_bitstrm);
u4_sym += bin << numones++;
}
numones -= 1;
numones = CLIP3(numones, 0, 16);
if(numones)
{
UWORD32 u4_suffix;
IHEVCD_CABAC_DECODE_BYPASS_BINS(u4_suffix, ps_cabac, ps_bitstrm, numones);
u4_sym += u4_suffix;
}
return (u4_sym);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
content::BrowserContext* browser_context,
const GURL& site) {
std::string partition_id;
if (site.SchemeIs(content::kGuestScheme))
partition_id = site.spec();
#if BUILDFLAG(ENABLE_EXTENSIONS)
else if (site.SchemeIs(extensions::kExtensionScheme) &&
extensions::util::SiteHasIsolatedStorage(site, browser_context))
partition_id = site.spec();
#endif
DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
return partition_id;
}
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: AutofillDialogViews::AutofillDialogViews(AutofillDialogViewDelegate* delegate)
: delegate_(delegate),
updates_scope_(0),
needs_update_(false),
window_(NULL),
notification_area_(NULL),
account_chooser_(NULL),
sign_in_web_view_(NULL),
scrollable_area_(NULL),
details_container_(NULL),
loading_shield_(NULL),
loading_shield_height_(0),
overlay_view_(NULL),
button_strip_extra_view_(NULL),
save_in_chrome_checkbox_(NULL),
save_in_chrome_checkbox_container_(NULL),
button_strip_image_(NULL),
footnote_view_(NULL),
legal_document_view_(NULL),
focus_manager_(NULL),
error_bubble_(NULL),
observer_(this) {
DCHECK(delegate);
detail_groups_.insert(std::make_pair(SECTION_CC,
DetailsGroup(SECTION_CC)));
detail_groups_.insert(std::make_pair(SECTION_BILLING,
DetailsGroup(SECTION_BILLING)));
detail_groups_.insert(std::make_pair(SECTION_CC_BILLING,
DetailsGroup(SECTION_CC_BILLING)));
detail_groups_.insert(std::make_pair(SECTION_SHIPPING,
DetailsGroup(SECTION_SHIPPING)));
}
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: make_error(png_store* volatile psIn, png_byte PNG_CONST colour_type,
png_byte bit_depth, int interlace_type, int test, png_const_charp name)
{
png_store * volatile ps = psIn;
context(ps, fault);
check_interlace_type(interlace_type);
Try
{
png_structp pp;
png_infop pi;
pp = set_store_for_write(ps, &pi, name);
if (pp == NULL)
Throw ps;
png_set_IHDR(pp, pi, transform_width(pp, colour_type, bit_depth),
transform_height(pp, colour_type, bit_depth), bit_depth, colour_type,
interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
if (colour_type == 3) /* palette */
init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/);
/* Time for a few errors; these are in various optional chunks, the
* standard tests test the standard chunks pretty well.
*/
# define exception__prev exception_prev_1
# define exception__env exception_env_1
Try
{
/* Expect this to throw: */
ps->expect_error = !error_test[test].warning;
ps->expect_warning = error_test[test].warning;
ps->saw_warning = 0;
error_test[test].fn(pp, pi);
/* Normally the error is only detected here: */
png_write_info(pp, pi);
/* And handle the case where it was only a warning: */
if (ps->expect_warning && ps->saw_warning)
Throw ps;
/* If we get here there is a problem, we have success - no error or
* no warning - when we shouldn't have success. Log an error.
*/
store_log(ps, pp, error_test[test].msg, 1 /*error*/);
}
Catch (fault)
ps = fault; /* expected exit, make sure ps is not clobbered */
#undef exception__prev
#undef exception__env
/* And clear these flags */
ps->expect_error = 0;
ps->expect_warning = 0;
/* Now write the whole image, just to make sure that the detected, or
* undetected, errro has not created problems inside libpng.
*/
if (png_get_rowbytes(pp, pi) !=
transform_rowsize(pp, colour_type, bit_depth))
png_error(pp, "row size incorrect");
else
{
png_uint_32 h = transform_height(pp, colour_type, bit_depth);
int npasses = png_set_interlace_handling(pp);
int pass;
if (npasses != npasses_from_interlace_type(pp, interlace_type))
png_error(pp, "write: png_set_interlace_handling failed");
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
for (y=0; y<h; ++y)
{
png_byte buffer[TRANSFORM_ROWMAX];
transform_row(pp, buffer, colour_type, bit_depth, y);
png_write_row(pp, buffer);
}
}
}
png_write_end(pp, pi);
/* The following deletes the file that was just written. */
store_write_reset(ps);
}
Catch(fault)
{
store_write_reset(fault);
}
}
CWE ID:
Target: 1
Example 2:
Code: int msPostGISLayerIsOpen(layerObj *layer)
{
#ifdef USE_POSTGIS
if (layer->debug) {
msDebug("msPostGISLayerIsOpen called.\n");
}
if (layer->layerinfo)
return MS_TRUE;
else
return MS_FALSE;
#else
msSetError( MS_MISCERR,
"PostGIS support is not available.",
"msPostGISLayerIsOpen()");
return MS_FAILURE;
#endif
}
CWE ID: CWE-89
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: user_change_icon_file_authorized_cb (Daemon *daemon,
User *user,
GDBusMethodInvocation *context,
gpointer data)
{
g_autofree gchar *filename = NULL;
g_autoptr(GFile) file = NULL;
g_autoptr(GFileInfo) info = NULL;
guint32 mode;
GFileType type;
guint64 size;
filename = g_strdup (data);
if (filename == NULL ||
*filename == '\0') {
g_autofree gchar *dest_path = NULL;
g_autoptr(GFile) dest = NULL;
g_autoptr(GError) error = NULL;
g_clear_pointer (&filename, g_free);
dest_path = g_build_filename (ICONDIR, accounts_user_get_user_name (ACCOUNTS_USER (user)), NULL);
dest = g_file_new_for_path (dest_path);
if (!g_file_delete (dest, NULL, &error) &&
!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
throw_error (context, ERROR_FAILED, "failed to remove user icon, %s", error->message);
return;
}
goto icon_saved;
}
file = g_file_new_for_path (filename);
info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
return;
}
CWE ID: CWE-22
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void nsc_encode_sse2(NSC_CONTEXT* context, const BYTE* data,
UINT32 scanline)
{
nsc_encode_argb_to_aycocg_sse2(context, data, scanline);
if (context->ChromaSubsamplingLevel > 0)
{
nsc_encode_subsampling_sse2(context);
}
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: int SendKeyEvent(MockKeyboard::Layout layout,
int key_code,
MockKeyboard::Modifiers modifiers,
base::string16* output) {
#if defined(OS_WIN)
CHECK(mock_keyboard_.get());
CHECK(output);
int length = mock_keyboard_->GetCharacters(layout, key_code, modifiers,
output);
if (length != 1)
return -1;
MSG msg1 = { NULL, WM_KEYDOWN, key_code, 0 };
ui::KeyEvent evt1(msg1);
NativeWebKeyboardEvent keydown_event(evt1);
SendNativeKeyEvent(keydown_event);
MSG msg2 = { NULL, WM_CHAR, (*output)[0], 0 };
ui::KeyEvent evt2(msg2);
NativeWebKeyboardEvent char_event(evt2);
SendNativeKeyEvent(char_event);
MSG msg3 = { NULL, WM_KEYUP, key_code, 0 };
ui::KeyEvent evt3(msg3);
NativeWebKeyboardEvent keyup_event(evt3);
SendNativeKeyEvent(keyup_event);
return length;
#elif defined(USE_AURA) && defined(USE_X11)
CHECK(output);
const int flags = ConvertMockKeyboardModifier(modifiers);
ui::ScopedXI2Event xevent;
xevent.InitKeyEvent(ui::ET_KEY_PRESSED,
static_cast<ui::KeyboardCode>(key_code),
flags);
ui::KeyEvent event1(xevent);
NativeWebKeyboardEvent keydown_event(event1);
SendNativeKeyEvent(keydown_event);
xevent.InitKeyEvent(ui::ET_KEY_PRESSED,
static_cast<ui::KeyboardCode>(key_code),
flags);
ui::KeyEvent event2(xevent);
event2.set_character(
DomCodeToUsLayoutCharacter(event2.code(), event2.flags()));
ui::KeyEventTestApi test_event2(&event2);
test_event2.set_is_char(true);
NativeWebKeyboardEvent char_event(event2);
SendNativeKeyEvent(char_event);
xevent.InitKeyEvent(ui::ET_KEY_RELEASED,
static_cast<ui::KeyboardCode>(key_code),
flags);
ui::KeyEvent event3(xevent);
NativeWebKeyboardEvent keyup_event(event3);
SendNativeKeyEvent(keyup_event);
long c = DomCodeToUsLayoutCharacter(
UsLayoutKeyboardCodeToDomCode(static_cast<ui::KeyboardCode>(key_code)),
flags);
output->assign(1, static_cast<base::char16>(c));
return 1;
#elif defined(USE_OZONE)
const int flags = ConvertMockKeyboardModifier(modifiers);
ui::KeyEvent keydown_event(ui::ET_KEY_PRESSED,
static_cast<ui::KeyboardCode>(key_code),
flags);
NativeWebKeyboardEvent keydown_web_event(keydown_event);
SendNativeKeyEvent(keydown_web_event);
ui::KeyEvent char_event(keydown_event.GetCharacter(),
static_cast<ui::KeyboardCode>(key_code),
ui::DomCode::NONE, flags);
NativeWebKeyboardEvent char_web_event(char_event);
SendNativeKeyEvent(char_web_event);
ui::KeyEvent keyup_event(ui::ET_KEY_RELEASED,
static_cast<ui::KeyboardCode>(key_code),
flags);
NativeWebKeyboardEvent keyup_web_event(keyup_event);
SendNativeKeyEvent(keyup_web_event);
long c = DomCodeToUsLayoutCharacter(
UsLayoutKeyboardCodeToDomCode(static_cast<ui::KeyboardCode>(key_code)),
flags);
output->assign(1, static_cast<base::char16>(c));
return 1;
#else
NOTIMPLEMENTED();
return L'\0';
#endif
}
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: mojom::KeypressResponseForRulebasedPtr GenerateKeypressResponseForRulebased(
rulebased::ProcessKeyResult& process_key_result) {
mojom::KeypressResponseForRulebasedPtr keypress_response =
mojom::KeypressResponseForRulebased::New();
keypress_response->result = process_key_result.key_handled;
if (!process_key_result.commit_text.empty()) {
std::string commit_text;
base::EscapeJSONString(process_key_result.commit_text, false, &commit_text);
keypress_response->operations.push_back(mojom::OperationForRulebased::New(
mojom::OperationMethodForRulebased::COMMIT_TEXT, commit_text));
}
if (!process_key_result.composition_text.empty() ||
(process_key_result.key_handled &&
process_key_result.commit_text.empty())) {
std::string composition_text;
base::EscapeJSONString(process_key_result.composition_text, false,
&composition_text);
keypress_response->operations.push_back(mojom::OperationForRulebased::New(
mojom::OperationMethodForRulebased::SET_COMPOSITION, composition_text));
}
return keypress_response;
}
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: Chapters::~Chapters()
{
while (m_editions_count > 0)
{
Edition& e = m_editions[--m_editions_count];
e.Clear();
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: isofs_dentry_cmp_ms(const struct dentry *parent, const struct dentry *dentry,
unsigned int len, const char *str, const struct qstr *name)
{
return isofs_dentry_cmp_common(len, str, name, 1, 0);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool tight_can_send_png_rect(VncState *vs, int w, int h)
{
if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) {
return false;
}
if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
vs->clientds.pf.bytes_per_pixel == 1) {
return false;
}
return true;
}
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 int nsv_read_chunk(AVFormatContext *s, int fill_header)
{
NSVContext *nsv = s->priv_data;
AVIOContext *pb = s->pb;
AVStream *st[2] = {NULL, NULL};
NSVStream *nst;
AVPacket *pkt;
int i, err = 0;
uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */
uint32_t vsize;
uint16_t asize;
uint16_t auxsize;
if (nsv->ahead[0].data || nsv->ahead[1].data)
return 0; //-1; /* hey! eat what you've in your plate first! */
null_chunk_retry:
if (pb->eof_reached)
return -1;
for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)
err = nsv_resync(s);
if (err < 0)
return err;
if (nsv->state == NSV_FOUND_NSVS)
err = nsv_parse_NSVs_header(s);
if (err < 0)
return err;
if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)
return -1;
auxcount = avio_r8(pb);
vsize = avio_rl16(pb);
asize = avio_rl16(pb);
vsize = (vsize << 4) | (auxcount >> 4);
auxcount &= 0x0f;
av_log(s, AV_LOG_TRACE, "NSV CHUNK %"PRIu8" aux, %"PRIu32" bytes video, %"PRIu16" bytes audio\n",
auxcount, vsize, asize);
/* skip aux stuff */
for (i = 0; i < auxcount; i++) {
uint32_t av_unused auxtag;
auxsize = avio_rl16(pb);
auxtag = avio_rl32(pb);
avio_skip(pb, auxsize);
vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */
}
if (pb->eof_reached)
return -1;
if (!vsize && !asize) {
nsv->state = NSV_UNSYNC;
goto null_chunk_retry;
}
/* map back streams to v,a */
if (s->nb_streams > 0)
st[s->streams[0]->id] = s->streams[0];
if (s->nb_streams > 1)
st[s->streams[1]->id] = s->streams[1];
if (vsize && st[NSV_ST_VIDEO]) {
nst = st[NSV_ST_VIDEO]->priv_data;
pkt = &nsv->ahead[NSV_ST_VIDEO];
av_get_packet(pb, pkt, vsize);
pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;
pkt->dts = nst->frame_offset;
pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
for (i = 0; i < FFMIN(8, vsize); i++)
av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02"PRIx8"\n",
i, pkt->data[i]);
}
if(st[NSV_ST_VIDEO])
((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
if (asize && st[NSV_ST_AUDIO]) {
nst = st[NSV_ST_AUDIO]->priv_data;
pkt = &nsv->ahead[NSV_ST_AUDIO];
/* read raw audio specific header on the first audio chunk... */
/* on ALL audio chunks ?? seems so! */
if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {
uint8_t bps;
uint8_t channels;
uint16_t samplerate;
bps = avio_r8(pb);
channels = avio_r8(pb);
samplerate = avio_rl16(pb);
if (!channels || !samplerate)
return AVERROR_INVALIDDATA;
asize-=4;
av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",
bps, channels, samplerate);
if (fill_header) {
st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */
if (bps != 16) {
av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%"PRIu8")!!!\n", bps);
}
bps /= channels; // ???
if (bps == 8)
st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
samplerate /= 4;/* UGH ??? XXX */
channels = 1;
st[NSV_ST_AUDIO]->codecpar->channels = channels;
st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate;
av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",
bps, channels, samplerate);
}
}
av_get_packet(pb, pkt, asize);
pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;
pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {
/* on a nsvs frame we have new information on a/v sync */
pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);
pkt->dts *= (int64_t)1000 * nsv->framerate.den;
pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;
av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%"PRId16", dts:%"PRId64,
nsv->avsync, pkt->dts);
}
nst->frame_offset++;
}
nsv->state = NSV_UNSYNC;
return 0;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: void php_snmp_add_property(HashTable *h, const char *name, size_t name_length, php_snmp_read_t read_func, php_snmp_write_t write_func)
{
php_snmp_prop_handler p;
p.name = (char*) name;
p.name_length = name_length;
p.read_func = (read_func) ? read_func : NULL;
p.write_func = (write_func) ? write_func : NULL;
zend_hash_str_add_mem(h, (char *)name, name_length, &p, sizeof(php_snmp_prop_handler));
}
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 MSG_WriteDeltaUsercmdKey( msg_t *msg, int key, usercmd_t *from, usercmd_t *to ) {
if ( to->serverTime - from->serverTime < 256 ) {
MSG_WriteBits( msg, 1, 1 );
MSG_WriteBits( msg, to->serverTime - from->serverTime, 8 );
} else {
MSG_WriteBits( msg, 0, 1 );
MSG_WriteBits( msg, to->serverTime, 32 );
}
if (from->angles[0] == to->angles[0] &&
from->angles[1] == to->angles[1] &&
from->angles[2] == to->angles[2] &&
from->forwardmove == to->forwardmove &&
from->rightmove == to->rightmove &&
from->upmove == to->upmove &&
from->buttons == to->buttons &&
from->weapon == to->weapon) {
MSG_WriteBits( msg, 0, 1 ); // no change
oldsize += 7;
return;
}
key ^= to->serverTime;
MSG_WriteBits( msg, 1, 1 );
MSG_WriteDeltaKey( msg, key, from->angles[0], to->angles[0], 16 );
MSG_WriteDeltaKey( msg, key, from->angles[1], to->angles[1], 16 );
MSG_WriteDeltaKey( msg, key, from->angles[2], to->angles[2], 16 );
MSG_WriteDeltaKey( msg, key, from->forwardmove, to->forwardmove, 8 );
MSG_WriteDeltaKey( msg, key, from->rightmove, to->rightmove, 8 );
MSG_WriteDeltaKey( msg, key, from->upmove, to->upmove, 8 );
MSG_WriteDeltaKey( msg, key, from->buttons, to->buttons, 16 );
MSG_WriteDeltaKey( msg, key, from->weapon, to->weapon, 8 );
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t OMXNodeInstance::sendCommand(
OMX_COMMANDTYPE cmd, OMX_S32 param) {
if (cmd == OMX_CommandStateSet) {
mSailed = true;
}
const sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && cmd == OMX_CommandStateSet) {
if (param == OMX_StateIdle) {
bufferSource->omxIdle();
} else if (param == OMX_StateLoaded) {
bufferSource->omxLoaded();
setGraphicBufferSource(NULL);
}
}
Mutex::Autolock autoLock(mLock);
{
Mutex::Autolock _l(mDebugLock);
bumpDebugLevel_l(2 /* numInputBuffers */, 2 /* numOutputBuffers */);
}
const char *paramString =
cmd == OMX_CommandStateSet ? asString((OMX_STATETYPE)param) : portString(param);
CLOG_STATE(sendCommand, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
OMX_ERRORTYPE err = OMX_SendCommand(mHandle, cmd, param, NULL);
CLOG_IF_ERROR(sendCommand, err, "%s(%d), %s(%d)", asString(cmd), cmd, paramString, param);
return StatusFromOMXError(err);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void RenderProcessHostImpl::WidgetRestored() {
visible_widgets_++;
UpdateProcessPriority();
DCHECK(!is_process_backgrounded_);
}
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 hugetlb_unreserve_pages(struct inode *inode, long offset, long freed)
{
struct hstate *h = hstate_inode(inode);
long chg = region_truncate(&inode->i_mapping->private_list, offset);
spin_lock(&inode->i_lock);
inode->i_blocks -= (blocks_per_huge_page(h) * freed);
spin_unlock(&inode->i_lock);
hugetlb_put_quota(inode->i_mapping, (chg - freed));
hugetlb_acct_memory(h, -(chg - freed));
}
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 readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
{
mainprog_info *mainprog_ptr;
/* retrieve the pointer to our special-purpose struct */
mainprog_ptr = png_get_progressive_ptr(png_ptr);
/* let the main program know that it should flush any buffered image
* data to the display now and set a "done" flag or whatever, but note
* that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
* NOT call readpng2_cleanup() either here or in the finish_display()
* routine; wait until control returns to the main program via
* readpng2_decode_data() */
(*mainprog_ptr->mainprog_finish_display)();
/* all done */
return;
}
CWE ID:
Target: 1
Example 2:
Code: GLES2DecoderPassthroughImpl::GetTranslator(GLenum type) {
return nullptr;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool CopyDirectory(const FilePath& from_path,
const FilePath& to_path,
bool recursive) {
base::ThreadRestrictions::AssertIOAllowed();
DCHECK(to_path.value().find('*') == std::string::npos);
DCHECK(from_path.value().find('*') == std::string::npos);
char top_dir[PATH_MAX];
if (base::strlcpy(top_dir, from_path.value().c_str(),
arraysize(top_dir)) >= arraysize(top_dir)) {
return false;
}
FilePath real_to_path = to_path;
if (PathExists(real_to_path)) {
if (!AbsolutePath(&real_to_path))
return false;
} else {
real_to_path = real_to_path.DirName();
if (!AbsolutePath(&real_to_path))
return false;
}
FilePath real_from_path = from_path;
if (!AbsolutePath(&real_from_path))
return false;
if (real_to_path.value().size() >= real_from_path.value().size() &&
real_to_path.value().compare(0, real_from_path.value().size(),
real_from_path.value()) == 0)
return false;
bool success = true;
int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS;
if (recursive)
traverse_type |= FileEnumerator::DIRECTORIES;
FileEnumerator traversal(from_path, recursive, traverse_type);
FileEnumerator::FindInfo info;
FilePath current = from_path;
if (stat(from_path.value().c_str(), &info.stat) < 0) {
DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: "
<< from_path.value() << " errno = " << errno;
success = false;
}
struct stat to_path_stat;
FilePath from_path_base = from_path;
if (recursive && stat(to_path.value().c_str(), &to_path_stat) == 0 &&
S_ISDIR(to_path_stat.st_mode)) {
from_path_base = from_path.DirName();
}
DCHECK(recursive || S_ISDIR(info.stat.st_mode));
while (success && !current.empty()) {
std::string suffix(¤t.value().c_str()[from_path_base.value().size()]);
if (!suffix.empty()) {
DCHECK_EQ('/', suffix[0]);
suffix.erase(0, 1);
}
const FilePath target_path = to_path.Append(suffix);
if (S_ISDIR(info.stat.st_mode)) {
if (mkdir(target_path.value().c_str(), info.stat.st_mode & 01777) != 0 &&
errno != EEXIST) {
DLOG(ERROR) << "CopyDirectory() couldn't create directory: "
<< target_path.value() << " errno = " << errno;
success = false;
}
} else if (S_ISREG(info.stat.st_mode)) {
if (!CopyFile(current, target_path)) {
DLOG(ERROR) << "CopyDirectory() couldn't create file: "
<< target_path.value();
success = false;
}
} else {
DLOG(WARNING) << "CopyDirectory() skipping non-regular file: "
<< current.value();
}
current = traversal.Next();
traversal.GetFindInfo(&info);
}
return success;
}
CWE ID: CWE-22
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(SplFileObject, fputcsv)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape;
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0, ret;
zval *fields = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|sss", &fields, &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 4:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 3:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 2:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 1:
case 0:
break;
}
ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC);
RETURN_LONG(ret);
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: xps_select_best_font_encoding(xps_document *doc, fz_font *font)
{
static struct { int pid, eid; } xps_cmap_list[] =
{
{ 3, 10 }, /* Unicode with surrogates */
{ 3, 1 }, /* Unicode without surrogates */
{ 3, 5 }, /* Wansung */
{ 3, 4 }, /* Big5 */
{ 3, 3 }, /* Prc */
{ 3, 2 }, /* ShiftJis */
{ 3, 0 }, /* Symbol */
{ 1, 0 },
{ -1, -1 },
};
int i, k, n, pid, eid;
n = xps_count_font_encodings(font);
for (k = 0; xps_cmap_list[k].pid != -1; k++)
{
for (i = 0; i < n; i++)
{
xps_identify_font_encoding(font, i, &pid, &eid);
if (pid == xps_cmap_list[k].pid && eid == xps_cmap_list[k].eid)
{
xps_select_font_encoding(font, i);
return;
}
}
}
fz_warn(doc->ctx, "cannot find a suitable cmap");
}
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: __visible void __noreturn handle_stack_overflow(const char *message,
struct pt_regs *regs,
unsigned long fault_address)
{
printk(KERN_EMERG "BUG: stack guard page was hit at %p (stack is %p..%p)\n",
(void *)fault_address, current->stack,
(char *)current->stack + THREAD_SIZE - 1);
die(message, regs, 0);
/* Be absolutely certain we don't return. */
panic(message);
}
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: _ksba_name_new_from_der (ksba_name_t *r_name,
const unsigned char *image, size_t imagelen)
{
gpg_error_t err;
ksba_name_t name;
struct tag_info ti;
const unsigned char *der;
size_t derlen;
int n;
char *p;
if (!r_name || !image)
return gpg_error (GPG_ERR_INV_VALUE);
*r_name = NULL;
/* count and check for encoding errors - we won;t do this again
during the second pass */
der = image;
derlen = imagelen;
n = 0;
while (derlen)
{
err = _ksba_ber_parse_tl (&der, &derlen, &ti);
if (err)
return err;
if (ti.class != CLASS_CONTEXT)
return gpg_error (GPG_ERR_INV_CERT_OBJ); /* we expected a tag */
if (ti.ndef)
return gpg_error (GPG_ERR_NOT_DER_ENCODED);
if (derlen < ti.length)
return gpg_error (GPG_ERR_BAD_BER);
switch (ti.tag)
{
case 1: /* rfc822Name - this is an imlicit IA5_STRING */
case 4: /* Name */
case 6: /* URI */
n++;
break;
default:
break;
}
/* advance pointer */
der += ti.length;
derlen -= ti.length;
}
/* allocate array and set all slots to NULL for easier error recovery */
err = ksba_name_new (&name);
if (err)
return err;
if (!n)
return 0; /* empty GeneralNames */
name->names = xtrycalloc (n, sizeof *name->names);
if (!name->names)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
name->n_names = n;
/* start the second pass */
der = image;
derlen = imagelen;
n = 0;
while (derlen)
{
char numbuf[21];
err = _ksba_ber_parse_tl (&der, &derlen, &ti);
assert (!err);
switch (ti.tag)
{
case 1: /* rfc822Name - this is an imlicit IA5_STRING */
p = name->names[n] = xtrymalloc (ti.length+3);
if (!p)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
*p++ = '<';
memcpy (p, der, ti.length);
p += ti.length;
*p++ = '>';
*p = 0;
n++;
break;
case 4: /* Name */
err = _ksba_derdn_to_str (der, ti.length, &p);
if (err)
return err; /* FIXME: we need to release some of the memory */
name->names[n++] = p;
break;
case 6: /* URI */
sprintf (numbuf, "%u:", (unsigned int)ti.length);
p = name->names[n] = xtrymalloc (1+5+strlen (numbuf)
+ ti.length +1+1);
if (!p)
{
ksba_name_release (name);
return gpg_error (GPG_ERR_ENOMEM);
}
p = stpcpy (p, "(3:uri");
p = stpcpy (p, numbuf);
memcpy (p, der, ti.length);
p += ti.length;
*p++ = ')';
*p = 0; /* extra safeguard null */
n++;
break;
default:
break;
}
/* advance pointer */
der += ti.length;
derlen -= ti.length;
}
*r_name = name;
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: TIFFInitSGILog(TIFF* tif, int scheme)
{
static const char module[] = "TIFFInitSGILog";
LogLuvState* sp;
assert(scheme == COMPRESSION_SGILOG24 || scheme == COMPRESSION_SGILOG);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, LogLuvFields,
TIFFArrayCount(LogLuvFields))) {
TIFFErrorExt(tif->tif_clientdata, module,
"Merging SGILog codec-specific tags failed");
return 0;
}
/*
* Allocate state block so tag methods have storage to record values.
*/
tif->tif_data = (uint8*) _TIFFmalloc(sizeof (LogLuvState));
if (tif->tif_data == NULL)
goto bad;
sp = (LogLuvState*) tif->tif_data;
_TIFFmemset((void*)sp, 0, sizeof (*sp));
sp->user_datafmt = SGILOGDATAFMT_UNKNOWN;
sp->encode_meth = (scheme == COMPRESSION_SGILOG24) ?
SGILOGENCODE_RANDITHER : SGILOGENCODE_NODITHER;
sp->tfunc = _logLuvNop;
/*
* Install codec methods.
* NB: tif_decoderow & tif_encoderow are filled
* in at setup time.
*/
tif->tif_fixuptags = LogLuvFixupTags;
tif->tif_setupdecode = LogLuvSetupDecode;
tif->tif_decodestrip = LogLuvDecodeStrip;
tif->tif_decodetile = LogLuvDecodeTile;
tif->tif_setupencode = LogLuvSetupEncode;
tif->tif_encodestrip = LogLuvEncodeStrip;
tif->tif_encodetile = LogLuvEncodeTile;
tif->tif_close = LogLuvClose;
tif->tif_cleanup = LogLuvCleanup;
/*
* Override parent get/set field methods.
*/
sp->vgetparent = tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield = LogLuvVGetField; /* hook for codec tags */
sp->vsetparent = tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield = LogLuvVSetField; /* hook for codec tags */
return (1);
bad:
TIFFErrorExt(tif->tif_clientdata, module,
"%s: No space for LogLuv state block", tif->tif_name);
return (0);
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cisco_autorp_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int type;
int numrps;
int hold;
ND_TCHECK(bp[0]);
ND_PRINT((ndo, " auto-rp "));
type = bp[0];
switch (type) {
case 0x11:
ND_PRINT((ndo, "candidate-advert"));
break;
case 0x12:
ND_PRINT((ndo, "mapping"));
break;
default:
ND_PRINT((ndo, "type-0x%02x", type));
break;
}
ND_TCHECK(bp[1]);
numrps = bp[1];
ND_TCHECK2(bp[2], 2);
ND_PRINT((ndo, " Hold "));
hold = EXTRACT_16BITS(&bp[2]);
if (hold)
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
else
ND_PRINT((ndo, "FOREVER"));
/* Next 4 bytes are reserved. */
bp += 8; len -= 8;
/*XXX skip unless -v? */
/*
* Rest of packet:
* numrps entries of the form:
* 32 bits: RP
* 6 bits: reserved
* 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2".
* 8 bits: # of entries for this RP
* each entry: 7 bits: reserved, 1 bit: negative,
* 8 bits: mask 32 bits: source
* lather, rinse, repeat.
*/
while (numrps--) {
int nentries;
char s;
ND_TCHECK2(bp[0], 4);
ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp)));
ND_TCHECK(bp[4]);
switch (bp[4] & 0x3) {
case 0: ND_PRINT((ndo, " PIMv?"));
break;
case 1: ND_PRINT((ndo, " PIMv1"));
break;
case 2: ND_PRINT((ndo, " PIMv2"));
break;
case 3: ND_PRINT((ndo, " PIMv1+2"));
break;
}
if (bp[4] & 0xfc)
ND_PRINT((ndo, " [rsvd=0x%02x]", bp[4] & 0xfc));
ND_TCHECK(bp[5]);
nentries = bp[5];
bp += 6; len -= 6;
s = ' ';
for (; nentries; nentries--) {
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "",
ipaddr_string(ndo, &bp[2]), bp[1]));
if (bp[0] & 0x02) {
ND_PRINT((ndo, " bidir"));
}
if (bp[0] & 0xfc) {
ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc));
}
s = ',';
bp += 6; len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|autorp]"));
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: png_get_uint_32(png_bytep buf)
{
png_uint_32 i = ((png_uint_32)(*buf) << 24) +
((png_uint_32)(*(buf + 1)) << 16) +
((png_uint_32)(*(buf + 2)) << 8) +
(png_uint_32)(*(buf + 3));
return (i);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int32_t WebPage::setComposingText(spannable_string_t* spannableString, int32_t relativeCursorPosition)
{
if (d->m_page->defersLoading())
return -1;
return d->m_inputHandler->setComposingText(spannableString, relativeCursorPosition);
}
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: aodv_extension(netdissect_options *ndo,
const struct aodv_ext *ep, u_int length)
{
const struct aodv_hello *ah;
switch (ep->type) {
case AODV_EXT_HELLO:
ah = (const struct aodv_hello *)(const void *)ep;
ND_TCHECK(*ah);
if (length < sizeof(struct aodv_hello))
goto trunc;
ND_PRINT((ndo, "\n\text HELLO %ld ms",
(unsigned long)EXTRACT_32BITS(&ah->interval)));
break;
default:
ND_PRINT((ndo, "\n\text %u %u", ep->type, ep->length));
break;
}
return;
trunc:
ND_PRINT((ndo, " [|hello]"));
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
if (ShowingInterstitialPage()) {
GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse);
return;
}
RenderWidgetHostView* const fullscreen_view =
GetFullscreenRenderWidgetHostView();
if (fullscreen_view) {
fullscreen_view->Focus();
return;
}
GetRenderViewHost()->SetInitialFocus(reverse);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static RList* sections(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t)* obj = (bf && bf->o)? bf->o->bin_obj : NULL;
struct r_bin_elf_section_t *section = NULL;
int i, num, found_load = 0;
Elf_(Phdr)* phdr = NULL;
RBinSection *ptr = NULL;
RList *ret = NULL;
if (!obj || !(ret = r_list_newf (free))) {
return NULL;
}
if ((section = Elf_(r_bin_elf_get_sections) (obj))) {
for (i = 0; !section[i].last; i++) {
if (!(ptr = R_NEW0 (RBinSection))) {
break;
}
strncpy (ptr->name, (char*)section[i].name, R_BIN_SIZEOF_STRINGS);
if (strstr (ptr->name, "data") && !strstr (ptr->name, "rel")) {
ptr->is_data = true;
}
ptr->size = section[i].type != SHT_NOBITS ? section[i].size : 0;
ptr->vsize = section[i].size;
ptr->paddr = section[i].offset;
ptr->vaddr = section[i].rva;
ptr->add = !obj->phdr; // Load sections if there is no PHDR
ptr->srwx = 0;
if (R_BIN_ELF_SCN_IS_EXECUTABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_EXECUTABLE;
}
if (R_BIN_ELF_SCN_IS_WRITABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_WRITABLE;
}
if (R_BIN_ELF_SCN_IS_READABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_READABLE;
}
r_list_append (ret, ptr);
}
}
num = obj->ehdr.e_phnum;
phdr = obj->phdr;
if (phdr) {
int n = 0;
for (i = 0; i < num; i++) {
if (!(ptr = R_NEW0 (RBinSection))) {
return ret;
}
ptr->add = false;
ptr->size = phdr[i].p_filesz;
ptr->vsize = phdr[i].p_memsz;
ptr->paddr = phdr[i].p_offset;
ptr->vaddr = phdr[i].p_vaddr;
ptr->srwx = phdr[i].p_flags;
switch (phdr[i].p_type) {
case PT_DYNAMIC:
strncpy (ptr->name, "DYNAMIC", R_BIN_SIZEOF_STRINGS);
break;
case PT_LOAD:
snprintf (ptr->name, R_BIN_SIZEOF_STRINGS, "LOAD%d", n++);
found_load = 1;
ptr->add = true;
break;
case PT_INTERP:
strncpy (ptr->name, "INTERP", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_STACK:
strncpy (ptr->name, "GNU_STACK", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_RELRO:
strncpy (ptr->name, "GNU_RELRO", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_EH_FRAME:
strncpy (ptr->name, "GNU_EH_FRAME", R_BIN_SIZEOF_STRINGS);
break;
case PT_PHDR:
strncpy (ptr->name, "PHDR", R_BIN_SIZEOF_STRINGS);
break;
case PT_TLS:
strncpy (ptr->name, "TLS", R_BIN_SIZEOF_STRINGS);
break;
case PT_NOTE:
strncpy (ptr->name, "NOTE", R_BIN_SIZEOF_STRINGS);
break;
default:
strncpy (ptr->name, "UNKNOWN", R_BIN_SIZEOF_STRINGS);
break;
}
ptr->name[R_BIN_SIZEOF_STRINGS - 1] = '\0';
r_list_append (ret, ptr);
}
}
if (r_list_empty (ret)) {
if (!bf->size) {
struct Elf_(r_bin_elf_obj_t) *bin = bf->o->bin_obj;
bf->size = bin? bin->size: 0x9999;
}
if (found_load == 0) {
if (!(ptr = R_NEW0 (RBinSection))) {
return ret;
}
sprintf (ptr->name, "uphdr");
ptr->size = bf->size;
ptr->vsize = bf->size;
ptr->paddr = 0;
ptr->vaddr = 0x10000;
ptr->add = true;
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE |
R_BIN_SCN_EXECUTABLE;
r_list_append (ret, ptr);
}
}
ptr = R_NEW0 (RBinSection);
if (ptr) {
ut64 ehdr_size = sizeof (obj->ehdr);
if (bf->size < ehdr_size) {
ehdr_size = bf->size;
}
sprintf (ptr->name, "ehdr");
ptr->paddr = 0;
ptr->vaddr = obj->baddr;
ptr->size = ehdr_size;
ptr->vsize = ehdr_size;
ptr->add = false;
if (obj->ehdr.e_type == ET_REL) {
ptr->add = true;
}
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE;
r_list_append (ret, ptr);
}
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: void writeDOMFileSystem(int type, const String& name, const String& url)
{
append(DOMFileSystemTag);
doWriteUint32(type);
doWriteWebCoreString(name);
doWriteWebCoreString(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: XGetFeedbackControl(
register Display *dpy,
XDevice *dev,
int *num_feedbacks)
{
XFeedbackState *Feedback = NULL;
XFeedbackState *Sav = NULL;
xFeedbackState *f = NULL;
xFeedbackState *sav = NULL;
xGetFeedbackControlReq *req;
xGetFeedbackControlReply rep;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1)
return NULL;
GetReq(GetFeedbackControl, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetFeedbackControl;
req->deviceid = dev->device_id;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
goto out;
if (rep.length > 0) {
unsigned long nbytes;
size_t size = 0;
int i;
*num_feedbacks = rep.num_feedbacks;
if (rep.length < (INT_MAX >> 2)) {
nbytes = rep.length << 2;
f = Xmalloc(nbytes);
}
if (!f) {
_XEatDataWords(dpy, rep.length);
goto out;
goto out;
}
sav = f;
_XRead(dpy, (char *)f, nbytes);
for (i = 0; i < *num_feedbacks; i++) {
if (f->length > nbytes)
goto out;
nbytes -= f->length;
break;
case PtrFeedbackClass:
size += sizeof(XPtrFeedbackState);
break;
case IntegerFeedbackClass:
size += sizeof(XIntegerFeedbackState);
break;
case StringFeedbackClass:
{
xStringFeedbackState *strf = (xStringFeedbackState *) f;
case StringFeedbackClass:
{
xStringFeedbackState *strf = (xStringFeedbackState *) f;
size += sizeof(XStringFeedbackState) +
(strf->num_syms_supported * sizeof(KeySym));
}
size += sizeof(XBellFeedbackState);
break;
default:
size += f->length;
break;
}
if (size > INT_MAX)
goto out;
f = (xFeedbackState *) ((char *)f + f->length);
}
Feedback = Xmalloc(size);
if (!Feedback)
goto out;
Sav = Feedback;
f = sav;
for (i = 0; i < *num_feedbacks; i++) {
switch (f->class) {
case KbdFeedbackClass:
{
xKbdFeedbackState *k;
XKbdFeedbackState *K;
k = (xKbdFeedbackState *) f;
K = (XKbdFeedbackState *) Feedback;
K->class = k->class;
K->length = sizeof(XKbdFeedbackState);
K->id = k->id;
K->click = k->click;
K->percent = k->percent;
K->pitch = k->pitch;
K->duration = k->duration;
K->led_mask = k->led_mask;
K->global_auto_repeat = k->global_auto_repeat;
memcpy((char *)&K->auto_repeats[0],
(char *)&k->auto_repeats[0], 32);
break;
}
case PtrFeedbackClass:
{
xPtrFeedbackState *p;
XPtrFeedbackState *P;
p = (xPtrFeedbackState *) f;
P = (XPtrFeedbackState *) Feedback;
P->class = p->class;
P->length = sizeof(XPtrFeedbackState);
P->id = p->id;
P->accelNum = p->accelNum;
P->accelDenom = p->accelDenom;
P->threshold = p->threshold;
break;
}
case IntegerFeedbackClass:
{
xIntegerFeedbackState *ifs;
XIntegerFeedbackState *I;
ifs = (xIntegerFeedbackState *) f;
I = (XIntegerFeedbackState *) Feedback;
I->class = ifs->class;
I->length = sizeof(XIntegerFeedbackState);
I->id = ifs->id;
I->resolution = ifs->resolution;
I->minVal = ifs->min_value;
I->maxVal = ifs->max_value;
break;
}
case StringFeedbackClass:
{
xStringFeedbackState *s;
XStringFeedbackState *S;
s = (xStringFeedbackState *) f;
S = (XStringFeedbackState *) Feedback;
S->class = s->class;
S->length = sizeof(XStringFeedbackState) +
(s->num_syms_supported * sizeof(KeySym));
S->id = s->id;
S->max_symbols = s->max_symbols;
S->num_syms_supported = s->num_syms_supported;
S->syms_supported = (KeySym *) (S + 1);
memcpy((char *)S->syms_supported, (char *)(s + 1),
(S->num_syms_supported * sizeof(KeySym)));
break;
}
case LedFeedbackClass:
{
xLedFeedbackState *l;
XLedFeedbackState *L;
l = (xLedFeedbackState *) f;
L = (XLedFeedbackState *) Feedback;
L->class = l->class;
L->length = sizeof(XLedFeedbackState);
L->id = l->id;
L->led_values = l->led_values;
L->led_mask = l->led_mask;
break;
}
case BellFeedbackClass:
{
xBellFeedbackState *b;
XBellFeedbackState *B;
b = (xBellFeedbackState *) f;
B = (XBellFeedbackState *) Feedback;
B->class = b->class;
B->length = sizeof(XBellFeedbackState);
B->id = b->id;
B->percent = b->percent;
B->pitch = b->pitch;
B->duration = b->duration;
break;
}
default:
break;
}
f = (xFeedbackState *) ((char *)f + f->length);
Feedback = (XFeedbackState *) ((char *)Feedback + Feedback->length);
}
}
out:
XFree((char *)sav);
UnlockDisplay(dpy);
SyncHandle();
return (Sav);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: explicit CloseWindowTask(Browser* browser) : browser_(browser) {}
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: std::unique_ptr<gfx::GpuMemoryBuffer> GLManager::CreateGpuMemoryBuffer(
const gfx::Size& size,
gfx::BufferFormat format) {
#if defined(OS_MACOSX)
if (use_iosurface_memory_buffers_) {
return base::WrapUnique<gfx::GpuMemoryBuffer>(
new IOSurfaceGpuMemoryBuffer(size, format));
}
#endif // defined(OS_MACOSX)
std::vector<uint8_t> data(gfx::BufferSizeForBufferFormat(size, format), 0);
scoped_refptr<base::RefCountedBytes> bytes(new base::RefCountedBytes(data));
return base::WrapUnique<gfx::GpuMemoryBuffer>(
new GpuMemoryBufferImpl(bytes.get(), size, format));
}
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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert1(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
a* (toa(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert1();
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int qemu_fdt_setprop_cell(void *fdt, const char *node_path,
const char *property, uint32_t val)
{
int r;
r = fdt_setprop_cell(fdt, findnode_nofail(fdt, node_path), property, val);
if (r < 0) {
error_report("%s: Couldn't set %s/%s = %#08x: %s", __func__,
node_path, property, val, fdt_strerror(r));
exit(1);
}
return r;
}
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: T42_Driver_Done( FT_Module module )
{
FT_UNUSED( module );
}
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 IBusBusGlobalEngineChangedCallback(
IBusBus* bus, const gchar* engine_name, gpointer user_data) {
DCHECK(engine_name);
DLOG(INFO) << "Global engine is changed to " << engine_name;
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->UpdateUI(engine_name);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool Dispatcher::IsWithinPlatformApp() {
for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
iter != active_extension_ids_.end();
++iter) {
const Extension* extension =
RendererExtensionRegistry::Get()->GetByID(*iter);
if (extension && extension->is_platform_app())
return true;
}
return false;
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc,
struct pluto_crypto_req *r,
err_t ugh)
{
struct dh_continuation *dh = (struct dh_continuation *)pcrc;
struct msg_digest *md = dh->md;
struct state *const st = md->st;
stf_status e;
DBG(DBG_CONTROLMORE,
DBG_log("ikev2 parent inR1outI2: calculating g^{xy}, sending I2"));
if (st == NULL) {
loglog(RC_LOG_SERIOUS,
"%s: Request was disconnected from state",
__FUNCTION__);
if (dh->md)
release_md(dh->md);
return;
}
/* XXX should check out ugh */
passert(ugh == NULL);
passert(cur_state == NULL);
passert(st != NULL);
passert(st->st_suspended_md == dh->md);
set_suspended(st, NULL); /* no longer connected or suspended */
set_cur_state(st);
st->st_calculating = FALSE;
e = ikev2_parent_inR1outI2_tail(pcrc, r);
if (dh->md != NULL) {
complete_v2_state_transition(&dh->md, e);
if (dh->md)
release_md(dh->md);
}
reset_globals();
passert(GLOBALS_ARE_RESET());
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int pvc_getname(struct socket *sock, struct sockaddr *sockaddr,
int *sockaddr_len, int peer)
{
struct sockaddr_atmpvc *addr;
struct atm_vcc *vcc = ATM_SD(sock);
if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags))
return -ENOTCONN;
*sockaddr_len = sizeof(struct sockaddr_atmpvc);
addr = (struct sockaddr_atmpvc *)sockaddr;
addr->sap_family = AF_ATMPVC;
addr->sap_addr.itf = vcc->dev->number;
addr->sap_addr.vpi = vcc->vpi;
addr->sap_addr.vci = vcc->vci;
return 0;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: int DiskCacheBackendTest::GetEntryMetadataSize(std::string key) {
if (!simple_cache_mode_)
return key.size();
return disk_cache::kSimpleEntryStreamCount *
(sizeof(disk_cache::SimpleFileHeader) +
sizeof(disk_cache::SimpleFileEOF) + key.size());
}
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 send_event (int fd, uint16_t type, uint16_t code, int32_t value)
{
struct uinput_event event;
BTIF_TRACE_DEBUG("%s type:%u code:%u value:%d", __FUNCTION__,
type, code, value);
memset(&event, 0, sizeof(event));
event.type = type;
event.code = code;
event.value = value;
return write(fd, &event, sizeof(event));
}
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: UsbChooserContext::UsbChooserContext(Profile* profile)
: ChooserContextBase(profile,
CONTENT_SETTINGS_TYPE_USB_GUARD,
CONTENT_SETTINGS_TYPE_USB_CHOOSER_DATA),
is_incognito_(profile->IsOffTheRecord()),
client_binding_(this),
weak_factory_(this) {}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ofpact_decode_raw(enum ofp_version ofp_version,
const struct ofp_action_header *oah, size_t length,
const struct ofpact_raw_instance **instp)
{
const struct ofpact_raw_instance *inst;
struct ofpact_hdrs hdrs;
*instp = NULL;
if (length < sizeof *oah) {
return OFPERR_OFPBAC_BAD_LEN;
}
/* Get base action type. */
if (oah->type == htons(OFPAT_VENDOR)) {
/* Get vendor. */
hdrs.vendor = ntohl(oah->vendor);
if (hdrs.vendor == NX_VENDOR_ID || hdrs.vendor == ONF_VENDOR_ID) {
/* Get extension subtype. */
const struct ext_action_header *nah;
nah = ALIGNED_CAST(const struct ext_action_header *, oah);
if (length < sizeof *nah) {
return OFPERR_OFPBAC_BAD_LEN;
}
hdrs.type = ntohs(nah->subtype);
} else {
VLOG_WARN_RL(&rl, "OpenFlow action has unknown vendor %#"PRIx32,
hdrs.vendor);
return OFPERR_OFPBAC_BAD_VENDOR;
}
} else {
hdrs.vendor = 0;
hdrs.type = ntohs(oah->type);
}
hdrs.ofp_version = ofp_version;
HMAP_FOR_EACH_WITH_HASH (inst, decode_node, ofpact_hdrs_hash(&hdrs),
ofpact_decode_hmap()) {
if (ofpact_hdrs_equal(&hdrs, &inst->hdrs)) {
*instp = inst;
return 0;
}
}
return (hdrs.vendor
? OFPERR_OFPBAC_BAD_VENDOR_TYPE
: OFPERR_OFPBAC_BAD_TYPE);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void smp_task_done(struct sas_task *task)
{
if (!del_timer(&task->slow_task->timer))
return;
complete(&task->slow_task->completion);
}
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 const char *check_secret(int module, const char *user, const char *group,
const char *challenge, const char *pass)
{
char line[1024];
char pass2[MAX_DIGEST_LEN*2];
const char *fname = lp_secrets_file(module);
STRUCT_STAT st;
int fd, ok = 1;
int user_len = strlen(user);
int group_len = group ? strlen(group) : 0;
char *err;
if (!fname || !*fname || (fd = open(fname, O_RDONLY)) < 0)
return "no secrets file";
if (do_fstat(fd, &st) == -1) {
rsyserr(FLOG, errno, "fstat(%s)", fname);
ok = 0;
} else if (lp_strict_modes(module)) {
rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n");
ok = 0;
} else if (MY_UID() == 0 && st.st_uid != 0) {
rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n");
ok = 0;
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void RenderLayerCompositor::resetTrackedRepaintRects()
{
if (GraphicsLayer* rootLayer = rootGraphicsLayer())
resetTrackedRepaintRectsRecursive(rootLayer);
}
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 advance_rx_queue(struct sock *sk)
{
kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
}
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 struct dst_entry *inet6_csk_route_socket(struct sock *sk,
struct flowi6 *fl6)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *final_p, final;
struct dst_entry *dst;
memset(fl6, 0, sizeof(*fl6));
fl6->flowi6_proto = sk->sk_protocol;
fl6->daddr = sk->sk_v6_daddr;
fl6->saddr = np->saddr;
fl6->flowlabel = np->flow_label;
IP6_ECN_flow_xmit(sk, fl6->flowlabel);
fl6->flowi6_oif = sk->sk_bound_dev_if;
fl6->flowi6_mark = sk->sk_mark;
fl6->fl6_sport = inet->inet_sport;
fl6->fl6_dport = inet->inet_dport;
security_sk_classify_flow(sk, flowi6_to_flowi(fl6));
final_p = fl6_update_dst(fl6, np->opt, &final);
dst = __inet6_csk_dst_check(sk, np->dst_cookie);
if (!dst) {
dst = ip6_dst_lookup_flow(sk, fl6, final_p);
if (!IS_ERR(dst))
__inet6_csk_dst_store(sk, dst, NULL, NULL);
}
return dst;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: inline const InlineIterator& RenderBlock::restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight, FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver& resolver, const InlineIterator& oldEnd)
{
removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
setLogicalHeight(newLogicalHeight);
resolver.setPositionIgnoringNestedIsolates(oldEnd);
return oldEnd;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_skcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_skcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_skcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
atomic_set(&ctx->inflight, 0);
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
skcipher_request_set_tfm(&ctx->req, private);
skcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Textfield::OnFocus() {
GetRenderText()->set_focused(true);
if (ShouldShowCursor()) {
UpdateCursorViewPosition();
cursor_view_.SetVisible(true);
}
if (GetInputMethod())
GetInputMethod()->SetFocusedTextInputClient(this);
OnCaretBoundsChanged();
if (ShouldBlinkCursor())
StartBlinkingCursor();
if (use_focus_ring_) {
FocusRing::Install(this, invalid_
? ui::NativeTheme::kColorId_AlertSeverityHigh
: ui::NativeTheme::kColorId_NumColors);
}
SchedulePaint();
View::OnFocus();
}
CWE ID:
Target: 1
Example 2:
Code: void Con_RunConsole( void ) {
if ( Key_GetCatcher( ) & KEYCATCH_CONSOLE ) {
con.finalFrac = 0.5; // half screen
} else {
con.finalFrac = 0; // none visible
}
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac -= con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac > con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
} else if ( con.finalFrac > con.displayFrac ) {
con.displayFrac += con_conspeed->value * cls.realFrametime * 0.001;
if ( con.finalFrac < con.displayFrac ) {
con.displayFrac = con.finalFrac;
}
}
}
CWE ID: CWE-269
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DiscardAndExplicitlyReloadTest(DiscardReason reason) {
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true));
background_lifecycle_unit->Discard(reason);
testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false));
tab_strip_model_->GetWebContentsAt(0)->GetController().Reload(
content::ReloadType::NORMAL, false);
testing::Mock::VerifyAndClear(&tab_observer_);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ProfileSyncComponentsFactoryImpl::RegisterDataTypes(
ProfileSyncService* pss) {
if (!command_line_->HasSwitch(switches::kDisableSyncApps)) {
pss->RegisterDataTypeController(
new ExtensionDataTypeController(syncable::APPS, this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncAutofill)) {
pss->RegisterDataTypeController(
new AutofillDataTypeController(this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncBookmarks)) {
pss->RegisterDataTypeController(
new BookmarkDataTypeController(this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncExtensions)) {
pss->RegisterDataTypeController(
new ExtensionDataTypeController(syncable::EXTENSIONS,
this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncPasswords)) {
pss->RegisterDataTypeController(
new PasswordDataTypeController(this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncPreferences)) {
pss->RegisterDataTypeController(
new UIDataTypeController(syncable::PREFERENCES, this, profile_, pss));
}
#if defined(ENABLE_THEMES)
if (!command_line_->HasSwitch(switches::kDisableSyncThemes)) {
pss->RegisterDataTypeController(
new ThemeDataTypeController(this, profile_, pss));
}
#endif
if (!profile_->GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled) &&
!command_line_->HasSwitch(switches::kDisableSyncTypedUrls)) {
pss->RegisterDataTypeController(
new TypedUrlDataTypeController(this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncSearchEngines)) {
pss->RegisterDataTypeController(
new SearchEngineDataTypeController(this, profile_, pss));
}
pss->RegisterDataTypeController(
new SessionDataTypeController(this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncExtensionSettings)) {
pss->RegisterDataTypeController(
new ExtensionSettingDataTypeController(
syncable::EXTENSION_SETTINGS, this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncAppSettings)) {
pss->RegisterDataTypeController(
new ExtensionSettingDataTypeController(
syncable::APP_SETTINGS, this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncAutofillProfile)) {
pss->RegisterDataTypeController(
new AutofillProfileDataTypeController(this, profile_, pss));
}
if (!command_line_->HasSwitch(switches::kDisableSyncAppNotifications)) {
pss->RegisterDataTypeController(
new AppNotificationDataTypeController(this, profile_, pss));
}
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static void h2_recv(struct connection *conn)
{
struct h2c *h2c = conn->mux_ctx;
struct buffer *buf;
int max;
if (!h2_recv_allowed(h2c))
return;
buf = h2_get_buf(h2c, &h2c->dbuf);
if (!buf) {
h2c->flags |= H2_CF_DEM_DALLOC;
return;
}
/* note: buf->o == 0 */
max = buf->size - buf->i;
if (max)
conn->xprt->rcv_buf(conn, buf, max);
if (!buf->i) {
h2_release_buf(h2c, &h2c->dbuf);
return;
}
if (buf->i == buf->size)
h2c->flags |= H2_CF_DEM_DFULL;
return;
}
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 VRDisplay::BeginPresent() {
Document* doc = this->GetDocument();
if (capabilities_->hasExternalDisplay()) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError,
"VR Presentation not implemented for this VRDisplay.");
while (!pending_present_resolvers_.IsEmpty()) {
ScriptPromiseResolver* resolver = pending_present_resolvers_.TakeFirst();
resolver->Reject(exception);
}
ReportPresentationResult(
PresentationResult::kPresentationNotSupportedByDisplay);
return;
} else {
if (layer_.source().isHTMLCanvasElement()) {
} else {
DCHECK(layer_.source().isOffscreenCanvas());
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "OffscreenCanvas presentation not implemented.");
while (!pending_present_resolvers_.IsEmpty()) {
ScriptPromiseResolver* resolver =
pending_present_resolvers_.TakeFirst();
resolver->Reject(exception);
}
ReportPresentationResult(
PresentationResult::kPresentationNotSupportedByDisplay);
return;
}
}
if (doc) {
Platform::Current()->RecordRapporURL("VR.WebVR.PresentSuccess",
WebURL(doc->Url()));
}
is_presenting_ = true;
ReportPresentationResult(PresentationResult::kSuccess);
UpdateLayerBounds();
while (!pending_present_resolvers_.IsEmpty()) {
ScriptPromiseResolver* resolver = pending_present_resolvers_.TakeFirst();
resolver->Resolve();
}
OnPresentChange();
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderThreadImpl::EnsureWebKitInitialized() {
if (webkit_platform_support_.get())
return;
v8::V8::SetCounterFunction(base::StatsTable::FindLocation);
v8::V8::SetCreateHistogramFunction(CreateHistogram);
v8::V8::SetAddHistogramSampleFunction(AddHistogramSample);
webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl);
WebKit::initialize(webkit_platform_support_.get());
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableThreadedCompositing)) {
compositor_thread_.reset(new CompositorThread(this));
AddFilter(compositor_thread_->GetMessageFilter());
WebKit::WebCompositor::initialize(compositor_thread_->GetWebThread());
} else
WebKit::WebCompositor::initialize(NULL);
compositor_initialized_ = true;
WebScriptController::enableV8SingleThreadMode();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
webkit_glue::EnableWebCoreLogChannels(
command_line.GetSwitchValueASCII(switches::kWebCoreLogChannels));
if (command_line.HasSwitch(switches::kPlaybackMode) ||
command_line.HasSwitch(switches::kRecordMode) ||
command_line.HasSwitch(switches::kNoJsRandomness)) {
RegisterExtension(extensions_v8::PlaybackExtension::Get());
}
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDomAutomationController)) {
base::StringPiece extension = content::GetContentClient()->GetDataResource(
IDR_DOM_AUTOMATION_JS);
RegisterExtension(new v8::Extension(
"dom_automation.js", extension.data(), 0, NULL, extension.size()));
}
web_database_observer_impl_.reset(
new WebDatabaseObserverImpl(sync_message_filter()));
WebKit::WebDatabase::setObserver(web_database_observer_impl_.get());
WebRuntimeFeatures::enableSockets(
!command_line.HasSwitch(switches::kDisableWebSockets));
WebRuntimeFeatures::enableDatabase(
!command_line.HasSwitch(switches::kDisableDatabases));
WebRuntimeFeatures::enableDataTransferItems(
!command_line.HasSwitch(switches::kDisableDataTransferItems));
WebRuntimeFeatures::enableApplicationCache(
!command_line.HasSwitch(switches::kDisableApplicationCache));
WebRuntimeFeatures::enableNotifications(
!command_line.HasSwitch(switches::kDisableDesktopNotifications));
WebRuntimeFeatures::enableLocalStorage(
!command_line.HasSwitch(switches::kDisableLocalStorage));
WebRuntimeFeatures::enableSessionStorage(
!command_line.HasSwitch(switches::kDisableSessionStorage));
WebRuntimeFeatures::enableIndexedDatabase(true);
WebRuntimeFeatures::enableGeolocation(
!command_line.HasSwitch(switches::kDisableGeolocation));
WebKit::WebRuntimeFeatures::enableMediaSource(
command_line.HasSwitch(switches::kEnableMediaSource));
WebRuntimeFeatures::enableMediaPlayer(
media::IsMediaLibraryInitialized());
WebKit::WebRuntimeFeatures::enableMediaStream(
command_line.HasSwitch(switches::kEnableMediaStream));
WebKit::WebRuntimeFeatures::enableFullScreenAPI(
!command_line.HasSwitch(switches::kDisableFullScreen));
WebKit::WebRuntimeFeatures::enablePointerLock(
command_line.HasSwitch(switches::kEnablePointerLock));
WebKit::WebRuntimeFeatures::enableVideoTrack(
command_line.HasSwitch(switches::kEnableVideoTrack));
#if defined(OS_CHROMEOS)
WebRuntimeFeatures::enableWebAudio(false);
#else
WebRuntimeFeatures::enableWebAudio(
!command_line.HasSwitch(switches::kDisableWebAudio));
#endif
WebRuntimeFeatures::enablePushState(true);
WebRuntimeFeatures::enableTouch(
command_line.HasSwitch(switches::kEnableTouchEvents));
WebRuntimeFeatures::enableDeviceMotion(
command_line.HasSwitch(switches::kEnableDeviceMotion));
WebRuntimeFeatures::enableDeviceOrientation(
!command_line.HasSwitch(switches::kDisableDeviceOrientation));
WebRuntimeFeatures::enableSpeechInput(
!command_line.HasSwitch(switches::kDisableSpeechInput));
WebRuntimeFeatures::enableScriptedSpeech(
command_line.HasSwitch(switches::kEnableScriptedSpeech));
WebRuntimeFeatures::enableFileSystem(
!command_line.HasSwitch(switches::kDisableFileSystem));
WebRuntimeFeatures::enableJavaScriptI18NAPI(
!command_line.HasSwitch(switches::kDisableJavaScriptI18NAPI));
WebRuntimeFeatures::enableGamepad(
command_line.HasSwitch(switches::kEnableGamepad));
WebRuntimeFeatures::enableQuota(true);
WebRuntimeFeatures::enableShadowDOM(
command_line.HasSwitch(switches::kEnableShadowDOM));
WebRuntimeFeatures::enableStyleScoped(
command_line.HasSwitch(switches::kEnableStyleScoped));
FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized());
if (content::GetContentClient()->renderer()->
RunIdleHandlerWhenWidgetsHidden()) {
ScheduleIdleHandler(kLongIdleHandlerDelayMs);
}
}
CWE ID:
Target: 1
Example 2:
Code: WebRunnerContentBrowserClient::WebRunnerContentBrowserClient(
zx::channel context_channel)
: context_channel_(std::move(context_channel)) {}
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 WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame)
{
EAS_PCM *pOutputBuffer;
EAS_I32 phaseInc;
EAS_I32 phaseFrac;
EAS_I32 acc0;
const EAS_SAMPLE *pSamples;
EAS_I32 samp1;
EAS_I32 samp2;
EAS_I32 numSamples;
/* initialize some local variables */
numSamples = pWTIntFrame->numSamples;
pOutputBuffer = pWTIntFrame->pAudioBuffer;
phaseInc = pWTIntFrame->frame.phaseIncrement;
pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum;
phaseFrac = (EAS_I32)pWTVoice->phaseFrac;
/* fetch adjacent samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
while (numSamples--) {
/* linear interpolation */
acc0 = samp2 - samp1;
acc0 = acc0 * phaseFrac;
/*lint -e{704} <avoid divide>*/
acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS);
/* save new output sample in buffer */
/*lint -e{704} <avoid divide>*/
*pOutputBuffer++ = (EAS_I16)(acc0 >> 2);
/* increment phase */
phaseFrac += phaseInc;
/*lint -e{704} <avoid divide>*/
acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS;
/* next sample */
if (acc0 > 0) {
/* advance sample pointer */
pSamples += acc0;
phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK);
/* fetch new samples */
#if defined(_8_BIT_SAMPLES)
/*lint -e{701} <avoid multiply for performance>*/
samp1 = pSamples[0] << 8;
/*lint -e{701} <avoid multiply for performance>*/
samp2 = pSamples[1] << 8;
#else
samp1 = pSamples[0];
samp2 = pSamples[1];
#endif
}
}
/* save pointer and phase */
pWTVoice->phaseAccum = (EAS_U32) pSamples;
pWTVoice->phaseFrac = (EAS_U32) phaseFrac;
}
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 Reset() {
events_.clear();
tap_ = false;
tap_down_ = false;
tap_cancel_ = false;
begin_ = false;
end_ = false;
scroll_begin_ = false;
scroll_update_ = false;
scroll_end_ = false;
pinch_begin_ = false;
pinch_update_ = false;
pinch_end_ = false;
long_press_ = false;
fling_ = false;
two_finger_tap_ = false;
show_press_ = false;
swipe_left_ = false;
swipe_right_ = false;
swipe_up_ = false;
swipe_down_ = false;
scroll_begin_position_.SetPoint(0, 0);
tap_location_.SetPoint(0, 0);
gesture_end_location_.SetPoint(0, 0);
scroll_x_ = 0;
scroll_y_ = 0;
scroll_velocity_x_ = 0;
scroll_velocity_y_ = 0;
velocity_x_ = 0;
velocity_y_ = 0;
scroll_x_hint_ = 0;
scroll_y_hint_ = 0;
tap_count_ = 0;
scale_ = 0;
flags_ = 0;
}
CWE ID:
Target: 1
Example 2:
Code: static int mounts_open_common(struct inode *inode, struct file *file,
const struct seq_operations *op)
{
struct task_struct *task = get_proc_task(inode);
struct nsproxy *nsp;
struct mnt_namespace *ns = NULL;
struct path root;
struct proc_mounts *p;
int ret = -EINVAL;
if (task) {
rcu_read_lock();
nsp = task_nsproxy(task);
if (nsp) {
ns = nsp->mnt_ns;
if (ns)
get_mnt_ns(ns);
}
rcu_read_unlock();
if (ns && get_task_root(task, &root) == 0)
ret = 0;
put_task_struct(task);
}
if (!ns)
goto err;
if (ret)
goto err_put_ns;
ret = -ENOMEM;
p = kmalloc(sizeof(struct proc_mounts), GFP_KERNEL);
if (!p)
goto err_put_path;
file->private_data = &p->m;
ret = seq_open(file, op);
if (ret)
goto err_free;
p->m.private = p;
p->ns = ns;
p->root = root;
p->event = ns->event;
return 0;
err_free:
kfree(p);
err_put_path:
path_put(&root);
err_put_ns:
put_mnt_ns(ns);
err:
return ret;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int GetLastCursorType() const { return last_cursor_type_; }
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: int NsGetParameter(preproc_effect_t *effect,
void *pParam,
uint32_t *pValueSize,
void *pValue)
{
int status = 0;
return status;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: xmlParseNotationType(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
if (RAW != '(') {
xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
return(NULL);
}
SHRINK;
do {
NEXT;
SKIP_BLANKS;
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"Name expected in NOTATION declaration\n");
xmlFreeEnumeration(ret);
return(NULL);
}
tmp = ret;
while (tmp != NULL) {
if (xmlStrEqual(name, tmp->name)) {
xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
"standalone: attribute notation value token %s duplicated\n",
name, NULL);
if (!xmlDictOwns(ctxt->dict, name))
xmlFree((xmlChar *) name);
break;
}
tmp = tmp->next;
}
if (tmp == NULL) {
cur = xmlCreateEnumeration(name);
if (cur == NULL) {
xmlFreeEnumeration(ret);
return(NULL);
}
if (last == NULL) ret = last = cur;
else {
last->next = cur;
last = cur;
}
}
SKIP_BLANKS;
} while (RAW == '|');
if (RAW != ')') {
xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_FINISHED, NULL);
xmlFreeEnumeration(ret);
return(NULL);
}
NEXT;
return(ret);
}
CWE ID: CWE-611
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Texture::Invalidate() {
id_ = 0;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderFrameImpl::OnSelectPopupMenuItems(
bool canceled,
const std::vector<int>& selected_indices) {
if (!external_popup_menu_)
return;
blink::WebScopedUserGesture gesture(frame_);
external_popup_menu_->DidSelectItems(canceled, selected_indices);
external_popup_menu_.reset();
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: ft_smooth_set_mode( FT_Renderer render,
FT_ULong mode_tag,
FT_Pointer data )
{
/* we simply pass it to the raster */
return render->clazz->raster_class->raster_set_mode( render->raster,
mode_tag,
data );
}
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: spnego_gss_get_mic_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, gss_qop_t qop_req,
gss_iov_buffer_desc *iov, int iov_count)
{
return gss_get_mic_iov_length(minor_status, context_handle, qop_req, iov,
iov_count);
}
CWE ID: CWE-18
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 do_siocgstampns(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timespec kts;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts);
set_fs(old_fs);
if (!err)
err = compat_put_timespec(up, &kts);
return err;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void dentry_lru_add(struct dentry *dentry)
{
if (unlikely(!(dentry->d_flags & DCACHE_LRU_LIST)))
d_lru_add(dentry);
else if (unlikely(!(dentry->d_flags & DCACHE_REFERENCED)))
dentry->d_flags |= DCACHE_REFERENCED;
}
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: int BrowserMainLoop::PreCreateThreads() {
if (parts_) {
TRACE_EVENT0("startup",
"BrowserMainLoop::CreateThreads:PreCreateThreads");
result_code_ = parts_->PreCreateThreads();
}
if (!base::SequencedWorkerPool::IsEnabled())
base::SequencedWorkerPool::EnableForProcess();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
base::FeatureList::InitializeInstance(
command_line->GetSwitchValueASCII(switches::kEnableFeatures),
command_line->GetSwitchValueASCII(switches::kDisableFeatures));
InitializeMemoryManagementComponent();
#if defined(OS_MACOSX)
if (base::CommandLine::InitializedForCurrentProcess() &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableHeapProfiling)) {
base::allocator::PeriodicallyShimNewMallocZones();
}
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
{
TRACE_EVENT0("startup", "BrowserMainLoop::CreateThreads:PluginService");
PluginService::GetInstance()->Init();
}
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
CdmRegistry::GetInstance()->Init();
#endif
#if defined(OS_MACOSX)
ui::WindowResizeHelperMac::Get()->Init(base::ThreadTaskRunnerHandle::Get());
#endif
GpuDataManagerImpl* gpu_data_manager = GpuDataManagerImpl::GetInstance();
#if defined(USE_X11)
gpu_data_manager_visual_proxy_.reset(
new internal::GpuDataManagerVisualProxy(gpu_data_manager));
#endif
gpu_data_manager->Initialize();
#if !defined(GOOGLE_CHROME_BUILD) || defined(OS_ANDROID)
if (parsed_command_line_.HasSwitch(switches::kSingleProcess))
RenderProcessHost::SetRunRendererInProcess(true);
#endif
std::vector<url::Origin> origins =
GetContentClient()->browser()->GetOriginsRequiringDedicatedProcess();
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
for (auto origin : origins)
policy->AddIsolatedOrigin(origin);
EVP_set_buggy_rsa_parser(
base::FeatureList::IsEnabled(features::kBuggyRSAParser));
return result_code_;
}
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: email_close(FILE *mailer)
{
char *temp;
mode_t prev_umask;
priv_state priv;
char *customSig;
if ( mailer == NULL ) {
return;
}
/* Want the letter to come from "condor" if possible */
priv = set_condor_priv();
customSig = NULL;
if ((customSig = param("EMAIL_SIGNATURE")) != NULL) {
fprintf( mailer, "\n\n");
fprintf( mailer, customSig);
fprintf( mailer, "\n");
free(customSig);
} else {
/* Put a signature on the bottom of the email */
fprintf( mailer, "\n\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n" );
fprintf( mailer, "Questions about this message or Condor in general?\n" );
/* See if there's an address users should use for help */
temp = param( "CONDOR_SUPPORT_EMAIL" );
if( ! temp ) {
temp = param( "CONDOR_ADMIN" );
}
if( temp ) {
fprintf( mailer, "Email address of the local Condor administrator: "
"%s\n", temp );
free( temp );
}
fprintf( mailer, "The Official Condor Homepage is "
"http://www.cs.wisc.edu/condor\n" );
}
fflush(mailer);
/* there are some oddities with how pclose can close a file. In some
arches, pclose will create temp files for locking and they need to
be of the correct perms in order to be deleted. So the umask is
set to something useable for the close operation. -pete 9/11/99
*/
prev_umask = umask(022);
/*
** we fclose() on UNIX, pclose on win32
*/
#if defined(WIN32)
if (EMAIL_FINAL_COMMAND == NULL) {
my_pclose( mailer );
} else {
char *email_filename = NULL;
/* Should this be a pclose??? -Erik 9/21/00 */
fclose( mailer );
dprintf(D_FULLDEBUG,"Sending email via system(%s)\n",
EMAIL_FINAL_COMMAND);
system(EMAIL_FINAL_COMMAND);
if ( (email_filename=strrchr(EMAIL_FINAL_COMMAND,'<')) ) {
email_filename++; /* go past the "<" */
email_filename++; /* go past the space after the < */
if ( unlink(email_filename) == -1 ) {
dprintf(D_ALWAYS,"email_close: cannot unlink temp file %s\n",
email_filename);
}
}
free(EMAIL_FINAL_COMMAND);
EMAIL_FINAL_COMMAND = NULL;
}
#else
(void)fclose( mailer );
#endif
umask(prev_umask);
/* Set priv state back */
set_priv(priv);
}
CWE ID: CWE-134
Target: 1
Example 2:
Code: void advanceClock(double seconds)
{
m_elapsedSeconds += seconds;
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void OpenTwoTabs(const GURL& first_url, const GURL& second_url) {
content::WindowedNotificationObserver load1(
content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
content::NotificationService::AllSources());
OpenURLParams open1(first_url, content::Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false);
browser()->OpenURL(open1);
load1.Wait();
content::WindowedNotificationObserver load2(
content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
content::NotificationService::AllSources());
OpenURLParams open2(second_url, content::Referrer(),
WindowOpenDisposition::NEW_BACKGROUND_TAB,
ui::PAGE_TRANSITION_TYPED, false);
browser()->OpenURL(open2);
load2.Wait();
ASSERT_EQ(2, tsm()->count());
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void btsock_rfc_signaled(UNUSED_ATTR int fd, int flags, uint32_t user_id) {
pthread_mutex_lock(&slot_lock);
rfc_slot_t *slot = find_rfc_slot_by_id(user_id);
if (!slot)
goto out;
bool need_close = false;
if (flags & SOCK_THREAD_FD_RD && !slot->f.server) {
if (slot->f.connected) {
int size = 0;
if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(slot->fd, FIONREAD, &size) == 0 && size))
pthread_mutex_unlock(&slot_lock);
BTA_JvRfcommWrite(slot->rfc_handle, slot->id);
} else {
LOG_ERROR("%s socket signaled for read while disconnected, slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (flags & SOCK_THREAD_FD_WR) {
if (!slot->f.connected || !flush_incoming_que_on_wr_signal(slot)) {
LOG_ERROR("%s socket signaled for write while disconnected (or write failure), slot: %d, channel: %d", __func__, slot->id, slot->scn);
need_close = true;
}
}
if (need_close || (flags & SOCK_THREAD_FD_EXCEPTION)) {
int size = 0;
if (need_close || ioctl(slot->fd, FIONREAD, &size) != 0 || !size)
cleanup_rfc_slot(slot);
}
out:;
pthread_mutex_unlock(&slot_lock);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: MagickExport MagickBooleanType ModuleComponentGenesis(void)
{
ExceptionInfo
*exception;
MagickBooleanType
status;
if (module_semaphore == (SemaphoreInfo *) NULL)
module_semaphore=AllocateSemaphoreInfo();
exception=AcquireExceptionInfo();
status=IsModuleTreeInstantiated(exception);
exception=DestroyExceptionInfo(exception);
return(status);
}
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 update_exception_bitmap(struct kvm_vcpu *vcpu)
{
u32 eb;
eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
(1u << NM_VECTOR) | (1u << DB_VECTOR);
if ((vcpu->guest_debug &
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
(KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
eb |= 1u << BP_VECTOR;
if (to_vmx(vcpu)->rmode.vm86_active)
eb = ~0;
if (enable_ept)
eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
if (vcpu->fpu_active)
eb &= ~(1u << NM_VECTOR);
/* When we are running a nested L2 guest and L1 specified for it a
* certain exception bitmap, we must trap the same exceptions and pass
* them to L1. When running L2, we will only handle the exceptions
* specified above if L1 did not want them.
*/
if (is_guest_mode(vcpu))
eb |= get_vmcs12(vcpu)->exception_bitmap;
vmcs_write32(EXCEPTION_BITMAP, eb);
}
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: XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chstart;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chstart = ch;
chend = ch + (rlen + 1);
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
if (ch <= chend) {
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
}
}
CWE ID: CWE-682
Target: 1
Example 2:
Code: CanvasPattern* BaseRenderingContext2D::createPattern(
ScriptState* script_state,
const CanvasImageSourceUnion& image_source,
const String& repetition_type,
ExceptionState& exception_state) {
CanvasImageSource* image_source_internal =
ToImageSourceInternal(image_source, exception_state);
if (!image_source_internal) {
return nullptr;
}
return createPattern(script_state, image_source_internal, repetition_type,
exception_state);
}
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: PHP_METHOD(Phar, count)
{
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest));
}
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 const SSL_METHOD *ssl23_get_client_method(int ver)
{
#ifndef OPENSSL_NO_SSL2
if (ver == SSL2_VERSION)
return(SSLv2_client_method());
#endif
if (ver == SSL3_VERSION)
return(SSLv3_client_method());
else if (ver == TLS1_VERSION)
return(TLSv1_client_method());
else if (ver == TLS1_1_VERSION)
return(TLSv1_1_client_method());
else
return(NULL);
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: _TIFFNoPostDecode(TIFF* tif, uint8* buf, tmsize_t cc)
{
(void) tif; (void) buf; (void) cc;
}
CWE ID: CWE-369
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void snd_card_set_id_no_lock(struct snd_card *card, const char *src,
const char *nid)
{
int len, loops;
bool is_default = false;
char *id;
copy_valid_id_string(card, src, nid);
id = card->id;
again:
/* use "Default" for obviously invalid strings
* ("card" conflicts with proc directories)
*/
if (!*id || !strncmp(id, "card", 4)) {
strcpy(id, "Default");
is_default = true;
}
len = strlen(id);
for (loops = 0; loops < SNDRV_CARDS; loops++) {
char *spos;
char sfxstr[5]; /* "_012" */
int sfxlen;
if (card_id_ok(card, id))
return; /* OK */
/* Add _XYZ suffix */
sprintf(sfxstr, "_%X", loops + 1);
sfxlen = strlen(sfxstr);
if (len + sfxlen >= sizeof(card->id))
spos = id + sizeof(card->id) - sfxlen - 1;
else
spos = id + len;
strcpy(spos, sfxstr);
}
/* fallback to the default id */
if (!is_default) {
*id = 0;
goto again;
}
/* last resort... */
dev_err(card->dev, "unable to set card id (%s)\n", id);
if (card->proc_root->name)
strlcpy(card->id, card->proc_root->name, sizeof(card->id));
}
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: PHP_FUNCTION(mcrypt_get_iv_size)
{
char *cipher;
char *module;
int cipher_len, module_len;
char *cipher_dir_string;
char *module_dir_string;
MCRYPT td;
MCRYPT_GET_INI
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
&cipher, &cipher_len, &module, &module_len) == FAILURE) {
return;
}
td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
if (td != MCRYPT_FAILED) {
RETVAL_LONG(mcrypt_enc_get_iv_size(td));
mcrypt_module_close(td);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int em_sahf(struct x86_emulate_ctxt *ctxt)
{
u32 flags;
flags = EFLG_CF | EFLG_PF | EFLG_AF | EFLG_ZF | EFLG_SF;
flags &= *reg_rmw(ctxt, VCPU_REGS_RAX) >> 8;
ctxt->eflags &= ~0xffUL;
ctxt->eflags |= flags | X86_EFLAGS_FIXED;
return X86EMUL_CONTINUE;
}
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 SetPreviewDataForIndex(int index, const base::RefCountedBytes* data) {
if (index != printing::COMPLETE_PREVIEW_DOCUMENT_INDEX &&
index < printing::FIRST_PAGE_INDEX) {
return;
}
page_data_map_[index] = const_cast<base::RefCountedBytes*>(data);
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline int btif_hl_select_wake_reset(void){
char sig_recv = 0;
BTIF_TRACE_DEBUG("btif_hl_select_wake_reset");
recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL);
return(int)sig_recv;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: int dev_hard_start_xmit(struct sk_buff *skb, struct net_device *dev,
struct netdev_queue *txq)
{
const struct net_device_ops *ops = dev->netdev_ops;
int rc = NETDEV_TX_OK;
if (likely(!skb->next)) {
if (!list_empty(&ptype_all))
dev_queue_xmit_nit(skb, dev);
/*
* If device doesnt need skb->dst, release it right now while
* its hot in this cpu cache
*/
if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
skb_dst_drop(skb);
skb_orphan_try(skb);
if (netif_needs_gso(dev, skb)) {
if (unlikely(dev_gso_segment(skb)))
goto out_kfree_skb;
if (skb->next)
goto gso;
} else {
if (skb_needs_linearize(skb, dev) &&
__skb_linearize(skb))
goto out_kfree_skb;
/* If packet is not checksummed and device does not
* support checksumming for this protocol, complete
* checksumming here.
*/
if (skb->ip_summed == CHECKSUM_PARTIAL) {
skb_set_transport_header(skb, skb->csum_start -
skb_headroom(skb));
if (!dev_can_checksum(dev, skb) &&
skb_checksum_help(skb))
goto out_kfree_skb;
}
}
rc = ops->ndo_start_xmit(skb, dev);
if (rc == NETDEV_TX_OK)
txq_trans_update(txq);
return rc;
}
gso:
do {
struct sk_buff *nskb = skb->next;
skb->next = nskb->next;
nskb->next = NULL;
/*
* If device doesnt need nskb->dst, release it right now while
* its hot in this cpu cache
*/
if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
skb_dst_drop(nskb);
rc = ops->ndo_start_xmit(nskb, dev);
if (unlikely(rc != NETDEV_TX_OK)) {
if (rc & ~NETDEV_TX_MASK)
goto out_kfree_gso_skb;
nskb->next = skb->next;
skb->next = nskb;
return rc;
}
txq_trans_update(txq);
if (unlikely(netif_tx_queue_stopped(txq) && skb->next))
return NETDEV_TX_BUSY;
} while (skb->next);
out_kfree_gso_skb:
if (likely(skb->next == NULL))
skb->destructor = DEV_GSO_CB(skb)->destructor;
out_kfree_skb:
kfree_skb(skb);
return rc;
}
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: sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
{
int mxsize, cmd_size, k;
int input_size, blocking;
unsigned char opcode;
Sg_device *sdp;
Sg_fd *sfp;
Sg_request *srp;
struct sg_header old_hdr;
sg_io_hdr_t *hp;
unsigned char cmnd[SG_MAX_CDB_SIZE];
if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp,
"sg_write: count=%d\n", (int) count));
if (atomic_read(&sdp->detaching))
return -ENODEV;
if (!((filp->f_flags & O_NONBLOCK) ||
scsi_block_when_processing_errors(sdp->device)))
return -ENXIO;
if (!access_ok(VERIFY_READ, buf, count))
return -EFAULT; /* protects following copy_from_user()s + get_user()s */
if (count < SZ_SG_HEADER)
return -EIO;
if (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER))
return -EFAULT;
blocking = !(filp->f_flags & O_NONBLOCK);
if (old_hdr.reply_len < 0)
return sg_new_write(sfp, filp, buf, count,
blocking, 0, 0, NULL);
if (count < (SZ_SG_HEADER + 6))
return -EIO; /* The minimum scsi command length is 6 bytes. */
if (!(srp = sg_add_request(sfp))) {
SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sdp,
"sg_write: queue full\n"));
return -EDOM;
}
buf += SZ_SG_HEADER;
__get_user(opcode, buf);
if (sfp->next_cmd_len > 0) {
cmd_size = sfp->next_cmd_len;
sfp->next_cmd_len = 0; /* reset so only this write() effected */
} else {
cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */
if ((opcode >= 0xc0) && old_hdr.twelve_byte)
cmd_size = 12;
}
SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sdp,
"sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size));
/* Determine buffer size. */
input_size = count - cmd_size;
mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;
mxsize -= SZ_SG_HEADER;
input_size -= SZ_SG_HEADER;
if (input_size < 0) {
sg_remove_request(sfp, srp);
return -EIO; /* User did not pass enough bytes for this command. */
}
hp = &srp->header;
hp->interface_id = '\0'; /* indicator of old interface tunnelled */
hp->cmd_len = (unsigned char) cmd_size;
hp->iovec_count = 0;
hp->mx_sb_len = 0;
if (input_size > 0)
hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?
SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;
else
hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;
hp->dxfer_len = mxsize;
if ((hp->dxfer_direction == SG_DXFER_TO_DEV) ||
(hp->dxfer_direction == SG_DXFER_TO_FROM_DEV))
hp->dxferp = (char __user *)buf + cmd_size;
else
hp->dxferp = NULL;
hp->sbp = NULL;
hp->timeout = old_hdr.reply_len; /* structure abuse ... */
hp->flags = input_size; /* structure abuse ... */
hp->pack_id = old_hdr.pack_id;
hp->usr_ptr = NULL;
if (__copy_from_user(cmnd, buf, cmd_size))
return -EFAULT;
/*
* SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,
* but is is possible that the app intended SG_DXFER_TO_DEV, because there
* is a non-zero input_size, so emit a warning.
*/
if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) {
static char cmd[TASK_COMM_LEN];
if (strcmp(current->comm, cmd)) {
printk_ratelimited(KERN_WARNING
"sg_write: data in/out %d/%d bytes "
"for SCSI command 0x%x-- guessing "
"data in;\n program %s not setting "
"count and/or reply_len properly\n",
old_hdr.reply_len - (int)SZ_SG_HEADER,
input_size, (unsigned int) cmnd[0],
current->comm);
strcpy(cmd, current->comm);
}
}
k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);
return (k < 0) ? k : count;
}
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: write_message( RenderState state )
{
ADisplay adisplay = (ADisplay)state->display.disp;
if ( state->message == NULL )
{
FontFace face = &state->faces[state->face_index];
int idx, total;
idx = face->index;
total = 1;
while ( total + state->face_index < state->num_faces &&
face[total].filepath == face[0].filepath )
total++;
total += idx;
state->message = state->message0;
if ( total > 1 )
sprintf( state->message0, "%s %d/%d @ %5.1fpt",
state->filename, idx + 1, total,
state->char_size );
else
sprintf( state->message0, "%s @ %5.1fpt",
state->filename,
state->char_size );
}
grWriteCellString( adisplay->bitmap, 0, DIM_Y - 10, state->message,
adisplay->fore_color );
state->message = NULL;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ResourceDispatcherHostImpl::RemovePendingLoader(
const LoaderMap::iterator& iter) {
ResourceRequestInfoImpl* info = iter->second->GetRequestInfo();
if (info->keepalive())
keepalive_statistics_recorder_.OnLoadFinished(info->GetChildID());
IncrementOutstandingRequestsMemory(-1, *info);
pending_loaders_.erase(iter);
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int ip_options_get(struct net *net, struct ip_options **optp,
unsigned char *data, int optlen)
{
struct ip_options *opt = ip_options_get_alloc(optlen);
if (!opt)
return -ENOMEM;
if (optlen)
memcpy(opt->__data, data, optlen);
return ip_options_get_finish(net, optp, opt, optlen);
}
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: PHP_METHOD(snmp, setSecurity)
{
php_snmp_object *snmp_object;
zval *object = getThis();
char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = "";
int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0;
int argc = ZEND_NUM_ARGS();
snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC);
if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len,
&a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) {
RETURN_FALSE;
}
if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) {
/* Warning message sent already, just bail out */
RETURN_FALSE;
}
RETURN_TRUE;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static PassOwnPtr<LocalErrorCallback> create(FileError::ErrorCode& errorCode)
{
return adoptPtr(new LocalErrorCallback(errorCode));
}
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 jlong Region_createFromParcel(JNIEnv* env, jobject clazz, jobject parcel)
{
if (parcel == NULL) {
return NULL;
}
android::Parcel* p = android::parcelForJavaObject(env, parcel);
const size_t size = p->readInt32();
const void* regionData = p->readInplace(size);
if (regionData == NULL) {
return NULL;
}
SkRegion* region = new SkRegion;
region->readFromMemory(regionData, size);
return reinterpret_cast<jlong>(region);
}
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int netbk_count_requests(struct xenvif *vif,
struct xen_netif_tx_request *first,
struct xen_netif_tx_request *txp,
int work_to_do)
{
RING_IDX cons = vif->tx.req_cons;
int frags = 0;
if (!(first->flags & XEN_NETTXF_more_data))
return 0;
do {
if (frags >= work_to_do) {
netdev_dbg(vif->dev, "Need more frags\n");
return -frags;
}
if (unlikely(frags >= MAX_SKB_FRAGS)) {
netdev_dbg(vif->dev, "Too many frags\n");
return -frags;
}
memcpy(txp, RING_GET_REQUEST(&vif->tx, cons + frags),
sizeof(*txp));
if (txp->size > first->size) {
netdev_dbg(vif->dev, "Frags galore\n");
return -frags;
}
first->size -= txp->size;
frags++;
if (unlikely((txp->offset + txp->size) > PAGE_SIZE)) {
netdev_dbg(vif->dev, "txp->offset: %x, size: %u\n",
txp->offset, txp->size);
return -frags;
}
} while ((txp++)->flags & XEN_NETTXF_more_data);
return frags;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void cm_free_msg(struct ib_mad_send_buf *msg)
{
ib_destroy_ah(msg->ah);
if (msg->context[0])
cm_deref_id(msg->context[0]);
ib_free_send_mad(msg);
}
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: PassRefPtr<HTMLCollection> HTMLSelectElement::selectedOptions()
{
updateListItemSelectedStates();
return ensureCachedHTMLCollection(SelectedOptions);
}
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: horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
assert((cc%(4*stride))==0);
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& es)
{
if (m_state >= LOADING) {
es.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type cannot be set if the object's state is LOADING or DONE."));
return;
}
if (!m_async && scriptExecutionContext()->isDocument() && m_url.protocolIsInHTTPFamily()) {
es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type can only be changed for asynchronous HTTP requests made from a document."));
return;
}
if (responseType == "") {
m_responseTypeCode = ResponseTypeDefault;
} else if (responseType == "text") {
m_responseTypeCode = ResponseTypeText;
} else if (responseType == "json") {
m_responseTypeCode = ResponseTypeJSON;
} else if (responseType == "document") {
m_responseTypeCode = ResponseTypeDocument;
} else if (responseType == "blob") {
m_responseTypeCode = ResponseTypeBlob;
} else if (responseType == "arraybuffer") {
m_responseTypeCode = ResponseTypeArrayBuffer;
} else if (responseType == "stream") {
if (RuntimeEnabledFeatures::streamEnabled())
m_responseTypeCode = ResponseTypeStream;
else
return;
} else {
ASSERT_NOT_REACHED();
}
}
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 ImageInputType::ensurePrimaryContent()
{
if (!m_useFallbackContent)
return;
m_useFallbackContent = false;
reattachFallbackContent();
}
CWE ID: CWE-361
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: ScriptPromise BluetoothRemoteGATTCharacteristic::getDescriptorsImpl(
ScriptState* scriptState,
mojom::blink::WebBluetoothGATTQueryQuantity quantity,
const String& descriptor) {
if (!getGatt()->connected()) {
return ScriptPromise::rejectWithDOMException(
scriptState,
BluetoothRemoteGATTUtils::CreateDOMException(
BluetoothRemoteGATTUtils::ExceptionType::kGATTServerNotConnected));
}
if (!getGatt()->device()->isValidCharacteristic(
m_characteristic->instance_id)) {
return ScriptPromise::rejectWithDOMException(
scriptState,
BluetoothRemoteGATTUtils::CreateDOMException(
BluetoothRemoteGATTUtils::ExceptionType::kInvalidCharacteristic));
}
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
getGatt()->AddToActiveAlgorithms(resolver);
mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service();
WTF::Optional<String> uuid = WTF::nullopt;
if (!descriptor.isEmpty())
uuid = descriptor;
service->RemoteCharacteristicGetDescriptors(
m_characteristic->instance_id, quantity, uuid,
convertToBaseCallback(
WTF::bind(&BluetoothRemoteGATTCharacteristic::GetDescriptorsCallback,
wrapPersistent(this), m_characteristic->instance_id,
quantity, wrapPersistent(resolver))));
return promise;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void nfs4_destroy_slot_tables(struct nfs4_session *session)
{
if (session->fc_slot_table.slots != NULL) {
kfree(session->fc_slot_table.slots);
session->fc_slot_table.slots = NULL;
}
if (session->bc_slot_table.slots != NULL) {
kfree(session->bc_slot_table.slots);
session->bc_slot_table.slots = NULL;
}
return;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void LocalFileSystem::fileSystemAllowedInternal(
PassRefPtrWillBeRawPtr<ExecutionContext> context,
FileSystemType type,
PassRefPtr<CallbackWrapper> callbacks)
{
if (!fileSystem()) {
fileSystemNotAvailable(context, callbacks);
return;
}
KURL storagePartition = KURL(KURL(), context->securityOrigin()->toString());
fileSystem()->openFileSystem(storagePartition, static_cast<WebFileSystemType>(type), callbacks->release());
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FileReaderLoader::OnCalculatedSize(uint64_t total_size,
uint64_t expected_content_size) {
OnStartLoading(expected_content_size);
if (expected_content_size == 0) {
received_all_data_ = true;
return;
}
if (IsSyncLoad()) {
OnDataPipeReadable(MOJO_RESULT_OK);
} else {
handle_watcher_.Watch(
consumer_handle_.get(), MOJO_HANDLE_SIGNAL_READABLE,
WTF::BindRepeating(&FileReaderLoader::OnDataPipeReadable,
WTF::Unretained(this)));
}
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: PageCaptureSaveAsMHTMLFunction::PageCaptureSaveAsMHTMLFunction() {
}
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 IsLightOrSwitch(const int devType, const int subType)
{
bool bIsLightSwitch = false;
switch (devType)
{
case pTypeLighting1:
case pTypeLighting2:
case pTypeLighting3:
case pTypeLighting4:
case pTypeLighting5:
case pTypeLighting6:
case pTypeFan:
case pTypeColorSwitch:
case pTypeSecurity1:
case pTypeSecurity2:
case pTypeCurtain:
case pTypeBlinds:
case pTypeRFY:
case pTypeThermostat2:
case pTypeThermostat3:
case pTypeThermostat4:
case pTypeRemote:
case pTypeGeneralSwitch:
case pTypeHomeConfort:
case pTypeFS20:
bIsLightSwitch = true;
break;
case pTypeRadiator1:
bIsLightSwitch = (subType == sTypeSmartwaresSwitchRadiator);
break;
}
return bIsLightSwitch;
}
CWE ID: CWE-93
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: sctp_disposition_t sctp_sf_ootb(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sk_buff *skb = chunk->skb;
sctp_chunkhdr_t *ch;
sctp_errhdr_t *err;
__u8 *ch_end;
int ootb_shut_ack = 0;
int ootb_cookie_ack = 0;
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
ch = (sctp_chunkhdr_t *) chunk->chunk_hdr;
do {
/* Report violation if the chunk is less then minimal */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* Now that we know we at least have a chunk header,
* do things that are type appropriate.
*/
if (SCTP_CID_SHUTDOWN_ACK == ch->type)
ootb_shut_ack = 1;
/* RFC 2960, Section 3.3.7
* Moreover, under any circumstances, an endpoint that
* receives an ABORT MUST NOT respond to that ABORT by
* sending an ABORT of its own.
*/
if (SCTP_CID_ABORT == ch->type)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR
* or a COOKIE ACK the SCTP Packet should be silently
* discarded.
*/
if (SCTP_CID_COOKIE_ACK == ch->type)
ootb_cookie_ack = 1;
if (SCTP_CID_ERROR == ch->type) {
sctp_walk_errors(err, ch) {
if (SCTP_ERROR_STALE_COOKIE == err->cause) {
ootb_cookie_ack = 1;
break;
}
}
}
/* Report violation if chunk len overflows */
ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
ch = (sctp_chunkhdr_t *) ch_end;
} while (ch_end < skb_tail_pointer(skb));
if (ootb_shut_ack)
return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands);
else if (ootb_cookie_ack)
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
else
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: int __weak phys_mem_access_prot_allowed(struct file *file,
unsigned long pfn, unsigned long size, pgprot_t *vma_prot)
{
return 1;
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::unique_ptr<FormStructure> AutofillManager::ValidateSubmittedForm(
const FormData& form) {
std::unique_ptr<FormStructure> submitted_form(
std::make_unique<FormStructure>(form));
if (!ShouldUploadForm(*submitted_form))
return std::unique_ptr<FormStructure>();
FormStructure* cached_submitted_form;
if (!FindCachedForm(form, &cached_submitted_form))
return std::unique_ptr<FormStructure>();
submitted_form->RetrieveFromCache(*cached_submitted_form,
/*apply_is_autofilled=*/false,
/*only_server_and_autofill_state=*/false);
return submitted_form;
}
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: long long Chapters::Atom::GetStopTimecode() const
{
return m_stop_timecode;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: unsigned int inet_addr_type_table(struct net *net, __be32 addr, u32 tb_id)
{
return __inet_dev_addr_type(net, NULL, addr, tb_id);
}
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 RenderWidgetHostViewAura::SetOverscrollControllerEnabled(bool enabled) {
if (!enabled)
overscroll_controller_.reset();
else if (!overscroll_controller_)
overscroll_controller_.reset(new OverscrollController());
}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int handle_vmptrst(struct kvm_vcpu *vcpu)
{
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t vmcs_gva;
struct x86_exception e;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &vmcs_gva))
return 1;
/* ok to use *_system, as hardware has verified cpl=0 */
if (kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, vmcs_gva,
(void *)&to_vmx(vcpu)->nested.current_vmptr,
sizeof(u64), &e)) {
kvm_inject_page_fault(vcpu, &e);
return 1;
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
CWE ID:
Target: 1
Example 2:
Code: static long hi3660_stub_clk_round_rate(struct clk_hw *hw, unsigned long rate,
unsigned long *prate)
{
/*
* LPM3 handles rate rounding so just return whatever
* rate is requested.
*/
return rate;
}
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 uint32_t i6300esb_mem_readb(void *vp, hwaddr addr)
{
i6300esb_debug ("addr = %x\n", (int) addr);
return 0;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: char *cJSON_PrintUnformatted( cJSON *item )
{
return print_value( item, 0, 0 );
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: LayerTreeHostTestContinuousInvalidate()
: num_commit_complete_(0), num_draw_layers_(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: sp<IMemoryHeap> BpMemory::getMemory(ssize_t* offset, size_t* size) const
{
if (mHeap == 0) {
Parcel data, reply;
data.writeInterfaceToken(IMemory::getInterfaceDescriptor());
if (remote()->transact(GET_MEMORY, data, &reply) == NO_ERROR) {
sp<IBinder> heap = reply.readStrongBinder();
ssize_t o = reply.readInt32();
size_t s = reply.readInt32();
if (heap != 0) {
mHeap = interface_cast<IMemoryHeap>(heap);
if (mHeap != 0) {
mOffset = o;
mSize = s;
}
}
}
}
if (offset) *offset = mOffset;
if (size) *size = mSize;
return mHeap;
}
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: mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int group, nsrcs, ngroups;
u_int i, j;
/* Minimum len is 8 */
if (len < 8) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[1]);
ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]);
ND_PRINT((ndo,", %d group record(s)", ngroups));
if (ndo->ndo_vflag > 0) {
/* Print the group records */
group = 8;
for (i = 0; i < ngroups; i++) {
/* type(1) + auxlen(1) + numsrc(2) + grp(16) */
if (len < group + 20) {
ND_PRINT((ndo," [invalid number of groups]"));
return;
}
ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4])));
ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]",
bp[group])));
nsrcs = (bp[group + 2] << 8) + bp[group + 3];
/* Check the number of sources and print them */
if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) {
ND_PRINT((ndo," [invalid number of sources %d]", nsrcs));
return;
}
if (ndo->ndo_vflag == 1)
ND_PRINT((ndo,", %d source(s)", nsrcs));
else {
/* Print the sources */
ND_PRINT((ndo," {"));
for (j = 0; j < nsrcs; j++) {
ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
}
/* Next group record */
group += 20 + nsrcs * sizeof(struct in6_addr);
ND_PRINT((ndo,"]"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static u32 md_csum_fold(u32 csum)
{
csum = (csum & 0xffff) + (csum >> 16);
return (csum & 0xffff) + (csum >> 16);
}
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 Framebuffer::MarkAttachmentAsCleared(
RenderbufferManager* renderbuffer_manager,
TextureManager* texture_manager,
GLenum attachment,
bool cleared) {
AttachmentMap::iterator it = attachments_.find(attachment);
if (it != attachments_.end()) {
Attachment* a = it->second.get();
if (a->cleared() != cleared) {
a->SetCleared(renderbuffer_manager,
texture_manager,
cleared);
}
}
}
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: SYSCALL_DEFINE2(timerfd_create, int, clockid, int, flags)
{
int ufd;
struct timerfd_ctx *ctx;
/* Check the TFD_* constants for consistency. */
BUILD_BUG_ON(TFD_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(TFD_NONBLOCK != O_NONBLOCK);
if ((flags & ~TFD_CREATE_FLAGS) ||
(clockid != CLOCK_MONOTONIC &&
clockid != CLOCK_REALTIME &&
clockid != CLOCK_REALTIME_ALARM &&
clockid != CLOCK_BOOTTIME &&
clockid != CLOCK_BOOTTIME_ALARM))
return -EINVAL;
if (!capable(CAP_WAKE_ALARM) &&
(clockid == CLOCK_REALTIME_ALARM ||
clockid == CLOCK_BOOTTIME_ALARM))
return -EPERM;
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
init_waitqueue_head(&ctx->wqh);
ctx->clockid = clockid;
if (isalarm(ctx))
alarm_init(&ctx->t.alarm,
ctx->clockid == CLOCK_REALTIME_ALARM ?
ALARM_REALTIME : ALARM_BOOTTIME,
timerfd_alarmproc);
else
hrtimer_init(&ctx->t.tmr, clockid, HRTIMER_MODE_ABS);
ctx->moffs = ktime_mono_to_real(0);
ufd = anon_inode_getfd("[timerfd]", &timerfd_fops, ctx,
O_RDWR | (flags & TFD_SHARED_FCNTL_FLAGS));
if (ufd < 0)
kfree(ctx);
return ufd;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void r_bin_mdmp_free(struct r_bin_mdmp_obj *obj) {
if (!obj) return;
r_list_free (obj->streams.ex_threads);
r_list_free (obj->streams.memories);
r_list_free (obj->streams.memories64.memories);
r_list_free (obj->streams.memory_infos);
r_list_free (obj->streams.modules);
r_list_free (obj->streams.operations);
r_list_free (obj->streams.thread_infos);
r_list_free (obj->streams.threads);
r_list_free (obj->streams.unloaded_modules);
r_list_free (obj->pe32_bins);
r_list_free (obj->pe64_bins);
r_buf_free (obj->b);
obj->b = NULL;
free (obj);
return;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GpuProcessHost::OnProcessLaunched() {
base::ProcessHandle child_handle = in_process_ ?
base::GetCurrentProcessHandle() : process_->GetData().handle;
#if defined(OS_WIN)
DuplicateHandle(base::GetCurrentProcessHandle(),
child_handle,
base::GetCurrentProcessHandle(),
&gpu_process_,
PROCESS_DUP_HANDLE,
FALSE,
0);
#else
gpu_process_ = child_handle;
#endif
UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime",
base::TimeTicks::Now() - init_start_time_);
}
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: v8::Handle<v8::Value> V8WebGLRenderingContext::getAttachedShadersCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebGLRenderingContext.getAttachedShaders()");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLProgram::HasInstance(args[0])) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
WebGLProgram* program = V8WebGLProgram::HasInstance(args[0]) ? V8WebGLProgram::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0;
Vector<RefPtr<WebGLShader> > shaders;
bool succeed = context->getAttachedShaders(program, shaders, ec);
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Null();
}
if (!succeed)
return v8::Null();
v8::Local<v8::Array> array = v8::Array::New(shaders.size());
for (size_t ii = 0; ii < shaders.size(); ++ii)
array->Set(v8::Integer::New(ii), toV8(shaders[ii].get(), args.GetIsolate()));
return array;
}
CWE ID:
Target: 1
Example 2:
Code: process_persistent_configs()
{
char *tmp = NULL;
int rval;
bool processed = false;
if( access( toplevel_persistent_config.Value(), R_OK ) == 0 &&
PersistAdminList.number() == 0 )
{
processed = true;
rval = Read_config( toplevel_persistent_config.Value(), ConfigTab,
TABLESIZE, EXPAND_LAZY, true, extra_info );
if (rval < 0) {
dprintf( D_ALWAYS, "Configuration Error Line %d while reading "
"top-level persistent config source: %s\n",
ConfigLineNo, toplevel_persistent_config.Value() );
exit(1);
}
tmp = param ("RUNTIME_CONFIG_ADMIN");
if (tmp) {
PersistAdminList.initializeFromString(tmp);
free(tmp);
}
}
PersistAdminList.rewind();
while ((tmp = PersistAdminList.next())) {
processed = true;
MyString config_source;
config_source.sprintf( "%s.%s", toplevel_persistent_config.Value(),
tmp );
rval = Read_config( config_source.Value(), ConfigTab, TABLESIZE,
EXPAND_LAZY, true, extra_info );
if (rval < 0) {
dprintf( D_ALWAYS, "Configuration Error Line %d "
"while reading persistent config source: %s\n",
ConfigLineNo, config_source.Value() );
exit(1);
}
}
return (int)processed;
}
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: static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
nodemask_t *nodes)
{
unsigned long copy = ALIGN(maxnode-1, 64) / 8;
const int nbytes = BITS_TO_LONGS(MAX_NUMNODES) * sizeof(long);
if (copy > nbytes) {
if (copy > PAGE_SIZE)
return -EINVAL;
if (clear_user((char __user *)mask + nbytes, copy - nbytes))
return -EFAULT;
copy = nbytes;
}
return copy_to_user(mask, nodes_addr(*nodes), copy) ? -EFAULT : 0;
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length)
{
struct pipe_vertex_element *ve = NULL;
int num_elements;
int i;
int ret;
if (length < 1)
return EINVAL;
if ((length - 1) % 4)
return EINVAL;
num_elements = (length - 1) / 4;
if (num_elements) {
ve = calloc(num_elements, sizeof(struct pipe_vertex_element));
if (!ve)
return ENOMEM;
for (i = 0; i < num_elements; i++) {
ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i));
ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i));
ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i));
ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i));
}
}
return ret;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static inline void add_offset_pair(zval *result, char *str, int len, int offset, char *name)
{
zval *match_pair;
ALLOC_ZVAL(match_pair);
array_init(match_pair);
INIT_PZVAL(match_pair);
/* Add (match, offset) to the return value */
add_next_index_stringl(match_pair, str, len, 1);
add_next_index_long(match_pair, offset);
if (name) {
zval_add_ref(&match_pair);
zend_hash_update(Z_ARRVAL_P(result), name, strlen(name)+1, &match_pair, sizeof(zval *), NULL);
}
zend_hash_next_index_insert(Z_ARRVAL_P(result), &match_pair, sizeof(zval *), NULL);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
{
vmx_vcpu_pi_put(vcpu);
__vmx_load_host_state(to_vmx(vcpu));
if (!vmm_exclusive) {
__loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
vcpu->cpu = -1;
kvm_cpu_vmxoff();
}
}
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: svcauth_gss_accept_sec_context(struct svc_req *rqst,
struct rpc_gss_init_res *gr)
{
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
gss_buffer_desc recv_tok, seqbuf;
gss_OID mech;
OM_uint32 maj_stat = 0, min_stat = 0, ret_flags, seq;
log_debug("in svcauth_gss_accept_context()");
gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gr, 0, sizeof(*gr));
/* Deserialize arguments. */
memset(&recv_tok, 0, sizeof(recv_tok));
if (!svc_getargs(rqst->rq_xprt, xdr_rpc_gss_init_args,
(caddr_t)&recv_tok))
return (FALSE);
gr->gr_major = gss_accept_sec_context(&gr->gr_minor,
&gd->ctx,
svcauth_gss_creds,
&recv_tok,
GSS_C_NO_CHANNEL_BINDINGS,
&gd->client_name,
&mech,
&gr->gr_token,
&ret_flags,
NULL,
NULL);
svc_freeargs(rqst->rq_xprt, xdr_rpc_gss_init_args, (caddr_t)&recv_tok);
log_status("accept_sec_context", gr->gr_major, gr->gr_minor);
if (gr->gr_major != GSS_S_COMPLETE &&
gr->gr_major != GSS_S_CONTINUE_NEEDED) {
badauth(gr->gr_major, gr->gr_minor, rqst->rq_xprt);
gd->ctx = GSS_C_NO_CONTEXT;
goto errout;
}
/*
* ANDROS: krb5 mechglue returns ctx of size 8 - two pointers,
* one to the mechanism oid, one to the internal_ctx_id
*/
if ((gr->gr_ctx.value = mem_alloc(sizeof(gss_union_ctx_id_desc))) == NULL) {
fprintf(stderr, "svcauth_gss_accept_context: out of memory\n");
goto errout;
}
memcpy(gr->gr_ctx.value, gd->ctx, sizeof(gss_union_ctx_id_desc));
gr->gr_ctx.length = sizeof(gss_union_ctx_id_desc);
/* gr->gr_win = 0x00000005; ANDROS: for debugging linux kernel version... */
gr->gr_win = sizeof(gd->seqmask) * 8;
/* Save client info. */
gd->sec.mech = mech;
gd->sec.qop = GSS_C_QOP_DEFAULT;
gd->sec.svc = gc->gc_svc;
gd->seq = gc->gc_seq;
gd->win = gr->gr_win;
if (gr->gr_major == GSS_S_COMPLETE) {
#ifdef SPKM
/* spkm3: no src_name (anonymous) */
if(!g_OID_equal(gss_mech_spkm3, mech)) {
#endif
maj_stat = gss_display_name(&min_stat, gd->client_name,
&gd->cname, &gd->sec.mech);
#ifdef SPKM
}
#endif
if (maj_stat != GSS_S_COMPLETE) {
log_status("display_name", maj_stat, min_stat);
goto errout;
}
#ifdef DEBUG
#ifdef HAVE_HEIMDAL
log_debug("accepted context for %.*s with "
"<mech {}, qop %d, svc %d>",
gd->cname.length, (char *)gd->cname.value,
gd->sec.qop, gd->sec.svc);
#else
{
gss_buffer_desc mechname;
gss_oid_to_str(&min_stat, mech, &mechname);
log_debug("accepted context for %.*s with "
"<mech %.*s, qop %d, svc %d>",
gd->cname.length, (char *)gd->cname.value,
mechname.length, (char *)mechname.value,
gd->sec.qop, gd->sec.svc);
gss_release_buffer(&min_stat, &mechname);
}
#endif
#endif /* DEBUG */
seq = htonl(gr->gr_win);
seqbuf.value = &seq;
seqbuf.length = sizeof(seq);
gss_release_buffer(&min_stat, &gd->checksum);
maj_stat = gss_sign(&min_stat, gd->ctx, GSS_C_QOP_DEFAULT,
&seqbuf, &gd->checksum);
if (maj_stat != GSS_S_COMPLETE) {
goto errout;
}
rqst->rq_xprt->xp_verf.oa_flavor = RPCSEC_GSS;
rqst->rq_xprt->xp_verf.oa_base = gd->checksum.value;
rqst->rq_xprt->xp_verf.oa_length = gd->checksum.length;
}
return (TRUE);
errout:
gss_release_buffer(&min_stat, &gr->gr_token);
return (FALSE);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool MockContentSettingsClient::allowScript(bool enabled_per_settings) {
return enabled_per_settings && flags_->scripts_allowed();
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL)
return cdf_read_short_sector_chain(h, ssat, sst, sid, len,
scn);
else
return cdf_read_long_sector_chain(info, h, sat, sid, len, scn);
}
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: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_MODERATELY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ =
icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
transliterator_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d; ӏ > l; [кĸκ] > k; п > n;"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int max_bfregs(struct mlx5_ib_dev *dev, struct mlx5_bfreg_info *bfregi)
{
return get_num_static_uars(dev, bfregi) * MLX5_NON_FP_BFREGS_PER_UAR;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void ext4_xattr_shift_entries(struct ext4_xattr_entry *entry,
int value_offs_shift, void *to,
void *from, size_t n, int blocksize)
{
struct ext4_xattr_entry *last = entry;
int new_offs;
/* Adjust the value offsets of the entries */
for (; !IS_LAST_ENTRY(last); last = EXT4_XATTR_NEXT(last)) {
if (!last->e_value_block && last->e_value_size) {
new_offs = le16_to_cpu(last->e_value_offs) +
value_offs_shift;
BUG_ON(new_offs + le32_to_cpu(last->e_value_size)
> blocksize);
last->e_value_offs = cpu_to_le16(new_offs);
}
}
/* Shift the entries by n bytes */
memmove(to, from, n);
}
CWE ID: CWE-19
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: _gcry_ecc_ecdsa_sign (gcry_mpi_t input, ECC_secret_key *skey,
gcry_mpi_t r, gcry_mpi_t s,
int flags, int hashalgo)
{
gpg_err_code_t rc = 0;
int extraloops = 0;
gcry_mpi_t k, dr, sum, k_1, x;
mpi_point_struct I;
gcry_mpi_t hash;
const void *abuf;
unsigned int abits, qbits;
mpi_ec_t ctx;
if (DBG_CIPHER)
log_mpidump ("ecdsa sign hash ", input );
/* Convert the INPUT into an MPI if needed. */
rc = _gcry_dsa_normalize_hash (input, &hash, qbits);
if (rc)
return rc;
if (rc)
return rc;
k = NULL;
dr = mpi_alloc (0);
sum = mpi_alloc (0);
{
do
{
mpi_free (k);
k = NULL;
if ((flags & PUBKEY_FLAG_RFC6979) && hashalgo)
{
/* Use Pornin's method for deterministic DSA. If this
flag is set, it is expected that HASH is an opaque
MPI with the to be signed hash. That hash is also
used as h1 from 3.2.a. */
if (!mpi_is_opaque (input))
{
rc = GPG_ERR_CONFLICT;
goto leave;
}
abuf = mpi_get_opaque (input, &abits);
rc = _gcry_dsa_gen_rfc6979_k (&k, skey->E.n, skey->d,
abuf, (abits+7)/8,
hashalgo, extraloops);
if (rc)
goto leave;
extraloops++;
}
else
k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);
_gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);
if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))
{
if (DBG_CIPHER)
log_debug ("ecc sign: Failed to get affine coordinates\n");
rc = GPG_ERR_BAD_SIGNATURE;
goto leave;
}
mpi_mod (r, x, skey->E.n); /* r = x mod n */
}
while (!mpi_cmp_ui (r, 0));
mpi_mulm (dr, skey->d, r, skey->E.n); /* dr = d*r mod n */
mpi_addm (sum, hash, dr, skey->E.n); /* sum = hash + (d*r) mod n */
mpi_invm (k_1, k, skey->E.n); /* k_1 = k^(-1) mod n */
mpi_mulm (s, k_1, sum, skey->E.n); /* s = k^(-1)*(hash+(d*r)) mod n */
}
while (!mpi_cmp_ui (s, 0));
if (DBG_CIPHER)
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void srpt_mgmt_method_get(struct srpt_port *sp, struct ib_mad *rq_mad,
struct ib_dm_mad *rsp_mad)
{
u16 attr_id;
u32 slot;
u8 hi, lo;
attr_id = be16_to_cpu(rq_mad->mad_hdr.attr_id);
switch (attr_id) {
case DM_ATTR_CLASS_PORT_INFO:
srpt_get_class_port_info(rsp_mad);
break;
case DM_ATTR_IOU_INFO:
srpt_get_iou(rsp_mad);
break;
case DM_ATTR_IOC_PROFILE:
slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
srpt_get_ioc(sp, slot, rsp_mad);
break;
case DM_ATTR_SVC_ENTRIES:
slot = be32_to_cpu(rq_mad->mad_hdr.attr_mod);
hi = (u8) ((slot >> 8) & 0xff);
lo = (u8) (slot & 0xff);
slot = (u16) ((slot >> 16) & 0xffff);
srpt_get_svc_entries(srpt_service_guid,
slot, hi, lo, rsp_mad);
break;
default:
rsp_mad->mad_hdr.status =
cpu_to_be16(DM_MAD_STATUS_UNSUP_METHOD_ATTR);
break;
}
}
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: _pango_emoji_iter_next (PangoEmojiIter *iter)
{
PangoEmojiType current_emoji_type = PANGO_EMOJI_TYPE_INVALID;
if (iter->end == iter->text_end)
return FALSE;
iter->start = iter->end;
for (; iter->end < iter->text_end; iter->end = g_utf8_next_char (iter->end))
{
gunichar ch = g_utf8_get_char (iter->end);
/* Except at the beginning, ZWJ just carries over the emoji or neutral
* text type, VS15 & VS16 we just carry over as well, since we already
* resolved those through lookahead. Also, don't downgrade to text
* presentation for emoji that are part of a ZWJ sequence, example
* U+1F441 U+200D U+1F5E8, eye (text presentation) + ZWJ + left speech
* bubble, see below. */
if ((!(ch == kZeroWidthJoinerCharacter && !iter->is_emoji) &&
ch != kVariationSelector15Character &&
ch != kVariationSelector16Character &&
ch != kCombiningEnclosingCircleBackslashCharacter &&
!_pango_Is_Regional_Indicator(ch) &&
!((ch == kLeftSpeechBubbleCharacter ||
ch == kRainbowCharacter ||
ch == kMaleSignCharacter ||
ch == kFemaleSignCharacter ||
ch == kStaffOfAesculapiusCharacter) &&
!iter->is_emoji)) ||
current_emoji_type == PANGO_EMOJI_TYPE_INVALID) {
current_emoji_type = _pango_get_emoji_type (ch);
}
if (g_utf8_next_char (iter->end) < iter->text_end) /* Optimize. */
{
gunichar peek_char = g_utf8_get_char (g_utf8_next_char (iter->end));
/* Variation Selectors */
if (current_emoji_type ==
PANGO_EMOJI_TYPE_EMOJI_EMOJI &&
peek_char == kVariationSelector15Character) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_TEXT;
}
if ((current_emoji_type ==
PANGO_EMOJI_TYPE_EMOJI_TEXT ||
_pango_Is_Emoji_Keycap_Base(ch)) &&
peek_char == kVariationSelector16Character) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI;
}
/* Combining characters Keycap... */
if (_pango_Is_Emoji_Keycap_Base(ch) &&
peek_char == kCombiningEnclosingKeycapCharacter) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI;
};
/* Regional indicators */
if (_pango_Is_Regional_Indicator(ch) &&
_pango_Is_Regional_Indicator(peek_char)) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI;
}
/* Upgrade text presentation emoji to emoji presentation when followed by
* ZWJ, Example U+1F441 U+200D U+1F5E8, eye + ZWJ + left speech bubble. */
if ((ch == kEyeCharacter ||
ch == kWavingWhiteFlagCharacter) &&
peek_char == kZeroWidthJoinerCharacter) {
current_emoji_type = PANGO_EMOJI_TYPE_EMOJI_EMOJI;
}
}
if (iter->is_emoji == (gboolean) 2)
iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type);
if (iter->is_emoji == PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type))
{
iter->is_emoji = !PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type);
return TRUE;
}
}
iter->is_emoji = PANGO_EMOJI_TYPE_IS_EMOJI (current_emoji_type);
return TRUE;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int sysMapFile(const char* fn, MemMapping* pMap)
{
memset(pMap, 0, sizeof(*pMap));
if (fn && fn[0] == '@') {
FILE* mapf = fopen(fn+1, "r");
if (mapf == NULL) {
LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno));
return -1;
}
if (sysMapBlockFile(mapf, pMap) != 0) {
LOGW("Map of '%s' failed\n", fn);
return -1;
}
fclose(mapf);
} else {
int fd = open(fn, O_RDONLY, 0);
if (fd < 0) {
LOGE("Unable to open '%s': %s\n", fn, strerror(errno));
return -1;
}
if (sysMapFD(fd, pMap) != 0) {
LOGE("Map of '%s' failed\n", fn);
close(fd);
return -1;
}
close(fd);
}
return 0;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static inline void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
CWE ID: CWE-287
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 sum_update(const char *p, int32 len)
{
switch (cursum_type) {
case CSUM_MD5:
md5_update(&md, (uchar *)p, len);
break;
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
if (len + sumresidue < CSUM_CHUNK) {
memcpy(md.buffer + sumresidue, p, len);
sumresidue += len;
}
if (sumresidue) {
int32 i = CSUM_CHUNK - sumresidue;
memcpy(md.buffer + sumresidue, p, i);
mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK);
len -= i;
p += i;
}
while (len >= CSUM_CHUNK) {
mdfour_update(&md, (uchar *)p, CSUM_CHUNK);
len -= CSUM_CHUNK;
p += CSUM_CHUNK;
}
sumresidue = len;
if (sumresidue)
memcpy(md.buffer, p, sumresidue);
break;
case CSUM_NONE:
break;
}
}
CWE ID: CWE-354
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: DataReductionProxySettings::~DataReductionProxySettings() {
spdy_proxy_auth_enabled_.Destroy();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void AddElementsToKeyAccumulatorImpl(Handle<JSObject> receiver,
KeyAccumulator* accumulator,
AddKeyConversion convert) {
Isolate* isolate = accumulator->isolate();
Handle<FixedArrayBase> elements(receiver->elements(), isolate);
uint32_t length = GetCapacityImpl(*receiver, *elements);
for (uint32_t entry = 0; entry < length; entry++) {
if (!HasEntryImpl(isolate, *elements, entry)) continue;
Handle<Object> value = GetImpl(isolate, *elements, entry);
accumulator->AddKey(value, convert);
}
}
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 *tcp_seek_last_pos(struct seq_file *seq)
{
struct tcp_iter_state *st = seq->private;
int offset = st->offset;
int orig_num = st->num;
void *rc = NULL;
switch (st->state) {
case TCP_SEQ_STATE_OPENREQ:
case TCP_SEQ_STATE_LISTENING:
if (st->bucket >= INET_LHTABLE_SIZE)
break;
st->state = TCP_SEQ_STATE_LISTENING;
rc = listening_get_next(seq, NULL);
while (offset-- && rc)
rc = listening_get_next(seq, rc);
if (rc)
break;
st->bucket = 0;
/* Fallthrough */
case TCP_SEQ_STATE_ESTABLISHED:
case TCP_SEQ_STATE_TIME_WAIT:
st->state = TCP_SEQ_STATE_ESTABLISHED;
if (st->bucket > tcp_hashinfo.ehash_mask)
break;
rc = established_get_first(seq);
while (offset-- && rc)
rc = established_get_next(seq, rc);
}
st->num = orig_num;
return rc;
}
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: _xfs_buf_find(
struct xfs_buftarg *btp,
struct xfs_buf_map *map,
int nmaps,
xfs_buf_flags_t flags,
xfs_buf_t *new_bp)
{
size_t numbytes;
struct xfs_perag *pag;
struct rb_node **rbp;
struct rb_node *parent;
xfs_buf_t *bp;
xfs_daddr_t blkno = map[0].bm_bn;
int numblks = 0;
int i;
for (i = 0; i < nmaps; i++)
numblks += map[i].bm_len;
numbytes = BBTOB(numblks);
/* Check for IOs smaller than the sector size / not sector aligned */
ASSERT(!(numbytes < (1 << btp->bt_sshift)));
ASSERT(!(BBTOB(blkno) & (xfs_off_t)btp->bt_smask));
/* get tree root */
pag = xfs_perag_get(btp->bt_mount,
xfs_daddr_to_agno(btp->bt_mount, blkno));
/* walk tree */
spin_lock(&pag->pag_buf_lock);
rbp = &pag->pag_buf_tree.rb_node;
parent = NULL;
bp = NULL;
while (*rbp) {
parent = *rbp;
bp = rb_entry(parent, struct xfs_buf, b_rbnode);
if (blkno < bp->b_bn)
rbp = &(*rbp)->rb_left;
else if (blkno > bp->b_bn)
rbp = &(*rbp)->rb_right;
else {
/*
* found a block number match. If the range doesn't
* match, the only way this is allowed is if the buffer
* in the cache is stale and the transaction that made
* it stale has not yet committed. i.e. we are
* reallocating a busy extent. Skip this buffer and
* continue searching to the right for an exact match.
*/
if (bp->b_length != numblks) {
ASSERT(bp->b_flags & XBF_STALE);
rbp = &(*rbp)->rb_right;
continue;
}
atomic_inc(&bp->b_hold);
goto found;
}
}
/* No match found */
if (new_bp) {
rb_link_node(&new_bp->b_rbnode, parent, rbp);
rb_insert_color(&new_bp->b_rbnode, &pag->pag_buf_tree);
/* the buffer keeps the perag reference until it is freed */
new_bp->b_pag = pag;
spin_unlock(&pag->pag_buf_lock);
} else {
XFS_STATS_INC(xb_miss_locked);
spin_unlock(&pag->pag_buf_lock);
xfs_perag_put(pag);
}
return new_bp;
found:
spin_unlock(&pag->pag_buf_lock);
xfs_perag_put(pag);
if (!xfs_buf_trylock(bp)) {
if (flags & XBF_TRYLOCK) {
xfs_buf_rele(bp);
XFS_STATS_INC(xb_busy_locked);
return NULL;
}
xfs_buf_lock(bp);
XFS_STATS_INC(xb_get_locked_waited);
}
/*
* if the buffer is stale, clear all the external state associated with
* it. We need to keep flags such as how we allocated the buffer memory
* intact here.
*/
if (bp->b_flags & XBF_STALE) {
ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0);
ASSERT(bp->b_iodone == NULL);
bp->b_flags &= _XBF_KMEM | _XBF_PAGES;
bp->b_ops = NULL;
}
trace_xfs_buf_find(bp, flags, _RET_IP_);
XFS_STATS_INC(xb_get_locked);
return bp;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: AutofillPopupFooterView* AutofillPopupFooterView::Create(
AutofillPopupViewNativeViews* popup_view,
int line_number,
int frontend_id) {
AutofillPopupFooterView* result =
new AutofillPopupFooterView(popup_view, line_number, frontend_id);
result->Init();
return result;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ScreenOrientationDispatcherHost::OnLockRequest(
RenderFrameHost* render_frame_host,
blink::WebScreenOrientationLockType orientation,
int request_id) {
if (current_lock_) {
NotifyLockError(current_lock_->request_id,
blink::WebLockOrientationErrorCanceled);
}
current_lock_ = new LockInformation(request_id,
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID());
if (!provider_) {
NotifyLockError(request_id,
blink::WebLockOrientationErrorNotAvailable);
return;
}
provider_->LockOrientation(request_id, orientation);
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int jffs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int rc, xprefix;
switch (type) {
case ACL_TYPE_ACCESS:
xprefix = JFFS2_XPREFIX_ACL_ACCESS;
if (acl) {
umode_t mode = inode->i_mode;
rc = posix_acl_equiv_mode(acl, &mode);
if (rc < 0)
return rc;
if (inode->i_mode != mode) {
struct iattr attr;
attr.ia_valid = ATTR_MODE | ATTR_CTIME;
attr.ia_mode = mode;
attr.ia_ctime = CURRENT_TIME_SEC;
rc = jffs2_do_setattr(inode, &attr);
if (rc < 0)
return rc;
}
if (rc == 0)
acl = NULL;
}
break;
case ACL_TYPE_DEFAULT:
xprefix = JFFS2_XPREFIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
rc = __jffs2_set_acl(inode, xprefix, acl);
if (!rc)
set_cached_acl(inode, type, acl);
return rc;
}
CWE ID: CWE-285
Target: 1
Example 2:
Code: SplashError Splash::clipToRect(SplashCoord x0, SplashCoord y0,
SplashCoord x1, SplashCoord y1) {
return state->clip->clipToRect(x0, y0, x1, y1);
}
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: RunLoop::RunLoop()
: delegate_(tls_delegate.Get().Get()),
origin_task_runner_(ThreadTaskRunnerHandle::Get()),
weak_factory_(this) {
DCHECK(delegate_) << "A RunLoop::Delegate must be bound to this thread prior "
"to using RunLoop.";
DCHECK(origin_task_runner_);
}
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: xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
{
xmlParserCtxtPtr ctxt = NULL;
xmlDocPtr ret;
/*
xmlInitParser();
*/
ctxt = xmlCreateMemoryParserCtxt(buf, buf_size);
if (ctxt) {
ctxt->options -= XML_PARSE_DTDLOAD;
ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace;
ctxt->sax->comment = soap_Comment;
ctxt->sax->warning = NULL;
ctxt->sax->error = NULL;
/*ctxt->sax->fatalError = NULL;*/
#if LIBXML_VERSION >= 20703
ctxt->options |= XML_PARSE_HUGE;
#endif
xmlParseDocument(ctxt);
if (ctxt->wellFormed) {
ret = ctxt->myDoc;
if (ret->URL == NULL && ctxt->directory != NULL) {
ret->URL = xmlCharStrdup(ctxt->directory);
}
} else {
ret = NULL;
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
xmlFreeParserCtxt(ctxt);
} else {
ret = NULL;
}
/*
xmlCleanupParser();
*/
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
}
*/
return ret;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static uint64_t megasas_port_read(void *opaque, hwaddr addr,
unsigned size)
{
return megasas_mmio_read(opaque, addr & 0xff, size);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BackingStore* RenderWidgetHostViewAndroid::AllocBackingStore(
const gfx::Size& size) {
NOTIMPLEMENTED();
return NULL;
}
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 FaviconSource::SendDefaultResponse(int request_id) {
if (!default_favicon_.get()) {
default_favicon_ =
ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
IDR_DEFAULT_FAVICON);
}
SendResponse(request_id, default_favicon_);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: kdc_check_transited_list(kdc_realm_t *kdc_active_realm,
const krb5_data *trans,
const krb5_data *realm1,
const krb5_data *realm2)
{
krb5_error_code code;
/* Check against the KDB module. Treat this answer as authoritative if the
* method is supported and doesn't explicitly pass control. */
code = krb5_db_check_transited_realms(kdc_context, trans, realm1, realm2);
if (code != KRB5_PLUGIN_OP_NOTSUPP && code != KRB5_PLUGIN_NO_HANDLE)
return code;
/* Check using krb5.conf [capaths] or hierarchical relationships. */
return krb5_check_transited_list(kdc_context, trans, realm1, realm2);
}
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 EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod4(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->overloadedMethod(intArg);
return JSValue::encode(jsUndefined());
}
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: BGD_DECLARE(void) gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit, rightLimit;
int i;
int restoreAlphaBleding;
if (border < 0) {
/* Refuse to fill to a non-solid border */
return;
}
leftLimit = (-1);
restoreAlphaBleding = im->alphaBlendingFlag;
im->alphaBlendingFlag = 0;
if (x >= im->sx) {
x = im->sx - 1;
} else if (x < 0) {
x = 0;
}
if (y >= im->sy) {
y = im->sy - 1;
} else if (y < 0) {
y = 0;
}
for (i = x; (i >= 0); i--) {
if (gdImageGetPixel (im, i, y) == border) {
break;
}
gdImageSetPixel (im, i, y, color);
leftLimit = i;
}
if (leftLimit == (-1)) {
im->alphaBlendingFlag = restoreAlphaBleding;
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); (i < im->sx); i++) {
if (gdImageGetPixel (im, i, y) == border) {
break;
}
gdImageSetPixel (im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0) {
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++) {
int c;
c = gdImageGetPixel (im, i, y - 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder (im, i, y - 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1)) {
lastBorder = 1;
for (i = leftLimit; (i <= rightLimit); i++) {
int c = gdImageGetPixel (im, i, y + 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder (im, i, y + 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
im->alphaBlendingFlag = restoreAlphaBleding;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: AppendStmt(ParseCommon *to, ParseCommon *append)
{
ParseCommon *iter;
if (!to)
return append;
for (iter = to; iter->next; iter = iter->next);
iter->next = append;
return to;
}
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: int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
pte_t *dst_pte,
struct vm_area_struct *dst_vma,
unsigned long dst_addr,
unsigned long src_addr,
struct page **pagep)
{
int vm_shared = dst_vma->vm_flags & VM_SHARED;
struct hstate *h = hstate_vma(dst_vma);
pte_t _dst_pte;
spinlock_t *ptl;
int ret;
struct page *page;
if (!*pagep) {
ret = -ENOMEM;
page = alloc_huge_page(dst_vma, dst_addr, 0);
if (IS_ERR(page))
goto out;
ret = copy_huge_page_from_user(page,
(const void __user *) src_addr,
pages_per_huge_page(h), false);
/* fallback to copy_from_user outside mmap_sem */
if (unlikely(ret)) {
ret = -EFAULT;
*pagep = page;
/* don't free the page */
goto out;
}
} else {
page = *pagep;
*pagep = NULL;
}
/*
* The memory barrier inside __SetPageUptodate makes sure that
* preceding stores to the page contents become visible before
* the set_pte_at() write.
*/
__SetPageUptodate(page);
set_page_huge_active(page);
/*
* If shared, add to page cache
*/
if (vm_shared) {
struct address_space *mapping = dst_vma->vm_file->f_mapping;
pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr);
ret = huge_add_to_page_cache(page, mapping, idx);
if (ret)
goto out_release_nounlock;
}
ptl = huge_pte_lockptr(h, dst_mm, dst_pte);
spin_lock(ptl);
ret = -EEXIST;
if (!huge_pte_none(huge_ptep_get(dst_pte)))
goto out_release_unlock;
if (vm_shared) {
page_dup_rmap(page, true);
} else {
ClearPagePrivate(page);
hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
}
_dst_pte = make_huge_pte(dst_vma, page, dst_vma->vm_flags & VM_WRITE);
if (dst_vma->vm_flags & VM_WRITE)
_dst_pte = huge_pte_mkdirty(_dst_pte);
_dst_pte = pte_mkyoung(_dst_pte);
set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
(void)huge_ptep_set_access_flags(dst_vma, dst_addr, dst_pte, _dst_pte,
dst_vma->vm_flags & VM_WRITE);
hugetlb_count_add(pages_per_huge_page(h), dst_mm);
/* No need to invalidate - it was non-present before */
update_mmu_cache(dst_vma, dst_addr, dst_pte);
spin_unlock(ptl);
if (vm_shared)
unlock_page(page);
ret = 0;
out:
return ret;
out_release_unlock:
spin_unlock(ptl);
out_release_nounlock:
if (vm_shared)
unlock_page(page);
put_page(page);
goto out;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AutoFillManager::LogMetricsAboutSubmittedForm(
const FormData& form,
const FormStructure* submitted_form) {
FormStructure* cached_submitted_form;
if (!FindCachedForm(form, &cached_submitted_form)) {
NOTREACHED();
return;
}
std::map<std::string, const AutoFillField*> cached_fields;
for (size_t i = 0; i < cached_submitted_form->field_count(); ++i) {
const AutoFillField* field = cached_submitted_form->field(i);
cached_fields[field->FieldSignature()] = field;
}
for (size_t i = 0; i < submitted_form->field_count(); ++i) {
const AutoFillField* field = submitted_form->field(i);
FieldTypeSet field_types;
personal_data_->GetPossibleFieldTypes(field->value(), &field_types);
DCHECK(!field_types.empty());
if (field->form_control_type() == ASCIIToUTF16("select-one")) {
continue;
}
metric_logger_->Log(AutoFillMetrics::FIELD_SUBMITTED);
if (field_types.find(EMPTY_TYPE) == field_types.end() &&
field_types.find(UNKNOWN_TYPE) == field_types.end()) {
if (field->is_autofilled()) {
metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILLED);
} else {
metric_logger_->Log(AutoFillMetrics::FIELD_AUTOFILL_FAILED);
AutoFillFieldType heuristic_type = UNKNOWN_TYPE;
AutoFillFieldType server_type = NO_SERVER_DATA;
std::map<std::string, const AutoFillField*>::const_iterator
cached_field = cached_fields.find(field->FieldSignature());
if (cached_field != cached_fields.end()) {
heuristic_type = cached_field->second->heuristic_type();
server_type = cached_field->second->server_type();
}
if (heuristic_type == UNKNOWN_TYPE)
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_UNKNOWN);
else if (field_types.count(heuristic_type))
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MATCH);
else
metric_logger_->Log(AutoFillMetrics::FIELD_HEURISTIC_TYPE_MISMATCH);
if (server_type == NO_SERVER_DATA)
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_UNKNOWN);
else if (field_types.count(server_type))
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MATCH);
else
metric_logger_->Log(AutoFillMetrics::FIELD_SERVER_TYPE_MISMATCH);
}
}
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void classMethodWithClampMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "classMethodWithClamp", "TestObject", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(2, info.Length()));
exceptionState.throwIfNeeded();
return;
}
TestObject* imp = V8TestObject::toNative(info.Holder());
unsigned objArgsShort = 0;
V8TRYCATCH_VOID(double, objArgsShortNativeValue, info[0]->NumberValue());
if (!std::isnan(objArgsShortNativeValue))
objArgsShort = clampTo<unsigned short>(objArgsShortNativeValue);
unsigned objArgsLong = 0;
V8TRYCATCH_VOID(double, objArgsLongNativeValue, info[1]->NumberValue());
if (!std::isnan(objArgsLongNativeValue))
objArgsLong = clampTo<unsigned long>(objArgsLongNativeValue);
imp->classMethodWithClamp(objArgsShort, objArgsLong);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
WARN_ON(!is_guest_mode(vcpu));
/* TODO: also check PFEC_MATCH/MASK, not just EB.PF. */
if (vmcs12->exception_bitmap & (1u << PF_VECTOR))
nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
vmcs_read32(VM_EXIT_INTR_INFO),
vmcs_readl(EXIT_QUALIFICATION));
else
kvm_inject_page_fault(vcpu, fault);
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void initializeHolderIfNeeded(ScriptState* scriptState, v8::Local<v8::Object> classObject, v8::Local<v8::Value> holder)
{
RELEASE_ASSERT(!holder.IsEmpty());
RELEASE_ASSERT(holder->IsObject());
v8::Local<v8::Object> holderObject = v8::Local<v8::Object>::Cast(holder);
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Context> context = scriptState->context();
auto privateIsInitialized = V8PrivateProperty::getPrivateScriptRunnerIsInitialized(isolate);
if (privateIsInitialized.hasValue(context, holderObject))
return; // Already initialized.
v8::TryCatch block(isolate);
v8::Local<v8::Value> initializeFunction;
if (classObject->Get(scriptState->context(), v8String(isolate, "initialize")).ToLocal(&initializeFunction) && initializeFunction->IsFunction()) {
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(initializeFunction), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) {
fprintf(stderr, "Private script error: Object constructor threw an exception.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (classObject->GetPrototype() != holderObject->GetPrototype()) {
if (!v8CallBoolean(classObject->SetPrototype(context, holderObject->GetPrototype()))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
}
if (!v8CallBoolean(holderObject->SetPrototype(context, classObject))) {
fprintf(stderr, "Private script error: SetPrototype failed.\n");
dumpV8Message(context, block.Message());
RELEASE_NOTREACHED();
}
privateIsInitialized.set(context, holderObject, v8Boolean(true, isolate));
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: static inline void __netif_reschedule(struct Qdisc *q)
{
struct softnet_data *sd;
unsigned long flags;
local_irq_save(flags);
sd = this_cpu_ptr(&softnet_data);
q->next_sched = NULL;
*sd->output_queue_tailp = q;
sd->output_queue_tailp = &q->next_sched;
raise_softirq_irqoff(NET_TX_SOFTIRQ);
local_irq_restore(flags);
}
CWE ID: CWE-400
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: WebCore::IntRect InputHandler::rectForCaret(int index)
{
if (!isActiveTextEdit())
return WebCore::IntRect();
ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
if (index < 0 || index > static_cast<int>(elementText().length())) {
return WebCore::IntRect();
}
FrameSelection caretSelection;
caretSelection.setSelection(DOMSupport::visibleSelectionForRangeInputElement(m_currentFocusElement.get(), index, index).visibleStart());
caretSelection.modify(FrameSelection::AlterationExtend, DirectionForward, CharacterGranularity);
return caretSelection.selection().visibleStart().absoluteCaretBounds();
}
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 int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
{
ulonglong tmp;
if (jas_iccgetuint(in, 8, &tmp))
return -1;
*val = tmp;
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: error::Error GLES2DecoderPassthroughImpl::DoGetIntegerv(GLenum pname,
GLsizei bufsize,
GLsizei* length,
GLint* params) {
return GetNumericHelper(
pname, bufsize, length, params,
[this](GLenum pname, GLsizei bufsize, GLsizei* length, GLint* params) {
api()->glGetIntegervRobustANGLEFn(pname, bufsize, length, params);
});
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ra_node_page(struct f2fs_sb_info *sbi, nid_t nid)
{
struct page *apage;
int err;
if (!nid)
return;
f2fs_bug_on(sbi, check_nid_range(sbi, nid));
rcu_read_lock();
apage = radix_tree_lookup(&NODE_MAPPING(sbi)->page_tree, nid);
rcu_read_unlock();
if (apage)
return;
apage = f2fs_grab_cache_page(NODE_MAPPING(sbi), nid, false);
if (!apage)
return;
err = read_node_page(apage, REQ_RAHEAD);
f2fs_put_page(apage, err ? 1 : 0);
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void fht8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fht8x8_c(in, out, stride, tx_type);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: BackendIO::BackendIO(InFlightIO* controller, BackendImpl* backend,
const net::CompletionCallback& callback)
: BackgroundIO(controller),
backend_(backend),
callback_(callback),
operation_(OP_NONE),
entry_ptr_(NULL),
iterator_(NULL),
entry_(NULL),
index_(0),
offset_(0),
buf_len_(0),
truncate_(false),
offset64_(0),
start_(NULL) {
start_time_ = base::TimeTicks::Now();
}
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: fbCombineOutU (CARD32 *dest, const CARD32 *src, int width)
{
int i;
for (i = 0; i < width; ++i) {
CARD32 s = READ(src + i);
CARD32 a = Alpha(~READ(dest + i));
FbByteMul(s, a);
WRITE(dest + i, s);
}
}
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 char *print_array( cJSON *item, int depth, int fmt )
{
char **entries;
char *out = 0, *ptr, *ret;
int len = 5;
cJSON *child = item->child;
int numentries = 0, i = 0, fail = 0;
/* How many entries in the array? */
while ( child ) {
++numentries;
child = child->next;
}
/* Allocate an array to hold the values for each. */
if ( ! ( entries = (char**) cJSON_malloc( numentries * sizeof(char*) ) ) )
return 0;
memset( entries, 0, numentries * sizeof(char*) );
/* Retrieve all the results. */
child = item->child;
while ( child && ! fail ) {
ret = print_value( child, depth + 1, fmt );
entries[i++] = ret;
if ( ret )
len += strlen( ret ) + 2 + ( fmt ? 1 : 0 );
else
fail = 1;
child = child -> next;
}
/* If we didn't fail, try to malloc 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 ( entries[i] )
cJSON_free( entries[i] );
cJSON_free( entries );
return 0;
}
/* Compose the output array. */
*out = '[';
ptr = out + 1;
*ptr = 0;
for ( i = 0; i < numentries; ++i ) {
strcpy( ptr, entries[i] );
ptr += strlen( entries[i] );
if ( i != numentries - 1 ) {
*ptr++ = ',';
if ( fmt )
*ptr++ = ' ';
*ptr = 0;
}
cJSON_free( entries[i] );
}
cJSON_free( entries );
*ptr++ = ']';
*ptr++ = 0;
return out;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool Document::SetFocusedElement(Element* new_focused_element,
const FocusParams& params) {
DCHECK(!lifecycle_.InDetach());
clear_focused_element_timer_.Stop();
if (new_focused_element && (new_focused_element->GetDocument() != this))
return true;
if (NodeChildRemovalTracker::IsBeingRemoved(new_focused_element))
return true;
if (focused_element_ == new_focused_element)
return true;
bool focus_change_blocked = false;
Element* old_focused_element = focused_element_;
focused_element_ = nullptr;
UpdateDistribution();
Node* ancestor = (old_focused_element && old_focused_element->isConnected() &&
new_focused_element)
? FlatTreeTraversal::CommonAncestor(*old_focused_element,
*new_focused_element)
: nullptr;
if (old_focused_element) {
old_focused_element->SetFocused(false, params.type);
old_focused_element->SetHasFocusWithinUpToAncestor(false, ancestor);
if (GetPage() && (GetPage()->GetFocusController().IsFocused())) {
old_focused_element->DispatchBlurEvent(new_focused_element, params.type,
params.source_capabilities);
if (focused_element_) {
focus_change_blocked = true;
new_focused_element = nullptr;
}
old_focused_element->DispatchFocusOutEvent(EventTypeNames::focusout,
new_focused_element,
params.source_capabilities);
old_focused_element->DispatchFocusOutEvent(EventTypeNames::DOMFocusOut,
new_focused_element,
params.source_capabilities);
if (focused_element_) {
focus_change_blocked = true;
new_focused_element = nullptr;
}
}
}
if (new_focused_element)
UpdateStyleAndLayoutTreeForNode(new_focused_element);
if (new_focused_element && new_focused_element->IsFocusable()) {
if (IsRootEditableElement(*new_focused_element) &&
!AcceptsEditingFocus(*new_focused_element)) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
focused_element_ = new_focused_element;
SetSequentialFocusNavigationStartingPoint(focused_element_.Get());
focused_element_->SetFocused(true, params.type);
focused_element_->SetHasFocusWithinUpToAncestor(true, ancestor);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
CancelFocusAppearanceUpdate();
focused_element_->UpdateFocusAppearance(params.selection_behavior);
if (GetPage() && (GetPage()->GetFocusController().IsFocused())) {
focused_element_->DispatchFocusEvent(old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
focused_element_->DispatchFocusInEvent(EventTypeNames::focusin,
old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
focused_element_->DispatchFocusInEvent(EventTypeNames::DOMFocusIn,
old_focused_element, params.type,
params.source_capabilities);
if (focused_element_ != new_focused_element) {
focus_change_blocked = true;
goto SetFocusedElementDone;
}
}
}
if (!focus_change_blocked && focused_element_) {
if (AXObjectCache* cache = AxObjectCache())
cache->HandleFocusedUIElementChanged(old_focused_element,
new_focused_element);
}
if (!focus_change_blocked && GetPage()) {
GetPage()->GetChromeClient().FocusedNodeChanged(old_focused_element,
focused_element_.Get());
}
SetFocusedElementDone:
UpdateStyleAndLayoutTree();
if (LocalFrame* frame = GetFrame())
frame->Selection().DidChangeFocus();
return !focus_change_blocked;
}
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 HTMLMediaElement::requestReload(const WebURL& newUrl) {
DCHECK(webMediaPlayer());
DCHECK(!m_srcObject);
DCHECK(newUrl.isValid());
DCHECK(isSafeToLoadURL(newUrl, Complain));
resetMediaPlayerAndMediaSource();
startPlayerLoad(newUrl);
}
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 bool ShouldAutofocus(const HTMLFormControlElement* element) {
if (!element->isConnected())
return false;
if (!element->IsAutofocusable())
return false;
Document& doc = element->GetDocument();
if (doc.IsSandboxed(WebSandboxFlags::kAutomaticFeatures)) {
doc.AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
"Blocked autofocusing on a form control because the form's frame is "
"sandboxed and the 'allow-scripts' permission is not set."));
return false;
}
if (!doc.IsInMainFrame() &&
!doc.TopFrameOrigin()->CanAccess(doc.GetSecurityOrigin())) {
doc.AddConsoleMessage(ConsoleMessage::Create(
mojom::ConsoleMessageSource::kSecurity,
mojom::ConsoleMessageLevel::kError,
"Blocked autofocusing on a form control in a cross-origin subframe."));
return false;
}
return true;
}
CWE ID: CWE-704
Target: 1
Example 2:
Code: int _yr_scan_verify_chained_string_match(
YR_STRING* matching_string,
YR_SCAN_CONTEXT* context,
uint8_t* match_data,
uint64_t match_base,
uint64_t match_offset,
int32_t match_length)
{
YR_STRING* string;
YR_MATCH* match;
YR_MATCH* next_match;
YR_MATCH* new_match;
uint64_t lower_offset;
uint64_t ending_offset;
int32_t full_chain_length;
int tidx = context->tidx;
int add_match = FALSE;
if (matching_string->chained_to == NULL)
{
add_match = TRUE;
}
else
{
if (matching_string->unconfirmed_matches[tidx].head != NULL)
lower_offset = matching_string->unconfirmed_matches[tidx].head->offset;
else
lower_offset = match_offset;
match = matching_string->chained_to->unconfirmed_matches[tidx].head;
while (match != NULL)
{
next_match = match->next;
ending_offset = match->offset + match->match_length;
if (ending_offset + matching_string->chain_gap_max < lower_offset)
{
_yr_scan_remove_match_from_list(
match, &matching_string->chained_to->unconfirmed_matches[tidx]);
}
else
{
if (ending_offset + matching_string->chain_gap_max >= match_offset &&
ending_offset + matching_string->chain_gap_min <= match_offset)
{
add_match = TRUE;
break;
}
}
match = next_match;
}
}
if (add_match)
{
if (STRING_IS_CHAIN_TAIL(matching_string))
{
assert(matching_string->chained_to != NULL);
match = matching_string->chained_to->unconfirmed_matches[tidx].head;
while (match != NULL)
{
ending_offset = match->offset + match->match_length;
if (ending_offset + matching_string->chain_gap_max >= match_offset &&
ending_offset + matching_string->chain_gap_min <= match_offset)
{
_yr_scan_update_match_chain_length(
tidx, matching_string->chained_to, match, 1);
}
match = match->next;
}
full_chain_length = 0;
string = matching_string;
while(string->chained_to != NULL)
{
full_chain_length++;
string = string->chained_to;
}
match = string->unconfirmed_matches[tidx].head;
while (match != NULL)
{
next_match = match->next;
if (match->chain_length == full_chain_length)
{
_yr_scan_remove_match_from_list(
match, &string->unconfirmed_matches[tidx]);
match->match_length = (int32_t) \
(match_offset - match->offset + match_length);
match->data_length = yr_min(match->match_length, MAX_MATCH_DATA);
FAIL_ON_ERROR(yr_arena_write_data(
context->matches_arena,
match_data - match_offset + match->offset,
match->data_length,
(void**) &match->data));
FAIL_ON_ERROR(_yr_scan_add_match_to_list(
match, &string->matches[tidx], FALSE));
}
match = next_match;
}
}
else
{
if (matching_string->matches[tidx].count == 0 &&
matching_string->unconfirmed_matches[tidx].count == 0)
{
FAIL_ON_ERROR(yr_arena_write_data(
context->matching_strings_arena,
&matching_string,
sizeof(matching_string),
NULL));
}
FAIL_ON_ERROR(yr_arena_allocate_memory(
context->matches_arena,
sizeof(YR_MATCH),
(void**) &new_match));
new_match->data_length = yr_min(match_length, MAX_MATCH_DATA);
FAIL_ON_ERROR(yr_arena_write_data(
context->matches_arena,
match_data,
new_match->data_length,
(void**) &new_match->data));
new_match->base = match_base;
new_match->offset = match_offset;
new_match->match_length = match_length;
new_match->chain_length = 0;
new_match->prev = NULL;
new_match->next = NULL;
FAIL_ON_ERROR(_yr_scan_add_match_to_list(
new_match,
&matching_string->unconfirmed_matches[tidx],
FALSE));
}
}
return ERROR_SUCCESS;
}
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 proc_connectinfo(struct usb_dev_state *ps, void __user *arg)
{
struct usbdevfs_connectinfo ci = {
.devnum = ps->dev->devnum,
.slow = ps->dev->speed == USB_SPEED_LOW
};
if (copy_to_user(arg, &ci, sizeof(ci)))
return -EFAULT;
return 0;
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __kprobes perf_event_nmi_handler(struct notifier_block *self,
unsigned long cmd, void *__args)
{
struct die_args *args = __args;
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int i;
if (!atomic_read(&active_events))
return NOTIFY_DONE;
switch (cmd) {
case DIE_NMI:
break;
default:
return NOTIFY_DONE;
}
regs = args->regs;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/* If the PMU has the TOE IRQ enable bits, we need to do a
* dummy write to the %pcr to clear the overflow bits and thus
* the interrupt.
*
* Do this before we peek at the counters to determine
* overflow so we don't lose any events.
*/
if (sparc_pmu->irq_bit)
pcr_ops->write(cpuc->pcr);
for (i = 0; i < cpuc->n_events; i++) {
struct perf_event *event = cpuc->event[i];
int idx = cpuc->current_idx[i];
struct hw_perf_event *hwc;
u64 val;
hwc = &event->hw;
val = sparc_perf_event_update(event, hwc, idx);
if (val & (1ULL << 31))
continue;
data.period = event->hw.last_period;
if (!sparc_perf_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, 1, &data, regs))
sparc_pmu_stop(event, 0);
}
return NOTIFY_STOP;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void phar_manifest_copy_ctor(zval *zv) /* {{{ */
{
phar_entry_info *info = emalloc(sizeof(phar_entry_info));
memcpy(info, Z_PTR_P(zv), sizeof(phar_entry_info));
Z_PTR_P(zv) = info;
}
/* }}} */
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: nfssvc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_writeargs *args)
{
unsigned int len, hdr, dlen;
struct kvec *head = rqstp->rq_arg.head;
int v;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p++; /* beginoffset */
args->offset = ntohl(*p++); /* offset */
p++; /* totalcount */
len = args->len = ntohl(*p++);
/*
* The protocol specifies a maximum of 8192 bytes.
*/
if (len > NFSSVC_MAXBLKSIZE_V2)
return 0;
/*
* Check to make sure that we got the right number of
* bytes.
*/
hdr = (void*)p - head->iov_base;
dlen = head->iov_len + rqstp->rq_arg.page_len - hdr;
/*
* Round the length of the data which was specified up to
* the next multiple of XDR units and then compare that
* against the length which was actually received.
* Note that when RPCSEC/GSS (for example) is used, the
* data buffer can be padded so dlen might be larger
* than required. It must never be smaller.
*/
if (dlen < XDR_QUADLEN(len)*4)
return 0;
rqstp->rq_vec[0].iov_base = (void*)p;
rqstp->rq_vec[0].iov_len = head->iov_len - hdr;
v = 0;
while (len > rqstp->rq_vec[v].iov_len) {
len -= rqstp->rq_vec[v].iov_len;
v++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]);
rqstp->rq_vec[v].iov_len = PAGE_SIZE;
}
rqstp->rq_vec[v].iov_len = len;
args->vlen = v + 1;
return 1;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int LELib_Create(const effect_uuid_t *uuid,
int32_t sessionId,
int32_t ioId,
effect_handle_t *pHandle) {
ALOGV("LELib_Create()");
int ret;
int i;
if (pHandle == NULL || uuid == NULL) {
return -EINVAL;
}
if (memcmp(uuid, &gLEDescriptor.uuid, sizeof(effect_uuid_t)) != 0) {
return -EINVAL;
}
LoudnessEnhancerContext *pContext = new LoudnessEnhancerContext;
pContext->mItfe = &gLEInterface;
pContext->mState = LOUDNESS_ENHANCER_STATE_UNINITIALIZED;
pContext->mCompressor = NULL;
ret = LE_init(pContext);
if (ret < 0) {
ALOGW("LELib_Create() init failed");
delete pContext;
return ret;
}
*pHandle = (effect_handle_t)pContext;
pContext->mState = LOUDNESS_ENHANCER_STATE_INITIALIZED;
ALOGV(" LELib_Create context is %p", pContext);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: JsVar *jsvNewArrayBufferWithPtr(unsigned int length, char **ptr) {
assert(ptr);
*ptr=0;
JsVar *backingString = jsvNewFlatStringOfLength(length);
if (!backingString) return 0;
JsVar *arr = jsvNewArrayBufferFromString(backingString, length);
if (!arr) {
jsvUnLock(backingString);
return 0;
}
*ptr = jsvGetFlatStringPointer(backingString);
jsvUnLock(backingString);
return arr;
}
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: char *ldb_dn_canonical_ex_string(TALLOC_CTX *mem_ctx, struct ldb_dn *dn) {
return ldb_dn_canonical(mem_ctx, dn, 1);
}
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: base::MessageLoopProxy* ProxyChannelDelegate::GetIPCMessageLoop() {
return RenderThread::Get()->GetIOMessageLoopProxy().get();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void SSLCertErrorHandler::OnDispatched() {
manager_->policy()->OnCertError(this);
}
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 read_entry(
git_index_entry **out,
size_t *out_size,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return -1;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return -1;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len;
size_t strip_len = git_decode_varint((const unsigned char *)path_ptr,
&varint_len);
size_t last_len = strlen(last);
size_t prefix_len = last_len - strip_len;
size_t suffix_len = strlen(path_ptr + varint_len);
size_t path_len;
if (varint_len == 0)
return index_error_invalid("incorrect prefix length");
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (entry_size == 0)
return -1;
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return -1;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return -1;
}
git__free(tmp_path);
*out_size = entry_size;
return 0;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::unique_ptr<JSONObject> EffectPaintPropertyNode::ToJSON() const {
auto json = JSONObject::Create();
if (Parent())
json->SetString("parent", String::Format("%p", Parent()));
json->SetString("localTransformSpace",
String::Format("%p", state_.local_transform_space.get()));
json->SetString("outputClip", String::Format("%p", state_.output_clip.get()));
if (state_.color_filter != kColorFilterNone)
json->SetInteger("colorFilter", state_.color_filter);
if (!state_.filter.IsEmpty())
json->SetString("filter", state_.filter.ToString());
if (state_.opacity != 1.0f)
json->SetDouble("opacity", state_.opacity);
if (state_.blend_mode != SkBlendMode::kSrcOver)
json->SetString("blendMode", SkBlendMode_Name(state_.blend_mode));
if (state_.direct_compositing_reasons != CompositingReason::kNone) {
json->SetString(
"directCompositingReasons",
CompositingReason::ToString(state_.direct_compositing_reasons));
}
if (state_.compositor_element_id) {
json->SetString("compositorElementId",
state_.compositor_element_id.ToString().c_str());
}
if (state_.paint_offset != FloatPoint())
json->SetString("paintOffset", state_.paint_offset.ToString());
return json;
}
CWE ID:
Target: 1
Example 2:
Code: entry_guards_update_state(or_state_t *state)
{
entry_guards_dirty = 0;
entry_guards_update_guards_in_state(state);
entry_guards_dirty = 0;
if (!get_options()->AvoidDiskWrites)
or_state_mark_dirty(get_or_state(), 0);
entry_guards_dirty = 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: static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVParallelsState *s = bs->opaque;
int i;
struct parallels_header ph;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));
if (ret < 0) {
goto fail;
}
if (memcmp(ph.magic, HEADER_MAGIC, 16) ||
(le32_to_cpu(ph.version) != HEADER_VERSION)) {
error_setg(errp, "Image not in Parallels format");
ret = -EINVAL;
goto fail;
}
bs->total_sectors = le32_to_cpu(ph.nb_sectors);
s->tracks = le32_to_cpu(ph.tracks);
s->catalog_size = le32_to_cpu(ph.catalog_entries);
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4);
le32_to_cpus(&s->catalog_bitmap[i]);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->catalog_bitmap);
return ret;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp,
int in_depth, int out_depth)
{
PNG_CONST unsigned int outmax = (1U<<out_depth)-1;
vi->pp = pp;
vi->dp = dp;
if (dp->sbit > 0 && dp->sbit < in_depth)
{
vi->sbit = dp->sbit;
vi->isbit_shift = in_depth - dp->sbit;
}
else
{
vi->sbit = (png_byte)in_depth;
vi->isbit_shift = 0;
}
vi->sbit_max = (1U << vi->sbit)-1;
/* This mimics the libpng threshold test, '0' is used to prevent gamma
* correction in the validation test.
*/
vi->screen_gamma = dp->screen_gamma;
if (fabs(vi->screen_gamma-1) < PNG_GAMMA_THRESHOLD)
vi->screen_gamma = vi->screen_inverse = 0;
else
vi->screen_inverse = 1/vi->screen_gamma;
vi->use_input_precision = dp->use_input_precision;
vi->outmax = outmax;
vi->maxabs = abserr(dp->pm, in_depth, out_depth);
vi->maxpc = pcerr(dp->pm, in_depth, out_depth);
vi->maxcalc = calcerr(dp->pm, in_depth, out_depth);
vi->maxout = outerr(dp->pm, in_depth, out_depth);
vi->outquant = output_quantization_factor(dp->pm, in_depth, out_depth);
vi->maxout_total = vi->maxout + vi->outquant * .5;
vi->outlog = outlog(dp->pm, in_depth, out_depth);
if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 ||
(dp->this.colour_type == 3 && dp->this.is_transparent))
{
vi->do_background = dp->do_background;
if (vi->do_background != 0)
{
PNG_CONST double bg_inverse = 1/dp->background_gamma;
double r, g, b;
/* Caller must at least put the gray value into the red channel */
r = dp->background_color.red; r /= outmax;
g = dp->background_color.green; g /= outmax;
b = dp->background_color.blue; b /= outmax;
# if 0
/* libpng doesn't do this optimization, if we do pngvalid will fail.
*/
if (fabs(bg_inverse-1) >= PNG_GAMMA_THRESHOLD)
# endif
{
r = pow(r, bg_inverse);
g = pow(g, bg_inverse);
b = pow(b, bg_inverse);
}
vi->background_red = r;
vi->background_green = g;
vi->background_blue = b;
}
}
else
vi->do_background = 0;
if (vi->do_background == 0)
vi->background_red = vi->background_green = vi->background_blue = 0;
vi->gamma_correction = 1/(dp->file_gamma*dp->screen_gamma);
if (fabs(vi->gamma_correction-1) < PNG_GAMMA_THRESHOLD)
vi->gamma_correction = 0;
vi->file_inverse = 1/dp->file_gamma;
if (fabs(vi->file_inverse-1) < PNG_GAMMA_THRESHOLD)
vi->file_inverse = 0;
vi->scale16 = dp->scale16;
}
CWE ID:
Target: 1
Example 2:
Code: BOOL IsAllZeroes (unsigned char* pbData, DWORD dwDataLen)
{
while (dwDataLen--)
{
if (*pbData)
return FALSE;
pbData++;
}
return TRUE;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int install_user_keyrings(void)
{
struct user_struct *user;
const struct cred *cred;
struct key *uid_keyring, *session_keyring;
key_perm_t user_keyring_perm;
char buf[20];
int ret;
uid_t uid;
user_keyring_perm = (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL;
cred = current_cred();
user = cred->user;
uid = from_kuid(cred->user_ns, user->uid);
kenter("%p{%u}", user, uid);
if (user->uid_keyring && user->session_keyring) {
kleave(" = 0 [exist]");
return 0;
}
mutex_lock(&key_user_keyring_mutex);
ret = 0;
if (!user->uid_keyring) {
/* get the UID-specific keyring
* - there may be one in existence already as it may have been
* pinned by a session, but the user_struct pointing to it
* may have been destroyed by setuid */
sprintf(buf, "_uid.%u", uid);
uid_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(uid_keyring)) {
uid_keyring = keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(uid_keyring)) {
ret = PTR_ERR(uid_keyring);
goto error;
}
}
/* get a default session keyring (which might also exist
* already) */
sprintf(buf, "_uid_ses.%u", uid);
session_keyring = find_keyring_by_name(buf, true);
if (IS_ERR(session_keyring)) {
session_keyring =
keyring_alloc(buf, user->uid, INVALID_GID,
cred, user_keyring_perm,
KEY_ALLOC_IN_QUOTA,
NULL, NULL);
if (IS_ERR(session_keyring)) {
ret = PTR_ERR(session_keyring);
goto error_release;
}
/* we install a link from the user session keyring to
* the user keyring */
ret = key_link(session_keyring, uid_keyring);
if (ret < 0)
goto error_release_both;
}
/* install the keyrings */
user->uid_keyring = uid_keyring;
user->session_keyring = session_keyring;
}
mutex_unlock(&key_user_keyring_mutex);
kleave(" = 0");
return 0;
error_release_both:
key_put(session_keyring);
error_release:
key_put(uid_keyring);
error:
mutex_unlock(&key_user_keyring_mutex);
kleave(" = %d", ret);
return ret;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ecryptfs_parse_options(struct ecryptfs_sb_info *sbi, char *options)
{
char *p;
int rc = 0;
int sig_set = 0;
int cipher_name_set = 0;
int fn_cipher_name_set = 0;
int cipher_key_bytes;
int cipher_key_bytes_set = 0;
int fn_cipher_key_bytes;
int fn_cipher_key_bytes_set = 0;
struct ecryptfs_mount_crypt_stat *mount_crypt_stat =
&sbi->mount_crypt_stat;
substring_t args[MAX_OPT_ARGS];
int token;
char *sig_src;
char *cipher_name_dst;
char *cipher_name_src;
char *fn_cipher_name_dst;
char *fn_cipher_name_src;
char *fnek_dst;
char *fnek_src;
char *cipher_key_bytes_src;
char *fn_cipher_key_bytes_src;
if (!options) {
rc = -EINVAL;
goto out;
}
ecryptfs_init_mount_crypt_stat(mount_crypt_stat);
while ((p = strsep(&options, ",")) != NULL) {
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case ecryptfs_opt_sig:
case ecryptfs_opt_ecryptfs_sig:
sig_src = args[0].from;
rc = ecryptfs_add_global_auth_tok(mount_crypt_stat,
sig_src, 0);
if (rc) {
printk(KERN_ERR "Error attempting to register "
"global sig; rc = [%d]\n", rc);
goto out;
}
sig_set = 1;
break;
case ecryptfs_opt_cipher:
case ecryptfs_opt_ecryptfs_cipher:
cipher_name_src = args[0].from;
cipher_name_dst =
mount_crypt_stat->
global_default_cipher_name;
strncpy(cipher_name_dst, cipher_name_src,
ECRYPTFS_MAX_CIPHER_NAME_SIZE);
cipher_name_dst[ECRYPTFS_MAX_CIPHER_NAME_SIZE] = '\0';
cipher_name_set = 1;
break;
case ecryptfs_opt_ecryptfs_key_bytes:
cipher_key_bytes_src = args[0].from;
cipher_key_bytes =
(int)simple_strtol(cipher_key_bytes_src,
&cipher_key_bytes_src, 0);
mount_crypt_stat->global_default_cipher_key_size =
cipher_key_bytes;
cipher_key_bytes_set = 1;
break;
case ecryptfs_opt_passthrough:
mount_crypt_stat->flags |=
ECRYPTFS_PLAINTEXT_PASSTHROUGH_ENABLED;
break;
case ecryptfs_opt_xattr_metadata:
mount_crypt_stat->flags |=
ECRYPTFS_XATTR_METADATA_ENABLED;
break;
case ecryptfs_opt_encrypted_view:
mount_crypt_stat->flags |=
ECRYPTFS_XATTR_METADATA_ENABLED;
mount_crypt_stat->flags |=
ECRYPTFS_ENCRYPTED_VIEW_ENABLED;
break;
case ecryptfs_opt_fnek_sig:
fnek_src = args[0].from;
fnek_dst =
mount_crypt_stat->global_default_fnek_sig;
strncpy(fnek_dst, fnek_src, ECRYPTFS_SIG_SIZE_HEX);
mount_crypt_stat->global_default_fnek_sig[
ECRYPTFS_SIG_SIZE_HEX] = '\0';
rc = ecryptfs_add_global_auth_tok(
mount_crypt_stat,
mount_crypt_stat->global_default_fnek_sig,
ECRYPTFS_AUTH_TOK_FNEK);
if (rc) {
printk(KERN_ERR "Error attempting to register "
"global fnek sig [%s]; rc = [%d]\n",
mount_crypt_stat->global_default_fnek_sig,
rc);
goto out;
}
mount_crypt_stat->flags |=
(ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES
| ECRYPTFS_GLOBAL_ENCFN_USE_MOUNT_FNEK);
break;
case ecryptfs_opt_fn_cipher:
fn_cipher_name_src = args[0].from;
fn_cipher_name_dst =
mount_crypt_stat->global_default_fn_cipher_name;
strncpy(fn_cipher_name_dst, fn_cipher_name_src,
ECRYPTFS_MAX_CIPHER_NAME_SIZE);
mount_crypt_stat->global_default_fn_cipher_name[
ECRYPTFS_MAX_CIPHER_NAME_SIZE] = '\0';
fn_cipher_name_set = 1;
break;
case ecryptfs_opt_fn_cipher_key_bytes:
fn_cipher_key_bytes_src = args[0].from;
fn_cipher_key_bytes =
(int)simple_strtol(fn_cipher_key_bytes_src,
&fn_cipher_key_bytes_src, 0);
mount_crypt_stat->global_default_fn_cipher_key_bytes =
fn_cipher_key_bytes;
fn_cipher_key_bytes_set = 1;
break;
case ecryptfs_opt_unlink_sigs:
mount_crypt_stat->flags |= ECRYPTFS_UNLINK_SIGS;
break;
case ecryptfs_opt_mount_auth_tok_only:
mount_crypt_stat->flags |=
ECRYPTFS_GLOBAL_MOUNT_AUTH_TOK_ONLY;
break;
case ecryptfs_opt_err:
default:
printk(KERN_WARNING
"%s: eCryptfs: unrecognized option [%s]\n",
__func__, p);
}
}
if (!sig_set) {
rc = -EINVAL;
ecryptfs_printk(KERN_ERR, "You must supply at least one valid "
"auth tok signature as a mount "
"parameter; see the eCryptfs README\n");
goto out;
}
if (!cipher_name_set) {
int cipher_name_len = strlen(ECRYPTFS_DEFAULT_CIPHER);
BUG_ON(cipher_name_len >= ECRYPTFS_MAX_CIPHER_NAME_SIZE);
strcpy(mount_crypt_stat->global_default_cipher_name,
ECRYPTFS_DEFAULT_CIPHER);
}
if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)
&& !fn_cipher_name_set)
strcpy(mount_crypt_stat->global_default_fn_cipher_name,
mount_crypt_stat->global_default_cipher_name);
if (!cipher_key_bytes_set)
mount_crypt_stat->global_default_cipher_key_size = 0;
if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)
&& !fn_cipher_key_bytes_set)
mount_crypt_stat->global_default_fn_cipher_key_bytes =
mount_crypt_stat->global_default_cipher_key_size;
mutex_lock(&key_tfm_list_mutex);
if (!ecryptfs_tfm_exists(mount_crypt_stat->global_default_cipher_name,
NULL)) {
rc = ecryptfs_add_new_key_tfm(
NULL, mount_crypt_stat->global_default_cipher_name,
mount_crypt_stat->global_default_cipher_key_size);
if (rc) {
printk(KERN_ERR "Error attempting to initialize "
"cipher with name = [%s] and key size = [%td]; "
"rc = [%d]\n",
mount_crypt_stat->global_default_cipher_name,
mount_crypt_stat->global_default_cipher_key_size,
rc);
rc = -EINVAL;
mutex_unlock(&key_tfm_list_mutex);
goto out;
}
}
if ((mount_crypt_stat->flags & ECRYPTFS_GLOBAL_ENCRYPT_FILENAMES)
&& !ecryptfs_tfm_exists(
mount_crypt_stat->global_default_fn_cipher_name, NULL)) {
rc = ecryptfs_add_new_key_tfm(
NULL, mount_crypt_stat->global_default_fn_cipher_name,
mount_crypt_stat->global_default_fn_cipher_key_bytes);
if (rc) {
printk(KERN_ERR "Error attempting to initialize "
"cipher with name = [%s] and key size = [%td]; "
"rc = [%d]\n",
mount_crypt_stat->global_default_fn_cipher_name,
mount_crypt_stat->global_default_fn_cipher_key_bytes,
rc);
rc = -EINVAL;
mutex_unlock(&key_tfm_list_mutex);
goto out;
}
}
mutex_unlock(&key_tfm_list_mutex);
rc = ecryptfs_init_global_auth_toks(mount_crypt_stat);
if (rc)
printk(KERN_WARNING "One or more global auth toks could not "
"properly register; rc = [%d]\n", rc);
out:
return rc;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static __inline VOID PrintOutParsingResult(
tTcpIpPacketParsingResult res,
int level,
LPCSTR procname)
{
DPrintf(level, ("[%s] %s packet IPCS %s%s, checksum %s%s\n", procname,
GetPacketCase(res),
GetIPCSCase(res),
res.fixedIpCS ? "(fixed)" : "",
GetXxpCSCase(res),
res.fixedXxpCS ? "(fixed)" : ""));
}
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 remove_pidfile(const char *pid_file) {
if (pid_file == NULL)
return;
if (unlink(pid_file) != 0) {
vperror("Could not remove the pid file %s", pid_file);
}
}
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: zsetdevice(i_ctx_t *i_ctx_p)
{
gx_device *dev = gs_currentdevice(igs);
os_ptr op = osp;
int code = 0;
check_write_type(*op, t_device);
if (dev->LockSafetyParams) { /* do additional checking if locked */
if(op->value.pdevice != dev) /* don't allow a different device */
return_error(gs_error_invalidaccess);
}
dev->ShowpageCount = 0;
code = gs_setdevice_no_erase(igs, op->value.pdevice);
if (code < 0)
return code;
make_bool(op, code != 0); /* erase page if 1 */
invalidate_stack_devices(i_ctx_p);
clear_pagedevice(istate);
return code;
}
CWE ID:
Target: 1
Example 2:
Code: void rds_tcp_set_callbacks(struct socket *sock, struct rds_conn_path *cp)
{
struct rds_tcp_connection *tc = cp->cp_transport_data;
rdsdebug("setting sock %p callbacks to tc %p\n", sock, tc);
write_lock_bh(&sock->sk->sk_callback_lock);
/* done under the callback_lock to serialize with write_space */
spin_lock(&rds_tcp_tc_list_lock);
list_add_tail(&tc->t_list_item, &rds_tcp_tc_list);
#if IS_ENABLED(CONFIG_IPV6)
rds6_tcp_tc_count++;
#endif
if (!tc->t_cpath->cp_conn->c_isv6)
rds_tcp_tc_count++;
spin_unlock(&rds_tcp_tc_list_lock);
/* accepted sockets need our listen data ready undone */
if (sock->sk->sk_data_ready == rds_tcp_listen_data_ready)
sock->sk->sk_data_ready = sock->sk->sk_user_data;
tc->t_sock = sock;
tc->t_cpath = cp;
tc->t_orig_data_ready = sock->sk->sk_data_ready;
tc->t_orig_write_space = sock->sk->sk_write_space;
tc->t_orig_state_change = sock->sk->sk_state_change;
sock->sk->sk_user_data = cp;
sock->sk->sk_data_ready = rds_tcp_data_ready;
sock->sk->sk_write_space = rds_tcp_write_space;
sock->sk->sk_state_change = rds_tcp_state_change;
write_unlock_bh(&sock->sk->sk_callback_lock);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int link_pipe(struct pipe_inode_info *ipipe,
struct pipe_inode_info *opipe,
size_t len, unsigned int flags)
{
struct pipe_buffer *ibuf, *obuf;
int ret = 0, i = 0, nbuf;
/*
* Potential ABBA deadlock, work around it by ordering lock
* grabbing by pipe info address. Otherwise two different processes
* could deadlock (one doing tee from A -> B, the other from B -> A).
*/
pipe_double_lock(ipipe, opipe);
do {
if (!opipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
break;
}
/*
* If we have iterated all input buffers or ran out of
* output room, break.
*/
if (i >= ipipe->nrbufs || opipe->nrbufs >= opipe->buffers)
break;
ibuf = ipipe->bufs + ((ipipe->curbuf + i) & (ipipe->buffers-1));
nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1);
/*
* Get a reference to this pipe buffer,
* so we can copy the contents over.
*/
pipe_buf_get(ipipe, ibuf);
obuf = opipe->bufs + nbuf;
*obuf = *ibuf;
/*
* Don't inherit the gift flag, we need to
* prevent multiple steals of this page.
*/
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
pipe_buf_mark_unmergeable(obuf);
if (obuf->len > len)
obuf->len = len;
opipe->nrbufs++;
ret += obuf->len;
len -= obuf->len;
i++;
} while (len);
/*
* return EAGAIN if we have the potential of some data in the
* future, otherwise just return 0
*/
if (!ret && ipipe->waiting_writers && (flags & SPLICE_F_NONBLOCK))
ret = -EAGAIN;
pipe_unlock(ipipe);
pipe_unlock(opipe);
/*
* If we put data in the output pipe, wakeup any potential readers.
*/
if (ret > 0)
wakeup_pipe_readers(opipe);
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: mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_TCHECK_16BITS(&bp[i+2]);
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void r_pkcs7_free_extendedcertificatesandcertificates (RPKCS7ExtendedCertificatesAndCertificates *ecac) {
ut32 i;
if (ecac) {
for (i = 0; i < ecac->length; ++i) {
r_x509_free_certificate (ecac->elements[i]);
ecac->elements[i] = NULL;
}
R_FREE (ecac->elements);
}
}
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 CoordinatorImpl::GetVmRegionsForHeapProfiler(
const std::vector<base::ProcessId>& pids,
GetVmRegionsForHeapProfilerCallback callback) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
uint64_t dump_guid = ++next_dump_id_;
std::unique_ptr<QueuedVmRegionRequest> request =
std::make_unique<QueuedVmRegionRequest>(dump_guid, std::move(callback));
in_progress_vm_region_requests_[dump_guid] = std::move(request);
std::vector<QueuedRequestDispatcher::ClientInfo> clients;
for (const auto& kv : clients_) {
auto client_identity = kv.second->identity;
const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity);
clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type);
}
QueuedVmRegionRequest* request_ptr =
in_progress_vm_region_requests_[dump_guid].get();
auto os_callback =
base::BindRepeating(&CoordinatorImpl::OnOSMemoryDumpForVMRegions,
base::Unretained(this), dump_guid);
QueuedRequestDispatcher::SetUpAndDispatchVmRegionRequest(request_ptr, clients,
pids, os_callback);
FinalizeVmRegionDumpIfAllManagersReplied(dump_guid);
}
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: svc_rdma_is_backchannel_reply(struct svc_xprt *xprt, struct rpcrdma_msg *rmsgp)
{
__be32 *p = (__be32 *)rmsgp;
if (!xprt->xpt_bc_xprt)
return false;
if (rmsgp->rm_type != rdma_msg)
return false;
if (rmsgp->rm_body.rm_chunks[0] != xdr_zero)
return false;
if (rmsgp->rm_body.rm_chunks[1] != xdr_zero)
return false;
if (rmsgp->rm_body.rm_chunks[2] != xdr_zero)
return false;
/* sanity */
if (p[7] != rmsgp->rm_xid)
return false;
/* call direction */
if (p[8] == cpu_to_be32(RPC_CALL))
return false;
return true;
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: uint32_t GPMF_Key(GPMF_stream *ms)
{
if (ms)
{
uint32_t key = ms->buffer[ms->pos];
return key;
}
return 0;
}
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 ImageLoader::updatedHasPendingEvent() {
bool wasProtected = m_elementIsProtected;
m_elementIsProtected = m_hasPendingLoadEvent || m_hasPendingErrorEvent;
if (wasProtected == m_elementIsProtected)
return;
if (m_elementIsProtected) {
if (m_derefElementTimer.isActive())
m_derefElementTimer.stop();
else
m_keepAlive = m_element;
} else {
DCHECK(!m_derefElementTimer.isActive());
m_derefElementTimer.startOneShot(0, BLINK_FROM_HERE);
}
}
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 PageInfo::OnChangePasswordButtonPressed(
content::WebContents* web_contents) {
#if defined(FULL_SAFE_BROWSING)
DCHECK(password_protection_service_);
DCHECK(safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE ||
safe_browsing_status_ ==
SAFE_BROWSING_STATUS_ENTERPRISE_PASSWORD_REUSE);
password_protection_service_->OnUserAction(
web_contents,
safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE
? PasswordReuseEvent::SIGN_IN_PASSWORD
: PasswordReuseEvent::ENTERPRISE_PASSWORD,
safe_browsing::WarningUIType::PAGE_INFO,
safe_browsing::WarningAction::CHANGE_PASSWORD);
#endif
}
CWE ID: CWE-311
Target: 1
Example 2:
Code: SProcRenderTriStrip(ClientPtr client)
{
REQUEST(xRenderTriStripReq);
REQUEST_AT_LEAST_SIZE(xRenderTriStripReq);
swaps(&stuff->length);
swapl(&stuff->src);
swapl(&stuff->dst);
swapl(&stuff->maskFormat);
swaps(&stuff->xSrc);
swaps(&stuff->ySrc);
SwapRestL(stuff);
return (*ProcRenderVector[stuff->renderReqType]) (client);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __init apparmor_enabled_setup(char *str)
{
unsigned long enabled;
int error = kstrtoul(str, 0, &enabled);
if (!error)
apparmor_enabled = enabled ? 1 : 0;
return 1;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void jas_matrix_setall(jas_matrix_t *matrix, jas_seqent_t val)
{
int i;
int j;
jas_seqent_t *rowstart;
int rowstep;
jas_seqent_t *data;
if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {
assert(matrix->rows_);
rowstep = jas_matrix_rowstep(matrix);
for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,
rowstart += rowstep) {
for (j = matrix->numcols_, data = rowstart; j > 0; --j,
++data) {
*data = val;
}
}
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: eval_op_unary(uschar **sptr, BOOL decimal, uschar **error)
{
uschar *s = *sptr;
int_eximarith_t x;
while (isspace(*s)) s++;
if (*s == '+' || *s == '-' || *s == '~')
{
int op = *s++;
x = eval_op_unary(&s, decimal, error);
if (op == '-') x = -x;
else if (op == '~') x = ~x;
}
else
{
x = eval_number(&s, decimal, error);
}
*sptr = s;
return x;
}
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: test_js (void) {
GString *result = g_string_new("");
/* simple javascript can be evaluated and returned */
parse_cmd_line("js ('x' + 345).toUpperCase()", result);
g_assert_cmpstr("X345", ==, result->str);
/* uzbl commands can be run from javascript */
uzbl.net.useragent = "Test useragent";
parse_cmd_line("js Uzbl.run('print @useragent').toUpperCase();", result);
g_assert_cmpstr("TEST USERAGENT", ==, result->str);
g_string_free(result, 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: static v8::Handle<v8::Value> objMethodWithArgsCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.objMethodWithArgs");
if (args.Length() < 3)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0);
return toV8(imp->objMethodWithArgs(intArg, strArg, objArg), args.GetIsolate());
}
CWE ID:
Target: 1
Example 2:
Code: krb5_gss_unwrap(minor_status, context_handle,
input_message_buffer, output_message_buffer,
conf_state, qop_state)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_message_buffer;
gss_buffer_t output_message_buffer;
int *conf_state;
gss_qop_t *qop_state;
{
OM_uint32 rstat;
rstat = kg_unseal(minor_status, context_handle,
input_message_buffer, output_message_buffer,
conf_state, qop_state, KG_TOK_WRAP_MSG);
return(rstat);
}
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: gplotRead(const char *filename)
{
char buf[L_BUF_SIZE];
char *rootname, *title, *xlabel, *ylabel, *ignores;
l_int32 outformat, ret, version, ignore;
FILE *fp;
GPLOT *gplot;
PROCNAME("gplotRead");
if (!filename)
return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL);
if ((fp = fopenReadStream(filename)) == NULL)
return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL);
ret = fscanf(fp, "Gplot Version %d\n", &version);
if (ret != 1) {
fclose(fp);
return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL);
}
if (version != GPLOT_VERSION_NUMBER) {
fclose(fp);
return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL);
}
ignore = fscanf(fp, "Rootname: %s\n", buf);
rootname = stringNew(buf);
ignore = fscanf(fp, "Output format: %d\n", &outformat);
ignores = fgets(buf, L_BUF_SIZE, fp); /* Title: ... */
title = stringNew(buf + 7);
title[strlen(title) - 1] = '\0';
ignores = fgets(buf, L_BUF_SIZE, fp); /* X axis label: ... */
xlabel = stringNew(buf + 14);
xlabel[strlen(xlabel) - 1] = '\0';
ignores = fgets(buf, L_BUF_SIZE, fp); /* Y axis label: ... */
ylabel = stringNew(buf + 14);
ylabel[strlen(ylabel) - 1] = '\0';
gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel);
LEPT_FREE(rootname);
LEPT_FREE(title);
LEPT_FREE(xlabel);
LEPT_FREE(ylabel);
if (!gplot) {
fclose(fp);
return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL);
}
sarrayDestroy(&gplot->cmddata);
sarrayDestroy(&gplot->datanames);
sarrayDestroy(&gplot->plotdata);
sarrayDestroy(&gplot->plottitles);
numaDestroy(&gplot->plotstyles);
ignore = fscanf(fp, "Commandfile name: %s\n", buf);
stringReplace(&gplot->cmdname, buf);
ignore = fscanf(fp, "\nCommandfile data:");
gplot->cmddata = sarrayReadStream(fp);
ignore = fscanf(fp, "\nDatafile names:");
gplot->datanames = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot data:");
gplot->plotdata = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot titles:");
gplot->plottitles = sarrayReadStream(fp);
ignore = fscanf(fp, "\nPlot styles:");
gplot->plotstyles = numaReadStream(fp);
ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots);
ignore = fscanf(fp, "Output file name: %s\n", buf);
stringReplace(&gplot->outname, buf);
ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling);
fclose(fp);
return gplot;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static v8::Handle<v8::Value> methodWithSequenceArgCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodWithSequenceArg");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(sequence<ScriptProfile>*, sequenceArg, toNativeArray<ScriptProfile>(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
imp->methodWithSequenceArg(sequenceArg);
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: int dev_get_nest_level(struct net_device *dev)
{
struct net_device *lower = NULL;
struct list_head *iter;
int max_nest = -1;
int nest;
ASSERT_RTNL();
netdev_for_each_lower_dev(dev, lower, iter) {
nest = dev_get_nest_level(lower);
if (max_nest < nest)
max_nest = nest;
}
return max_nest + 1;
}
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: my_object_dict_of_dicts (MyObject *obj, GHashTable *in,
GHashTable **out, GError **error)
{
*out = g_hash_table_new_full (g_str_hash, g_str_equal,
(GDestroyNotify) g_free,
(GDestroyNotify) g_hash_table_destroy);
g_hash_table_foreach (in, hash_foreach_mangle_dict_of_strings, *out);
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: static void smp_task_timedout(struct timer_list *t)
{
struct sas_task_slow *slow = from_timer(slow, t, timer);
struct sas_task *task = slow->task;
unsigned long flags;
spin_lock_irqsave(&task->task_state_lock, flags);
if (!(task->task_state_flags & SAS_TASK_STATE_DONE))
task->task_state_flags |= SAS_TASK_STATE_ABORTED;
spin_unlock_irqrestore(&task->task_state_lock, flags);
complete(&task->slow_task->completion);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static bool reachedEndOfTextRenderer(const BidiRunList<BidiRun>& bidiRuns)
{
BidiRun* run = bidiRuns.logicallyLastRun();
if (!run)
return true;
unsigned pos = run->stop();
RenderObject* r = run->m_object;
if (!r->isText() || r->isBR())
return false;
RenderText* renderText = toRenderText(r);
unsigned length = renderText->textLength();
if (pos >= length)
return true;
if (renderText->is8Bit())
return endsWithASCIISpaces(renderText->characters8(), pos, length);
return endsWithASCIISpaces(renderText->characters16(), pos, length);
}
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 WebUIExtension::Send(gin::Arguments* args) {
blink::WebLocalFrame* frame;
RenderFrame* render_frame;
if (!ShouldRespondToRequest(&frame, &render_frame))
return;
std::string message;
if (!args->GetNext(&message)) {
args->ThrowError();
return;
}
if (base::EndsWith(message, "RequiringGesture",
base::CompareCase::SENSITIVE) &&
!blink::WebUserGestureIndicator::IsProcessingUserGesture(frame)) {
NOTREACHED();
return;
}
std::unique_ptr<base::ListValue> content;
if (args->PeekNext().IsEmpty() || args->PeekNext()->IsUndefined()) {
content.reset(new base::ListValue());
} else {
v8::Local<v8::Object> obj;
if (!args->GetNext(&obj)) {
args->ThrowError();
return;
}
content = base::ListValue::From(V8ValueConverter::Create()->FromV8Value(
obj, frame->MainWorldScriptContext()));
DCHECK(content);
}
render_frame->Send(new FrameHostMsg_WebUISend(render_frame->GetRoutingID(),
frame->GetDocument().Url(),
message, *content));
}
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 SharedWorkerDevToolsAgentHost::WorkerRestarted(
SharedWorkerHost* worker_host) {
DCHECK_EQ(WORKER_TERMINATED, state_);
DCHECK(!worker_host_);
state_ = WORKER_NOT_READY;
worker_host_ = worker_host;
for (DevToolsSession* session : sessions())
session->SetRenderer(GetProcess(), nullptr);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: user_change_real_name_authorized_cb (Daemon *daemon,
User *user,
GDBusMethodInvocation *context,
gpointer data)
{
gchar *name = data;
GError *error;
const gchar *argv[6];
if (g_strcmp0 (user->real_name, name) != 0) {
sys_log (context,
"change real name of user '%s' (%d) to '%s'",
user->user_name, user->uid, name);
argv[0] = "/usr/sbin/usermod";
argv[1] = "-c";
argv[2] = name;
argv[3] = "--";
argv[4] = user->user_name;
argv[5] = NULL;
error = NULL;
if (!spawn_with_login_uid (context, argv, &error)) {
throw_error (context, ERROR_FAILED, "running '%s' failed: %s", argv[0], error->message);
g_error_free (error);
return;
}
g_free (user->real_name);
user->real_name = g_strdup (name);
accounts_user_emit_changed (ACCOUNTS_USER (user));
g_object_notify (G_OBJECT (user), "real-name");
}
accounts_user_complete_set_real_name (ACCOUNTS_USER (user), context);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int atm_change_qos(struct atm_vcc *vcc, struct atm_qos *qos)
{
int error;
/*
* Don't let the QoS change the already connected AAL type nor the
* traffic class.
*/
if (qos->aal != vcc->qos.aal ||
qos->rxtp.traffic_class != vcc->qos.rxtp.traffic_class ||
qos->txtp.traffic_class != vcc->qos.txtp.traffic_class)
return -EINVAL;
error = adjust_tp(&qos->txtp, qos->aal);
if (!error)
error = adjust_tp(&qos->rxtp, qos->aal);
if (error)
return error;
if (!vcc->dev->ops->change_qos)
return -EOPNOTSUPP;
if (sk_atm(vcc)->sk_family == AF_ATMPVC)
return vcc->dev->ops->change_qos(vcc, qos, ATM_MF_SET);
return svc_change_qos(vcc, qos);
}
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: nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd_readargs *args)
{
unsigned int len;
int v;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
args->offset = ntohl(*p++);
len = args->count = ntohl(*p++);
p++; /* totalcount - unused */
len = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2);
/* set up somewhere to store response.
* We take pages, put them on reslist and include in iovec
*/
v=0;
while (len > 0) {
struct page *p = *(rqstp->rq_next_page++);
rqstp->rq_vec[v].iov_base = page_address(p);
rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE);
len -= rqstp->rq_vec[v].iov_len;
v++;
}
args->vlen = v;
return xdr_argsize_check(rqstp, p);
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: static void set_ethernet_addr(pegasus_t *pegasus)
{
__u8 node_id[6];
if (pegasus->features & PEGASUS_II) {
get_registers(pegasus, 0x10, sizeof(node_id), node_id);
} else {
get_node_id(pegasus, node_id);
set_registers(pegasus, EthID, sizeof(node_id), node_id);
}
memcpy(pegasus->net->dev_addr, node_id, sizeof(node_id));
}
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: xmlXPtrEvalXPtrPart(xmlXPathParserContextPtr ctxt, xmlChar *name) {
xmlChar *buffer, *cur;
int len;
int level;
if (name == NULL)
name = xmlXPathParseName(ctxt);
if (name == NULL)
XP_ERROR(XPATH_EXPR_ERROR);
if (CUR != '(')
XP_ERROR(XPATH_EXPR_ERROR);
NEXT;
level = 1;
len = xmlStrlen(ctxt->cur);
len++;
buffer = (xmlChar *) xmlMallocAtomic(len * sizeof (xmlChar));
if (buffer == NULL) {
xmlXPtrErrMemory("allocating buffer");
return;
}
cur = buffer;
while (CUR != 0) {
if (CUR == ')') {
level--;
if (level == 0) {
NEXT;
break;
}
*cur++ = CUR;
} else if (CUR == '(') {
level++;
*cur++ = CUR;
} else if (CUR == '^') {
NEXT;
if ((CUR == ')') || (CUR == '(') || (CUR == '^')) {
*cur++ = CUR;
} else {
*cur++ = '^';
*cur++ = CUR;
}
} else {
*cur++ = CUR;
}
NEXT;
}
*cur = 0;
if ((level != 0) && (CUR == 0)) {
xmlFree(buffer);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
if (xmlStrEqual(name, (xmlChar *) "xpointer")) {
const xmlChar *left = CUR_PTR;
CUR_PTR = buffer;
/*
* To evaluate an xpointer scheme element (4.3) we need:
* context initialized to the root
* context position initalized to 1
* context size initialized to 1
*/
ctxt->context->node = (xmlNodePtr)ctxt->context->doc;
ctxt->context->proximityPosition = 1;
ctxt->context->contextSize = 1;
xmlXPathEvalExpr(ctxt);
CUR_PTR=left;
} else if (xmlStrEqual(name, (xmlChar *) "element")) {
const xmlChar *left = CUR_PTR;
xmlChar *name2;
CUR_PTR = buffer;
if (buffer[0] == '/') {
xmlXPathRoot(ctxt);
xmlXPtrEvalChildSeq(ctxt, NULL);
} else {
name2 = xmlXPathParseName(ctxt);
if (name2 == NULL) {
CUR_PTR = left;
xmlFree(buffer);
XP_ERROR(XPATH_EXPR_ERROR);
}
xmlXPtrEvalChildSeq(ctxt, name2);
}
CUR_PTR = left;
#ifdef XPTR_XMLNS_SCHEME
} else if (xmlStrEqual(name, (xmlChar *) "xmlns")) {
const xmlChar *left = CUR_PTR;
xmlChar *prefix;
xmlChar *URI;
xmlURIPtr value;
CUR_PTR = buffer;
prefix = xmlXPathParseNCName(ctxt);
if (prefix == NULL) {
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
SKIP_BLANKS;
if (CUR != '=') {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
NEXT;
SKIP_BLANKS;
/* @@ check escaping in the XPointer WD */
value = xmlParseURI((const char *)ctxt->cur);
if (value == NULL) {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPTR_SYNTAX_ERROR);
}
URI = xmlSaveUri(value);
xmlFreeURI(value);
if (URI == NULL) {
xmlFree(prefix);
xmlFree(buffer);
xmlFree(name);
XP_ERROR(XPATH_MEMORY_ERROR);
}
xmlXPathRegisterNs(ctxt->context, prefix, URI);
CUR_PTR = left;
xmlFree(URI);
xmlFree(prefix);
#endif /* XPTR_XMLNS_SCHEME */
} else {
xmlXPtrErr(ctxt, XML_XPTR_UNKNOWN_SCHEME,
"unsupported scheme '%s'\n", name);
}
xmlFree(buffer);
xmlFree(name);
}
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: long VideoTrack::Seek(
long long time_ns,
const BlockEntry*& pResult) const
{
const long status = GetFirst(pResult);
if (status < 0) //buffer underflow, etc
return status;
assert(pResult);
if (pResult->EOS())
return 0;
const Cluster* pCluster = pResult->GetCluster();
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
return 0;
Cluster** const clusters = m_pSegment->m_clusters;
assert(clusters);
const long count = m_pSegment->GetCount(); //loaded only, not pre-loaded
assert(count > 0);
Cluster** const i = clusters + pCluster->GetIndex();
assert(i);
assert(*i == pCluster);
assert(pCluster->GetTime() <= time_ns);
Cluster** const j = clusters + count;
Cluster** lo = i;
Cluster** hi = j;
while (lo < hi)
{
Cluster** const mid = lo + (hi - lo) / 2;
assert(mid < hi);
pCluster = *mid;
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
const long long t = pCluster->GetTime();
if (t <= time_ns)
lo = mid + 1;
else
hi = mid;
assert(lo <= hi);
}
assert(lo == hi);
assert(lo > i);
assert(lo <= j);
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
pResult = pCluster->GetEntry(this, time_ns);
if ((pResult != 0) && !pResult->EOS()) //found a keyframe
return 0;
while (lo != i)
{
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
#if 0
pResult = pCluster->GetMaxKey(this);
#else
pResult = pCluster->GetEntry(this, time_ns);
#endif
if ((pResult != 0) && !pResult->EOS())
return 0;
}
pResult = GetEOS();
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
assert(0);
return NULL;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type,
png_byte bit_depth, png_uint_32 x, store_palette palette)
{
PNG_CONST png_byte sample_depth = (png_byte)(colour_type ==
PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth);
PNG_CONST unsigned int max = (1U<<sample_depth)-1;
/* Initially just set everything to the same number and the alpha to opaque.
* Note that this currently assumes a simple palette where entry x has colour
* rgb(x,x,x)!
*/
this->palette_index = this->red = this->green = this->blue =
sample(row, colour_type, bit_depth, x, 0);
this->alpha = max;
this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT =
sample_depth;
/* Then override as appropriate: */
if (colour_type == 3) /* palette */
{
/* This permits the caller to default to the sample value. */
if (palette != 0)
{
PNG_CONST unsigned int i = this->palette_index;
this->red = palette[i].red;
this->green = palette[i].green;
this->blue = palette[i].blue;
this->alpha = palette[i].alpha;
}
}
else /* not palette */
{
unsigned int i = 0;
if (colour_type & 2)
{
this->green = sample(row, colour_type, bit_depth, x, 1);
this->blue = sample(row, colour_type, bit_depth, x, 2);
i = 2;
}
if (colour_type & 4)
this->alpha = sample(row, colour_type, bit_depth, x, ++i);
}
/* Calculate the scaled values, these are simply the values divided by
* 'max' and the error is initialized to the double precision epsilon value
* from the header file.
*/
image_pixel_setf(this, max);
/* Store the input information for use in the transforms - these will
* modify the information.
*/
this->colour_type = colour_type;
this->bit_depth = bit_depth;
this->sample_depth = sample_depth;
this->have_tRNS = 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: log2vis_encoded_string (PyObject * string, const char *encoding,
FriBidiParType base_direction, int clean, int reordernsm)
{
PyObject *logical = NULL; /* logical unicode object */
PyObject *result = NULL; /* output string object */
/* Always needed for the string length */
logical = PyUnicode_Decode (PyString_AS_STRING (string),
PyString_GET_SIZE (string),
encoding, "strict");
if (logical == NULL)
return NULL;
if (strcmp (encoding, "utf-8") == 0)
/* Shortcut for utf8 strings (little faster) */
result = log2vis_utf8 (string,
PyUnicode_GET_SIZE (logical),
base_direction, clean, reordernsm);
else
{
/* Invoke log2vis_unicode and encode back to encoding */
PyObject *visual = log2vis_unicode (logical, base_direction, clean, reordernsm);
if (visual)
{
result = PyUnicode_Encode (PyUnicode_AS_UNICODE
(visual),
PyUnicode_GET_SIZE (visual),
encoding, "strict");
Py_DECREF (visual);
}
}
Py_DECREF (logical);
return result;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ParentWithMixinPointer() : mixin_(nullptr) {}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int jas_icccurv_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval)
{
/* Avoid compiler warnings about unused parameters. */
attrval = 0;
othattrval = 0;
/* Not yet implemented. */
abort();
return -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: ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port)
{
char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
char *s;
struct kex *kex;
int r;
xxx_host = host;
xxx_hostaddr = hostaddr;
if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL)
fatal("%s: kex_names_cat", __func__);
myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s);
myproposal[PROPOSAL_ENC_ALGS_CTOS] =
compat_cipher_proposal(options.ciphers);
myproposal[PROPOSAL_ENC_ALGS_STOC] =
compat_cipher_proposal(options.ciphers);
myproposal[PROPOSAL_COMP_ALGS_CTOS] =
myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ?
"[email protected],zlib,none" : "none,[email protected],zlib";
myproposal[PROPOSAL_MAC_ALGS_CTOS] =
myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
if (options.hostkeyalgorithms != NULL) {
if (kex_assemble_names(KEX_DEFAULT_PK_ALG,
&options.hostkeyalgorithms) != 0)
fatal("%s: kex_assemble_namelist", __func__);
myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
compat_pkalg_proposal(options.hostkeyalgorithms);
} else {
/* Enforce default */
options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG);
/* Prefer algorithms that we already have keys for */
myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] =
compat_pkalg_proposal(
order_hostkeyalgs(host, hostaddr, port));
}
if (options.rekey_limit || options.rekey_interval)
packet_set_rekey_limits((u_int32_t)options.rekey_limit,
(time_t)options.rekey_interval);
/* start key exchange */
if ((r = kex_setup(active_state, myproposal)) != 0)
fatal("kex_setup: %s", ssh_err(r));
kex = active_state->kex;
#ifdef WITH_OPENSSL
kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
kex->kex[KEX_DH_GRP14_SHA256] = kexdh_client;
kex->kex[KEX_DH_GRP16_SHA512] = kexdh_client;
kex->kex[KEX_DH_GRP18_SHA512] = kexdh_client;
kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
#endif
kex->kex[KEX_C25519_SHA256] = kexc25519_client;
kex->client_version_string=client_version_string;
kex->server_version_string=server_version_string;
kex->verify_host_key=&verify_host_key_callback;
dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
/* remove ext-info from the KEX proposals for rekeying */
myproposal[PROPOSAL_KEX_ALGS] =
compat_kex_proposal(options.kex_algorithms);
if ((r = kex_prop2buf(kex->my, myproposal)) != 0)
fatal("kex_prop2buf: %s", ssh_err(r));
session_id2 = kex->session_id;
session_id2_len = kex->session_id_len;
#ifdef DEBUG_KEXDH
/* send 1st encrypted/maced/compressed message */
packet_start(SSH2_MSG_IGNORE);
packet_put_cstring("markus");
packet_send();
packet_write_wait();
#endif
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void dvcman_channel_free(void* arg)
{
DVCMAN_CHANNEL* channel = (DVCMAN_CHANNEL*) arg;
UINT error = CHANNEL_RC_OK;
if (channel)
{
if (channel->channel_callback)
{
IFCALL(channel->channel_callback->OnClose,
channel->channel_callback);
}
if (channel->status == CHANNEL_RC_OK)
{
IWTSVirtualChannel* ichannel = (IWTSVirtualChannel*) channel;
if (channel->dvcman && channel->dvcman->drdynvc)
{
DrdynvcClientContext* context = channel->dvcman->drdynvc->context;
if (context)
{
IFCALLRET(context->OnChannelDisconnected, error,
context, channel->channel_name,
channel->pInterface);
}
}
error = IFCALLRESULT(CHANNEL_RC_OK, ichannel->Close, ichannel);
if (error != CHANNEL_RC_OK)
WLog_ERR(TAG, "Close failed with error %"PRIu32"!", error);
}
if (channel->dvc_data)
Stream_Release(channel->dvc_data);
DeleteCriticalSection(&(channel->lock));
free(channel->channel_name);
}
free(channel);
}
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 numa_default_policy(void)
{
do_set_mempolicy(MPOL_DEFAULT, 0, NULL);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: exsltCryptoPopString (xmlXPathParserContextPtr ctxt, int nargs,
xmlChar ** str) {
int str_len = 0;
if ((nargs < 1) || (nargs > 2)) {
xmlXPathSetArityError (ctxt);
return 0;
}
*str = xmlXPathPopString (ctxt);
str_len = xmlUTF8Strlen (*str);
if (str_len == 0) {
xmlXPathReturnEmptyString (ctxt);
xmlFree (*str);
return 0;
}
return str_len;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ServiceWorkerDevToolsAgentHost::~ServiceWorkerDevToolsAgentHost() {
ServiceWorkerDevToolsManager::GetInstance()->AgentHostDestroyed(this);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void VRDisplay::FocusChanged() {
vr_v_sync_provider_.reset();
ConnectVSyncProvider();
}
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: int ovl_setattr(struct dentry *dentry, struct iattr *attr)
{
int err;
struct dentry *upperdentry;
err = ovl_want_write(dentry);
if (err)
goto out;
upperdentry = ovl_dentry_upper(dentry);
if (upperdentry) {
mutex_lock(&upperdentry->d_inode->i_mutex);
err = notify_change(upperdentry, attr, NULL);
mutex_unlock(&upperdentry->d_inode->i_mutex);
} else {
err = ovl_copy_up_last(dentry, attr, false);
}
ovl_drop_write(dentry);
out:
return err;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: int btrfs_prev_leaf(struct btrfs_root *root, struct btrfs_path *path)
{
struct btrfs_key key;
struct btrfs_disk_key found_key;
int ret;
btrfs_item_key_to_cpu(path->nodes[0], &key, 0);
if (key.offset > 0) {
key.offset--;
} else if (key.type > 0) {
key.type--;
key.offset = (u64)-1;
} else if (key.objectid > 0) {
key.objectid--;
key.type = (u8)-1;
key.offset = (u64)-1;
} else {
return 1;
}
btrfs_release_path(path);
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
return ret;
btrfs_item_key(path->nodes[0], &found_key, 0);
ret = comp_keys(&found_key, &key);
/*
* We might have had an item with the previous key in the tree right
* before we released our path. And after we released our path, that
* item might have been pushed to the first slot (0) of the leaf we
* were holding due to a tree balance. Alternatively, an item with the
* previous key can exist as the only element of a leaf (big fat item).
* Therefore account for these 2 cases, so that our callers (like
* btrfs_previous_item) don't miss an existing item with a key matching
* the previous key we computed above.
*/
if (ret <= 0)
return 0;
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: static void ZSTD_invalidateMatchState(ZSTD_matchState_t* ms)
{
ZSTD_window_clear(&ms->window);
ms->nextToUpdate = ms->window.dictLimit + 1;
ms->nextToUpdate3 = ms->window.dictLimit + 1;
ms->loadedDictEnd = 0;
ms->opt.litLengthSum = 0; /* force reset of btopt stats */
ms->dictMatchState = NULL;
}
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 dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
if (cid <= 0)
continue;
dctx->remaining = avpriv_dnxhd_get_frame_size(cid);
if (dctx->remaining <= 0) {
dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (dctx->remaining <= 0)
return dctx->remaining;
}
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void vrend_destroy_shader_object(void *obj_ptr)
{
struct vrend_shader_selector *state = obj_ptr;
vrend_shader_state_reference(&state, NULL);
}
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: static int tg3_halt_cpu(struct tg3 *tp, u32 offset)
{
int i;
BUG_ON(offset == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS));
if (tg3_asic_rev(tp) == ASIC_REV_5906) {
u32 val = tr32(GRC_VCPU_EXT_CTRL);
tw32(GRC_VCPU_EXT_CTRL, val | GRC_VCPU_EXT_CTRL_HALT_CPU);
return 0;
}
if (offset == RX_CPU_BASE) {
for (i = 0; i < 10000; i++) {
tw32(offset + CPU_STATE, 0xffffffff);
tw32(offset + CPU_MODE, CPU_MODE_HALT);
if (tr32(offset + CPU_MODE) & CPU_MODE_HALT)
break;
}
tw32(offset + CPU_STATE, 0xffffffff);
tw32_f(offset + CPU_MODE, CPU_MODE_HALT);
udelay(10);
} else {
/*
* There is only an Rx CPU for the 5750 derivative in the
* BCM4785.
*/
if (tg3_flag(tp, IS_SSB_CORE))
return 0;
for (i = 0; i < 10000; i++) {
tw32(offset + CPU_STATE, 0xffffffff);
tw32(offset + CPU_MODE, CPU_MODE_HALT);
if (tr32(offset + CPU_MODE) & CPU_MODE_HALT)
break;
}
}
if (i >= 10000) {
netdev_err(tp->dev, "%s timed out, %s CPU\n",
__func__, offset == RX_CPU_BASE ? "RX" : "TX");
return -ENODEV;
}
/* Clear firmware's nvram arbitration. */
if (tg3_flag(tp, NVRAM))
tw32(NVRAM_SWARB, SWARB_REQ_CLR0);
return 0;
}
CWE ID: CWE-119
Output: | 0 |
Subsets and Splits