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: void* H264SwDecMalloc(u32 size)
{
#if defined(CHECK_MEMORY_USAGE)
/* Note that if the decoder has to free and reallocate some of the buffers
* the total value will be invalid */
static u32 numBytes = 0;
numBytes += size;
DEBUG(("Allocated %d bytes, total %d\n", size, numBytes));
#endif
return malloc(size);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool WebGLRenderingContextBase::ValidateDrawElements(const char* function_name,
GLenum type,
long long offset) {
if (isContextLost())
return false;
if (type == GL_UNSIGNED_INT && !IsWebGL2OrHigher() &&
!ExtensionEnabled(kOESElementIndexUintName)) {
SynthesizeGLError(GL_INVALID_ENUM, function_name, "invalid type");
return false;
}
if (!ValidateValueFitNonNegInt32(function_name, "offset", offset))
return false;
if (!ValidateRenderingState(function_name)) {
return false;
}
const char* reason = "framebuffer incomplete";
if (framebuffer_binding_ && framebuffer_binding_->CheckDepthStencilStatus(
&reason) != GL_FRAMEBUFFER_COMPLETE) {
SynthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, function_name, reason);
return false;
}
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: static void locationWithCallWithAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithCallWith());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefCallWith(callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()), cppValue);
}
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: bool TestDataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const {
return add_default_proxy_bypass_rules_;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void complete_vfork_done(struct task_struct *tsk)
{
struct completion *vfork;
task_lock(tsk);
vfork = tsk->vfork_done;
if (likely(vfork)) {
tsk->vfork_done = NULL;
complete(vfork);
}
task_unlock(tsk);
}
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: http_rxchunk(struct http *hp)
{
char *q;
int l, i;
l = hp->prxbuf;
do
(void)http_rxchar(hp, 1, 0);
while (hp->rxbuf[hp->prxbuf - 1] != '\n');
vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1);
i = strtoul(hp->rxbuf + l, &q, 16);
bprintf(hp->chunklen, "%d", i);
if ((q == hp->rxbuf + l) ||
(*q != '\0' && !vct_islws(*q))) {
vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d",
*q, q - (hp->rxbuf + l));
}
assert(q != hp->rxbuf + l);
assert(*q == '\0' || vct_islws(*q));
hp->prxbuf = l;
if (i > 0) {
(void)http_rxchar(hp, i, 0);
vtc_dump(hp->vl, 4, "chunk",
hp->rxbuf + l, i);
}
l = hp->prxbuf;
(void)http_rxchar(hp, 2, 0);
if(!vct_iscrlf(hp->rxbuf[l]))
vtc_log(hp->vl, hp->fatal,
"Wrong chunk tail[0] = %02x",
hp->rxbuf[l] & 0xff);
if(!vct_iscrlf(hp->rxbuf[l + 1]))
vtc_log(hp->vl, hp->fatal,
"Wrong chunk tail[1] = %02x",
hp->rxbuf[l + 1] & 0xff);
hp->prxbuf = l;
hp->rxbuf[l] = '\0';
return (i);
}
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 DeleteSymlink(const FilePath& file_path) {
const bool deleted = HANDLE_EINTR(unlink(file_path.value().c_str())) == 0;
return deleted;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int midi_setup_portprefix(struct _mdi *mdi, uint32_t setting) {
MIDI_EVENT_DEBUG(__FUNCTION__,0, setting);
_WM_CheckEventMemoryPool(mdi);
mdi->events[mdi->event_count].do_event = *_WM_do_meta_portprefix;
mdi->events[mdi->event_count].event_data.channel = 0;
mdi->events[mdi->event_count].event_data.data.value = setting;
mdi->events[mdi->event_count].samples_to_next = 0;
mdi->event_count++;
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: static void carray(JF, js_Ast *list)
{
int i = 0;
while (list) {
if (list->a->type != EXP_UNDEF) {
emitnumber(J, F, i++);
cexp(J, F, list->a);
emit(J, F, OP_INITPROP);
} else {
++i;
}
list = list->b;
}
}
CWE ID: CWE-476
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int load_misc_binary(struct linux_binprm *bprm)
{
Node *fmt;
struct file * interp_file = NULL;
char iname[BINPRM_BUF_SIZE];
const char *iname_addr = iname;
int retval;
int fd_binary = -1;
retval = -ENOEXEC;
if (!enabled)
goto _ret;
/* to keep locking time low, we copy the interpreter string */
read_lock(&entries_lock);
fmt = check_file(bprm);
if (fmt)
strlcpy(iname, fmt->interpreter, BINPRM_BUF_SIZE);
read_unlock(&entries_lock);
if (!fmt)
goto _ret;
if (!(fmt->flags & MISC_FMT_PRESERVE_ARGV0)) {
retval = remove_arg_zero(bprm);
if (retval)
goto _ret;
}
if (fmt->flags & MISC_FMT_OPEN_BINARY) {
/* if the binary should be opened on behalf of the
* interpreter than keep it open and assign descriptor
* to it */
fd_binary = get_unused_fd();
if (fd_binary < 0) {
retval = fd_binary;
goto _ret;
}
fd_install(fd_binary, bprm->file);
/* if the binary is not readable than enforce mm->dumpable=0
regardless of the interpreter's permissions */
would_dump(bprm, bprm->file);
allow_write_access(bprm->file);
bprm->file = NULL;
/* mark the bprm that fd should be passed to interp */
bprm->interp_flags |= BINPRM_FLAGS_EXECFD;
bprm->interp_data = fd_binary;
} else {
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
}
/* make argv[1] be the path to the binary */
retval = copy_strings_kernel (1, &bprm->interp, bprm);
if (retval < 0)
goto _error;
bprm->argc++;
/* add the interp as argv[0] */
retval = copy_strings_kernel (1, &iname_addr, bprm);
if (retval < 0)
goto _error;
bprm->argc ++;
bprm->interp = iname; /* for binfmt_script */
interp_file = open_exec (iname);
retval = PTR_ERR (interp_file);
if (IS_ERR (interp_file))
goto _error;
bprm->file = interp_file;
if (fmt->flags & MISC_FMT_CREDENTIALS) {
/*
* No need to call prepare_binprm(), it's already been
* done. bprm->buf is stale, update from interp_file.
*/
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
retval = kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
} else
retval = prepare_binprm (bprm);
if (retval < 0)
goto _error;
retval = search_binary_handler(bprm);
if (retval < 0)
goto _error;
_ret:
return retval;
_error:
if (fd_binary > 0)
sys_close(fd_binary);
bprm->interp_flags = 0;
bprm->interp_data = 0;
goto _ret;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int ecp_normalize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P )
{
int ret;
#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
if ( mbedtls_internal_ecp_grp_capable( grp ) )
{
return mbedtls_internal_ecp_normalize_mxz( grp, P );
}
#endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &P->Z, &P->Z, &grp->P ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &P->X, &P->X, &P->Z ) ); MOD_MUL( P->X );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) );
cleanup:
return( ret );
}
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 gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct)
{
int c, dc;
int x, y;
int tox, toy;
int ncR, ncG, ncB;
toy = dstY;
for (y = srcY; y < (srcY + h); y++) {
tox = dstX;
for (x = srcX; x < (srcX + w); x++) {
int nc;
c = gdImageGetPixel(src, x, y);
/* Added 7/24/95: support transparent copies */
if (gdImageGetTransparent(src) == c) {
tox++;
continue;
}
/* If it's the same image, mapping is trivial */
if (dst == src) {
nc = c;
} else {
dc = gdImageGetPixel(dst, tox, toy);
ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0));
ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0));
ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0));
/* Find a reasonable color */
nc = gdImageColorResolve (dst, ncR, ncG, ncB);
}
gdImageSetPixel (dst, tox, toy, nc);
tox++;
}
toy++;
}
}
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: SMBC_server_internal(TALLOC_CTX *ctx,
SMBCCTX *context,
bool connect_if_not_found,
const char *server,
uint16_t port,
const char *share,
char **pp_workgroup,
char **pp_username,
char **pp_password,
bool *in_cache)
{
SMBCSRV *srv=NULL;
char *workgroup = NULL;
struct cli_state *c = NULL;
const char *server_n = server;
int is_ipc = (share != NULL && strcmp(share, "IPC$") == 0);
uint32_t fs_attrs = 0;
const char *username_used;
NTSTATUS status;
char *newserver, *newshare;
int flags = 0;
struct smbXcli_tcon *tcon = NULL;
ZERO_STRUCT(c);
*in_cache = false;
if (server[0] == 0) {
errno = EPERM;
return NULL;
}
/* Look for a cached connection */
srv = SMBC_find_server(ctx, context, server, share,
pp_workgroup, pp_username, pp_password);
/*
* If we found a connection and we're only allowed one share per
* server...
*/
if (srv &&
share != NULL && *share != '\0' &&
smbc_getOptionOneSharePerServer(context)) {
/*
* ... then if there's no current connection to the share,
* connect to it. SMBC_find_server(), or rather the function
* pointed to by context->get_cached_srv_fn which
* was called by SMBC_find_server(), will have issued a tree
* disconnect if the requested share is not the same as the
* one that was already connected.
*/
/*
* Use srv->cli->desthost and srv->cli->share instead of
* server and share below to connect to the actual share,
* i.e., a normal share or a referred share from
* 'msdfs proxy' share.
*/
if (!cli_state_has_tcon(srv->cli)) {
/* Ensure we have accurate auth info */
SMBC_call_auth_fn(ctx, context,
smbXcli_conn_remote_name(srv->cli->conn),
srv->cli->share,
pp_workgroup,
pp_username,
pp_password);
if (!*pp_workgroup || !*pp_username || !*pp_password) {
errno = ENOMEM;
cli_shutdown(srv->cli);
srv->cli = NULL;
smbc_getFunctionRemoveCachedServer(context)(context,
srv);
return NULL;
}
/*
* We don't need to renegotiate encryption
* here as the encryption context is not per
* tid.
*/
status = cli_tree_connect(srv->cli,
srv->cli->share,
"?????",
*pp_password,
strlen(*pp_password)+1);
if (!NT_STATUS_IS_OK(status)) {
errno = map_errno_from_nt_status(status);
cli_shutdown(srv->cli);
srv->cli = NULL;
smbc_getFunctionRemoveCachedServer(context)(context,
srv);
srv = NULL;
}
/* Determine if this share supports case sensitivity */
if (is_ipc) {
DEBUG(4,
("IPC$ so ignore case sensitivity\n"));
status = NT_STATUS_OK;
} else {
status = cli_get_fs_attr_info(c, &fs_attrs);
}
if (!NT_STATUS_IS_OK(status)) {
DEBUG(4, ("Could not retrieve "
"case sensitivity flag: %s.\n",
nt_errstr(status)));
/*
* We can't determine the case sensitivity of
* the share. We have no choice but to use the
* user-specified case sensitivity setting.
*/
if (smbc_getOptionCaseSensitive(context)) {
cli_set_case_sensitive(c, True);
} else {
cli_set_case_sensitive(c, False);
}
} else if (!is_ipc) {
DEBUG(4,
("Case sensitive: %s\n",
(fs_attrs & FILE_CASE_SENSITIVE_SEARCH
? "True"
: "False")));
cli_set_case_sensitive(
c,
(fs_attrs & FILE_CASE_SENSITIVE_SEARCH
? True
: False));
}
/*
* Regenerate the dev value since it's based on both
* server and share
*/
if (srv) {
const char *remote_name =
smbXcli_conn_remote_name(srv->cli->conn);
srv->dev = (dev_t)(str_checksum(remote_name) ^
str_checksum(srv->cli->share));
}
}
}
/* If we have a connection... */
if (srv) {
/* ... then we're done here. Give 'em what they came for. */
*in_cache = true;
goto done;
}
/* If we're not asked to connect when a connection doesn't exist... */
if (! connect_if_not_found) {
/* ... then we're done here. */
return NULL;
}
if (!*pp_workgroup || !*pp_username || !*pp_password) {
errno = ENOMEM;
return NULL;
}
DEBUG(4,("SMBC_server: server_n=[%s] server=[%s]\n", server_n, server));
DEBUG(4,(" -> server_n=[%s] server=[%s]\n", server_n, server));
status = NT_STATUS_UNSUCCESSFUL;
if (smbc_getOptionUseKerberos(context)) {
flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
}
if (smbc_getOptionFallbackAfterKerberos(context)) {
flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
}
if (smbc_getOptionUseCCache(context)) {
flags |= CLI_FULL_CONNECTION_USE_CCACHE;
}
if (smbc_getOptionUseNTHash(context)) {
flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
flags |= CLI_FULL_CONNECTION_USE_NT_HASH;
}
if (port == 0) {
if (share == NULL || *share == '\0' || is_ipc) {
/*
}
*/
status = cli_connect_nb(server_n, NULL, NBT_SMB_PORT, 0x20,
smbc_getNetbiosName(context),
SMB_SIGNING_DEFAULT, flags, &c);
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: const char* ValueForType(ServerFieldType type) {
switch (type) {
case EMPTY_TYPE:
return "";
case NO_SERVER_DATA:
case UNKNOWN_TYPE:
return "unknown";
case COMPANY_NAME:
return "RCA";
case NAME_FIRST:
return "Elvis";
case NAME_MIDDLE:
return "Aaron";
case NAME_LAST:
return "Presley";
case NAME_FULL:
return "Elvis Aaron Presley";
case EMAIL_ADDRESS:
return "[email protected]";
case PHONE_HOME_NUMBER:
case PHONE_HOME_WHOLE_NUMBER:
case PHONE_HOME_CITY_AND_NUMBER:
return "2345678901";
case ADDRESS_HOME_STREET_ADDRESS:
return "123 Apple St.\nunit 6";
case ADDRESS_HOME_LINE1:
return "123 Apple St.";
case ADDRESS_HOME_LINE2:
return "unit 6";
case ADDRESS_HOME_CITY:
return "Lubbock";
case ADDRESS_HOME_STATE:
return "Texas";
case ADDRESS_HOME_ZIP:
return "79401";
case ADDRESS_HOME_COUNTRY:
return "US";
case AMBIGUOUS_TYPE:
CreateAmbiguousProfiles();
return "Decca";
default:
NOTREACHED(); // Fall through
return "unexpected!";
}
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int wait_task_zombie(struct wait_opts *wo, struct task_struct *p)
{
int state, status;
pid_t pid = task_pid_vnr(p);
uid_t uid = from_kuid_munged(current_user_ns(), task_uid(p));
struct waitid_info *infop;
if (!likely(wo->wo_flags & WEXITED))
return 0;
if (unlikely(wo->wo_flags & WNOWAIT)) {
status = p->exit_code;
get_task_struct(p);
read_unlock(&tasklist_lock);
sched_annotate_sleep();
if (wo->wo_rusage)
getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
put_task_struct(p);
goto out_info;
}
/*
* Move the task's state to DEAD/TRACE, only one thread can do this.
*/
state = (ptrace_reparented(p) && thread_group_leader(p)) ?
EXIT_TRACE : EXIT_DEAD;
if (cmpxchg(&p->exit_state, EXIT_ZOMBIE, state) != EXIT_ZOMBIE)
return 0;
/*
* We own this thread, nobody else can reap it.
*/
read_unlock(&tasklist_lock);
sched_annotate_sleep();
/*
* Check thread_group_leader() to exclude the traced sub-threads.
*/
if (state == EXIT_DEAD && thread_group_leader(p)) {
struct signal_struct *sig = p->signal;
struct signal_struct *psig = current->signal;
unsigned long maxrss;
u64 tgutime, tgstime;
/*
* The resource counters for the group leader are in its
* own task_struct. Those for dead threads in the group
* are in its signal_struct, as are those for the child
* processes it has previously reaped. All these
* accumulate in the parent's signal_struct c* fields.
*
* We don't bother to take a lock here to protect these
* p->signal fields because the whole thread group is dead
* and nobody can change them.
*
* psig->stats_lock also protects us from our sub-theads
* which can reap other children at the same time. Until
* we change k_getrusage()-like users to rely on this lock
* we have to take ->siglock as well.
*
* We use thread_group_cputime_adjusted() to get times for
* the thread group, which consolidates times for all threads
* in the group including the group leader.
*/
thread_group_cputime_adjusted(p, &tgutime, &tgstime);
spin_lock_irq(¤t->sighand->siglock);
write_seqlock(&psig->stats_lock);
psig->cutime += tgutime + sig->cutime;
psig->cstime += tgstime + sig->cstime;
psig->cgtime += task_gtime(p) + sig->gtime + sig->cgtime;
psig->cmin_flt +=
p->min_flt + sig->min_flt + sig->cmin_flt;
psig->cmaj_flt +=
p->maj_flt + sig->maj_flt + sig->cmaj_flt;
psig->cnvcsw +=
p->nvcsw + sig->nvcsw + sig->cnvcsw;
psig->cnivcsw +=
p->nivcsw + sig->nivcsw + sig->cnivcsw;
psig->cinblock +=
task_io_get_inblock(p) +
sig->inblock + sig->cinblock;
psig->coublock +=
task_io_get_oublock(p) +
sig->oublock + sig->coublock;
maxrss = max(sig->maxrss, sig->cmaxrss);
if (psig->cmaxrss < maxrss)
psig->cmaxrss = maxrss;
task_io_accounting_add(&psig->ioac, &p->ioac);
task_io_accounting_add(&psig->ioac, &sig->ioac);
write_sequnlock(&psig->stats_lock);
spin_unlock_irq(¤t->sighand->siglock);
}
if (wo->wo_rusage)
getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
status = (p->signal->flags & SIGNAL_GROUP_EXIT)
? p->signal->group_exit_code : p->exit_code;
wo->wo_stat = status;
if (state == EXIT_TRACE) {
write_lock_irq(&tasklist_lock);
/* We dropped tasklist, ptracer could die and untrace */
ptrace_unlink(p);
/* If parent wants a zombie, don't release it now */
state = EXIT_ZOMBIE;
if (do_notify_parent(p, p->exit_signal))
state = EXIT_DEAD;
p->exit_state = state;
write_unlock_irq(&tasklist_lock);
}
if (state == EXIT_DEAD)
release_task(p);
out_info:
infop = wo->wo_info;
if (infop) {
if ((status & 0x7f) == 0) {
infop->cause = CLD_EXITED;
infop->status = status >> 8;
} else {
infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
infop->status = status & 0x7f;
}
infop->pid = pid;
infop->uid = uid;
}
return pid;
}
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: xfs_attr_shortform_list(xfs_attr_list_context_t *context)
{
attrlist_cursor_kern_t *cursor;
xfs_attr_sf_sort_t *sbuf, *sbp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_inode_t *dp;
int sbsize, nsbuf, count, i;
int error;
ASSERT(context != NULL);
dp = context->dp;
ASSERT(dp != NULL);
ASSERT(dp->i_afp != NULL);
sf = (xfs_attr_shortform_t *)dp->i_afp->if_u1.if_data;
ASSERT(sf != NULL);
if (!sf->hdr.count)
return 0;
cursor = context->cursor;
ASSERT(cursor != NULL);
trace_xfs_attr_list_sf(context);
/*
* If the buffer is large enough and the cursor is at the start,
* do not bother with sorting since we will return everything in
* one buffer and another call using the cursor won't need to be
* made.
* Note the generous fudge factor of 16 overhead bytes per entry.
* If bufsize is zero then put_listent must be a search function
* and can just scan through what we have.
*/
if (context->bufsize == 0 ||
(XFS_ISRESET_CURSOR(cursor) &&
(dp->i_afp->if_bytes + sf->hdr.count * 16) < context->bufsize)) {
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
error = context->put_listent(context,
sfe->flags,
sfe->nameval,
(int)sfe->namelen,
(int)sfe->valuelen,
&sfe->nameval[sfe->namelen]);
/*
* Either search callback finished early or
* didn't fit it all in the buffer after all.
*/
if (context->seen_enough)
break;
if (error)
return error;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
trace_xfs_attr_list_sf_all(context);
return 0;
}
/* do no more for a search callback */
if (context->bufsize == 0)
return 0;
/*
* It didn't all fit, so we have to sort everything on hashval.
*/
sbsize = sf->hdr.count * sizeof(*sbuf);
sbp = sbuf = kmem_alloc(sbsize, KM_SLEEP | KM_NOFS);
/*
* Scan the attribute list for the rest of the entries, storing
* the relevant info from only those that match into a buffer.
*/
nsbuf = 0;
for (i = 0, sfe = &sf->list[0]; i < sf->hdr.count; i++) {
if (unlikely(
((char *)sfe < (char *)sf) ||
((char *)sfe >= ((char *)sf + dp->i_afp->if_bytes)))) {
XFS_CORRUPTION_ERROR("xfs_attr_shortform_list",
XFS_ERRLEVEL_LOW,
context->dp->i_mount, sfe);
kmem_free(sbuf);
return -EFSCORRUPTED;
}
sbp->entno = i;
sbp->hash = xfs_da_hashname(sfe->nameval, sfe->namelen);
sbp->name = sfe->nameval;
sbp->namelen = sfe->namelen;
/* These are bytes, and both on-disk, don't endian-flip */
sbp->valuelen = sfe->valuelen;
sbp->flags = sfe->flags;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
sbp++;
nsbuf++;
}
/*
* Sort the entries on hash then entno.
*/
xfs_sort(sbuf, nsbuf, sizeof(*sbuf), xfs_attr_shortform_compare);
/*
* Re-find our place IN THE SORTED LIST.
*/
count = 0;
cursor->initted = 1;
cursor->blkno = 0;
for (sbp = sbuf, i = 0; i < nsbuf; i++, sbp++) {
if (sbp->hash == cursor->hashval) {
if (cursor->offset == count) {
break;
}
count++;
} else if (sbp->hash > cursor->hashval) {
break;
}
}
if (i == nsbuf) {
kmem_free(sbuf);
return 0;
}
/*
* Loop putting entries into the user buffer.
*/
for ( ; i < nsbuf; i++, sbp++) {
if (cursor->hashval != sbp->hash) {
cursor->hashval = sbp->hash;
cursor->offset = 0;
}
error = context->put_listent(context,
sbp->flags,
sbp->name,
sbp->namelen,
sbp->valuelen,
&sbp->name[sbp->namelen]);
if (error)
return error;
if (context->seen_enough)
break;
cursor->offset++;
}
kmem_free(sbuf);
return 0;
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc)
{
struct packet_type *ptype, *pt_prev;
rx_handler_func_t *rx_handler;
struct net_device *orig_dev;
bool deliver_exact = false;
int ret = NET_RX_DROP;
__be16 type;
net_timestamp_check(!netdev_tstamp_prequeue, skb);
trace_netif_receive_skb(skb);
orig_dev = skb->dev;
skb_reset_network_header(skb);
if (!skb_transport_header_was_set(skb))
skb_reset_transport_header(skb);
skb_reset_mac_len(skb);
pt_prev = NULL;
another_round:
skb->skb_iif = skb->dev->ifindex;
__this_cpu_inc(softnet_data.processed);
if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
skb = skb_vlan_untag(skb);
if (unlikely(!skb))
goto out;
}
if (skb_skip_tc_classify(skb))
goto skip_classify;
if (pfmemalloc)
goto skip_taps;
list_for_each_entry_rcu(ptype, &ptype_all, list) {
if (pt_prev)
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
if (pt_prev)
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
skip_taps:
#ifdef CONFIG_NET_INGRESS
if (static_key_false(&ingress_needed)) {
skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
if (!skb)
goto out;
if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
goto out;
}
#endif
skb_reset_tc(skb);
skip_classify:
if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
goto drop;
if (skb_vlan_tag_present(skb)) {
if (pt_prev) {
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = NULL;
}
if (vlan_do_receive(&skb))
goto another_round;
else if (unlikely(!skb))
goto out;
}
rx_handler = rcu_dereference(skb->dev->rx_handler);
if (rx_handler) {
if (pt_prev) {
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = NULL;
}
switch (rx_handler(&skb)) {
case RX_HANDLER_CONSUMED:
ret = NET_RX_SUCCESS;
goto out;
case RX_HANDLER_ANOTHER:
goto another_round;
case RX_HANDLER_EXACT:
deliver_exact = true;
case RX_HANDLER_PASS:
break;
default:
BUG();
}
}
if (unlikely(skb_vlan_tag_present(skb))) {
if (skb_vlan_tag_get_id(skb))
skb->pkt_type = PACKET_OTHERHOST;
/* Note: we might in the future use prio bits
* and set skb->priority like in vlan_do_receive()
* For the time being, just ignore Priority Code Point
*/
skb->vlan_tci = 0;
}
type = skb->protocol;
/* deliver only exact match when indicated */
if (likely(!deliver_exact)) {
deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
&ptype_base[ntohs(type) &
PTYPE_HASH_MASK]);
}
deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
&orig_dev->ptype_specific);
if (unlikely(skb->dev != orig_dev)) {
deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
&skb->dev->ptype_specific);
}
if (pt_prev) {
if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
goto drop;
else
ret = pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
} else {
drop:
if (!deliver_exact)
atomic_long_inc(&skb->dev->rx_dropped);
else
atomic_long_inc(&skb->dev->rx_nohandler);
kfree_skb(skb);
/* Jamal, now you will not able to escape explaining
* me how you were going to use this. :-)
*/
ret = NET_RX_DROP;
}
out:
return ret;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void handle_rc_metamsg_rsp(tBTA_AV_META_MSG *pmeta_msg)
{
tAVRC_RESPONSE avrc_response = {0};
UINT8 scratch_buf[512] = {0};
tAVRC_STS status = BT_STATUS_UNSUPPORTED;
if(AVRC_OP_VENDOR==pmeta_msg->p_msg->hdr.opcode &&(AVRC_RSP_CHANGED==pmeta_msg->code
|| AVRC_RSP_INTERIM==pmeta_msg->code || AVRC_RSP_ACCEPT==pmeta_msg->code
|| AVRC_RSP_REJ==pmeta_msg->code || AVRC_RSP_NOT_IMPL==pmeta_msg->code))
{
status=AVRC_ParsResponse(pmeta_msg->p_msg, &avrc_response, scratch_buf, sizeof(scratch_buf));
BTIF_TRACE_DEBUG("%s: code %d,event ID %d,PDU %x,parsing status %d, label:%d",
__FUNCTION__,pmeta_msg->code,avrc_response.reg_notif.event_id,avrc_response.reg_notif.pdu,
status, pmeta_msg->label);
if (status != AVRC_STS_NO_ERROR)
{
if(AVRC_PDU_REGISTER_NOTIFICATION==avrc_response.rsp.pdu
&& AVRC_EVT_VOLUME_CHANGE==avrc_response.reg_notif.event_id
&& btif_rc_cb.rc_vol_label==pmeta_msg->label)
{
btif_rc_cb.rc_vol_label=MAX_LABEL;
release_transaction(btif_rc_cb.rc_vol_label);
}
else if(AVRC_PDU_SET_ABSOLUTE_VOLUME==avrc_response.rsp.pdu)
{
release_transaction(pmeta_msg->label);
}
return;
}
else if(AVRC_PDU_REGISTER_NOTIFICATION==avrc_response.rsp.pdu
&& AVRC_EVT_VOLUME_CHANGE==avrc_response.reg_notif.event_id
&& btif_rc_cb.rc_vol_label!=pmeta_msg->label)
{
BTIF_TRACE_DEBUG("%s:Discarding register notfn in rsp.code: %d and label %d",
__FUNCTION__, pmeta_msg->code, pmeta_msg->label);
return;
}
}
else
{
BTIF_TRACE_DEBUG("%s:Received vendor dependent in adv ctrl rsp. code: %d len: %d. Not processing it.",
__FUNCTION__, pmeta_msg->code, pmeta_msg->len);
return;
}
if(AVRC_PDU_REGISTER_NOTIFICATION==avrc_response.rsp.pdu
&& AVRC_EVT_VOLUME_CHANGE==avrc_response.reg_notif.event_id
&& AVRC_RSP_CHANGED==pmeta_msg->code)
{
/* re-register for volume change notification */
register_volumechange(btif_rc_cb.rc_vol_label);
}
else if(AVRC_PDU_SET_ABSOLUTE_VOLUME==avrc_response.rsp.pdu)
{
/* free up the label here */
release_transaction(pmeta_msg->label);
}
BTIF_TRACE_EVENT("%s: Passing received metamsg response to app. pdu: %s",
__FUNCTION__, dump_rc_pdu(avrc_response.pdu));
btif_rc_upstreams_rsp_evt((uint16_t)avrc_response.rsp.pdu, &avrc_response, pmeta_msg->code,
pmeta_msg->label);
}
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 void kvmclock_reset(struct kvm_vcpu *vcpu)
{
if (vcpu->arch.time_page) {
kvm_release_page_dirty(vcpu->arch.time_page);
vcpu->arch.time_page = NULL;
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static bool fm10k_clean_tx_irq(struct fm10k_q_vector *q_vector,
struct fm10k_ring *tx_ring, int napi_budget)
{
struct fm10k_intfc *interface = q_vector->interface;
struct fm10k_tx_buffer *tx_buffer;
struct fm10k_tx_desc *tx_desc;
unsigned int total_bytes = 0, total_packets = 0;
unsigned int budget = q_vector->tx.work_limit;
unsigned int i = tx_ring->next_to_clean;
if (test_bit(__FM10K_DOWN, interface->state))
return true;
tx_buffer = &tx_ring->tx_buffer[i];
tx_desc = FM10K_TX_DESC(tx_ring, i);
i -= tx_ring->count;
do {
struct fm10k_tx_desc *eop_desc = tx_buffer->next_to_watch;
/* if next_to_watch is not set then there is no work pending */
if (!eop_desc)
break;
/* prevent any other reads prior to eop_desc */
smp_rmb();
/* if DD is not set pending work has not been completed */
if (!(eop_desc->flags & FM10K_TXD_FLAG_DONE))
break;
/* clear next_to_watch to prevent false hangs */
tx_buffer->next_to_watch = NULL;
/* update the statistics for this packet */
total_bytes += tx_buffer->bytecount;
total_packets += tx_buffer->gso_segs;
/* free the skb */
napi_consume_skb(tx_buffer->skb, napi_budget);
/* unmap skb header data */
dma_unmap_single(tx_ring->dev,
dma_unmap_addr(tx_buffer, dma),
dma_unmap_len(tx_buffer, len),
DMA_TO_DEVICE);
/* clear tx_buffer data */
tx_buffer->skb = NULL;
dma_unmap_len_set(tx_buffer, len, 0);
/* unmap remaining buffers */
while (tx_desc != eop_desc) {
tx_buffer++;
tx_desc++;
i++;
if (unlikely(!i)) {
i -= tx_ring->count;
tx_buffer = tx_ring->tx_buffer;
tx_desc = FM10K_TX_DESC(tx_ring, 0);
}
/* unmap any remaining paged data */
if (dma_unmap_len(tx_buffer, len)) {
dma_unmap_page(tx_ring->dev,
dma_unmap_addr(tx_buffer, dma),
dma_unmap_len(tx_buffer, len),
DMA_TO_DEVICE);
dma_unmap_len_set(tx_buffer, len, 0);
}
}
/* move us one more past the eop_desc for start of next pkt */
tx_buffer++;
tx_desc++;
i++;
if (unlikely(!i)) {
i -= tx_ring->count;
tx_buffer = tx_ring->tx_buffer;
tx_desc = FM10K_TX_DESC(tx_ring, 0);
}
/* issue prefetch for next Tx descriptor */
prefetch(tx_desc);
/* update budget accounting */
budget--;
} while (likely(budget));
i += tx_ring->count;
tx_ring->next_to_clean = i;
u64_stats_update_begin(&tx_ring->syncp);
tx_ring->stats.bytes += total_bytes;
tx_ring->stats.packets += total_packets;
u64_stats_update_end(&tx_ring->syncp);
q_vector->tx.total_bytes += total_bytes;
q_vector->tx.total_packets += total_packets;
if (check_for_tx_hang(tx_ring) && fm10k_check_tx_hang(tx_ring)) {
/* schedule immediate reset if we believe we hung */
struct fm10k_hw *hw = &interface->hw;
netif_err(interface, drv, tx_ring->netdev,
"Detected Tx Unit Hang\n"
" Tx Queue <%d>\n"
" TDH, TDT <%x>, <%x>\n"
" next_to_use <%x>\n"
" next_to_clean <%x>\n",
tx_ring->queue_index,
fm10k_read_reg(hw, FM10K_TDH(tx_ring->reg_idx)),
fm10k_read_reg(hw, FM10K_TDT(tx_ring->reg_idx)),
tx_ring->next_to_use, i);
netif_stop_subqueue(tx_ring->netdev,
tx_ring->queue_index);
netif_info(interface, probe, tx_ring->netdev,
"tx hang %d detected on queue %d, resetting interface\n",
interface->tx_timeout_count + 1,
tx_ring->queue_index);
fm10k_tx_timeout_reset(interface);
/* the netdev is about to reset, no point in enabling stuff */
return true;
}
/* notify netdev of completed buffers */
netdev_tx_completed_queue(txring_txq(tx_ring),
total_packets, total_bytes);
#define TX_WAKE_THRESHOLD min_t(u16, FM10K_MIN_TXD - 1, DESC_NEEDED * 2)
if (unlikely(total_packets && netif_carrier_ok(tx_ring->netdev) &&
(fm10k_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD))) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean.
*/
smp_mb();
if (__netif_subqueue_stopped(tx_ring->netdev,
tx_ring->queue_index) &&
!test_bit(__FM10K_DOWN, interface->state)) {
netif_wake_subqueue(tx_ring->netdev,
tx_ring->queue_index);
++tx_ring->tx_stats.restart_queue;
}
}
return !!budget;
}
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: PHP_FUNCTION(ltrim)
{
php_do_trim(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
CWE ID: CWE-17
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void StopInputMethodDaemon() {
if (!initialized_successfully_)
return;
should_launch_ime_ = false;
if (ibus_daemon_process_handle_ != base::kNullProcessHandle) {
const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_);
if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) {
LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to "
<< "PID " << pid;
base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */);
}
VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated";
ibus_daemon_process_handle_ = base::kNullProcessHandle;
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void arm_dma_sync_single_for_cpu(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
unsigned int offset = handle & (PAGE_SIZE - 1);
struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
__dma_page_dev_to_cpu(page, offset, size, dir);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool AppCacheDatabase::DeleteExistingAndCreateNewDatabase() {
DCHECK(!db_file_path_.empty());
DCHECK(base::PathExists(db_file_path_));
VLOG(1) << "Deleting existing appcache data and starting over.";
ResetConnectionAndTables();
base::FilePath directory = db_file_path_.DirName();
if (!base::DeleteFile(directory, true))
return false;
if (base::PathExists(directory))
return false;
if (!base::CreateDirectory(directory))
return false;
if (is_recreating_)
return false;
base::AutoReset<bool> auto_reset(&is_recreating_, true);
return LazyOpen(kCreateIfNeeded);
}
CWE ID: CWE-200
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int http_read_header(URLContext *h, int *new_location)
{
HTTPContext *s = h->priv_data;
char line[MAX_URL_SIZE];
int err = 0;
s->chunksize = -1;
for (;;) {
if ((err = http_get_line(s, line, sizeof(line))) < 0)
return err;
av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
err = process_line(h, line, s->line_count, new_location);
if (err < 0)
return err;
if (err == 0)
break;
s->line_count++;
}
if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
h->is_streamed = 1; /* we can in fact _not_ seek */
cookie_string(s->cookie_dict, &s->cookies);
av_dict_free(&s->cookie_dict);
return err;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void qeth_clear_recovery_task(struct qeth_card *card)
{
card->recovery_task = 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: void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) {
#ifdef SAVE_ON_FLASH
jsiConsolePrint("Trace unimplemented in this version.\n");
#else
int i;
for (i=0;i<indent;i++) jsiConsolePrint(" ");
if (!var) {
jsiConsolePrint("undefined");
return;
}
jsvTraceLockInfo(var);
int lowestLevel = _jsvTraceGetLowestLevel(baseVar, var);
if (lowestLevel < level) {
jsiConsolePrint("...\n");
return;
}
if (jsvIsName(var)) jsiConsolePrint("Name ");
char endBracket = ' ';
if (jsvIsObject(var)) { jsiConsolePrint("Object { "); endBracket = '}'; }
else if (jsvIsArray(var)) { jsiConsolePrintf("Array(%d) [ ", var->varData.integer); endBracket = ']'; }
else if (jsvIsNativeFunction(var)) { jsiConsolePrintf("NativeFunction 0x%x (%d) { ", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; }
else if (jsvIsFunction(var)) {
jsiConsolePrint("Function { ");
if (jsvIsFunctionReturn(var)) jsiConsolePrint("return ");
endBracket = '}';
} else if (jsvIsPin(var)) jsiConsolePrintf("Pin %d", jsvGetInteger(var));
else if (jsvIsInt(var)) jsiConsolePrintf("Integer %d", jsvGetInteger(var));
else if (jsvIsBoolean(var)) jsiConsolePrintf("Bool %s", jsvGetBool(var)?"true":"false");
else if (jsvIsFloat(var)) jsiConsolePrintf("Double %f", jsvGetFloat(var));
else if (jsvIsFunctionParameter(var)) jsiConsolePrintf("Param %q ", var);
else if (jsvIsArrayBufferName(var)) jsiConsolePrintf("ArrayBufferName[%d] ", jsvGetInteger(var));
else if (jsvIsArrayBuffer(var)) jsiConsolePrintf("%s ", jswGetBasicObjectName(var)); // way to get nice name
else if (jsvIsString(var)) {
size_t blocks = 1;
if (jsvGetLastChild(var)) {
JsVar *v = jsvLock(jsvGetLastChild(var));
blocks += jsvCountJsVarsUsed(v);
jsvUnLock(v);
}
if (jsvIsFlatString(var)) {
blocks += jsvGetFlatStringBlocks(var);
}
jsiConsolePrintf("%sString [%d blocks] %q", jsvIsFlatString(var)?"Flat":(jsvIsNativeString(var)?"Native":""), blocks, var);
} else {
jsiConsolePrintf("Unknown %d", var->flags & (JsVarFlags)~(JSV_LOCK_MASK));
}
if (jsvIsNameInt(var)) {
jsiConsolePrintf("= int %d\n", (int)jsvGetFirstChildSigned(var));
return;
} else if (jsvIsNameIntBool(var)) {
jsiConsolePrintf("= bool %s\n", jsvGetFirstChild(var)?"true":"false");
return;
}
if (jsvHasSingleChild(var)) {
JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0;
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
} else if (jsvHasChildren(var)) {
JsvIterator it;
jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS);
bool first = true;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
if (first) jsiConsolePrintf("\n");
first = false;
JsVar *child = jsvIteratorGetKey(&it);
_jsvTrace(child, indent+2, baseVar, level+1);
jsvUnLock(child);
jsiConsolePrintf("\n");
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
if (!first)
for (i=0;i<indent;i++) jsiConsolePrint(" ");
}
jsiConsolePrintf("%c", endBracket);
#endif
}
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: static int fetch_uidl(char *line, void *data)
{
int i, index;
struct Context *ctx = (struct Context *) data;
struct PopData *pop_data = (struct PopData *) ctx->data;
char *endp = NULL;
errno = 0;
index = strtol(line, &endp, 10);
if (errno)
return -1;
while (*endp == ' ')
endp++;
memmove(line, endp, strlen(endp) + 1);
for (i = 0; i < ctx->msgcount; i++)
if (mutt_str_strcmp(line, ctx->hdrs[i]->data) == 0)
break;
if (i == ctx->msgcount)
{
mutt_debug(1, "new header %d %s\n", index, line);
if (i >= ctx->hdrmax)
mx_alloc_memory(ctx);
ctx->msgcount++;
ctx->hdrs[i] = mutt_header_new();
ctx->hdrs[i]->data = mutt_str_strdup(line);
}
else if (ctx->hdrs[i]->index != index - 1)
pop_data->clear_cache = true;
ctx->hdrs[i]->refno = index;
ctx->hdrs[i]->index = index - 1;
return 0;
}
CWE ID: CWE-824
Target: 1
Example 2:
Code: omx_vdec::allocate_color_convert_buf::~allocate_color_convert_buf()
{
c2d.destroy();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
CWE ID:
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) {
DCHECK(!defer_page_unload_);
defer_page_unload_ = true;
bool rv = false;
switch (event.GetType()) {
case PP_INPUTEVENT_TYPE_MOUSEDOWN:
rv = OnMouseDown(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_MOUSEUP:
rv = OnMouseUp(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_MOUSEMOVE:
rv = OnMouseMove(pp::MouseInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_KEYDOWN:
rv = OnKeyDown(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_KEYUP:
rv = OnKeyUp(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_CHAR:
rv = OnChar(pp::KeyboardInputEvent(event));
break;
case PP_INPUTEVENT_TYPE_TOUCHSTART: {
KillTouchTimer(next_touch_timer_id_);
pp::TouchInputEvent touch_event(event);
if (touch_event.GetTouchCount(PP_TOUCHLIST_TYPE_TARGETTOUCHES) == 1)
ScheduleTouchTimer(touch_event);
break;
}
case PP_INPUTEVENT_TYPE_TOUCHEND:
KillTouchTimer(next_touch_timer_id_);
break;
case PP_INPUTEVENT_TYPE_TOUCHMOVE:
KillTouchTimer(next_touch_timer_id_);
default:
break;
}
DCHECK(defer_page_unload_);
defer_page_unload_ = false;
for (int page_index : deferred_page_unloads_)
pages_[page_index]->Unload();
deferred_page_unloads_.clear();
return rv;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: int lxc_clear_groups(struct lxc_conf *c)
{
struct lxc_list *it,*next;
lxc_list_for_each_safe(it, &c->groups, next) {
lxc_list_del(it);
free(it->elem);
free(it);
}
return 0;
}
CWE ID: CWE-59
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
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 + 3) / 4) * ((h + 3) / 4) * texel_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: int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
unsigned int flags, struct timespec *timeout)
{
int fput_needed, err, datagrams;
struct socket *sock;
struct mmsghdr __user *entry;
struct compat_mmsghdr __user *compat_entry;
struct msghdr msg_sys;
struct timespec end_time;
if (timeout &&
poll_select_set_timeout(&end_time, timeout->tv_sec,
timeout->tv_nsec))
return -EINVAL;
datagrams = 0;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
return err;
err = sock_error(sock->sk);
if (err)
goto out_put;
entry = mmsg;
compat_entry = (struct compat_mmsghdr __user *)mmsg;
while (datagrams < vlen) {
/*
* No need to ask LSM for more than the first datagram.
*/
if (MSG_CMSG_COMPAT & flags) {
err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,
&msg_sys, flags & ~MSG_WAITFORONE,
datagrams);
if (err < 0)
break;
err = __put_user(err, &compat_entry->msg_len);
++compat_entry;
} else {
err = ___sys_recvmsg(sock,
(struct user_msghdr __user *)entry,
&msg_sys, flags & ~MSG_WAITFORONE,
datagrams);
if (err < 0)
break;
err = put_user(err, &entry->msg_len);
++entry;
}
if (err)
break;
++datagrams;
/* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
if (flags & MSG_WAITFORONE)
flags |= MSG_DONTWAIT;
if (timeout) {
ktime_get_ts(timeout);
*timeout = timespec_sub(end_time, *timeout);
if (timeout->tv_sec < 0) {
timeout->tv_sec = timeout->tv_nsec = 0;
break;
}
/* Timeout, return less than vlen datagrams */
if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
break;
}
/* Out of band data, return right away */
if (msg_sys.msg_flags & MSG_OOB)
break;
cond_resched();
}
out_put:
fput_light(sock->file, fput_needed);
if (err == 0)
return datagrams;
if (datagrams != 0) {
/*
* We may return less entries than requested (vlen) if the
* sock is non block and there aren't enough datagrams...
*/
if (err != -EAGAIN) {
/*
* ... or if recvmsg returns an error after we
* received some datagrams, where we record the
* error to return on the next call or if the
* app asks about it using getsockopt(SO_ERROR).
*/
sock->sk->sk_err = -err;
}
return datagrams;
}
return err;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: void ResourceMultiBufferDataProvider::DidReceiveCachedMetadata(
const char* data,
int data_length) {
NOTIMPLEMENTED();
}
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: WORD32 impeg2d_get_slice_pos(dec_state_multi_core_t *ps_dec_state_multi_core)
{
WORD32 u4_bits;
WORD32 i4_row;
dec_state_t *ps_dec = ps_dec_state_multi_core->ps_dec_state[0];
WORD32 i4_prev_row;
stream_t s_bitstrm;
WORD32 i4_start_row;
WORD32 i4_slice_bistream_ofst;
WORD32 i;
s_bitstrm = ps_dec->s_bit_stream;
i4_prev_row = -1;
ps_dec_state_multi_core->ps_dec_state[0]->i4_start_mb_y = 0;
ps_dec_state_multi_core->ps_dec_state[1]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[2]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[3]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[0]->i4_end_mb_y = ps_dec->u2_num_vert_mb;
ps_dec_state_multi_core->ps_dec_state[1]->i4_end_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[2]->i4_end_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[3]->i4_end_mb_y = -1;
if(ps_dec->i4_num_cores == 1)
return 0;
/* Reset the jobq to start of the jobq buffer */
impeg2_jobq_reset((jobq_t *)ps_dec->pv_jobq);
i4_start_row = -1;
i4_slice_bistream_ofst = 0;
while(1)
{
WORD32 i4_is_slice;
if(s_bitstrm.u4_offset + START_CODE_LEN >= s_bitstrm.u4_max_offset)
{
break;
}
u4_bits = impeg2d_bit_stream_nxt(&s_bitstrm,START_CODE_LEN);
i4_row = u4_bits & 0xFF;
/* Detect end of frame */
i4_is_slice = (((u4_bits >> 8) == 0x01) && (i4_row) && (i4_row <= ps_dec->u2_num_vert_mb));
if(!i4_is_slice)
break;
i4_row -= 1;
if(i4_prev_row != i4_row)
{
/* Create a job for previous slice row */
if(i4_start_row != -1)
{
job_t s_job;
IV_API_CALL_STATUS_T ret;
s_job.i2_start_mb_y = i4_start_row;
s_job.i2_end_mb_y = i4_row;
s_job.i4_cmd = CMD_PROCESS;
s_job.i4_bistream_ofst = i4_slice_bistream_ofst;
ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(ret != IV_SUCCESS)
return ret;
}
/* Store current slice's bitstream offset */
i4_slice_bistream_ofst = s_bitstrm.u4_offset >> 3;
i4_slice_bistream_ofst -= (size_t)s_bitstrm.pv_bs_buf & 3;
i4_prev_row = i4_row;
/* Store current slice's row position */
i4_start_row = i4_row;
}
impeg2d_bit_stream_flush(&s_bitstrm, START_CODE_LEN);
/* Flush the bytes till a start code is encountered */
while(impeg2d_bit_stream_nxt(&s_bitstrm, 24) != START_CODE_PREFIX)
{
impeg2d_bit_stream_get(&s_bitstrm, 8);
if(s_bitstrm.u4_offset >= s_bitstrm.u4_max_offset)
{
break;
}
}
}
/* Create job for the last slice row */
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
s_job.i2_start_mb_y = i4_start_row;
s_job.i2_end_mb_y = ps_dec->u2_num_vert_mb;
s_job.i4_cmd = CMD_PROCESS;
s_job.i4_bistream_ofst = i4_slice_bistream_ofst;
e_ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(e_ret != IV_SUCCESS)
return e_ret;
}
if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat)))
{
for(i = 0; i < ps_dec->u2_vertical_size; i+=64)
{
job_t s_job;
IV_API_CALL_STATUS_T ret;
s_job.i2_start_mb_y = i;
s_job.i2_start_mb_y >>= 4;
s_job.i2_end_mb_y = (i + 64);
s_job.i2_end_mb_y >>= 4;
s_job.i4_cmd = CMD_FMTCONV;
s_job.i4_bistream_ofst = 0;
ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(ret != IV_SUCCESS)
return ret;
}
}
impeg2_jobq_terminate(ps_dec->pv_jobq);
ps_dec->i4_bytes_consumed = s_bitstrm.u4_offset >> 3;
ps_dec->i4_bytes_consumed -= ((size_t)s_bitstrm.pv_bs_buf & 3);
return 0;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: UseCounterPageLoadMetricsObserver::GetAllowedUkmFeatures() {
static base::NoDestructor<UseCounterPageLoadMetricsObserver::UkmFeatureList>
opt_in_features(std::initializer_list<WebFeature>({
WebFeature::kNavigatorVibrate,
WebFeature::kNavigatorVibrateSubFrame,
WebFeature::kTouchEventPreventedNoTouchAction,
WebFeature::kTouchEventPreventedForcedDocumentPassiveNoTouchAction,
WebFeature::kDataUriHasOctothorpe,
WebFeature::kApplicationCacheManifestSelectInsecureOrigin,
WebFeature::kApplicationCacheManifestSelectSecureOrigin,
WebFeature::kMixedContentAudio,
WebFeature::kMixedContentImage,
WebFeature::kMixedContentVideo,
WebFeature::kMixedContentPlugin,
WebFeature::kOpenerNavigationWithoutGesture,
WebFeature::kUsbRequestDevice,
WebFeature::kXMLHttpRequestSynchronous,
WebFeature::kPaymentHandler,
WebFeature::kPaymentRequestShowWithoutGesture,
WebFeature::kHTMLImports,
WebFeature::kHTMLImportsHasStyleSheets,
WebFeature::kElementCreateShadowRoot,
WebFeature::kDocumentRegisterElement,
WebFeature::kCredentialManagerCreatePublicKeyCredential,
WebFeature::kCredentialManagerGetPublicKeyCredential,
WebFeature::kCredentialManagerMakePublicKeyCredentialSuccess,
WebFeature::kCredentialManagerGetPublicKeyCredentialSuccess,
WebFeature::kV8AudioContext_Constructor,
WebFeature::kElementAttachShadow,
WebFeature::kElementAttachShadowOpen,
WebFeature::kElementAttachShadowClosed,
WebFeature::kCustomElementRegistryDefine,
WebFeature::kTextToSpeech_Speak,
WebFeature::kTextToSpeech_SpeakDisallowedByAutoplay,
WebFeature::kCSSEnvironmentVariable,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetTop,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetLeft,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetRight,
WebFeature::kCSSEnvironmentVariable_SafeAreaInsetBottom,
WebFeature::kMediaControlsDisplayCutoutGesture,
WebFeature::kPolymerV1Detected,
WebFeature::kPolymerV2Detected,
WebFeature::kFullscreenSecureOrigin,
WebFeature::kFullscreenInsecureOrigin,
WebFeature::kPrefixedVideoEnterFullscreen,
WebFeature::kPrefixedVideoExitFullscreen,
WebFeature::kPrefixedVideoEnterFullScreen,
WebFeature::kPrefixedVideoExitFullScreen,
WebFeature::kDocumentLevelPassiveDefaultEventListenerPreventedWheel,
WebFeature::kDocumentDomainBlockedCrossOriginAccess,
WebFeature::kDocumentDomainEnabledCrossOriginAccess,
WebFeature::kSuppressHistoryEntryWithoutUserGesture,
WebFeature::kCursorImageGT32x32,
WebFeature::kCursorImageLE32x32,
WebFeature::kHistoryPushState,
WebFeature::kHistoryReplaceState,
WebFeature::kCursorImageGT64x64,
WebFeature::kAdClick,
WebFeature::kUpdateWithoutShippingOptionOnShippingAddressChange,
WebFeature::kUpdateWithoutShippingOptionOnShippingOptionChange,
WebFeature::kSignedExchangeInnerResponseInMainFrame,
WebFeature::kSignedExchangeInnerResponseInSubFrame,
WebFeature::kWebShareShare,
WebFeature::kHTMLAnchorElementDownloadInSandboxWithUserGesture,
WebFeature::kHTMLAnchorElementDownloadInSandboxWithoutUserGesture,
WebFeature::kNavigationDownloadInSandboxWithUserGesture,
WebFeature::kNavigationDownloadInSandboxWithoutUserGesture,
WebFeature::kDownloadInAdFrameWithUserGesture,
WebFeature::kDownloadInAdFrameWithoutUserGesture,
WebFeature::kOpenWebDatabase,
WebFeature::kV8MediaCapabilities_DecodingInfo_Method,
}));
return *opt_in_features;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
{
struct netlink_sock *nlk = nlk_sk(sk);
int ret = 0;
if (sk == p->exclude_sk)
goto out;
if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
goto out;
if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
!test_bit(p->group - 1, nlk->groups))
goto out;
if (p->code == ENOBUFS && nlk->flags & NETLINK_RECV_NO_ENOBUFS) {
ret = 1;
goto out;
}
sk->sk_err = p->code;
sk->sk_error_report(sk);
out:
return ret;
}
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 SetAlignment(aura::Window* window, ShelfAlignment alignment) {
GetShelfForWindow(window)->SetAlignment(alignment);
}
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: v8::Local<v8::Object> V8Console::createCommandLineAPI(InspectedContext* inspectedContext)
{
v8::Local<v8::Context> context = inspectedContext->context();
v8::Isolate* isolate = context->GetIsolate();
v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Local<v8::Object> commandLineAPI = v8::Object::New(isolate);
createBoundFunctionProperty(context, commandLineAPI, "dir", V8Console::dirCallback, "function dir(value) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "dirxml", V8Console::dirxmlCallback, "function dirxml(value) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "profile", V8Console::profileCallback, "function profile(title) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "profileEnd", V8Console::profileEndCallback, "function profileEnd(title) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "clear", V8Console::clearCallback, "function clear() { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "table", V8Console::tableCallback, "function table(data, [columns]) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "keys", V8Console::keysCallback, "function keys(object) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "values", V8Console::valuesCallback, "function values(object) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "debug", V8Console::debugFunctionCallback, "function debug(function) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "undebug", V8Console::undebugFunctionCallback, "function undebug(function) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "monitor", V8Console::monitorFunctionCallback, "function monitor(function) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "unmonitor", V8Console::unmonitorFunctionCallback, "function unmonitor(function) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "inspect", V8Console::inspectCallback, "function inspect(object) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "copy", V8Console::copyCallback, "function copy(value) { [Command Line API] }");
createBoundFunctionProperty(context, commandLineAPI, "$_", V8Console::lastEvaluationResultCallback);
createBoundFunctionProperty(context, commandLineAPI, "$0", V8Console::inspectedObject0);
createBoundFunctionProperty(context, commandLineAPI, "$1", V8Console::inspectedObject1);
createBoundFunctionProperty(context, commandLineAPI, "$2", V8Console::inspectedObject2);
createBoundFunctionProperty(context, commandLineAPI, "$3", V8Console::inspectedObject3);
createBoundFunctionProperty(context, commandLineAPI, "$4", V8Console::inspectedObject4);
inspectedContext->inspector()->client()->installAdditionalCommandLineAPI(context, commandLineAPI);
commandLineAPI->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext));
return commandLineAPI;
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) {
uint32_t memlimit;
assert(c != NULL);
set_noreply_maybe(c, tokens, ntokens);
if (!safe_strtoul(tokens[1].value, &memlimit)) {
out_string(c, "ERROR");
} else {
if (memlimit < 8) {
out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m");
} else {
if (memlimit > 1000000000) {
out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes");
} else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) {
if (settings.verbose > 0) {
fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit);
}
out_string(c, "OK");
} else {
out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust");
}
}
}
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
enum bpf_access_type t, enum bpf_reg_type *reg_type)
{
/* for analyzer ctx accesses are already validated and converted */
if (env->analyzer_ops)
return 0;
if (env->prog->aux->ops->is_valid_access &&
env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
/* remember the offset of last byte accessed in ctx */
if (env->prog->aux->max_ctx_offset < off + size)
env->prog->aux->max_ctx_offset = off + size;
return 0;
}
verbose("invalid bpf_context access off=%d size=%d\n", off, size);
return -EACCES;
}
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: BookmarkManagerView::BookmarkManagerView(Profile* profile)
: profile_(profile->GetOriginalProfile()),
table_view_(NULL),
tree_view_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(search_factory_(this)) {
search_tf_ = new views::TextField();
search_tf_->set_default_width_in_chars(30);
table_view_ = new BookmarkTableView(profile_, NULL);
table_view_->SetObserver(this);
table_view_->SetContextMenuController(this);
tree_view_ = new BookmarkFolderTreeView(profile_, NULL);
tree_view_->SetController(this);
tree_view_->SetContextMenuController(this);
views::MenuButton* organize_menu_button = new views::MenuButton(
NULL, l10n_util::GetString(IDS_BOOKMARK_MANAGER_ORGANIZE_MENU),
this, true);
organize_menu_button->SetID(kOrganizeMenuButtonID);
views::MenuButton* tools_menu_button = new views::MenuButton(
NULL, l10n_util::GetString(IDS_BOOKMARK_MANAGER_TOOLS_MENU),
this, true);
tools_menu_button->SetID(kToolsMenuButtonID);
split_view_ = new views::SingleSplitView(tree_view_, table_view_);
split_view_->set_background(
views::Background::CreateSolidBackground(kBackgroundColorBottom));
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
const int top_id = 1;
const int split_cs_id = 2;
layout->SetInsets(2, 0, 0, 0); // 2px padding above content.
views::ColumnSet* column_set = layout->AddColumnSet(top_id);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(1, kUnrelatedControlHorizontalSpacing);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, 3); // 3px padding at end of row.
column_set = layout->AddColumnSet(split_cs_id);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, top_id);
layout->AddView(organize_menu_button);
layout->AddView(tools_menu_button);
layout->AddView(new views::Label(
l10n_util::GetString(IDS_BOOKMARK_MANAGER_SEARCH_TITLE)));
layout->AddView(search_tf_);
layout->AddPaddingRow(0, 3); // 3px padding between rows.
layout->StartRow(1, split_cs_id);
layout->AddView(split_view_);
BookmarkModel* bookmark_model = profile_->GetBookmarkModel();
if (!bookmark_model->IsLoaded())
bookmark_model->AddObserver(this);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void DownloadResourceHandler::PauseRequest() {
core_.PauseRequest();
}
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: PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool(
ResourceProvider* resource_provider,
ContextProvider* context_provider,
size_t num_threads,
size_t max_transfer_buffer_usage_bytes)
: RasterWorkerPool(resource_provider, context_provider, num_threads),
shutdown_(false),
scheduled_raster_task_count_(0),
bytes_pending_upload_(0),
max_bytes_pending_upload_(max_transfer_buffer_usage_bytes),
has_performed_uploads_since_last_flush_(false),
check_for_completed_raster_tasks_pending_(false),
should_notify_client_if_no_tasks_are_pending_(false),
should_notify_client_if_no_tasks_required_for_activation_are_pending_(
false) {
}
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 uint32_t fdctrl_read_data(FDCtrl *fdctrl)
{
FDrive *cur_drv;
uint32_t retval = 0;
int pos;
cur_drv = get_cur_drv(fdctrl);
fdctrl->dsr &= ~FD_DSR_PWRDOWN;
if (!(fdctrl->msr & FD_MSR_RQM) || !(fdctrl->msr & FD_MSR_DIO)) {
FLOPPY_DPRINTF("error: controller not ready for reading\n");
return 0;
}
pos = fdctrl->data_pos;
if (fdctrl->msr & FD_MSR_NONDMA) {
pos %= FD_SECTOR_LEN;
if (pos == 0) {
if (fdctrl->data_pos != 0)
if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) {
FLOPPY_DPRINTF("error seeking to next sector %d\n",
fd_sector(cur_drv));
return 0;
}
if (blk_read(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1)
< 0) {
FLOPPY_DPRINTF("error getting sector %d\n",
fd_sector(cur_drv));
/* Sure, image size is too small... */
memset(fdctrl->fifo, 0, FD_SECTOR_LEN);
}
}
}
retval = fdctrl->fifo[pos];
if (++fdctrl->data_pos == fdctrl->data_len) {
fdctrl->data_pos = 0;
/* Switch from transfer mode to status mode
* then from status mode to command mode
*/
if (fdctrl->msr & FD_MSR_NONDMA) {
fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);
} else {
fdctrl_reset_fifo(fdctrl);
fdctrl_reset_irq(fdctrl);
}
}
FLOPPY_DPRINTF("data register: 0x%02x\n", retval);
return retval;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: const Extension* ExtensionService::GetWebStoreApp() {
return GetExtensionById(extension_misc::kWebStoreAppId, false);
}
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 Document::Initialize() {
DCHECK_EQ(lifecycle_.GetState(), DocumentLifecycle::kInactive);
DCHECK(!ax_object_cache_ || this != &AXObjectCacheOwner());
layout_view_ = new LayoutView(this);
SetLayoutObject(layout_view_);
layout_view_->SetIsInWindow(true);
layout_view_->SetStyle(StyleResolver::StyleForViewport(*this));
layout_view_->Compositor()->SetNeedsCompositingUpdate(
kCompositingUpdateAfterCompositingInputChange);
{
ReattachLegacyLayoutObjectList legacy_layout_objects(*this);
AttachContext context;
ContainerNode::AttachLayoutTree(context);
legacy_layout_objects.ForceLegacyLayoutIfNeeded();
}
if (TextAutosizer* autosizer = GetTextAutosizer())
autosizer->UpdatePageInfo();
frame_->DidAttachDocument();
lifecycle_.AdvanceTo(DocumentLifecycle::kStyleClean);
if (View())
View()->DidAttachDocument();
network_state_observer_ = MakeGarbageCollected<NetworkStateObserver>(*this);
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init ();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput ();
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get ("cl_motd", "1", 0);
#endif
cl_timeout = Cvar_Get ("cl_timeout", "200", 0);
cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get ("timedemo", "0", 0);
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0);
rconAddress = Cvar_Get ("rconAddress", "", 0);
cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0);
cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE);
cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE);
cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE);
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE);
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE);
#endif
cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0);
#ifdef __APPLE__
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE);
#else
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE);
#endif
cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0);
Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
#ifdef __APPLE__
m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE);
#else
m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
#endif
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("teamtask", "0", CVAR_USERINFO );
Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("password", "", CVAR_USERINFO);
Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE );
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
Cmd_AddCommand ("cmd", CL_ForwardToServer_f);
Cmd_AddCommand ("configstrings", CL_Configstrings_f);
Cmd_AddCommand ("clientinfo", CL_Clientinfo_f);
Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f);
Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f);
Cmd_AddCommand ("disconnect", CL_Disconnect_f);
Cmd_AddCommand ("record", CL_Record_f);
Cmd_AddCommand ("demo", CL_PlayDemo_f);
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand ("cinematic", CL_PlayCinematic_f);
Cmd_AddCommand ("stoprecord", CL_StopRecord_f);
Cmd_AddCommand ("connect", CL_Connect_f);
Cmd_AddCommand ("reconnect", CL_Reconnect_f);
Cmd_AddCommand ("localservers", CL_LocalServers_f);
Cmd_AddCommand ("globalservers", CL_GlobalServers_f);
Cmd_AddCommand ("rcon", CL_Rcon_f);
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand ("ping", CL_Ping_f );
Cmd_AddCommand ("serverstatus", CL_ServerStatus_f );
Cmd_AddCommand ("showip", CL_ShowIP_f );
Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("model", CL_SetModel_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
if( !com_dedicated->integer ) {
Cmd_AddCommand ("sayto", CL_Sayto_f );
Cmd_SetCommandCompletionFunc( "sayto", CL_CompletePlayerName );
}
CL_InitRef();
SCR_Init ();
Cvar_Set( "cl_running", "1" );
CL_GenerateQKey();
Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM );
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
CWE ID: CWE-269
Target: 1
Example 2:
Code: bool ExtensionService::UninstallExtension(
const std::string& extension_id_unsafe,
bool external_uninstall,
std::string* error) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::string extension_id(extension_id_unsafe);
const Extension* extension = GetInstalledExtension(extension_id);
CHECK(extension);
GURL extension_url(extension->url());
Extension::Location location(extension->location());
if (!Extension::UserMayDisable(location) && !external_uninstall) {
NotificationService::current()->Notify(
NotificationType::EXTENSION_UNINSTALL_NOT_ALLOWED,
Source<Profile>(profile_),
Details<const Extension>(extension));
if (error != NULL) {
*error = errors::kCannotUninstallManagedExtension;
}
return false;
}
UninstalledExtensionInfo uninstalled_extension_info(*extension);
UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
extension->GetType(), 100);
RecordPermissionMessagesHistogram(
extension, "Extensions.Permissions_Uninstall");
if (profile_->GetTemplateURLModel())
profile_->GetTemplateURLModel()->UnregisterExtensionKeyword(extension);
UnloadExtension(extension_id, UnloadedExtensionInfo::UNINSTALL);
extension_prefs_->OnExtensionUninstalled(extension_id, location,
external_uninstall);
if (Extension::LOAD != location) {
if (!BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableFunction(
&extension_file_util::UninstallExtension,
install_directory_,
extension_id)))
NOTREACHED();
}
ClearExtensionData(extension_url);
UntrackTerminatedExtension(extension_id);
NotificationService::current()->Notify(
NotificationType::EXTENSION_UNINSTALLED,
Source<Profile>(profile_),
Details<UninstalledExtensionInfo>(&uninstalled_extension_info));
return true;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ChromeContentBrowserClient::GetOriginsRequiringDedicatedProcess() {
std::vector<url::Origin> isolated_origin_list;
#if !defined(OS_ANDROID)
isolated_origin_list.emplace_back(
url::Origin::Create(GaiaUrls::GetInstance()->gaia_url()));
#endif
return isolated_origin_list;
}
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: SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, char **buf, int *buf_type)
{
struct smb_rqst rqst;
int resp_buftype, rc = -EACCES;
struct smb2_read_plain_req *req = NULL;
struct smb2_read_rsp *rsp = NULL;
struct kvec iov[1];
struct kvec rsp_iov;
unsigned int total_len;
int flags = CIFS_LOG_ERROR;
struct cifs_ses *ses = io_parms->tcon->ses;
*nbytes = 0;
rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
if (rc)
return rc;
if (smb3_encryption_required(io_parms->tcon))
flags |= CIFS_TRANSFORM_REQ;
iov[0].iov_base = (char *)req;
iov[0].iov_len = total_len;
memset(&rqst, 0, sizeof(struct smb_rqst));
rqst.rq_iov = iov;
rqst.rq_nvec = 1;
rc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);
cifs_small_buf_release(req);
rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
if (rc) {
if (rc != -ENODATA) {
cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
cifs_dbg(VFS, "Send error in read = %d\n", rc);
trace_smb3_read_err(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length,
rc);
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, 0);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
return rc == -ENODATA ? 0 : rc;
} else
trace_smb3_read_done(xid, req->PersistentFileId,
io_parms->tcon->tid, ses->Suid,
io_parms->offset, io_parms->length);
*nbytes = le32_to_cpu(rsp->DataLength);
if ((*nbytes > CIFS_MAX_MSGSIZE) ||
(*nbytes > io_parms->length)) {
cifs_dbg(FYI, "bad length %d for count %d\n",
*nbytes, io_parms->length);
rc = -EIO;
*nbytes = 0;
}
if (*buf) {
memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
free_rsp_buf(resp_buftype, rsp_iov.iov_base);
} else if (resp_buftype != CIFS_NO_BUFFER) {
*buf = rsp_iov.iov_base;
if (resp_buftype == CIFS_SMALL_BUFFER)
*buf_type = CIFS_SMALL_BUFFER;
else if (resp_buftype == CIFS_LARGE_BUFFER)
*buf_type = CIFS_LARGE_BUFFER;
}
return rc;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: basic_obj_respond_to(mrb_state *mrb, mrb_value obj, mrb_sym id, int pub)
{
return mrb_respond_to(mrb, obj, id);
}
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 V8Console::dirCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ConsoleHelper(info).reportCall(ConsoleAPIType::kDir);
}
CWE ID: CWE-79
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 ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)
{
struct hlist_head *hashent = ucounts_hashentry(ns, uid);
struct ucounts *ucounts, *new;
spin_lock_irq(&ucounts_lock);
ucounts = find_ucounts(ns, uid, hashent);
if (!ucounts) {
spin_unlock_irq(&ucounts_lock);
new = kzalloc(sizeof(*new), GFP_KERNEL);
if (!new)
return NULL;
new->ns = ns;
new->uid = uid;
atomic_set(&new->count, 0);
spin_lock_irq(&ucounts_lock);
ucounts = find_ucounts(ns, uid, hashent);
if (ucounts) {
kfree(new);
} else {
hlist_add_head(&new->node, hashent);
ucounts = new;
}
}
if (!atomic_add_unless(&ucounts->count, 1, INT_MAX))
ucounts = NULL;
spin_unlock_irq(&ucounts_lock);
return ucounts;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void cifs_oplock_break(struct work_struct *work)
{
struct cifsFileInfo *cfile = container_of(work, struct cifsFileInfo,
oplock_break);
struct inode *inode = cfile->dentry->d_inode;
struct cifsInodeInfo *cinode = CIFS_I(inode);
struct cifs_tcon *tcon = tlink_tcon(cfile->tlink);
int rc = 0;
if (!CIFS_CACHE_WRITE(cinode) && CIFS_CACHE_READ(cinode) &&
cifs_has_mand_locks(cinode)) {
cifs_dbg(FYI, "Reset oplock to None for inode=%p due to mand locks\n",
inode);
cinode->oplock = 0;
}
if (inode && S_ISREG(inode->i_mode)) {
if (CIFS_CACHE_READ(cinode))
break_lease(inode, O_RDONLY);
else
break_lease(inode, O_WRONLY);
rc = filemap_fdatawrite(inode->i_mapping);
if (!CIFS_CACHE_READ(cinode)) {
rc = filemap_fdatawait(inode->i_mapping);
mapping_set_error(inode->i_mapping, rc);
cifs_invalidate_mapping(inode);
}
cifs_dbg(FYI, "Oplock flush inode %p rc %d\n", inode, rc);
}
rc = cifs_push_locks(cfile);
if (rc)
cifs_dbg(VFS, "Push locks rc = %d\n", rc);
/*
* releasing stale oplock after recent reconnect of smb session using
* a now incorrect file handle is not a data integrity issue but do
* not bother sending an oplock release if session to server still is
* disconnected since oplock already released by the server
*/
if (!cfile->oplock_break_cancelled) {
rc = tcon->ses->server->ops->oplock_response(tcon, &cfile->fid,
cinode);
cifs_dbg(FYI, "Oplock release rc = %d\n", 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: const BlockEntry* Cluster::GetEntry(const CuePoint& cp,
const CuePoint::TrackPosition& tp) const {
assert(m_pSegment);
#if 0
LoadBlockEntries();
if (m_entries == NULL)
return NULL;
const long long count = m_entries_count;
if (count <= 0)
return NULL;
const long long tc = cp.GetTimeCode();
if ((tp.m_block > 0) && (tp.m_block <= count))
{
const size_t block = static_cast<size_t>(tp.m_block);
const size_t index = block - 1;
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc))
{
return pEntry;
}
}
const BlockEntry* const* i = m_entries;
const BlockEntry* const* const j = i + count;
while (i != j)
{
#ifdef _DEBUG
const ptrdiff_t idx = i - m_entries;
idx;
#endif
const BlockEntry* const pEntry = *i++;
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track)
continue;
const long long tc_ = pBlock->GetTimeCode(this);
assert(tc_ >= 0);
if (tc_ < tc)
continue;
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) //audio
return pEntry;
if (type != 1) //not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
return NULL;
#else
const long long tc = cp.GetTimeCode();
if (tp.m_block > 0) {
const long block = static_cast<long>(tp.m_block);
const long index = block - 1;
while (index >= m_entries_count) {
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) // TODO: can this happen?
return NULL;
if (status > 0) // nothing remains to be parsed
return NULL;
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if ((pBlock->GetTrackNumber() == tp.m_track) &&
(pBlock->GetTimeCode(this) == tc)) {
return pEntry;
}
}
long index = 0;
for (;;) {
if (index >= m_entries_count) {
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) // TODO: can this happen?
return NULL;
if (status > 0) // nothing remains to be parsed
return NULL;
assert(m_entries);
assert(index < m_entries_count);
}
const BlockEntry* const pEntry = m_entries[index];
assert(pEntry);
assert(!pEntry->EOS());
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
if (pBlock->GetTrackNumber() != tp.m_track) {
++index;
continue;
}
const long long tc_ = pBlock->GetTimeCode(this);
if (tc_ < tc) {
++index;
continue;
}
if (tc_ > tc)
return NULL;
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(tp.m_track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return NULL;
const long long type = pTrack->GetType();
if (type == 2) // audio
return pEntry;
if (type != 1) // not video
return NULL;
if (!pBlock->IsKey())
return NULL;
return pEntry;
}
#endif
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1)))
goto out;
if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = &kvm->memslots->memslots[mem->slot];
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
#ifndef CONFIG_S390
if (npages && !new.rmap) {
new.rmap = vzalloc(npages * sizeof(*new.rmap));
if (!new.rmap)
goto out_free;
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
}
if (!npages)
goto skip_lpage;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
unsigned long ugfn;
unsigned long j;
int lpages;
int level = i + 2;
/* Avoid unused variable warning if no large pages */
(void)level;
if (new.lpage_info[i])
continue;
lpages = 1 + ((base_gfn + npages - 1)
>> KVM_HPAGE_GFN_SHIFT(level));
lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
if (!new.lpage_info[i])
goto out_free;
if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][0].write_count = 1;
if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][lpages - 1].write_count = 1;
ugfn = new.userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!largepages_enabled)
for (j = 0; j < lpages; ++j)
new.lpage_info[i][j].write_count = 1;
}
skip_lpage:
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
#else /* not defined CONFIG_S390 */
new.user_alloc = user_alloc;
if (user_alloc)
new.userspace_addr = mem->userspace_addr;
#endif /* not defined CONFIG_S390 */
if (!npages) {
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow(kvm);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
}
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.rmap = NULL;
new.dirty_bitmap = NULL;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
new.lpage_info[i] = NULL;
}
slots->memslots[mem->slot] = new;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void OfflinePageModelTaskified::InformDeletePageDone(
const DeletePageCallback& callback,
DeletePageResult result) {
if (!callback.is_null())
callback.Run(result);
}
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 NavigateToDataURLAndCheckForTerminationDisabler(
Shell* shell,
const std::string& html,
bool expect_onunload,
bool expect_onbeforeunload) {
NavigateToURL(shell, GURL("data:text/html," + html));
RenderFrameHostImpl* rfh =
static_cast<RenderFrameHostImpl*>(shell->web_contents()->GetMainFrame());
EXPECT_EQ(expect_onunload,
rfh->GetSuddenTerminationDisablerState(blink::kUnloadHandler));
EXPECT_EQ(expect_onbeforeunload, rfh->GetSuddenTerminationDisablerState(
blink::kBeforeUnloadHandler));
}
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: DWORD WtsSessionProcessDelegate::Core::GetExitCode() {
DCHECK(main_task_runner_->BelongsToCurrentThread());
DWORD exit_code = CONTROL_C_EXIT;
if (worker_process_.IsValid()) {
if (!::GetExitCodeProcess(worker_process_, &exit_code)) {
LOG_GETLASTERROR(INFO)
<< "Failed to query the exit code of the worker process";
exit_code = CONTROL_C_EXIT;
}
}
return exit_code;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: populate_recordset_object_field_start(void *state, char *fname, bool isnull)
{
PopulateRecordsetState *_state = (PopulateRecordsetState *) state;
if (_state->lex->lex_level > 2)
return;
if (_state->lex->token_type == JSON_TOKEN_ARRAY_START ||
_state->lex->token_type == JSON_TOKEN_OBJECT_START)
{
_state->save_json_start = _state->lex->token_start;
}
else
{
_state->save_json_start = 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 u16 frag_get_pending_idx(skb_frag_t *frag)
{
return (u16)frag->page_offset;
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response,
const GURL& url) {
//// static
DCHECK(response && response->headers.get());
std::string location;
if (!response->headers->IsRedirect(&location))
return false;
std::string fake_response_headers =
base::StringPrintf("HTTP/1.0 302 Found\n"
"Location: %s\n"
"Content-length: 0\n"
"Connection: close\n"
"\n",
location.c_str());
std::string raw_headers =
HttpUtil::AssembleRawHeaders(fake_response_headers.data(),
fake_response_headers.length());
response->headers = new HttpResponseHeaders(raw_headers);
return true;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: png_write_IEND(png_structp png_ptr)
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_IEND;
#endif
png_debug(1, "in png_write_IEND");
png_write_chunk(png_ptr, (png_bytep)png_IEND, png_bytep_NULL,
(png_size_t)0);
png_ptr->mode |= PNG_HAVE_IEND;
}
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 sta_prepare_rate_control(struct ieee80211_local *local,
struct sta_info *sta, gfp_t gfp)
{
if (local->hw.flags & IEEE80211_HW_HAS_RATE_CONTROL)
return 0;
sta->rate_ctrl = local->rate_ctrl;
sta->rate_ctrl_priv = rate_control_alloc_sta(sta->rate_ctrl,
&sta->sta, gfp);
if (!sta->rate_ctrl_priv)
return -ENOMEM;
return 0;
}
CWE ID: CWE-362
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void handle_data_packet(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr, int data_len) {
struct mt_mactelnet_control_hdr cpkt;
struct mt_packet pdata;
unsigned char *data = pkthdr->data;
unsigned int act_size = 0;
int got_user_packet = 0;
int got_pass_packet = 0;
int got_width_packet = 0;
int got_height_packet = 0;
int success;
/* Parse first control packet */
success = parse_control_packet(data, data_len - MT_HEADER_LEN, &cpkt);
while (success) {
if (cpkt.cptype == MT_CPTYPE_BEGINAUTH) {
int plen,i;
if (!curconn->have_pass_salt) {
for (i = 0; i < 16; ++i) {
curconn->pass_salt[i] = rand() % 256;
}
curconn->have_pass_salt = 1;
memset(curconn->trypassword, 0, sizeof(curconn->trypassword));
}
init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter);
plen = add_control_packet(&pdata, MT_CPTYPE_PASSSALT, (curconn->pass_salt), 16);
curconn->outcounter += plen;
send_udp(curconn, &pdata);
/* Don't change the username after the state is active */
} else if (cpkt.cptype == MT_CPTYPE_USERNAME && curconn->state != STATE_ACTIVE) {
memcpy(curconn->username, cpkt.data, act_size = (cpkt.length > MT_MNDP_MAX_STRING_SIZE - 1 ? MT_MNDP_MAX_STRING_SIZE - 1 : cpkt.length));
curconn->username[act_size] = 0;
got_user_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_WIDTH && cpkt.length >= 2) {
unsigned short width;
memcpy(&width, cpkt.data, 2);
curconn->terminal_width = le16toh(width);
got_width_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_HEIGHT && cpkt.length >= 2) {
unsigned short height;
memcpy(&height, cpkt.data, 2);
curconn->terminal_height = le16toh(height);
got_height_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_TERM_TYPE) {
memcpy(curconn->terminal_type, cpkt.data, act_size = (cpkt.length > 30 - 1 ? 30 - 1 : cpkt.length));
curconn->terminal_type[act_size] = 0;
} else if (cpkt.cptype == MT_CPTYPE_PASSWORD) {
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
mlock(curconn->trypassword, 17);
#endif
memcpy(curconn->trypassword, cpkt.data, 17);
got_pass_packet = 1;
} else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) {
/* relay data from client to shell */
if (curconn->state == STATE_ACTIVE && curconn->ptsfd != -1) {
write(curconn->ptsfd, cpkt.data, cpkt.length);
}
} else {
syslog(LOG_WARNING, _("(%d) Unhandeled control packet type: %d"), curconn->seskey, cpkt.cptype);
}
/* Parse next control packet */
success = parse_control_packet(NULL, 0, &cpkt);
}
if (got_user_packet && got_pass_packet) {
user_login(curconn, pkthdr);
}
if (curconn->state == STATE_ACTIVE && (got_width_packet || got_height_packet)) {
set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: __releases(mrt_lock)
{
read_unlock(&mrt_lock);
}
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 grow_pgdat_span(struct pglist_data *pgdat, unsigned long start_pfn,
unsigned long end_pfn)
{
unsigned long old_pgdat_end_pfn =
pgdat->node_start_pfn + pgdat->node_spanned_pages;
if (start_pfn < pgdat->node_start_pfn)
pgdat->node_start_pfn = start_pfn;
pgdat->node_spanned_pages = max(old_pgdat_end_pfn, end_pfn) -
pgdat->node_start_pfn;
}
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 NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) {
if (err != OK) {
mMetaDataSize = -1ll;
mContentType = "";
mSniffedMIME = "";
{
sp<DataSource> dataSource = mDataSource;
sp<NuCachedSource2> cachedSource = mCachedSource;
sp<DataSource> httpSource = mHttpSource;
{
Mutex::Autolock _l(mDisconnectLock);
mDataSource.clear();
mCachedSource.clear();
mHttpSource.clear();
}
}
cancelPollBuffering();
}
notifyPrepared(err);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderWidgetHostImpl::OnSyntheticGestureCompleted(
SyntheticGesture::Result result) {
Send(new InputMsg_SyntheticGestureCompleted(GetRoutingID()));
}
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 ParamTraits<DictionaryValue>::Log(const param_type& p, std::string* l) {
std::string json;
base::JSONWriter::Write(&p, &json);
l->append(json);
}
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 IBusBusNameOwnerChangedCallback(
IBusBus* bus,
const gchar* name, const gchar* old_name, const gchar* new_name,
gpointer user_data) {
DCHECK(name);
DCHECK(old_name);
DCHECK(new_name);
DLOG(INFO) << "Name owner is changed: name=" << name
<< ", old_name=" << old_name << ", new_name=" << new_name;
if (name != std::string("org.freedesktop.IBus.Config")) {
return;
}
const std::string empty_string;
if (old_name != empty_string || new_name == empty_string) {
LOG(WARNING) << "Unexpected name owner change: name=" << name
<< ", old_name=" << old_name << ", new_name=" << new_name;
return;
}
LOG(INFO) << "IBus config daemon is started. Recovering ibus_config_";
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->MaybeRestoreConnections();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int __br_mdb_add(struct net *net, struct net_bridge *br,
struct br_mdb_entry *entry)
{
struct br_ip ip;
struct net_device *dev;
struct net_bridge_port *p;
int ret;
if (!netif_running(br->dev) || br->multicast_disabled)
return -EINVAL;
dev = __dev_get_by_index(net, entry->ifindex);
if (!dev)
return -ENODEV;
p = br_port_get_rtnl(dev);
if (!p || p->br != br || p->state == BR_STATE_DISABLED)
return -EINVAL;
ip.proto = entry->addr.proto;
if (ip.proto == htons(ETH_P_IP))
ip.u.ip4 = entry->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
else
ip.u.ip6 = entry->addr.u.ip6;
#endif
spin_lock_bh(&br->multicast_lock);
ret = br_mdb_add_group(br, p, &ip, entry->state);
spin_unlock_bh(&br->multicast_lock);
return ret;
}
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: GraphicBuffer::GraphicBuffer(ANativeWindowBuffer* buffer, bool keepOwnership)
: BASE(), mOwner(keepOwnership ? ownHandle : ownNone),
mBufferMapper(GraphicBufferMapper::get()),
mInitCheck(NO_ERROR), mWrappedBuffer(buffer), mId(getUniqueId())
{
width = buffer->width;
height = buffer->height;
stride = buffer->stride;
format = buffer->format;
usage = buffer->usage;
handle = buffer->handle;
}
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: xmlParseElement(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
const xmlChar *prefix = NULL;
const xmlChar *URI = NULL;
xmlParserNodeInfo node_info;
int line, tlen;
xmlNodePtr ret;
int nsNr = ctxt->nsNr;
if (((unsigned int) ctxt->nameNr > xmlParserMaxDepth) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR,
"Excessive depth in document: %d use XML_PARSE_HUGE option\n",
xmlParserMaxDepth);
ctxt->instate = XML_PARSER_EOF;
return;
}
/* Capture start position */
if (ctxt->record_info) {
node_info.begin_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.begin_line = ctxt->input->line;
}
if (ctxt->spaceNr == 0)
spacePush(ctxt, -1);
else if (*ctxt->space == -2)
spacePush(ctxt, -1);
else
spacePush(ctxt, *ctxt->space);
line = ctxt->input->line;
#ifdef LIBXML_SAX1_ENABLED
if (ctxt->sax2)
#endif /* LIBXML_SAX1_ENABLED */
name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen);
#ifdef LIBXML_SAX1_ENABLED
else
name = xmlParseStartTag(ctxt);
#endif /* LIBXML_SAX1_ENABLED */
if (ctxt->instate == XML_PARSER_EOF)
return;
if (name == NULL) {
spacePop(ctxt);
return;
}
namePush(ctxt, name);
ret = ctxt->node;
#ifdef LIBXML_VALID_ENABLED
/*
* [ VC: Root Element Type ]
* The Name in the document type declaration must match the element
* type of the root element.
*/
if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
ctxt->node && (ctxt->node == ctxt->myDoc->children))
ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
#endif /* LIBXML_VALID_ENABLED */
/*
* Check for an Empty Element.
*/
if ((RAW == '/') && (NXT(1) == '>')) {
SKIP(2);
if (ctxt->sax2) {
if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI);
#ifdef LIBXML_SAX1_ENABLED
} else {
if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElement(ctxt->userData, name);
#endif /* LIBXML_SAX1_ENABLED */
}
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
return;
}
if (RAW == '>') {
NEXT1;
} else {
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED,
"Couldn't find end of Start Tag %s line %d\n",
name, line, NULL);
/*
* end of parsing of this node.
*/
nodePop(ctxt);
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
/*
* Capture end position and add node
*/
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
return;
}
/*
* Parse the content of the element:
*/
xmlParseContent(ctxt);
if (!IS_BYTE_CHAR(RAW)) {
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
"Premature end of data in tag %s line %d\n",
name, line, NULL);
/*
* end of parsing of this node.
*/
nodePop(ctxt);
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
return;
}
/*
* parse the end of tag: '</' should be here.
*/
if (ctxt->sax2) {
xmlParseEndTag2(ctxt, prefix, URI, line, ctxt->nsNr - nsNr, tlen);
namePop(ctxt);
}
#ifdef LIBXML_SAX1_ENABLED
else
xmlParseEndTag1(ctxt, line);
#endif /* LIBXML_SAX1_ENABLED */
/*
* Capture end position and add node
*/
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int Virtualizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int16_t strength;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param){
case VIRTUALIZER_PARAM_STRENGTH:
strength = *(int16_t *)pValue;
VirtualizerSetStrength(pContext, (int32_t)strength);
break;
default:
ALOGV("\tLVM_ERROR : Virtualizer_setParameter() invalid param %d", param);
break;
}
return status;
} /* end Virtualizer_setParameter */
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: vc4_submit_cl_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct vc4_dev *vc4 = to_vc4_dev(dev);
struct drm_vc4_submit_cl *args = data;
struct vc4_exec_info *exec;
int ret = 0;
if ((args->flags & ~VC4_SUBMIT_CL_USE_CLEAR_COLOR) != 0) {
DRM_ERROR("Unknown flags: 0x%02x\n", args->flags);
return -EINVAL;
}
exec = kcalloc(1, sizeof(*exec), GFP_KERNEL);
if (!exec) {
DRM_ERROR("malloc failure on exec struct\n");
return -ENOMEM;
}
mutex_lock(&vc4->power_lock);
if (vc4->power_refcount++ == 0)
ret = pm_runtime_get_sync(&vc4->v3d->pdev->dev);
mutex_unlock(&vc4->power_lock);
if (ret < 0) {
kfree(exec);
return ret;
}
exec->args = args;
INIT_LIST_HEAD(&exec->unref_list);
ret = vc4_cl_lookup_bos(dev, file_priv, exec);
if (ret)
goto fail;
if (exec->args->bin_cl_size != 0) {
ret = vc4_get_bcl(dev, exec);
if (ret)
goto fail;
} else {
exec->ct0ca = 0;
exec->ct0ea = 0;
}
ret = vc4_get_rcl(dev, exec);
if (ret)
goto fail;
/* Clear this out of the struct we'll be putting in the queue,
* since it's part of our stack.
*/
exec->args = NULL;
vc4_queue_submit(dev, exec);
/* Return the seqno for our job. */
args->seqno = vc4->emit_seqno;
return 0;
fail:
vc4_complete_exec(vc4->dev, exec);
return ret;
}
CWE ID: CWE-388
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: ossl_cipher_initialize(VALUE self, VALUE str)
{
EVP_CIPHER_CTX *ctx;
const EVP_CIPHER *cipher;
char *name;
unsigned char dummy_key[EVP_MAX_KEY_LENGTH] = { 0 };
name = StringValueCStr(str);
GetCipherInit(self, ctx);
if (ctx) {
ossl_raise(rb_eRuntimeError, "Cipher already inititalized!");
}
AllocCipher(self, ctx);
if (!(cipher = EVP_get_cipherbyname(name))) {
ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%"PRIsVALUE")", str);
}
/*
* EVP_CipherInit_ex() allows to specify NULL to key and IV, however some
* ciphers don't handle well (OpenSSL's bug). [Bug #2768]
*
* The EVP which has EVP_CIPH_RAND_KEY flag (such as DES3) allows
* uninitialized key, but other EVPs (such as AES) does not allow it.
* Calling EVP_CipherUpdate() without initializing key causes SEGV so we
* set the data filled with "\0" as the key by default.
*/
if (EVP_CipherInit_ex(ctx, cipher, NULL, dummy_key, NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
return self;
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: MSG_PROCESS_RETURN tls_process_key_exchange(SSL *s, PACKET *pkt)
{
int al = -1;
long alg_k;
EVP_PKEY *pkey = NULL;
PACKET save_param_start, signature;
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
save_param_start = *pkt;
#if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
EVP_PKEY_free(s->s3->peer_tmp);
s->s3->peer_tmp = NULL;
#endif
if (alg_k & SSL_PSK) {
if (!tls_process_ske_psk_preamble(s, pkt, &al))
goto err;
}
/* Nothing else to do for plain PSK or RSAPSK */
if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
} else if (alg_k & SSL_kSRP) {
if (!tls_process_ske_srp(s, pkt, &pkey, &al))
goto err;
} else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
if (!tls_process_ske_dhe(s, pkt, &pkey, &al))
goto err;
} else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
if (!tls_process_ske_ecdhe(s, pkt, &pkey, &al))
goto err;
} else if (alg_k) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE);
goto err;
}
/* if it was signed, check the signature */
if (pkey != NULL) {
PACKET params;
int maxsig;
const EVP_MD *md = NULL;
EVP_MD_CTX *md_ctx;
/*
* |pkt| now points to the beginning of the signature, so the difference
* equals the length of the parameters.
*/
if (!PACKET_get_sub_packet(&save_param_start, ¶ms,
PACKET_remaining(&save_param_start) -
PACKET_remaining(pkt))) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
if (SSL_USE_SIGALGS(s)) {
const unsigned char *sigalgs;
int rv;
if (!PACKET_get_bytes(pkt, &sigalgs, 2)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT);
goto err;
}
rv = tls12_check_peer_sigalg(&md, s, sigalgs, pkey);
if (rv == -1) {
al = SSL_AD_INTERNAL_ERROR;
goto err;
} else if (rv == 0) {
al = SSL_AD_DECODE_ERROR;
goto err;
}
#ifdef SSL_DEBUG
fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
#endif
} else if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) {
md = EVP_md5_sha1();
} else {
md = EVP_sha1();
}
if (!PACKET_get_length_prefixed_2(pkt, &signature)
|| PACKET_remaining(pkt) != 0) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
goto err;
}
maxsig = EVP_PKEY_size(pkey);
if (maxsig < 0) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
goto err;
}
/*
* Check signature length
*/
if (PACKET_remaining(&signature) > (size_t)maxsig) {
/* wrong packet length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE,
SSL_R_WRONG_SIGNATURE_LENGTH);
goto err;
}
md_ctx = EVP_MD_CTX_new();
if (md_ctx == NULL) {
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
goto err;
}
if (EVP_VerifyInit_ex(md_ctx, md, NULL) <= 0
|| EVP_VerifyUpdate(md_ctx, &(s->s3->client_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_VerifyUpdate(md_ctx, &(s->s3->server_random[0]),
SSL3_RANDOM_SIZE) <= 0
|| EVP_VerifyUpdate(md_ctx, PACKET_data(¶ms),
PACKET_remaining(¶ms)) <= 0) {
EVP_MD_CTX_free(md_ctx);
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_EVP_LIB);
goto err;
}
if (EVP_VerifyFinal(md_ctx, PACKET_data(&signature),
PACKET_remaining(&signature), pkey) <= 0) {
/* bad signature */
EVP_MD_CTX_free(md_ctx);
al = SSL_AD_DECRYPT_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_BAD_SIGNATURE);
goto err;
}
EVP_MD_CTX_free(md_ctx);
} else {
/* aNULL, aSRP or PSK do not need public keys */
if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
&& !(alg_k & SSL_PSK)) {
/* Might be wrong key type, check it */
if (ssl3_check_cert_and_algorithm(s)) {
/* Otherwise this shouldn't happen */
al = SSL_AD_INTERNAL_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
} else {
al = SSL_AD_DECODE_ERROR;
}
goto err;
}
/* still data left over */
if (PACKET_remaining(pkt) != 0) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_TLS_PROCESS_KEY_EXCHANGE, SSL_R_EXTRA_DATA_IN_MESSAGE);
goto err;
}
}
return MSG_PROCESS_CONTINUE_READING;
err:
if (al != -1)
ssl3_send_alert(s, SSL3_AL_FATAL, al);
ossl_statem_set_error(s);
return MSG_PROCESS_ERROR;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ModuleSystem::NativesEnabledScope::~NativesEnabledScope() {
module_system_->natives_enabled_--;
CHECK_GE(module_system_->natives_enabled_, 0);
}
CWE ID: CWE-264
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool FileUtilProxy::Read(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
int bytes_to_read,
ReadCallback* callback) {
if (bytes_to_read < 0)
return false;
return Start(FROM_HERE, message_loop_proxy,
new RelayRead(file, offset, bytes_to_read, callback));
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static inline bool is_debug(u32 intr_info)
{
return is_exception_n(intr_info, DB_VECTOR);
}
CWE ID: CWE-388
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: WKRetainPtr<WKImageRef> PlatformWebView::windowSnapshotImage()
{
return 0;
}
CWE ID:
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ExtensionsGuestViewMessageFilter::ExtensionsGuestViewMessageFilter(
int render_process_id,
BrowserContext* context)
: GuestViewMessageFilter(kFilteredMessageClasses,
base::size(kFilteredMessageClasses),
render_process_id,
context),
content::BrowserAssociatedInterface<mojom::GuestView>(this, this) {
GetProcessIdToFilterMap()->insert_or_assign(render_process_id_, this);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
ResetMagickMemory(&stream, 0, sizeof(z_stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(unsigned int) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(unsigned int) count;
if(inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream, Z_SYNC_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
}
}
if (compression == ZipWithPrediction)
{
p=pixels;
while(count > 0)
{
length=image->columns;
while(--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int zrle_send_framebuffer_update(VncState *vs, int x, int y,
int w, int h)
{
bool be = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);
size_t bytes;
int zywrle_level;
if (vs->zrle.type == VNC_ENCODING_ZYWRLE) {
if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1
|| vs->tight.quality == 9) {
zywrle_level = 0;
vs->zrle.type = VNC_ENCODING_ZRLE;
} else if (vs->tight.quality < 3) {
zywrle_level = 3;
} else if (vs->tight.quality < 6) {
zywrle_level = 2;
} else {
zywrle_level = 1;
}
} else {
zywrle_level = 0;
}
vnc_zrle_start(vs);
switch(vs->clientds.pf.bytes_per_pixel) {
case 1:
zrle_encode_8ne(vs, x, y, w, h, zywrle_level);
break;
case 2:
if (vs->clientds.pf.gmax > 0x1F) {
if (be) {
zrle_encode_16be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_16le(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_15be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_15le(vs, x, y, w, h, zywrle_level);
}
}
break;
case 4:
{
bool fits_in_ls3bytes;
bool fits_in_ms3bytes;
fits_in_ls3bytes =
((vs->clientds.pf.rmax << vs->clientds.pf.rshift) < (1 << 24) &&
(vs->clientds.pf.gmax << vs->clientds.pf.gshift) < (1 << 24) &&
(vs->clientds.pf.bmax << vs->clientds.pf.bshift) < (1 << 24));
fits_in_ms3bytes = (vs->clientds.pf.rshift > 7 &&
vs->clientds.pf.gshift > 7 &&
vs->clientds.pf.bshift > 7);
if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) {
if (be) {
zrle_encode_24abe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ale(vs, x, y, w, h, zywrle_level);
}
} else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) {
if (be) {
zrle_encode_24bbe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ble(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_32be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_32le(vs, x, y, w, h, zywrle_level);
}
}
}
break;
}
vnc_zrle_stop(vs);
bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION);
vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type);
vnc_write_u32(vs, bytes);
vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset);
return 1;
}
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 EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod1(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() < 2)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->overloadedMethod(objArg, strArg);
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void t1_read_subrs(void)
{
int i, s;
cs_entry *ptr;
t1_getline();
while (!(t1_charstrings() || t1_subrs())) {
t1_scan_param();
t1_putline();
t1_getline();
}
found:
t1_cs = true;
t1_scan = false;
if (!t1_subrs())
return;
subr_size_pos = strlen("/Subrs") + 1;
/* subr_size_pos points to the number indicating dict size after "/Subrs" */
subr_size = t1_scan_num(t1_line_array + subr_size_pos, 0);
if (subr_size == 0) {
while (!t1_charstrings())
t1_getline();
return;
}
subr_tab = xtalloc(subr_size, cs_entry);
for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
init_cs_entry(ptr);
subr_array_start = xstrdup(t1_line_array);
t1_getline();
while (t1_cslen) {
store_subr();
t1_getline();
}
/* mark the first four entries without parsing */
for (i = 0; i < subr_size && i < 4; i++)
subr_tab[i].used = true;
/* the end of the Subrs array might have more than one line so we need to
concatnate them to subr_array_end. Unfortunately some fonts don't have
the Subrs array followed by the CharStrings dict immediately (synthetic
fonts). If we cannot find CharStrings in next POST_SUBRS_SCAN lines then
we will treat the font as synthetic and ignore everything until next
Subrs is found
*/
#define POST_SUBRS_SCAN 5
s = 0;
*t1_buf_array = 0;
for (i = 0; i < POST_SUBRS_SCAN; i++) {
if (t1_charstrings())
break;
s += t1_line_ptr - t1_line_array;
alloc_array(t1_buf, s, T1_BUF_SIZE);
strcat(t1_buf_array, t1_line_array);
t1_getline();
}
subr_array_end = xstrdup(t1_buf_array);
if (i == POST_SUBRS_SCAN) { /* CharStrings not found;
suppose synthetic font */
for (ptr = subr_tab; ptr - subr_tab < subr_size; ptr++)
if (ptr->valid)
xfree(ptr->data);
xfree(subr_tab);
xfree(subr_array_start);
xfree(subr_array_end);
cs_init();
t1_cs = false;
t1_synthetic = true;
while (!(t1_charstrings() || t1_subrs()))
t1_getline();
goto found;
}
}
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 on_l2cap_connect(tBTA_JV *p_data, uint32_t id)
{
l2cap_socket *sock;
tBTA_JV_L2CAP_OPEN *psm_open = &p_data->l2c_open;
tBTA_JV_L2CAP_LE_OPEN *le_open = &p_data->l2c_le_open;
pthread_mutex_lock(&state_lock);
sock = btsock_l2cap_find_by_id_l(id);
if (!sock) {
APPL_TRACE_ERROR("on_l2cap_connect on unknown socket");
} else {
if (sock->fixed_chan && le_open->status == BTA_JV_SUCCESS) {
if (!sock->server)
on_cl_l2cap_le_connect_l(le_open, sock);
else
on_srv_l2cap_le_connect_l(le_open, sock);
} else if (!sock->fixed_chan && psm_open->status == BTA_JV_SUCCESS) {
if (!sock->server)
on_cl_l2cap_psm_connect_l(psm_open, sock);
else
on_srv_l2cap_psm_connect_l(psm_open, sock);
}
else
btsock_l2cap_free_l(sock);
}
pthread_mutex_unlock(&state_lock);
}
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 BlockAIOCB *iscsi_aio_ioctl(BlockDriverState *bs,
unsigned long int req, void *buf,
BlockCompletionFunc *cb, void *opaque)
{
IscsiLun *iscsilun = bs->opaque;
struct iscsi_context *iscsi = iscsilun->iscsi;
struct iscsi_data data;
IscsiAIOCB *acb;
acb = qemu_aio_get(&iscsi_aiocb_info, bs, cb, opaque);
acb->iscsilun = iscsilun;
acb->bh = NULL;
acb->status = -EINPROGRESS;
acb->buf = NULL;
acb->ioh = buf;
if (req != SG_IO) {
iscsi_ioctl_handle_emulated(acb, req, buf);
return &acb->common;
}
acb->task = malloc(sizeof(struct scsi_task));
if (acb->task == NULL) {
error_report("iSCSI: Failed to allocate task for scsi command. %s",
case SG_DXFER_TO_DEV:
acb->task->xfer_dir = SCSI_XFER_WRITE;
break;
case SG_DXFER_FROM_DEV:
acb->task->xfer_dir = SCSI_XFER_READ;
break;
default:
acb->task->xfer_dir = SCSI_XFER_NONE;
break;
}
acb->task->cdb_size = acb->ioh->cmd_len;
memcpy(&acb->task->cdb[0], acb->ioh->cmdp, acb->ioh->cmd_len);
acb->task->expxferlen = acb->ioh->dxfer_len;
data.size = 0;
if (acb->task->xfer_dir == SCSI_XFER_WRITE) {
if (acb->ioh->iovec_count == 0) {
data.data = acb->ioh->dxferp;
data.size = acb->ioh->dxfer_len;
} else {
scsi_task_set_iov_out(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
if (iscsi_scsi_command_async(iscsi, iscsilun->lun, acb->task,
iscsi_aio_ioctl_cb,
(data.size > 0) ? &data : NULL,
acb) != 0) {
scsi_free_scsi_task(acb->task);
qemu_aio_unref(acb);
return NULL;
}
/* tell libiscsi to read straight into the buffer we got from ioctl */
if (acb->task->xfer_dir == SCSI_XFER_READ) {
if (acb->ioh->iovec_count == 0) {
scsi_task_add_data_in_buffer(acb->task,
acb->ioh->dxfer_len,
acb->ioh->dxferp);
} else {
scsi_task_set_iov_in(acb->task,
(struct scsi_iovec *) acb->ioh->dxferp,
acb->ioh->iovec_count);
}
}
iscsi_set_events(iscsilun);
return &acb->common;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int __init dccp_v6_init(void)
{
int err = proto_register(&dccp_v6_prot, 1);
if (err != 0)
goto out;
err = inet6_add_protocol(&dccp_v6_protocol, IPPROTO_DCCP);
if (err != 0)
goto out_unregister_proto;
inet6_register_protosw(&dccp_v6_protosw);
err = register_pernet_subsys(&dccp_v6_ops);
if (err != 0)
goto out_destroy_ctl_sock;
out:
return err;
out_destroy_ctl_sock:
inet6_del_protocol(&dccp_v6_protocol, IPPROTO_DCCP);
inet6_unregister_protosw(&dccp_v6_protosw);
out_unregister_proto:
proto_unregister(&dccp_v6_prot);
goto out;
}
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: std::string ChromeOSGetKeyboardOverlayId(const std::string& input_method_id) {
for (size_t i = 0; i < arraysize(kKeyboardOverlayMap); ++i) {
if (kKeyboardOverlayMap[i].input_method_id == input_method_id) {
return kKeyboardOverlayMap[i].keyboard_overlay_id;
}
}
return "";
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
RenderWidgetHostImpl* receiving_widget) {
if (!SiteIsolationPolicy::AreCrossProcessFramesPossible())
return receiving_widget;
if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
return receiving_widget;
WebContentsImpl* focused_contents = GetFocusedWebContents();
if (focused_contents->ShowingInterstitialPage()) {
return static_cast<RenderFrameHostImpl*>(
focused_contents->GetRenderManager()
->interstitial_page()
->GetMainFrame())
->GetRenderWidgetHost();
}
FrameTreeNode* focused_frame = nullptr;
if (focused_contents->browser_plugin_guest_ &&
!GuestMode::IsCrossProcessFrameGuest(focused_contents)) {
focused_frame = frame_tree_.GetFocusedFrame();
} else {
focused_frame = GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
}
if (!focused_frame)
return receiving_widget;
RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
if (!view)
return nullptr;
return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool GLES2DecoderImpl::ClearLevel(
unsigned service_id,
unsigned bind_target,
unsigned target,
int level,
unsigned format,
unsigned type,
int width,
int height,
bool is_texture_immutable) {
uint32 channels = GLES2Util::GetChannelsForFormat(format);
if (IsAngle() && (channels & GLES2Util::kDepth) != 0) {
GLuint fb = 0;
glGenFramebuffersEXT(1, &fb);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, fb);
bool have_stencil = (channels & GLES2Util::kStencil) != 0;
GLenum attachment = have_stencil ? GL_DEPTH_STENCIL_ATTACHMENT :
GL_DEPTH_ATTACHMENT;
glFramebufferTexture2DEXT(
GL_DRAW_FRAMEBUFFER_EXT, attachment, target, service_id, level);
if (glCheckFramebufferStatusEXT(GL_DRAW_FRAMEBUFFER_EXT) !=
GL_FRAMEBUFFER_COMPLETE) {
return false;
}
glClearStencil(0);
glStencilMask(-1);
glClearDepth(1.0f);
glDepthMask(true);
glDisable(GL_SCISSOR_TEST);
glClear(GL_DEPTH_BUFFER_BIT | (have_stencil ? GL_STENCIL_BUFFER_BIT : 0));
RestoreClearState();
glDeleteFramebuffersEXT(1, &fb);
FramebufferManager::FramebufferInfo* framebuffer =
GetFramebufferInfoForTarget(GL_DRAW_FRAMEBUFFER_EXT);
GLuint fb_service_id =
framebuffer ? framebuffer->service_id() : GetBackbufferServiceId();
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, fb_service_id);
return true;
}
static const uint32 kMaxZeroSize = 1024 * 1024 * 4;
uint32 size;
uint32 padded_row_size;
if (!GLES2Util::ComputeImageDataSizes(
width, height, format, type, unpack_alignment_, &size,
NULL, &padded_row_size)) {
return false;
}
TRACE_EVENT1("gpu", "GLES2DecoderImpl::ClearLevel", "size", size);
int tile_height;
if (size > kMaxZeroSize) {
if (kMaxZeroSize < padded_row_size) {
return false;
}
DCHECK_GT(padded_row_size, 0U);
tile_height = kMaxZeroSize / padded_row_size;
if (!GLES2Util::ComputeImageDataSizes(
width, tile_height, format, type, unpack_alignment_, &size, NULL,
NULL)) {
return false;
}
} else {
tile_height = height;
}
scoped_array<char> zero(new char[size]);
memset(zero.get(), 0, size);
glBindTexture(bind_target, service_id);
GLint y = 0;
while (y < height) {
GLint h = y + tile_height > height ? height - y : tile_height;
if (is_texture_immutable || h != height) {
glTexSubImage2D(target, level, 0, y, width, h, format, type, zero.get());
} else {
WrappedTexImage2D(
target, level, format, width, h, 0, format, type, zero.get());
}
y += tile_height;
}
TextureManager::TextureInfo* info = GetTextureInfoForTarget(bind_target);
glBindTexture(bind_target, info ? info->service_id() : 0);
return true;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_MSB,op_LSB;
int ret;
if (!data)
return 0;
memset (op, '\0', sizeof (RAnalOp));
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->jump = op->fail = -1;
op->ptr = op->val = -1;
op->size = 2;
op_MSB = anal->big_endian? data[0]: data[1];
op_LSB = anal->big_endian? data[1]: data[0];
ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
return ret;
}
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: LockServer(void)
{
char tmp[PATH_MAX], pid_str[12];
int lfd, i, haslock, l_pid, t;
char *tmppath = NULL;
int len;
char port[20];
if (nolock) return;
/*
* Path names
*/
tmppath = LOCK_DIR;
sprintf(port, "%d", atoi(display));
len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) :
strlen(LOCK_TMP_PREFIX);
len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1;
if (len > sizeof(LockFile))
FatalError("Display name `%s' is too long\n", port);
(void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
(void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port);
/*
* Create a temporary file containing our PID. Attempt three times
* to create the file.
*/
StillLocking = TRUE;
i = 0;
do {
i++;
lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
if (lfd < 0)
sleep(2);
else
break;
} while (i < 3);
if (lfd < 0) {
unlink(tmp);
i = 0;
do {
i++;
lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);
if (lfd < 0)
sleep(2);
else
break;
} while (i < 3);
}
if (lfd < 0)
FatalError("Could not create lock file in %s\n", tmp);
(void) sprintf(pid_str, "%10ld\n", (long)getpid());
(void) write(lfd, pid_str, 11);
(void) chmod(tmp, 0444);
(void) close(lfd);
/*
* OK. Now the tmp file exists. Try three times to move it in place
* for the lock.
*/
i = 0;
haslock = 0;
while ((!haslock) && (i++ < 3)) {
haslock = (link(tmp,LockFile) == 0);
if (haslock) {
/*
* We're done.
*/
break;
}
else {
/*
* Read the pid from the existing file
*/
lfd = open(LockFile, O_RDONLY);
if (lfd < 0) {
unlink(tmp);
FatalError("Can't read lock file %s\n", LockFile);
}
pid_str[0] = '\0';
if (read(lfd, pid_str, 11) != 11) {
/*
* Bogus lock file.
*/
unlink(LockFile);
close(lfd);
continue;
}
pid_str[11] = '\0';
sscanf(pid_str, "%d", &l_pid);
close(lfd);
/*
* Now try to kill the PID to see if it exists.
*/
errno = 0;
t = kill(l_pid, 0);
if ((t< 0) && (errno == ESRCH)) {
/*
* Stale lock file.
*/
unlink(LockFile);
continue;
}
else if (((t < 0) && (errno == EPERM)) || (t == 0)) {
/*
* Process is still active.
*/
unlink(tmp);
FatalError("Server is already active for display %s\n%s %s\n%s\n",
port, "\tIf this server is no longer running, remove",
LockFile, "\tand start again.");
}
}
}
unlink(tmp);
if (!haslock)
FatalError("Could not create server lock file: %s\n", LockFile);
StillLocking = FALSE;
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: static int crypto_add_alg(struct sk_buff *skb, struct nlmsghdr *nlh,
struct nlattr **attrs)
{
int exact = 0;
const char *name;
struct crypto_alg *alg;
struct crypto_user_alg *p = nlmsg_data(nlh);
struct nlattr *priority = attrs[CRYPTOCFGA_PRIORITY_VAL];
if (strlen(p->cru_driver_name))
exact = 1;
if (priority && !exact)
return -EINVAL;
alg = crypto_alg_match(p, exact);
if (alg)
return -EEXIST;
if (strlen(p->cru_driver_name))
name = p->cru_driver_name;
else
name = p->cru_name;
switch (p->cru_type & p->cru_mask & CRYPTO_ALG_TYPE_MASK) {
case CRYPTO_ALG_TYPE_AEAD:
alg = crypto_user_aead_alg(name, p->cru_type, p->cru_mask);
break;
case CRYPTO_ALG_TYPE_GIVCIPHER:
case CRYPTO_ALG_TYPE_BLKCIPHER:
case CRYPTO_ALG_TYPE_ABLKCIPHER:
alg = crypto_user_skcipher_alg(name, p->cru_type, p->cru_mask);
break;
default:
alg = crypto_alg_mod_lookup(name, p->cru_type, p->cru_mask);
}
if (IS_ERR(alg))
return PTR_ERR(alg);
down_write(&crypto_alg_sem);
if (priority)
alg->cra_priority = nla_get_u32(priority);
up_write(&crypto_alg_sem);
crypto_mod_put(alg);
return 0;
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool DownloadItemImpl::CanOpenDownload() {
return !file_externally_removed_;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void keyring_describe(const struct key *keyring, struct seq_file *m)
{
if (keyring->description)
seq_puts(m, keyring->description);
else
seq_puts(m, "[anon]");
if (key_is_instantiated(keyring)) {
if (keyring->keys.nr_leaves_on_tree != 0)
seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
else
seq_puts(m, ": empty");
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: error::Error GLES2DecoderImpl::HandlePixelStorei(
uint32 immediate_data_size, const gles2::PixelStorei& c) {
GLenum pname = c.pname;
GLenum param = c.param;
if (!validators_->pixel_store.IsValid(pname)) {
SetGLError(GL_INVALID_ENUM, "glPixelStorei: pname GL_INVALID_ENUM");
return error::kNoError;
}
switch (pname) {
case GL_PACK_ALIGNMENT:
case GL_UNPACK_ALIGNMENT:
if (!validators_->pixel_store_alignment.IsValid(param)) {
SetGLError(GL_INVALID_VALUE,
"glPixelSTore: param GL_INVALID_VALUE");
return error::kNoError;
}
default:
break;
}
glPixelStorei(pname, param);
switch (pname) {
case GL_PACK_ALIGNMENT:
pack_alignment_ = param;
break;
case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
break;
case GL_UNPACK_ALIGNMENT:
unpack_alignment_ = param;
break;
default:
NOTREACHED();
break;
}
return error::kNoError;
}
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 sched_online_group(struct task_group *tg, struct task_group *parent)
{
unsigned long flags;
spin_lock_irqsave(&task_group_lock, flags);
list_add_rcu(&tg->list, &task_groups);
WARN_ON(!parent); /* root should already exist */
tg->parent = parent;
INIT_LIST_HEAD(&tg->children);
list_add_rcu(&tg->siblings, &parent->children);
spin_unlock_irqrestore(&task_group_lock, flags);
}
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: OVS_REQUIRES(ofproto_mutex)
{
const struct rule_actions *actions = rule_get_actions(rule);
/* A rule may not be reinserted. */
ovs_assert(rule->state == RULE_INITIALIZED);
if (rule->hard_timeout || rule->idle_timeout) {
ovs_list_insert(&ofproto->expirable, &rule->expirable);
}
cookies_insert(ofproto, rule);
eviction_group_add_rule(rule);
if (actions->has_meter) {
meter_insert_rule(rule);
}
if (actions->has_groups) {
const struct ofpact_group *a;
OFPACT_FOR_EACH_TYPE_FLATTENED (a, GROUP, actions->ofpacts,
actions->ofpacts_len) {
struct ofgroup *group;
group = ofproto_group_lookup(ofproto, a->group_id, OVS_VERSION_MAX,
false);
ovs_assert(group != NULL);
group_add_rule(group, rule);
}
}
rule->state = RULE_INSERTED;
}
CWE ID: CWE-617
Target: 1
Example 2:
Code: void cache_tmp_xattr(struct file_struct *file, stat_x *sxp)
{
int ndx;
if (!sxp->xattr)
return;
if (prior_xattr_count == (size_t)-1)
prior_xattr_count = rsync_xal_l.count;
ndx = find_matching_xattr(sxp->xattr);
if (ndx < 0)
rsync_xal_store(sxp->xattr); /* adds item to rsync_xal_l */
F_XATTR(file) = ndx;
}
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: _rsvg_io_get_file_path (const gchar * filename,
const gchar * base_uri)
{
gchar *absolute_filename;
if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) {
absolute_filename = g_strdup (filename);
} else {
gchar *tmpcdir;
gchar *base_filename;
if (base_uri) {
base_filename = g_filename_from_uri (base_uri, NULL, NULL);
if (base_filename != NULL) {
tmpcdir = g_path_get_dirname (base_filename);
g_free (base_filename);
} else
return NULL;
} else
tmpcdir = g_get_current_dir ();
absolute_filename = g_build_filename (tmpcdir, filename, NULL);
g_free (tmpcdir);
}
return absolute_filename;
}
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: _asn1_ltostr (long v, char *str)
{
long d, r;
char temp[LTOSTR_MAX_SIZE];
int count, k, start;
if (v < 0)
{
str[0] = '-';
start = 1;
v = -v;
}
else
start = 0;
count = 0;
do
{
d = v / 10;
r = v - d * 10;
temp[start + count] = '0' + (char) r;
count++;
v = d;
}
while (v);
for (k = 0; k < count; k++)
str[k + start] = temp[start + count - k - 1];
str[count + start] = 0;
return str;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static ssize_t TIFFReadCustomStream(unsigned char *data,const size_t count,
void *user_data)
{
PhotoshopProfile
*profile;
size_t
total;
ssize_t
remaining;
if (count == 0)
return(0);
profile=(PhotoshopProfile *) user_data;
remaining=(MagickOffsetType) profile->length-profile->offset;
if (remaining <= 0)
return(-1);
total=MagickMin(count, (size_t) remaining);
(void) memcpy(data,profile->data->datum+profile->offset,total);
profile->offset+=total;
return(total);
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool GLES2DecoderImpl::CheckFramebufferValid(
Framebuffer* framebuffer,
GLenum target, const char* func_name) {
if (!framebuffer) {
if (backbuffer_needs_clear_bits_) {
glClearColor(0, 0, 0, (GLES2Util::GetChannelsForFormat(
offscreen_target_color_format_) & 0x0008) != 0 ? 0 : 1);
state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glClearStencil(0);
state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1);
state_.SetDeviceStencilMaskSeparate(GL_BACK, -1);
glClearDepth(1.0f);
state_.SetDeviceDepthMask(GL_TRUE);
state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false);
glClear(backbuffer_needs_clear_bits_);
backbuffer_needs_clear_bits_ = 0;
RestoreClearState();
}
return true;
}
if (framebuffer_manager()->IsComplete(framebuffer)) {
return true;
}
GLenum completeness = framebuffer->IsPossiblyComplete();
if (completeness != GL_FRAMEBUFFER_COMPLETE) {
LOCAL_SET_GL_ERROR(
GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete");
return false;
}
if (renderbuffer_manager()->HaveUnclearedRenderbuffers() ||
texture_manager()->HaveUnclearedMips()) {
if (!framebuffer->IsCleared()) {
if (framebuffer->GetStatus(texture_manager(), target) !=
GL_FRAMEBUFFER_COMPLETE) {
LOCAL_SET_GL_ERROR(
GL_INVALID_FRAMEBUFFER_OPERATION, func_name,
"framebuffer incomplete (clear)");
return false;
}
ClearUnclearedAttachments(target, framebuffer);
}
}
if (!framebuffer_manager()->IsComplete(framebuffer)) {
if (framebuffer->GetStatus(texture_manager(), target) !=
GL_FRAMEBUFFER_COMPLETE) {
LOCAL_SET_GL_ERROR(
GL_INVALID_FRAMEBUFFER_OPERATION, func_name,
"framebuffer incomplete (check)");
return false;
}
framebuffer_manager()->MarkAsComplete(framebuffer);
}
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: setup_arch (char **cmdline_p)
{
unw_init();
ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist);
*cmdline_p = __va(ia64_boot_param->command_line);
strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE);
efi_init();
io_port_init();
#ifdef CONFIG_IA64_GENERIC
/* machvec needs to be parsed from the command line
* before parse_early_param() is called to ensure
* that ia64_mv is initialised before any command line
* settings may cause console setup to occur
*/
machvec_init_from_cmdline(*cmdline_p);
#endif
parse_early_param();
if (early_console_setup(*cmdline_p) == 0)
mark_bsp_online();
#ifdef CONFIG_ACPI
/* Initialize the ACPI boot-time table parser */
acpi_table_init();
# ifdef CONFIG_ACPI_NUMA
acpi_numa_init();
per_cpu_scan_finalize((cpus_weight(early_cpu_possible_map) == 0 ?
32 : cpus_weight(early_cpu_possible_map)), additional_cpus);
# endif
#else
# ifdef CONFIG_SMP
smp_build_cpu_map(); /* happens, e.g., with the Ski simulator */
# endif
#endif /* CONFIG_APCI_BOOT */
find_memory();
/* process SAL system table: */
ia64_sal_init(__va(efi.sal_systab));
#ifdef CONFIG_SMP
cpu_physical_id(0) = hard_smp_processor_id();
#endif
cpu_init(); /* initialize the bootstrap CPU */
mmu_context_init(); /* initialize context_id bitmap */
check_sal_cache_flush();
#ifdef CONFIG_ACPI
acpi_boot_init();
#endif
#ifdef CONFIG_VT
if (!conswitchp) {
# if defined(CONFIG_DUMMY_CONSOLE)
conswitchp = &dummy_con;
# endif
# if defined(CONFIG_VGA_CONSOLE)
/*
* Non-legacy systems may route legacy VGA MMIO range to system
* memory. vga_con probes the MMIO hole, so memory looks like
* a VGA device to it. The EFI memory map can tell us if it's
* memory so we can avoid this problem.
*/
if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY)
conswitchp = &vga_con;
# endif
}
#endif
/* enable IA-64 Machine Check Abort Handling unless disabled */
if (!nomca)
ia64_mca_init();
platform_setup(cmdline_p);
paging_init();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ParamTraits<unsigned long>::Log(const param_type& p, std::string* l) {
l->append(base::Uint64ToString(static_cast<uint64>(p)));
}
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: process_open(u_int32_t id)
{
u_int32_t pflags;
Attrib a;
char *name;
int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE;
if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
(r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */
(r = decode_attrib(iqueue, &a)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
debug3("request %u: open flags %d", id, pflags);
flags = flags_from_portable(pflags);
mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666;
logit("open \"%s\" flags %s mode 0%o",
name, string_from_portable(pflags), mode);
if (readonly &&
((flags & O_ACCMODE) == O_WRONLY ||
(flags & O_ACCMODE) == O_RDWR)) {
verbose("Refusing open request in read-only mode");
status = SSH2_FX_PERMISSION_DENIED;
} else {
fd = open(name, flags, mode);
if (fd < 0) {
status = errno_to_portable(errno);
} else {
handle = handle_new(HANDLE_FILE, name, fd, flags, NULL);
if (handle < 0) {
close(fd);
} else {
send_handle(id, handle);
status = SSH2_FX_OK;
}
}
}
if (status != SSH2_FX_OK)
send_status(id, status);
free(name);
}
CWE ID: CWE-269
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int compat_get_timex(struct timex *txc, const struct compat_timex __user *utp)
{
struct compat_timex tx32;
if (copy_from_user(&tx32, utp, sizeof(struct compat_timex)))
return -EFAULT;
txc->modes = tx32.modes;
txc->offset = tx32.offset;
txc->freq = tx32.freq;
txc->maxerror = tx32.maxerror;
txc->esterror = tx32.esterror;
txc->status = tx32.status;
txc->constant = tx32.constant;
txc->precision = tx32.precision;
txc->tolerance = tx32.tolerance;
txc->time.tv_sec = tx32.time.tv_sec;
txc->time.tv_usec = tx32.time.tv_usec;
txc->tick = tx32.tick;
txc->ppsfreq = tx32.ppsfreq;
txc->jitter = tx32.jitter;
txc->shift = tx32.shift;
txc->stabil = tx32.stabil;
txc->jitcnt = tx32.jitcnt;
txc->calcnt = tx32.calcnt;
txc->errcnt = tx32.errcnt;
txc->stbcnt = tx32.stbcnt;
return 0;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int _determine_leaf_words(int nodeb, int leafwidth){
if(leafwidth>nodeb)return 2;
return 1;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: channel_flush_from_first_active_circuit(channel_t *chan, int max)
{
circuitmux_t *cmux = NULL;
int n_flushed = 0;
cell_queue_t *queue;
circuit_t *circ;
or_circuit_t *or_circ;
int streams_blocked;
packed_cell_t *cell;
/* Get the cmux */
tor_assert(chan);
tor_assert(chan->cmux);
cmux = chan->cmux;
/* Main loop: pick a circuit, send a cell, update the cmux */
while (n_flushed < max) {
circ = circuitmux_get_first_active_circuit(cmux);
/* If it returns NULL, no cells left to send */
if (!circ) break;
assert_cmux_ok_paranoid(chan);
if (circ->n_chan == chan) {
queue = &circ->n_chan_cells;
streams_blocked = circ->streams_blocked_on_n_chan;
} else {
or_circ = TO_OR_CIRCUIT(circ);
tor_assert(or_circ->p_chan == chan);
queue = &TO_OR_CIRCUIT(circ)->p_chan_cells;
streams_blocked = circ->streams_blocked_on_p_chan;
}
/* Circuitmux told us this was active, so it should have cells */
tor_assert(queue->n > 0);
/*
* Get just one cell here; once we've sent it, that can change the circuit
* selection, so we have to loop around for another even if this circuit
* has more than one.
*/
cell = cell_queue_pop(queue);
/* Calculate the exact time that this cell has spent in the queue. */
if (get_options()->CellStatistics && !CIRCUIT_IS_ORIGIN(circ)) {
uint32_t msec_waiting;
struct timeval tvnow;
or_circ = TO_OR_CIRCUIT(circ);
tor_gettimeofday_cached(&tvnow);
msec_waiting = ((uint32_t)tv_to_msec(&tvnow)) - cell->inserted_time;
or_circ->total_cell_waiting_time += msec_waiting;
or_circ->processed_cells++;
}
/* If we just flushed our queue and this circuit is used for a
* tunneled directory request, possibly advance its state. */
if (queue->n == 0 && chan->dirreq_id)
geoip_change_dirreq_state(chan->dirreq_id,
DIRREQ_TUNNELED,
DIRREQ_CIRC_QUEUE_FLUSHED);
/* Now send the cell */
channel_write_packed_cell(chan, cell);
cell = NULL;
/*
* Don't packed_cell_free_unchecked(cell) here because the channel will
* do so when it gets out of the channel queue (probably already did, in
* which case that was an immediate double-free bug).
*/
/* Update the counter */
++n_flushed;
/*
* Now update the cmux; tell it we've just sent a cell, and how many
* we have left.
*/
circuitmux_notify_xmit_cells(cmux, circ, 1);
circuitmux_set_num_cells(cmux, circ, queue->n);
if (queue->n == 0)
log_debug(LD_GENERAL, "Made a circuit inactive.");
/* Is the cell queue low enough to unblock all the streams that are waiting
* to write to this circuit? */
if (streams_blocked && queue->n <= CELL_QUEUE_LOWWATER_SIZE)
set_streams_blocked_on_circ(circ, chan, 0, 0); /* unblock streams */
/* If n_flushed < max still, loop around and pick another circuit */
}
/* Okay, we're done sending now */
assert_cmux_ok_paranoid(chan);
return n_flushed;
}
CWE ID: CWE-617
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap)
{
RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context);
ScriptPromise promise = resolver->promise();
resolver->resolve(imageBitmap);
return promise;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: CtapDeviceResponseCode GetResponseCode(base::span<const uint8_t> buffer) {
if (buffer.empty())
return CtapDeviceResponseCode::kCtap2ErrInvalidCBOR;
auto code = static_cast<CtapDeviceResponseCode>(buffer[0]);
return base::ContainsValue(GetCtapResponseCodeList(), code)
? code
: CtapDeviceResponseCode::kCtap2ErrInvalidCBOR;
}
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: bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
RenderFrameObserver* observer;
while ((observer = it.GetNext()) != NULL) {
if (observer->OnMessageReceived(msg))
return true;
}
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(RenderFrameImpl, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
IPC_MESSAGE_HANDLER(FrameMsg_BuffersSwapped, OnBuffersSwapped)
IPC_MESSAGE_HANDLER_GENERIC(FrameMsg_CompositorFrameSwapped,
OnCompositorFrameSwapped(msg))
IPC_MESSAGE_HANDLER(FrameMsg_ChildFrameProcessGone, OnChildFrameProcessGone)
IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
OnCustomContextMenuAction)
IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
OnJavaScriptExecuteRequest)
IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
OnSetEditableSelectionOffsets)
IPC_MESSAGE_HANDLER(FrameMsg_SetCompositionFromExistingText,
OnSetCompositionFromExistingText)
IPC_MESSAGE_HANDLER(FrameMsg_ExtendSelectionAndDelete,
OnExtendSelectionAndDelete)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
#endif
IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
IPC_END_MESSAGE_MAP_EX()
if (!msg_is_ok) {
CHECK(false) << "Unable to deserialize message in RenderFrameImpl.";
}
return handled;
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: jbig2_sd_new(Jbig2Ctx *ctx, int n_symbols)
{
Jbig2SymbolDict *new = NULL;
if (n_symbols < 0) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "Negative number of symbols in symbol dict: %d", n_symbols);
return NULL;
}
new = jbig2_new(ctx, Jbig2SymbolDict, 1);
if (new != NULL) {
new->glyphs = jbig2_new(ctx, Jbig2Image *, n_symbols);
new->n_symbols = n_symbols;
} else {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate new empty symbol dict");
return NULL;
}
if (new->glyphs != NULL) {
memset(new->glyphs, 0, n_symbols * sizeof(Jbig2Image *));
} else {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "unable to allocate glyphs for new empty symbol dict");
jbig2_free(ctx->allocator, new);
return NULL;
}
return new;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void XMLRPC_ServerDestroy(XMLRPC_SERVER server) {
if(server) {
doc_method* dm = Q_Head(&server->docslist);
server_method* sm = Q_Head(&server->methodlist);
while( dm ) {
my_free(dm);
dm = Q_Next(&server->docslist);
}
while( sm ) {
if(sm->name) {
my_free(sm->name);
}
if(sm->desc) {
XMLRPC_CleanupValue(sm->desc);
}
my_free(sm);
sm = Q_Next(&server->methodlist);
}
if(server->xIntrospection) {
XMLRPC_CleanupValue(server->xIntrospection);
}
Q_Destroy(&server->methodlist);
Q_Destroy(&server->docslist);
my_free(server);
}
}
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: BGD_DECLARE(gdImagePtr) gdImageCreate (int sx, int sy)
{
int i;
gdImagePtr im;
if (overflow2(sx, sy)) {
return NULL;
}
if (overflow2(sizeof (unsigned char *), sy)) {
return NULL;
}
if (overflow2(sizeof (unsigned char), sx)) {
return NULL;
}
im = (gdImage *) gdCalloc(1, sizeof(gdImage));
if (!im) {
return NULL;
}
/* Row-major ever since gd 1.3 */
im->pixels = (unsigned char **) gdMalloc (sizeof (unsigned char *) * sy);
if (!im->pixels) {
gdFree(im);
return NULL;
}
im->polyInts = 0;
im->polyAllocated = 0;
im->brush = 0;
im->tile = 0;
im->style = 0;
for (i = 0; (i < sy); i++) {
/* Row-major ever since gd 1.3 */
im->pixels[i] = (unsigned char *) gdCalloc (sx, sizeof (unsigned char));
if (!im->pixels[i]) {
for (--i ; i >= 0; i--) {
gdFree(im->pixels[i]);
}
gdFree(im->pixels);
gdFree(im);
return NULL;
}
}
im->sx = sx;
im->sy = sy;
im->colorsTotal = 0;
im->transparent = (-1);
im->interlace = 0;
im->thick = 1;
im->AA = 0;
for (i = 0; (i < gdMaxColors); i++) {
im->open[i] = 1;
};
im->trueColor = 0;
im->tpixels = 0;
im->cx1 = 0;
im->cy1 = 0;
im->cx2 = im->sx - 1;
im->cy2 = im->sy - 1;
im->res_x = GD_RESOLUTION;
im->res_y = GD_RESOLUTION;
im->interpolation = NULL;
im->interpolation_id = GD_BILINEAR_FIXED;
return im;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(Phar, offsetSet)
{
char *fname, *cont_str = NULL;
size_t fname_len, cont_len;
zval *zresource;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly");
return;
}
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "sr", &fname, &fname_len, &zresource) == FAILURE
&& zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) {
return;
}
if (fname_len == sizeof(".phar/stub.php")-1 && !memcmp(fname, ".phar/stub.php", sizeof(".phar/stub.php")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set stub \".phar/stub.php\" directly in phar \"%s\", use setStub", phar_obj->archive->fname);
return;
}
if (fname_len == sizeof(".phar/alias.txt")-1 && !memcmp(fname, ".phar/alias.txt", sizeof(".phar/alias.txt")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set alias \".phar/alias.txt\" directly in phar \"%s\", use setAlias", phar_obj->archive->fname);
return;
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot set any files or directories in magic \".phar\" directory", phar_obj->archive->fname);
return;
}
phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int task_clock_event_add(struct perf_event *event, int flags)
{
if (flags & PERF_EF_START)
task_clock_event_start(event, flags);
perf_event_update_userpage(event);
return 0;
}
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 NTSTATUS check_base_file_access(struct connection_struct *conn,
struct smb_filename *smb_fname,
uint32_t access_mask)
{
NTSTATUS status;
status = smbd_calculate_access_mask(conn, smb_fname,
false,
access_mask,
&access_mask);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("smbd_calculate_access_mask "
"on file %s returned %s\n",
smb_fname_str_dbg(smb_fname),
nt_errstr(status)));
return status;
}
if (access_mask & (FILE_WRITE_DATA|FILE_APPEND_DATA)) {
uint32_t dosattrs;
if (!CAN_WRITE(conn)) {
return NT_STATUS_ACCESS_DENIED;
}
dosattrs = dos_mode(conn, smb_fname);
if (IS_DOS_READONLY(dosattrs)) {
return NT_STATUS_ACCESS_DENIED;
}
}
return smbd_check_access_rights(conn,
smb_fname,
false,
access_mask);
}
CWE ID: CWE-835
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool NormalPageArena::coalesce() {
if (m_promptlyFreedSize < 1024 * 1024)
return false;
if (getThreadState()->sweepForbidden())
return false;
ASSERT(!hasCurrentAllocationArea());
TRACE_EVENT0("blink_gc", "BaseArena::coalesce");
m_freeList.clear();
size_t freedSize = 0;
for (NormalPage* page = static_cast<NormalPage*>(m_firstPage); page;
page = static_cast<NormalPage*>(page->next())) {
Address startOfGap = page->payload();
for (Address headerAddress = startOfGap;
headerAddress < page->payloadEnd();) {
HeapObjectHeader* header =
reinterpret_cast<HeapObjectHeader*>(headerAddress);
size_t size = header->size();
ASSERT(size > 0);
ASSERT(size < blinkPagePayloadSize());
if (header->isPromptlyFreed()) {
ASSERT(size >= sizeof(HeapObjectHeader));
SET_MEMORY_INACCESSIBLE(headerAddress, sizeof(HeapObjectHeader));
CHECK_MEMORY_INACCESSIBLE(headerAddress, size);
freedSize += size;
headerAddress += size;
continue;
}
if (header->isFree()) {
SET_MEMORY_INACCESSIBLE(headerAddress, size < sizeof(FreeListEntry)
? size
: sizeof(FreeListEntry));
CHECK_MEMORY_INACCESSIBLE(headerAddress, size);
headerAddress += size;
continue;
}
ASSERT(header->checkHeader());
if (startOfGap != headerAddress)
addToFreeList(startOfGap, headerAddress - startOfGap);
headerAddress += size;
startOfGap = headerAddress;
}
if (startOfGap != page->payloadEnd())
addToFreeList(startOfGap, page->payloadEnd() - startOfGap);
}
getThreadState()->decreaseAllocatedObjectSize(freedSize);
ASSERT(m_promptlyFreedSize == freedSize);
m_promptlyFreedSize = 0;
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: polkit_backend_session_monitor_finalize (GObject *object)
{
PolkitBackendSessionMonitor *monitor = POLKIT_BACKEND_SESSION_MONITOR (object);
if (monitor->system_bus != NULL)
g_object_unref (monitor->system_bus);
if (monitor->sd_source != NULL)
{
g_source_destroy (monitor->sd_source);
g_source_unref (monitor->sd_source);
}
if (G_OBJECT_CLASS (polkit_backend_session_monitor_parent_class)->finalize != NULL)
G_OBJECT_CLASS (polkit_backend_session_monitor_parent_class)->finalize (object);
}
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 _xml_add_to_info(xml_parser *parser,char *name)
{
zval **element, *values;
if (! parser->info) {
return;
}
if (zend_hash_find(Z_ARRVAL_P(parser->info),name,strlen(name) + 1,(void **) &element) == FAILURE) {
MAKE_STD_ZVAL(values);
array_init(values);
zend_hash_update(Z_ARRVAL_P(parser->info), name, strlen(name)+1, (void *) &values, sizeof(zval*), (void **) &element);
}
add_next_index_long(*element,parser->curtag);
parser->curtag++;
}
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 NetworkHandler::ClearBrowserCache(
std::unique_ptr<ClearBrowserCacheCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
content::BrowsingDataRemover* remover =
content::BrowserContext::GetBrowsingDataRemover(
process_->GetBrowserContext());
remover->RemoveAndReply(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_CACHE,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
new DevtoolsClearCacheObserver(remover, std::move(callback)));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: GF_Err hinf_AddBox(GF_Box *s, GF_Box *a)
{
GF_MAXRBox *maxR;
GF_HintInfoBox *hinf = (GF_HintInfoBox *)s;
u32 i;
switch (a->type) {
case GF_ISOM_BOX_TYPE_MAXR:
i=0;
while ((maxR = (GF_MAXRBox *)gf_list_enum(hinf->other_boxes, &i))) {
if ((maxR->type==GF_ISOM_BOX_TYPE_MAXR) && (maxR->granularity == ((GF_MAXRBox *)a)->granularity))
return GF_ISOM_INVALID_FILE;
}
break;
}
return gf_isom_box_add_default(s, a);
}
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: destroy_server(struct server *server) {
if (server->method) ss_free(server->method);
if (server->plugin) ss_free(server->plugin);
if (server->plugin_opts) ss_free(server->plugin_opts);
if (server->mode) ss_free(server->mode);
}
CWE ID: CWE-78
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: find_extend_vma(struct mm_struct *mm, unsigned long addr)
{
struct vm_area_struct *vma;
unsigned long start;
addr &= PAGE_MASK;
vma = find_vma(mm, addr);
if (!vma)
return NULL;
if (vma->vm_start <= addr)
return vma;
if (!(vma->vm_flags & VM_GROWSDOWN))
return NULL;
start = vma->vm_start;
if (expand_stack(vma, addr))
return NULL;
if (vma->vm_flags & VM_LOCKED)
populate_vma_page_range(vma, addr, start, NULL);
return vma;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: QString IRCView::filter(const QString& line, const QString& defaultColor, const QString& whoSent,
bool doHighlight, bool parseURL, bool self, QChar::Direction* direction)
{
QString filteredLine(line);
Application* konvApp = static_cast<Application*>(kapp);
if (filteredLine[0] == ' ')
{
filteredLine[0] = '\xA0';
}
filteredLine.replace('<', "\x0blt;");
filteredLine.replace('>', "\x0bgt;");
if (filteredLine.contains('\x07'))
{
if (Preferences::self()->beep())
{
kapp->beep();
}
filteredLine.remove('\x07');
}
filteredLine = ircTextToHtml(filteredLine, parseURL, defaultColor, whoSent, true, direction);
QString ownNick;
if (m_server)
{
ownNick = m_server->getNickname();
}
else if (m_chatWin->getType() == ChatWindow::DccChat)
{
ownNick = static_cast<DCC::ChatContainer*>(m_chatWin)->ownNick();
}
if(doHighlight && (whoSent != ownNick) && !self)
{
QString highlightColor;
if (Preferences::self()->highlightNick() &&
line.toLower().contains(QRegExp("(^|[^\\d\\w])" +
QRegExp::escape(ownNick.toLower()) +
"([^\\d\\w]|$)")))
{
highlightColor = Preferences::self()->highlightNickColor().name();
m_tabNotification = Konversation::tnfNick;
}
else
{
QList<Highlight*> highlightList = Preferences::highlightList();
QListIterator<Highlight*> it(highlightList);
Highlight* highlight;
QStringList highlightChatWindowList;
bool patternFound = false;
QStringList captures;
while (it.hasNext())
{
highlight = it.next();
QStringList highlightChatWindowList = highlight->getChatWindowList();
if (highlightChatWindowList.isEmpty() ||
highlightChatWindowList.contains(m_chatWin->getName(), Qt::CaseInsensitive))
{
if (highlight->getRegExp())
{
QRegExp needleReg(highlight->getPattern());
needleReg.setCaseSensitivity(Qt::CaseInsensitive);
patternFound = ((line.contains(needleReg)) ||
(whoSent.contains(needleReg)));
captures = needleReg.capturedTexts();
}
else
{
QString needle = highlight->getPattern();
patternFound = ((line.contains(needle, Qt::CaseInsensitive)) ||
(whoSent.contains(needle, Qt::CaseInsensitive)));
}
if (patternFound)
{
break;
}
}
}
if (patternFound)
{
highlightColor = highlight->getColor().name();
m_highlightColor = highlightColor;
m_tabNotification = Konversation::tnfHighlight;
if (Preferences::self()->highlightSoundsEnabled() && m_chatWin->notificationsEnabled())
{
konvApp->sound()->play(highlight->getSoundURL());
}
konvApp->notificationHandler()->highlight(m_chatWin, whoSent, line);
m_autoTextToSend = highlight->getAutoText();
for (int capture = 0; capture < captures.count(); capture++)
{
m_autoTextToSend.replace(QString("%%1").arg(capture), captures[capture]);
}
m_autoTextToSend.remove(QRegExp("%[0-9]"));
}
}
if (!highlightColor.isEmpty())
{
filteredLine = QLatin1String("<font color=\"") + highlightColor + QLatin1String("\">") + filteredLine +
QLatin1String("</font>");
}
}
else if (doHighlight && (whoSent == ownNick) && Preferences::self()->highlightOwnLines())
{
filteredLine = QLatin1String("<font color=\"") + Preferences::self()->highlightOwnLinesColor().name() +
QLatin1String("\">") + filteredLine + QLatin1String("</font>");
}
filteredLine = Konversation::Emoticons::parseEmoticons(filteredLine);
return filteredLine;
}
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: OMX_ERRORTYPE omx_video::get_config(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_INDEXTYPE configIndex,
OMX_INOUT OMX_PTR configData)
{
(void)hComp;
if (configData == NULL) {
DEBUG_PRINT_ERROR("ERROR: param is null");
return OMX_ErrorBadParameter;
}
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: can't be in invalid state");
return OMX_ErrorIncorrectStateOperation;
}
switch ((int)configIndex) {
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE* pParam = reinterpret_cast<OMX_VIDEO_CONFIG_BITRATETYPE*>(configData);
memcpy(pParam, &m_sConfigBitrate, sizeof(m_sConfigBitrate));
break;
}
case OMX_IndexConfigVideoFramerate:
{
OMX_CONFIG_FRAMERATETYPE* pParam = reinterpret_cast<OMX_CONFIG_FRAMERATETYPE*>(configData);
memcpy(pParam, &m_sConfigFramerate, sizeof(m_sConfigFramerate));
break;
}
case OMX_IndexConfigCommonRotate:
{
OMX_CONFIG_ROTATIONTYPE* pParam = reinterpret_cast<OMX_CONFIG_ROTATIONTYPE*>(configData);
memcpy(pParam, &m_sConfigFrameRotation, sizeof(m_sConfigFrameRotation));
break;
}
case QOMX_IndexConfigVideoIntraperiod:
{
DEBUG_PRINT_LOW("get_config:QOMX_IndexConfigVideoIntraperiod");
QOMX_VIDEO_INTRAPERIODTYPE* pParam = reinterpret_cast<QOMX_VIDEO_INTRAPERIODTYPE*>(configData);
memcpy(pParam, &m_sIntraperiod, sizeof(m_sIntraperiod));
break;
}
case OMX_IndexConfigVideoAVCIntraPeriod:
{
OMX_VIDEO_CONFIG_AVCINTRAPERIOD *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_AVCINTRAPERIOD*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoAVCIntraPeriod");
memcpy(pParam, &m_sConfigAVCIDRPeriod, sizeof(m_sConfigAVCIDRPeriod));
break;
}
case OMX_IndexConfigCommonDeinterlace:
{
OMX_VIDEO_CONFIG_DEINTERLACE *pParam =
reinterpret_cast<OMX_VIDEO_CONFIG_DEINTERLACE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigCommonDeinterlace");
memcpy(pParam, &m_sConfigDeinterlace, sizeof(m_sConfigDeinterlace));
break;
}
case OMX_IndexConfigVideoVp8ReferenceFrame:
{
OMX_VIDEO_VP8REFERENCEFRAMETYPE* pParam =
reinterpret_cast<OMX_VIDEO_VP8REFERENCEFRAMETYPE*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_IndexConfigVideoVp8ReferenceFrame");
memcpy(pParam, &m_sConfigVp8ReferenceFrame, sizeof(m_sConfigVp8ReferenceFrame));
break;
}
case OMX_QcomIndexConfigPerfLevel:
{
OMX_U32 perflevel;
OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *pParam =
reinterpret_cast<OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL*>(configData);
DEBUG_PRINT_LOW("get_config: OMX_QcomIndexConfigPerfLevel");
if (!dev_get_performance_level(&perflevel)) {
DEBUG_PRINT_ERROR("Invalid entry returned from get_performance_level %d",
pParam->ePerfLevel);
} else {
pParam->ePerfLevel = (QOMX_VIDEO_PERF_LEVEL)perflevel;
}
break;
}
default:
DEBUG_PRINT_ERROR("ERROR: unsupported index %d", (int) configIndex);
return OMX_ErrorUnsupportedIndex;
}
return OMX_ErrorNone;
}
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: aspath_put (struct stream *s, struct aspath *as, int use32bit )
{
struct assegment *seg = as->segments;
size_t bytes = 0;
if (!seg || seg->length == 0)
return 0;
if (seg)
{
/*
* Hey, what do we do when we have > STREAM_WRITABLE(s) here?
* At the moment, we would write out a partial aspath, and our peer
* will complain and drop the session :-/
*
* The general assumption here is that many things tested will
* never happen. And, in real live, up to now, they have not.
*/
while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s)))
{
struct assegment *next = seg->next;
int written = 0;
int asns_packed = 0;
size_t lenp;
/* Overlength segments have to be split up */
while ( (seg->length - written) > AS_SEGMENT_MAX)
{
assegment_header_put (s, seg->type, AS_SEGMENT_MAX);
assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit);
written += AS_SEGMENT_MAX;
bytes += ASSEGMENT_SIZE (written, use32bit);
}
/* write the final segment, probably is also the first */
lenp = assegment_header_put (s, seg->type, seg->length - written);
assegment_data_put (s, (seg->as + written), seg->length - written,
use32bit);
/* Sequence-type segments can be 'packed' together
* Case of a segment which was overlength and split up
* will be missed here, but that doesn't matter.
*/
while (next && ASSEGMENTS_PACKABLE (seg, next))
{
/* NB: We should never normally get here given we
* normalise aspath data when parse them. However, better
* safe than sorry. We potentially could call
* assegment_normalise here instead, but it's cheaper and
* easier to do it on the fly here rather than go through
* the segment list twice every time we write out
* aspath's.
*/
/* Next segment's data can fit in this one */
assegment_data_put (s, next->as, next->length, use32bit);
/* update the length of the segment header */
stream_putc_at (s, lenp, seg->length - written + next->length);
asns_packed += next->length;
next = next->next;
}
bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed,
use32bit);
seg = next;
}
}
return bytes;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void AutofillManager::ShowAutofillSettings() {
client_->ShowAutofillSettings();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int add_camera_metadata_entry(camera_metadata_t *dst,
uint32_t tag,
const void *data,
size_t data_count) {
int type = get_camera_metadata_tag_type(tag);
if (type == -1) {
ALOGE("%s: Unknown tag %04x.", __FUNCTION__, tag);
return ERROR;
}
return add_camera_metadata_entry_raw(dst,
tag,
type,
data,
data_count);
}
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 V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name)
{
ASSERT(m_world->isMainWorld());
if (m_context.isEmpty())
return;
if (document->hasNamedItem(name.impl()) || document->hasExtraNamedItem(name.impl()))
return;
v8::HandleScope handleScope(m_isolate);
v8::Context::Scope contextScope(m_context.newLocal(m_isolate));
ASSERT(!m_document.isEmpty());
v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
checkDocumentWrapper(documentHandle, document);
documentHandle->Delete(v8String(name, m_isolate));
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void GenerateNtlmHashV1(const base::string16& password,
base::span<uint8_t, kNtlmHashLen> hash) {
size_t length = password.length() * 2;
NtlmBufferWriter writer(length);
bool result = writer.WriteUtf16String(password) && writer.IsEndOfBuffer();
DCHECK(result);
MD4(writer.GetBuffer().data(), writer.GetLength(), hash.data());
}
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 int takeover_tasklets(unsigned int cpu)
{
/* CPU is dead, so no lock needed. */
local_irq_disable();
/* Find end, append list for that CPU. */
if (&per_cpu(tasklet_vec, cpu).head != per_cpu(tasklet_vec, cpu).tail) {
*__this_cpu_read(tasklet_vec.tail) = per_cpu(tasklet_vec, cpu).head;
this_cpu_write(tasklet_vec.tail, per_cpu(tasklet_vec, cpu).tail);
per_cpu(tasklet_vec, cpu).head = NULL;
per_cpu(tasklet_vec, cpu).tail = &per_cpu(tasklet_vec, cpu).head;
}
raise_softirq_irqoff(TASKLET_SOFTIRQ);
if (&per_cpu(tasklet_hi_vec, cpu).head != per_cpu(tasklet_hi_vec, cpu).tail) {
*__this_cpu_read(tasklet_hi_vec.tail) = per_cpu(tasklet_hi_vec, cpu).head;
__this_cpu_write(tasklet_hi_vec.tail, per_cpu(tasklet_hi_vec, cpu).tail);
per_cpu(tasklet_hi_vec, cpu).head = NULL;
per_cpu(tasklet_hi_vec, cpu).tail = &per_cpu(tasklet_hi_vec, cpu).head;
}
raise_softirq_irqoff(HI_SOFTIRQ);
local_irq_enable();
return 0;
}
CWE ID: CWE-787
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: gdImagePtr gdImageCreate (int sx, int sy)
{
int i;
gdImagePtr im;
if (overflow2(sx, sy)) {
return NULL;
}
if (overflow2(sizeof(unsigned char *), sy)) {
return NULL;
}
im = (gdImage *) gdCalloc(1, sizeof(gdImage));
/* Row-major ever since gd 1.3 */
im->pixels = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->polyInts = 0;
im->polyAllocated = 0;
im->brush = 0;
im->tile = 0;
im->style = 0;
for (i = 0; i < sy; i++) {
/* Row-major ever since gd 1.3 */
im->pixels[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
}
im->sx = sx;
im->sy = sy;
im->colorsTotal = 0;
im->transparent = (-1);
im->interlace = 0;
im->thick = 1;
im->AA = 0;
im->AA_polygon = 0;
for (i = 0; i < gdMaxColors; i++) {
im->open[i] = 1;
im->red[i] = 0;
im->green[i] = 0;
im->blue[i] = 0;
}
im->trueColor = 0;
im->tpixels = 0;
im->cx1 = 0;
im->cy1 = 0;
im->cx2 = im->sx - 1;
im->cy2 = im->sy - 1;
im->interpolation = NULL;
im->interpolation_id = GD_BILINEAR_FIXED;
return im;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind)
: host_id_(host_id),
valid_(true),
in_process_(false),
software_rendering_(false),
kind_(kind),
process_launched_(false) {
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) ||
CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU))
in_process_ = true;
DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL);
g_gpu_process_hosts[kind] = this;
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id));
process_.reset(new BrowserChildProcessHostImpl(PROCESS_TYPE_GPU, this));
}
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 DataReductionProxySettings::RecordDataReductionInit() const {
DCHECK(thread_checker_.CalledOnValidThread());
RecordStartupState(IsDataReductionProxyEnabled() ? PROXY_ENABLED
: PROXY_DISABLED);
RecordStartupSavings();
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int mpeg4video_probe(AVProbeData *probe_packet)
{
uint32_t temp_buffer = -1;
int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;
int i;
for (i = 0; i < probe_packet->buf_size; i++) {
temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];
if ((temp_buffer & 0xffffff00) != 0x100)
continue;
if (temp_buffer == VOP_START_CODE)
VOP++;
else if (temp_buffer == VISUAL_OBJECT_START_CODE)
VISO++;
else if (temp_buffer < 0x120)
VO++;
else if (temp_buffer < 0x130)
VOL++;
else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&
!(0x1B9 < temp_buffer && temp_buffer < 0x1C4))
res++;
}
if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)
return AVPROBE_SCORE_EXTENSION;
return 0;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static inline void utf32_codepoint_to_utf8(uint8_t* dstP, char32_t srcChar, size_t bytes)
{
dstP += bytes;
switch (bytes)
{ /* note: everything falls through. */
case 4: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
case 3: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
case 2: *--dstP = (uint8_t)((srcChar | kByteMark) & kByteMask); srcChar >>= 6;
case 1: *--dstP = (uint8_t)(srcChar | kFirstByteMark[bytes]);
}
}
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 eager_reader_register(eager_reader_t *reader, reactor_t *reactor, eager_reader_cb read_cb, void *context) {
assert(reader != NULL);
assert(reactor != NULL);
assert(read_cb != NULL);
eager_reader_unregister(reader);
reader->outbound_read_ready = read_cb;
reader->outbound_context = context;
reader->outbound_registration = reactor_register(reactor, reader->bytes_available_fd, reader, internal_outbound_read_ready, NULL);
}
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 check_mtab(const char *progname, const char *devname,
const char *dir)
{
if (check_newline(progname, devname) == -1 ||
check_newline(progname, dir) == -1)
return EX_USAGE;
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: PHP_FUNCTION(radius_put_vendor_string)
{
char *str;
int str_len;
long type, vendor;
radius_descriptor *raddesc;
zval *z_radh;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlls", &z_radh, &vendor, &type, &str, &str_len)
== FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius);
if (rad_put_vendor_string(raddesc->radh, vendor, type, str) == -1) {
RETURN_FALSE;
} else {
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: void TestDataReductionProxyConfig::SetShouldAddDefaultProxyBypassRules(
bool add_default_proxy_bypass_rules) {
add_default_proxy_bypass_rules_ = add_default_proxy_bypass_rules;
}
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: int fscrypt_get_crypt_info(struct inode *inode)
{
struct fscrypt_info *crypt_info;
struct fscrypt_context ctx;
struct crypto_skcipher *ctfm;
const char *cipher_str;
int keysize;
u8 *raw_key = NULL;
int res;
res = fscrypt_initialize(inode->i_sb->s_cop->flags);
if (res)
return res;
if (!inode->i_sb->s_cop->get_context)
return -EOPNOTSUPP;
retry:
crypt_info = ACCESS_ONCE(inode->i_crypt_info);
if (crypt_info) {
if (!crypt_info->ci_keyring_key ||
key_validate(crypt_info->ci_keyring_key) == 0)
return 0;
fscrypt_put_encryption_info(inode, crypt_info);
goto retry;
}
res = inode->i_sb->s_cop->get_context(inode, &ctx, sizeof(ctx));
if (res < 0) {
if (!fscrypt_dummy_context_enabled(inode) ||
inode->i_sb->s_cop->is_encrypted(inode))
return res;
/* Fake up a context for an unencrypted directory */
memset(&ctx, 0, sizeof(ctx));
ctx.format = FS_ENCRYPTION_CONTEXT_FORMAT_V1;
ctx.contents_encryption_mode = FS_ENCRYPTION_MODE_AES_256_XTS;
ctx.filenames_encryption_mode = FS_ENCRYPTION_MODE_AES_256_CTS;
memset(ctx.master_key_descriptor, 0x42, FS_KEY_DESCRIPTOR_SIZE);
} else if (res != sizeof(ctx)) {
return -EINVAL;
}
if (ctx.format != FS_ENCRYPTION_CONTEXT_FORMAT_V1)
return -EINVAL;
if (ctx.flags & ~FS_POLICY_FLAGS_VALID)
return -EINVAL;
crypt_info = kmem_cache_alloc(fscrypt_info_cachep, GFP_NOFS);
if (!crypt_info)
return -ENOMEM;
crypt_info->ci_flags = ctx.flags;
crypt_info->ci_data_mode = ctx.contents_encryption_mode;
crypt_info->ci_filename_mode = ctx.filenames_encryption_mode;
crypt_info->ci_ctfm = NULL;
crypt_info->ci_keyring_key = NULL;
memcpy(crypt_info->ci_master_key, ctx.master_key_descriptor,
sizeof(crypt_info->ci_master_key));
res = determine_cipher_type(crypt_info, inode, &cipher_str, &keysize);
if (res)
goto out;
/*
* This cannot be a stack buffer because it is passed to the scatterlist
* crypto API as part of key derivation.
*/
res = -ENOMEM;
raw_key = kmalloc(FS_MAX_KEY_SIZE, GFP_NOFS);
if (!raw_key)
goto out;
res = validate_user_key(crypt_info, &ctx, raw_key, FS_KEY_DESC_PREFIX);
if (res && inode->i_sb->s_cop->key_prefix) {
int res2 = validate_user_key(crypt_info, &ctx, raw_key,
inode->i_sb->s_cop->key_prefix);
if (res2) {
if (res2 == -ENOKEY)
res = -ENOKEY;
goto out;
}
} else if (res) {
goto out;
}
ctfm = crypto_alloc_skcipher(cipher_str, 0, 0);
if (!ctfm || IS_ERR(ctfm)) {
res = ctfm ? PTR_ERR(ctfm) : -ENOMEM;
printk(KERN_DEBUG
"%s: error %d (inode %u) allocating crypto tfm\n",
__func__, res, (unsigned) inode->i_ino);
goto out;
}
crypt_info->ci_ctfm = ctfm;
crypto_skcipher_clear_flags(ctfm, ~0);
crypto_skcipher_set_flags(ctfm, CRYPTO_TFM_REQ_WEAK_KEY);
res = crypto_skcipher_setkey(ctfm, raw_key, keysize);
if (res)
goto out;
kzfree(raw_key);
raw_key = NULL;
if (cmpxchg(&inode->i_crypt_info, NULL, crypt_info) != NULL) {
put_crypt_info(crypt_info);
goto retry;
}
return 0;
out:
if (res == -ENOKEY)
res = 0;
put_crypt_info(crypt_info);
kzfree(raw_key);
return res;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int routing_ioctl(struct net *net, struct socket *sock,
unsigned int cmd, void __user *argp)
{
int ret;
void *r = NULL;
struct in6_rtmsg r6;
struct rtentry r4;
char devname[16];
u32 rtdev;
mm_segment_t old_fs = get_fs();
if (sock && sock->sk && sock->sk->sk_family == AF_INET6) { /* ipv6 */
struct in6_rtmsg32 __user *ur6 = argp;
ret = copy_from_user(&r6.rtmsg_dst, &(ur6->rtmsg_dst),
3 * sizeof(struct in6_addr));
ret |= __get_user(r6.rtmsg_type, &(ur6->rtmsg_type));
ret |= __get_user(r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len));
ret |= __get_user(r6.rtmsg_src_len, &(ur6->rtmsg_src_len));
ret |= __get_user(r6.rtmsg_metric, &(ur6->rtmsg_metric));
ret |= __get_user(r6.rtmsg_info, &(ur6->rtmsg_info));
ret |= __get_user(r6.rtmsg_flags, &(ur6->rtmsg_flags));
ret |= __get_user(r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex));
r = (void *) &r6;
} else { /* ipv4 */
struct rtentry32 __user *ur4 = argp;
ret = copy_from_user(&r4.rt_dst, &(ur4->rt_dst),
3 * sizeof(struct sockaddr));
ret |= __get_user(r4.rt_flags, &(ur4->rt_flags));
ret |= __get_user(r4.rt_metric, &(ur4->rt_metric));
ret |= __get_user(r4.rt_mtu, &(ur4->rt_mtu));
ret |= __get_user(r4.rt_window, &(ur4->rt_window));
ret |= __get_user(r4.rt_irtt, &(ur4->rt_irtt));
ret |= __get_user(rtdev, &(ur4->rt_dev));
if (rtdev) {
ret |= copy_from_user(devname, compat_ptr(rtdev), 15);
r4.rt_dev = (char __user __force *)devname;
devname[15] = 0;
} else
r4.rt_dev = NULL;
r = (void *) &r4;
}
if (ret) {
ret = -EFAULT;
goto out;
}
set_fs(KERNEL_DS);
ret = sock_do_ioctl(net, sock, cmd, (unsigned long) r);
set_fs(old_fs);
out:
return ret;
}
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 StoreExistingGroup() {
PushNextTask(
base::BindOnce(&AppCacheStorageImplTest::Verify_StoreExistingGroup,
base::Unretained(this)));
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
cache2_ = new AppCache(storage(), 2);
cache2_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::MASTER, 1,
kDefaultEntrySize + 100));
storage()->StoreGroupAndNewestCache(group_.get(), cache2_.get(),
delegate());
EXPECT_FALSE(delegate()->stored_group_success_);
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ProfileChooserView::RemoveAccount() {
DCHECK(!account_id_to_remove_.empty());
ProfileOAuth2TokenService* oauth2_token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile());
if (oauth2_token_service) {
oauth2_token_service->RevokeCredentials(account_id_to_remove_);
PostActionPerformed(ProfileMetrics::PROFILE_DESKTOP_MENU_REMOVE_ACCT);
}
account_id_to_remove_.clear();
ShowViewFromMode(profiles::BUBBLE_VIEW_MODE_ACCOUNT_MANAGEMENT);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void Con_Bottom( void ) {
con.display = con.current;
}
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 HttpAuthFilterWhitelist::SetWhitelist(
const std::string& server_whitelist) {
rules_.ParseFromString(server_whitelist);
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ResourceDispatcherHostImpl::InitializeURLRequest(
net::URLRequest* request,
const Referrer& referrer,
bool is_download,
int render_process_host_id,
int render_view_routing_id,
int render_frame_routing_id,
PreviewsState previews_state,
ResourceContext* context) {
DCHECK(io_thread_task_runner_->BelongsToCurrentThread());
DCHECK(!request->is_pending());
Referrer::SetReferrerForRequest(request, referrer);
ResourceRequestInfoImpl* info = CreateRequestInfo(
render_process_host_id, render_view_routing_id, render_frame_routing_id,
previews_state, is_download, context);
info->AssociateWithRequest(request);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void wake_up_partner(struct pipe_inode_info *pipe)
{
wake_up_interruptible(&pipe->wait);
}
CWE ID: CWE-17
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
int chan = sa->rc_channel;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->rc_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = chan;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
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: static int snd_timer_user_open(struct inode *inode, struct file *file)
{
struct snd_timer_user *tu;
int err;
err = nonseekable_open(inode, file);
if (err < 0)
return err;
tu = kzalloc(sizeof(*tu), GFP_KERNEL);
if (tu == NULL)
return -ENOMEM;
spin_lock_init(&tu->qlock);
init_waitqueue_head(&tu->qchange_sleep);
mutex_init(&tu->tread_sem);
tu->ticks = 1;
tu->queue_size = 128;
tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read),
GFP_KERNEL);
if (tu->queue == NULL) {
kfree(tu);
return -ENOMEM;
}
file->private_data = tu;
return 0;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: set_permissions_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
SetPermissionsJob *job = task_data;
CommonJob *common;
common = (CommonJob *) job;
nautilus_progress_info_set_status (common->progress,
_("Setting permissions"));
nautilus_progress_info_start (job->common.progress);
set_permissions_file (job, job->file, NULL);
}
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: spnego_gss_unwrap_iov(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)
{
OM_uint32 ret;
ret = gss_unwrap_iov(minor_status,
context_handle,
conf_state,
qop_state,
iov,
iov_count);
return (ret);
}
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: void nw_cache_free(nw_cache *cache, void *obj)
{
if (cache->free < cache->free_total) {
cache->free_arr[cache->free++] = obj;
} else {
uint32_t new_free_total = cache->free_total * 2;
void *new_arr = realloc(cache->free_arr, new_free_total * sizeof(void *));
if (new_arr) {
cache->free_total = new_free_total;
cache->free_arr = new_arr;
cache->free_arr[cache->free++] = obj;
} else {
free(obj);
}
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: PermissionUtil::ScopedRevocationReporter::ScopedRevocationReporter(
Profile* profile,
const ContentSettingsPattern& primary_pattern,
const ContentSettingsPattern& secondary_pattern,
ContentSettingsType content_type,
PermissionSourceUI source_ui)
: ScopedRevocationReporter(
profile,
GURL(primary_pattern.ToString()),
GURL((secondary_pattern == ContentSettingsPattern::Wildcard())
? primary_pattern.ToString()
: secondary_pattern.ToString()),
content_type,
source_ui) {}
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 MockRenderThread::RemoveRoute(int32 routing_id) {
EXPECT_EQ(routing_id_, routing_id);
widget_ = NULL;
}
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: ResourceHostMsg_Request CreateXHRRequestWithOrigin(const char* origin) {
ResourceHostMsg_Request request;
request.method = "GET";
request.url = GURL("http://bar.com/simple_page.html");
request.first_party_for_cookies = GURL(origin);
request.referrer_policy = blink::WebReferrerPolicyDefault;
request.headers = base::StringPrintf("Origin: %s\r\n", origin);
request.load_flags = 0;
request.origin_pid = 0;
request.resource_type = RESOURCE_TYPE_XHR;
request.request_context = 0;
request.appcache_host_id = kAppCacheNoHostId;
request.download_to_file = false;
request.should_reset_appcache = false;
request.is_main_frame = true;
request.parent_is_main_frame = false;
request.parent_render_frame_id = -1;
request.transition_type = ui::PAGE_TRANSITION_LINK;
request.allow_download = true;
return request;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static bool ExecuteStrikethrough(LocalFrame& frame,
Event*,
EditorCommandSource source,
const String&) {
CSSIdentifierValue* line_through =
CSSIdentifierValue::Create(CSSValueLineThrough);
return ExecuteToggleStyleInList(
frame, source, InputEvent::InputType::kFormatStrikeThrough,
CSSPropertyWebkitTextDecorationsInEffect, line_through);
}
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 impeg2d_dec_pic_data_thread(dec_state_t *ps_dec)
{
WORD32 i4_continue_decode;
WORD32 i4_cur_row, temp;
UWORD32 u4_bits_read;
WORD32 i4_dequeue_job;
IMPEG2D_ERROR_CODES_T e_error;
i4_cur_row = ps_dec->u2_mb_y + 1;
i4_continue_decode = 1;
i4_dequeue_job = 1;
do
{
if(i4_cur_row > ps_dec->u2_num_vert_mb)
{
i4_continue_decode = 0;
break;
}
{
if((ps_dec->i4_num_cores> 1) && (i4_dequeue_job))
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
UWORD8 *pu1_buf;
e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1);
if(e_ret != IV_SUCCESS)
break;
if(CMD_PROCESS == s_job.i4_cmd)
{
pu1_buf = ps_dec->pu1_inp_bits_buf + s_job.i4_bistream_ofst;
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), pu1_buf,
(ps_dec->u4_num_inp_bytes - s_job.i4_bistream_ofst) + 8);
i4_cur_row = s_job.i2_start_mb_y;
ps_dec->i4_start_mb_y = s_job.i2_start_mb_y;
ps_dec->i4_end_mb_y = s_job.i2_end_mb_y;
ps_dec->u2_mb_x = 0;
ps_dec->u2_mb_y = ps_dec->i4_start_mb_y;
ps_dec->u2_num_mbs_left = (ps_dec->i4_end_mb_y - ps_dec->i4_start_mb_y) * ps_dec->u2_num_horiz_mb;
}
else
{
WORD32 start_row;
WORD32 num_rows;
start_row = s_job.i2_start_mb_y << 4;
num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size);
num_rows -= start_row;
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
start_row, num_rows);
break;
}
}
e_error = impeg2d_dec_slice(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
impeg2d_next_start_code(ps_dec);
}
}
/* Detecting next slice start code */
while(1)
{
u4_bits_read = impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,START_CODE_LEN);
temp = u4_bits_read & 0xFF;
i4_continue_decode = (((u4_bits_read >> 8) == 0x01) && (temp) && (temp <= 0xAF));
if(i4_continue_decode)
{
/* If the slice is from the same row, then continue decoding without dequeue */
if((temp - 1) == i4_cur_row)
{
i4_dequeue_job = 0;
break;
}
if(temp < ps_dec->i4_end_mb_y)
{
i4_cur_row = ps_dec->u2_mb_y;
}
else
{
i4_dequeue_job = 1;
}
break;
}
else
break;
}
}while(i4_continue_decode);
if(ps_dec->i4_num_cores > 1)
{
while(1)
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
e_ret = impeg2_jobq_dequeue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 1);
if(e_ret != IV_SUCCESS)
break;
if(CMD_FMTCONV == s_job.i4_cmd)
{
WORD32 start_row;
WORD32 num_rows;
start_row = s_job.i2_start_mb_y << 4;
num_rows = MIN((s_job.i2_end_mb_y << 4), ps_dec->u2_vertical_size);
num_rows -= start_row;
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
start_row, num_rows);
}
}
}
else
{
if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat)))
impeg2d_format_convert(ps_dec, ps_dec->ps_disp_pic,
ps_dec->ps_disp_frm_buf,
0, ps_dec->u2_vertical_size);
}
}
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 ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: rpc_default_callback(struct rpc_task *task, void *data)
{
}
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 struct sctp_chunk *sctp_make_asconf(struct sctp_association *asoc,
union sctp_addr *addr,
int vparam_len)
{
sctp_addiphdr_t asconf;
struct sctp_chunk *retval;
int length = sizeof(asconf) + vparam_len;
union sctp_addr_param addrparam;
int addrlen;
struct sctp_af *af = sctp_get_af_specific(addr->v4.sin_family);
addrlen = af->to_addr_param(addr, &addrparam);
if (!addrlen)
return NULL;
length += addrlen;
/* Create the chunk. */
retval = sctp_make_control(asoc, SCTP_CID_ASCONF, 0, length);
if (!retval)
return NULL;
asconf.serial = htonl(asoc->addip_serial++);
retval->subh.addip_hdr =
sctp_addto_chunk(retval, sizeof(asconf), &asconf);
retval->param_hdr.v =
sctp_addto_chunk(retval, addrlen, &addrparam);
return retval;
}
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: PHP_METHOD(Phar, addFromString)
{
char *localname, *cont_str;
size_t localname_len, cont_len;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) {
return;
}
phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void tcp_parse_fastopen_option(int len, const unsigned char *cookie,
bool syn, struct tcp_fastopen_cookie *foc,
bool exp_opt)
{
/* Valid only in SYN or SYN-ACK with an even length. */
if (!foc || !syn || len < 0 || (len & 1))
return;
if (len >= TCP_FASTOPEN_COOKIE_MIN &&
len <= TCP_FASTOPEN_COOKIE_MAX)
memcpy(foc->val, cookie, len);
else if (len != 0)
len = -1;
foc->len = len;
foc->exp = exp_opt;
}
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: bool RenderBlock::hitTestColumns(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
if (!hasColumns())
return false;
for (ColumnRectIterator it(*this); it.hasMore(); it.advance()) {
LayoutRect hitRect = locationInContainer.boundingBox();
LayoutRect colRect = it.columnRect();
colRect.moveBy(accumulatedOffset);
if (locationInContainer.intersects(colRect)) {
LayoutSize offset;
it.adjust(offset);
LayoutPoint finalLocation = accumulatedOffset + offset;
if (!result.isRectBasedTest() || colRect.contains(hitRect))
return hitTestContents(request, result, locationInContainer, finalLocation, hitTestAction) || (hitTestAction == HitTestFloat && hitTestFloats(request, result, locationInContainer, finalLocation));
hitTestContents(request, result, locationInContainer, finalLocation, hitTestAction);
}
}
return false;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits)
{
if (!_zgfx)
return FALSE;
while (_zgfx->cBitsCurrent < _nbits)
{
_zgfx->BitsCurrent <<= 8;
if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd)
_zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++;
_zgfx->cBitsCurrent += 8;
}
_zgfx->cBitsRemaining -= _nbits;
_zgfx->cBitsCurrent -= _nbits;
_zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent;
_zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void InitializeWithCORS(const char* url,
bool expected,
UrlData::CORSMode cors_mode,
size_t file_size = kFileSize) {
GURL gurl(url);
data_source_.reset(new MockMultibufferDataSource(
base::ThreadTaskRunnerHandle::Get(),
url_index_->GetByUrl(gurl, cors_mode), &host_));
data_source_->SetPreload(preload_);
response_generator_.reset(new TestResponseGenerator(gurl, file_size));
EXPECT_CALL(*this, OnInitialize(expected));
data_source_->Initialize(base::Bind(
&MultibufferDataSourceTest::OnInitialize, base::Unretained(this)));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(data_source_->downloading(), false);
}
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: nfs3svc_encode_fsinfores(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_fsinfores *resp)
{
*p++ = xdr_zero; /* no post_op_attr */
if (resp->status == 0) {
*p++ = htonl(resp->f_rtmax);
*p++ = htonl(resp->f_rtpref);
*p++ = htonl(resp->f_rtmult);
*p++ = htonl(resp->f_wtmax);
*p++ = htonl(resp->f_wtpref);
*p++ = htonl(resp->f_wtmult);
*p++ = htonl(resp->f_dtpref);
p = xdr_encode_hyper(p, resp->f_maxfilesize);
*p++ = xdr_one;
*p++ = xdr_zero;
*p++ = htonl(resp->f_properties);
}
return xdr_ressize_check(rqstp, p);
}
CWE ID: CWE-404
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (session->restricted() && !IsFrameHostAllowedForRestrictedSessions())
return false;
session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID()
: ChildProcessHost::kInvalidUniqueID,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(
base::WrapUnique(new protocol::TargetHandler(false /* browser_only */)));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
if (!base::FeatureList::IsEnabled(features::kVizDisplayCompositor) &&
!base::FeatureList::IsEnabled(
features::kUseVideoCaptureApiForDevToolsSnapshots)) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
}
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool btif_av_state_idle_handler(btif_sm_event_t event, void* p_data) {
BTIF_TRACE_DEBUG("%s: event=%s flags=0x%x", __func__,
dump_av_sm_event_name((btif_av_sm_event_t)event),
btif_av_cb.flags);
switch (event) {
case BTIF_SM_ENTER_EVT:
/* clear the peer_bda */
btif_av_cb.peer_bda = RawAddress::kEmpty;
btif_av_cb.flags = 0;
btif_av_cb.edr = 0;
bta_av_co_init(btif_av_cb.codec_priorities);
btif_a2dp_on_idle();
break;
case BTIF_SM_EXIT_EVT:
break;
case BTA_AV_ENABLE_EVT:
break;
case BTA_AV_REGISTER_EVT:
btif_av_cb.bta_handle = ((tBTA_AV*)p_data)->registr.hndl;
break;
case BTA_AV_PENDING_EVT:
case BTIF_AV_CONNECT_REQ_EVT: {
if (event == BTIF_AV_CONNECT_REQ_EVT) {
btif_av_connect_req_t* connect_req_p = (btif_av_connect_req_t*)p_data;
btif_av_cb.peer_bda = *connect_req_p->target_bda;
btif_av_cb.self_initiated_connection = true;
BTA_AvOpen(btif_av_cb.peer_bda, btif_av_cb.bta_handle, true,
BTA_SEC_AUTHENTICATE, connect_req_p->uuid);
} else if (event == BTA_AV_PENDING_EVT) {
btif_av_cb.peer_bda = ((tBTA_AV*)p_data)->pend.bd_addr;
btif_av_cb.self_initiated_connection = false;
if (bt_av_src_callbacks != NULL) {
BTA_AvOpen(btif_av_cb.peer_bda, btif_av_cb.bta_handle, true,
BTA_SEC_AUTHENTICATE, UUID_SERVCLASS_AUDIO_SOURCE);
}
if (bt_av_sink_callbacks != NULL) {
BTA_AvOpen(btif_av_cb.peer_bda, btif_av_cb.bta_handle, true,
BTA_SEC_AUTHENTICATE, UUID_SERVCLASS_AUDIO_SINK);
}
}
btif_sm_change_state(btif_av_cb.sm_handle, BTIF_AV_STATE_OPENING);
} break;
case BTA_AV_RC_OPEN_EVT:
/* IOP_FIX: Jabra 620 only does RC open without AV open whenever it
* connects. So
* as per the AV WP, an AVRC connection cannot exist without an AV
* connection. Therefore,
* we initiate an AV connection if an RC_OPEN_EVT is received when we are
* in AV_CLOSED state.
* We initiate the AV connection after a small 3s timeout to avoid any
* collisions from the
* headsets, as some headsets initiate the AVRC connection first and then
* immediately initiate the AV connection
*
* TODO: We may need to do this only on an AVRCP Play. FixMe
*/
BTIF_TRACE_WARNING("%s: BTA_AV_RC_OPEN_EVT received w/o AV", __func__);
alarm_set_on_mloop(av_open_on_rc_timer, BTIF_TIMEOUT_AV_OPEN_ON_RC_MS,
btif_initiate_av_open_timer_timeout, NULL);
btif_rc_handler(event, (tBTA_AV*)p_data);
break;
case BTA_AV_RC_BROWSE_OPEN_EVT:
BTIF_TRACE_DEBUG("%s: BTA_AV_RC_BROWSE_OPEN_EVT received", __func__);
btif_rc_handler(event, (tBTA_AV*)p_data);
break;
case BTIF_AV_SOURCE_CONFIG_REQ_EVT:
btif_update_source_codec(p_data);
break;
case BTIF_AV_SOURCE_CONFIG_UPDATED_EVT:
btif_report_source_codec_state(p_data);
break;
/*
* In case Signalling channel is not down
* and remote started Streaming Procedure
* we have to handle config and open event in
* idle_state. We hit these scenarios while running
* PTS test case for AVRCP Controller
*/
case BTIF_AV_SINK_CONFIG_REQ_EVT: {
btif_av_sink_config_req_t req;
memcpy(&req, p_data, sizeof(req));
BTIF_TRACE_WARNING(
"%s: BTIF_AV_SINK_CONFIG_REQ_EVT sample_rate=%d "
"channel_count=%d",
__func__, req.sample_rate, req.channel_count);
if (bt_av_sink_callbacks != NULL) {
HAL_CBACK(bt_av_sink_callbacks, audio_config_cb, &(req.peer_bd),
req.sample_rate, req.channel_count);
}
} break;
case BTA_AV_OPEN_EVT: {
tBTA_AV* p_bta_data = (tBTA_AV*)p_data;
btav_connection_state_t state;
btif_sm_state_t av_state;
BTIF_TRACE_WARNING("%s: BTA_AV_OPEN_EVT status=%d, edr=0x%x", __func__,
p_bta_data->open.status, p_bta_data->open.edr);
if (p_bta_data->open.status == BTA_AV_SUCCESS) {
state = BTAV_CONNECTION_STATE_CONNECTED;
av_state = BTIF_AV_STATE_OPENED;
btif_av_cb.edr = p_bta_data->open.edr;
btif_av_cb.peer_sep = p_bta_data->open.sep;
} else {
BTIF_TRACE_WARNING("%s: BTA_AV_OPEN_EVT::FAILED status=%d", __func__,
p_bta_data->open.status);
state = BTAV_CONNECTION_STATE_DISCONNECTED;
av_state = BTIF_AV_STATE_IDLE;
}
/* inform the application of the event */
btif_report_connection_state(state, &(btif_av_cb.peer_bda));
/* change state to open/idle based on the status */
btif_sm_change_state(btif_av_cb.sm_handle, av_state);
if (btif_av_cb.peer_sep == AVDT_TSEP_SNK) {
/* if queued PLAY command, send it now */
btif_rc_check_handle_pending_play(
p_bta_data->open.bd_addr,
(p_bta_data->open.status == BTA_AV_SUCCESS));
} else if ((btif_av_cb.peer_sep == AVDT_TSEP_SRC) &&
(p_bta_data->open.status == BTA_AV_SUCCESS)) {
/* Bring up AVRCP connection too */
BTA_AvOpenRc(btif_av_cb.bta_handle);
}
btif_queue_advance();
} break;
case BTA_AV_REMOTE_CMD_EVT:
case BTA_AV_VENDOR_CMD_EVT:
case BTA_AV_META_MSG_EVT:
case BTA_AV_RC_FEAT_EVT:
case BTA_AV_REMOTE_RSP_EVT:
btif_rc_handler(event, (tBTA_AV*)p_data);
break;
case BTA_AV_RC_CLOSE_EVT:
BTIF_TRACE_DEBUG("%s: BTA_AV_RC_CLOSE_EVT: Stopping AV timer.", __func__);
alarm_cancel(av_open_on_rc_timer);
btif_rc_handler(event, (tBTA_AV*)p_data);
break;
case BTIF_AV_OFFLOAD_START_REQ_EVT:
BTIF_TRACE_ERROR(
"%s: BTIF_AV_OFFLOAD_START_REQ_EVT: Stream not Started IDLE",
__func__);
btif_a2dp_on_offload_started(BTA_AV_FAIL);
break;
default:
BTIF_TRACE_WARNING("%s: unhandled event=%s", __func__,
dump_av_sm_event_name((btif_av_sm_event_t)event));
return false;
}
return true;
}
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 jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,
int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,
int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,
uint_fast32_t inmem)
{
jas_image_cmpt_t *cmpt;
size_t size;
cmpt = 0;
if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {
goto error;
}
if (!jas_safe_intfast32_add(tlx, width, 0) ||
!jas_safe_intfast32_add(tly, height, 0)) {
goto error;
}
if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {
goto error;
}
cmpt->type_ = JAS_IMAGE_CT_UNKNOWN;
cmpt->tlx_ = tlx;
cmpt->tly_ = tly;
cmpt->hstep_ = hstep;
cmpt->vstep_ = vstep;
cmpt->width_ = width;
cmpt->height_ = height;
cmpt->prec_ = depth;
cmpt->sgnd_ = sgnd;
cmpt->stream_ = 0;
cmpt->cps_ = (depth + 7) / 8;
if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||
!jas_safe_size_mul(size, cmpt->cps_, &size)) {
goto error;
}
cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) :
jas_stream_tmpfile();
if (!cmpt->stream_) {
goto error;
}
/* Zero the component data. This isn't necessary, but it is
convenient for debugging purposes. */
/* Note: conversion of size - 1 to long can overflow */
if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||
jas_stream_putc(cmpt->stream_, 0) == EOF ||
jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {
goto error;
}
return cmpt;
error:
if (cmpt) {
jas_image_cmpt_destroy(cmpt);
}
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: bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) {
wchar_t argument[50];
for (int i = 0; argument_c[i]; ++i)
argument[i] = argument_c[i];
int argument_len = lstrlen(argument);
int command_line_len = lstrlen(command_line);
while (command_line_len > argument_len) {
wchar_t first_char = command_line[0];
wchar_t last_char = command_line[argument_len+1];
if ((first_char == L'-' || first_char == L'/') &&
(last_char == L' ' || last_char == 0 || last_char == L'=')) {
command_line[argument_len+1] = 0;
if (lstrcmpi(command_line+1, argument) == 0) {
command_line[argument_len+1] = last_char;
return true;
}
command_line[argument_len+1] = last_char;
}
++command_line;
--command_line_len;
}
return false;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in)
{
_noLibzError();
return NULL;
}
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: struct bpf_map *bpf_map_get_with_uref(u32 ufd)
{
struct fd f = fdget(ufd);
struct bpf_map *map;
map = __bpf_map_get(f);
if (IS_ERR(map))
return map;
bpf_map_inc(map, true);
fdput(f);
return map;
}
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 ssd0323_load(QEMUFile *f, void *opaque, int version_id)
{
SSISlave *ss = SSI_SLAVE(opaque);
ssd0323_state *s = (ssd0323_state *)opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->cmd_len = qemu_get_be32(f);
s->cmd = qemu_get_be32(f);
for (i = 0; i < 8; i++)
s->cmd_data[i] = qemu_get_be32(f);
s->row = qemu_get_be32(f);
s->row_start = qemu_get_be32(f);
s->row_end = qemu_get_be32(f);
s->col = qemu_get_be32(f);
s->col_start = qemu_get_be32(f);
s->col_end = qemu_get_be32(f);
s->redraw = qemu_get_be32(f);
s->remap = qemu_get_be32(f);
s->mode = qemu_get_be32(f);
qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer));
ss->cs = qemu_get_be32(f);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline void debugt(const char *func, const char *msg)
{
if (DP->flags & DEBUGT)
pr_info("%s:%s dtime=%lu\n", func, msg, jiffies - debugtimer);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static InputMethodStatusConnection* GetConnection(
void* language_library,
LanguageCurrentInputMethodMonitorFunction current_input_method_changed,
LanguageRegisterImePropertiesFunction register_ime_properties,
LanguageUpdateImePropertyFunction update_ime_property,
LanguageConnectionChangeMonitorFunction connection_change_handler) {
DCHECK(language_library);
DCHECK(current_input_method_changed),
DCHECK(register_ime_properties);
DCHECK(update_ime_property);
InputMethodStatusConnection* object = GetInstance();
if (!object->language_library_) {
object->language_library_ = language_library;
object->current_input_method_changed_ = current_input_method_changed;
object->register_ime_properties_= register_ime_properties;
object->update_ime_property_ = update_ime_property;
object->connection_change_handler_ = connection_change_handler;
object->MaybeRestoreConnections();
} else if (object->language_library_ != language_library) {
LOG(ERROR) << "Unknown language_library is passed";
}
return object;
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_cdef_t *cdef = &box->data.cdef;
jp2_cdefchan_t *chan;
unsigned int channo;
if (jp2_getuint16(in, &cdef->numchans)) {
return -1;
}
if (!(cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)))) {
return -1;
}
for (channo = 0; channo < cdef->numchans; ++channo) {
chan = &cdef->ents[channo];
if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) ||
jp2_getuint16(in, &chan->assoc)) {
return -1;
}
}
return 0;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: _dbus_win_error_from_last_error (void)
{
switch (GetLastError())
{
case 0:
return DBUS_ERROR_FAILED;
case ERROR_NO_MORE_FILES:
case ERROR_TOO_MANY_OPEN_FILES:
return DBUS_ERROR_LIMITS_EXCEEDED; /* kernel out of memory */
case ERROR_ACCESS_DENIED:
case ERROR_CANNOT_MAKE:
return DBUS_ERROR_ACCESS_DENIED;
case ERROR_NOT_ENOUGH_MEMORY:
return DBUS_ERROR_NO_MEMORY;
case ERROR_FILE_EXISTS:
return DBUS_ERROR_FILE_EXISTS;
case ERROR_FILE_NOT_FOUND:
case ERROR_PATH_NOT_FOUND:
return DBUS_ERROR_FILE_NOT_FOUND;
}
return DBUS_ERROR_FAILED;
}
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 khugepaged_enter_vma_merge(struct vm_area_struct *vma)
{
unsigned long hstart, hend;
if (!vma->anon_vma)
/*
* Not yet faulted in so we will register later in the
* page fault if needed.
*/
return 0;
if (vma->vm_file || vma->vm_ops)
/* khugepaged not yet working on file or special mappings */
return 0;
VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma));
hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK;
hend = vma->vm_end & HPAGE_PMD_MASK;
if (hstart < hend)
return khugepaged_enter(vma);
return 0;
}
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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert2(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"));
b* (tob(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert2();
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int cifs_close(struct inode *inode, struct file *file)
{
if (file->private_data != NULL) {
cifsFileInfo_put(file->private_data);
file->private_data = NULL;
}
/* return code from the ->release op is always ignored */
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static __always_inline void vmcs_write64(unsigned long field, u64 value)
{
vmcs_check64(field);
__vmcs_writel(field, value);
#ifndef CONFIG_X86_64
asm volatile ("");
__vmcs_writel(field+1, value >> 32);
#endif
}
CWE ID: CWE-388
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: NaClProcessHost::NaClProcessHost(const GURL& manifest_url, bool off_the_record)
: manifest_url_(manifest_url),
#if defined(OS_WIN)
process_launched_by_broker_(false),
#elif defined(OS_LINUX)
wait_for_nacl_gdb_(false),
#endif
reply_msg_(NULL),
#if defined(OS_WIN)
debug_exception_handler_requested_(false),
#endif
internal_(new NaClInternal()),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
enable_exception_handling_(false),
off_the_record_(off_the_record) {
process_.reset(content::BrowserChildProcessHost::Create(
content::PROCESS_TYPE_NACL_LOADER, this));
process_->SetName(net::FormatUrl(manifest_url_, std::string()));
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClExceptionHandling) ||
getenv("NACL_UNTRUSTED_EXCEPTION_HANDLING") != NULL) {
enable_exception_handling_ = true;
}
enable_ipc_proxy_ = CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClIPCProxy);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void RenderViewImpl::didStopLoading() {
if (!is_loading_) {
DVLOG(1) << "DidStopLoading called while not loading";
return;
}
is_loading_ = false;
Send(new ViewHostMsg_DidStopLoading(routing_id_));
if (load_progress_tracker_ != NULL)
load_progress_tracker_->DidStopLoading();
FOR_EACH_OBSERVER(RenderViewObserver, observers_, DidStopLoading());
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void get_icu_disp_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS)
{
const char* loc_name = NULL;
int loc_name_len = 0;
const char* disp_loc_name = NULL;
int disp_loc_name_len = 0;
int free_loc_name = 0;
UChar* disp_name = NULL;
int32_t disp_name_len = 0;
char* mod_loc_name = NULL;
int32_t buflen = 512;
UErrorCode status = U_ZERO_ERROR;
char* utf8value = NULL;
int utf8value_len = 0;
char* msg = NULL;
int grOffset = 0;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
&loc_name, &loc_name_len ,
&disp_loc_name ,&disp_loc_name_len ) == FAILURE)
{
spprintf(&msg , 0, "locale_get_display_%s : unable to parse input params", tag_name );
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC );
efree(msg);
RETURN_FALSE;
}
if(loc_name_len > ULOC_FULLNAME_CAPACITY) {
/* See bug 67397: overlong locale names cause trouble in uloc_getDisplayName */
spprintf(&msg , 0, "locale_get_display_%s : name too long", tag_name );
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC );
efree(msg);
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
if( strcmp(tag_name, DISP_NAME) != 0 ){
/* Handle grandfathered languages */
grOffset = findOffset( LOC_GRANDFATHERED , loc_name );
if( grOffset >= 0 ){
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
mod_loc_name = getPreferredTag( loc_name );
} else {
/* Since Grandfathered, no value, do nothing, retutn NULL */
RETURN_FALSE;
}
}
} /* end of if != LOC_CANONICAL_TAG */
if( mod_loc_name==NULL ){
mod_loc_name = estrdup( loc_name );
}
/* Check if disp_loc_name passed , if not use default locale */
if( !disp_loc_name){
disp_loc_name = estrdup(intl_locale_get_default(TSRMLS_C));
free_loc_name = 1;
}
/* Get the disp_value for the given locale */
do{
disp_name = erealloc( disp_name , buflen * sizeof(UChar) );
disp_name_len = buflen;
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
buflen = uloc_getDisplayLanguage ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
} else if( strcmp(tag_name , LOC_SCRIPT_TAG)==0 ){
buflen = uloc_getDisplayScript ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
} else if( strcmp(tag_name , LOC_REGION_TAG)==0 ){
buflen = uloc_getDisplayCountry ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
} else if( strcmp(tag_name , LOC_VARIANT_TAG)==0 ){
buflen = uloc_getDisplayVariant ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
} else if( strcmp(tag_name , DISP_NAME)==0 ){
buflen = uloc_getDisplayName ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
}
/* U_STRING_NOT_TERMINATED_WARNING is admissible here; don't look for it */
if( U_FAILURE( status ) )
{
if( status == U_BUFFER_OVERFLOW_ERROR )
{
status = U_ZERO_ERROR;
continue;
}
spprintf(&msg, 0, "locale_get_display_%s : unable to get locale %s", tag_name , tag_name );
intl_error_set( NULL, status, msg , 1 TSRMLS_CC );
efree(msg);
if( disp_name){
efree( disp_name );
}
if( mod_loc_name){
efree( mod_loc_name );
}
if (free_loc_name) {
efree((void *)disp_loc_name);
disp_loc_name = NULL;
}
RETURN_FALSE;
}
} while( buflen > disp_name_len );
if( mod_loc_name){
efree( mod_loc_name );
}
if (free_loc_name) {
efree((void *)disp_loc_name);
disp_loc_name = NULL;
}
/* Convert display locale name from UTF-16 to UTF-8. */
intl_convert_utf16_to_utf8( &utf8value, &utf8value_len, disp_name, buflen, &status );
efree( disp_name );
if( U_FAILURE( status ) )
{
spprintf(&msg, 0, "locale_get_display_%s :error converting display name for %s to UTF-8", tag_name , tag_name );
intl_error_set( NULL, status, msg , 1 TSRMLS_CC );
efree(msg);
RETURN_FALSE;
}
RETVAL_STRINGL( utf8value, utf8value_len , FALSE);
}
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: l2tp_framing_cap_print(netdissect_options *ndo, const u_char *dat)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_ASYNC_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_SYNC_MASK) {
ND_PRINT((ndo, "S"));
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: bool BrowserDevToolsAgentHost::Activate() {
return false;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor,
PolkitSubject *subject,
GError **error)
{
PolkitIdentity *ret;
guint32 uid;
ret = NULL;
if (POLKIT_IS_UNIX_PROCESS (subject))
{
uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject));
if ((gint) uid == -1)
{
g_set_error (error,
POLKIT_ERROR,
g_set_error (error,
"Unix process subject does not have uid set");
goto out;
}
ret = polkit_unix_user_new (uid);
}
else if (POLKIT_IS_SYSTEM_BUS_NAME (subject))
{
ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error);
}
else if (POLKIT_IS_UNIX_SESSION (subject))
{
if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0)
{
polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor,
PolkitSubject *subject,
GError **error)
{
PolkitUnixProcess *tmp_process = NULL;
}
ret = polkit_unix_user_new (uid);
}
out:
return ret;
}
if (!tmp_process)
goto out;
process = tmp_process;
}
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: PassRefPtr<DocumentFragment> createFragmentFromSource(const String& markup, Element* contextElement, ExceptionCode& ec)
{
Document* document = contextElement->document();
RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
if (document->isHTMLDocument()) {
fragment->parseHTML(markup, contextElement);
return fragment;
}
bool wasValid = fragment->parseXML(markup, contextElement);
if (!wasValid) {
ec = INVALID_STATE_ERR;
return 0;
}
return fragment.release();
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: SProcXFixesDispatch(ClientPtr client)
{
REQUEST(xXFixesReq);
if (stuff->xfixesReqType >= XFixesNumberRequests)
return BadRequest;
return (*SProcXFixesVector[stuff->xfixesReqType]) (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 skcipher_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_skcipher_setkey(private, key, keylen);
}
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 GpuChannel::OnChannelConnected(int32 peer_pid) {
renderer_pid_ = peer_pid;
}
CWE ID:
Target: 1
Example 2:
Code: void StringSplit(std::string str, const std::string &delim, std::vector<std::string> &results)
{
results.clear();
size_t cutAt;
while( (cutAt = str.find(delim)) != std::string::npos )
{
results.push_back(str.substr(0,cutAt));
str = str.substr(cutAt+ delim.size());
}
if (!str.empty())
{
results.push_back(str);
}
}
CWE ID: CWE-93
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long long Block::GetTrackNumber() const
{
return m_track;
}
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 ntlm_print_negotiate_flags(UINT32 flags)
{
int i;
const char* str;
WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags);
for (i = 31; i >= 0; i--)
{
if ((flags >> i) & 1)
{
str = NTLM_NEGOTIATE_STRINGS[(31 - i)];
WLog_INFO(TAG, "\t%s (%d),", str, (31 - i));
}
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
unsigned int i, entries;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_r8(pb); /* version */
avio_rb24(pb); /* flags */
entries = avio_rb32(pb);
av_dlog(c->fc, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);
if (!entries)
return 0;
if (entries >= UINT_MAX / sizeof(*sc->stsc_data))
return AVERROR_INVALIDDATA;
sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));
if (!sc->stsc_data)
return AVERROR(ENOMEM);
sc->stsc_count = entries;
for (i=0; i<entries; i++) {
sc->stsc_data[i].first = avio_rb32(pb);
sc->stsc_data[i].count = avio_rb32(pb);
sc->stsc_data[i].id = avio_rb32(pb);
}
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void kvm_sys_reg_table_init(void)
{
unsigned int i;
struct sys_reg_desc clidr;
/* Make sure tables are unique and in order. */
BUG_ON(check_sysreg_table(sys_reg_descs, ARRAY_SIZE(sys_reg_descs)));
BUG_ON(check_sysreg_table(cp14_regs, ARRAY_SIZE(cp14_regs)));
BUG_ON(check_sysreg_table(cp14_64_regs, ARRAY_SIZE(cp14_64_regs)));
BUG_ON(check_sysreg_table(cp15_regs, ARRAY_SIZE(cp15_regs)));
BUG_ON(check_sysreg_table(cp15_64_regs, ARRAY_SIZE(cp15_64_regs)));
BUG_ON(check_sysreg_table(invariant_sys_regs, ARRAY_SIZE(invariant_sys_regs)));
/* We abuse the reset function to overwrite the table itself. */
for (i = 0; i < ARRAY_SIZE(invariant_sys_regs); i++)
invariant_sys_regs[i].reset(NULL, &invariant_sys_regs[i]);
/*
* CLIDR format is awkward, so clean it up. See ARM B4.1.20:
*
* If software reads the Cache Type fields from Ctype1
* upwards, once it has seen a value of 0b000, no caches
* exist at further-out levels of the hierarchy. So, for
* example, if Ctype3 is the first Cache Type field with a
* value of 0b000, the values of Ctype4 to Ctype7 must be
* ignored.
*/
get_clidr_el1(NULL, &clidr); /* Ugly... */
cache_levels = clidr.val;
for (i = 0; i < 7; i++)
if (((cache_levels >> (i*3)) & 7) == 0)
break;
/* Clear all higher bits. */
cache_levels &= (1 << (i*3))-1;
}
CWE ID: CWE-617
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const SystemProfileProto& MetricsLog::RecordEnvironment(
DelegatingProvider* delegating_provider) {
DCHECK(!has_environment_);
has_environment_ = true;
SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(),
system_profile);
std::string brand_code;
if (client_->GetBrand(&brand_code))
system_profile->set_brand_code(brand_code);
SystemProfileProto::Hardware::CPU* cpu =
system_profile->mutable_hardware()->mutable_cpu();
base::CPU cpu_info;
cpu->set_vendor_name(cpu_info.vendor_name());
cpu->set_signature(cpu_info.signature());
cpu->set_num_cores(base::SysInfo::NumberOfProcessors());
delegating_provider->ProvideSystemProfileMetrics(system_profile);
return *system_profile;
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
uint32_t source, uint32_t policyFlags, int32_t action, int32_t actionButton,
int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
float xPrecision, float yPrecision, nsecs_t downTime,
int32_t displayId, uint32_t pointerCount,
const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
float xOffset, float yOffset) :
EventEntry(TYPE_MOTION, eventTime, policyFlags),
eventTime(eventTime),
deviceId(deviceId), source(source), action(action), actionButton(actionButton),
flags(flags), metaState(metaState), buttonState(buttonState),
edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
for (uint32_t i = 0; i < pointerCount; i++) {
this->pointerProperties[i].copyFrom(pointerProperties[i]);
this->pointerCoords[i].copyFrom(pointerCoords[i]);
if (xOffset || yOffset) {
this->pointerCoords[i].applyOffset(xOffset, yOffset);
}
}
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rfcomm_get_dev_list(void __user *arg)
{
struct rfcomm_dev *dev;
struct rfcomm_dev_list_req *dl;
struct rfcomm_dev_info *di;
int n = 0, size, err;
u16 dev_num;
BT_DBG("");
if (get_user(dev_num, (u16 __user *) arg))
return -EFAULT;
if (!dev_num || dev_num > (PAGE_SIZE * 4) / sizeof(*di))
return -EINVAL;
size = sizeof(*dl) + dev_num * sizeof(*di);
dl = kmalloc(size, GFP_KERNEL);
if (!dl)
return -ENOMEM;
di = dl->dev_info;
spin_lock(&rfcomm_dev_lock);
list_for_each_entry(dev, &rfcomm_dev_list, list) {
if (test_bit(RFCOMM_TTY_RELEASED, &dev->flags))
continue;
(di + n)->id = dev->id;
(di + n)->flags = dev->flags;
(di + n)->state = dev->dlc->state;
(di + n)->channel = dev->channel;
bacpy(&(di + n)->src, &dev->src);
bacpy(&(di + n)->dst, &dev->dst);
if (++n >= dev_num)
break;
}
spin_unlock(&rfcomm_dev_lock);
dl->dev_num = n;
size = sizeof(*dl) + n * sizeof(*di);
err = copy_to_user(arg, dl, size);
kfree(dl);
return err ? -EFAULT : 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: std::unique_ptr<JSONObject> ClipPaintPropertyNode::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("rect", state_.clip_rect.ToString());
if (state_.clip_rect_excluding_overlay_scrollbars) {
json->SetString("rectExcludingOverlayScrollbars",
state_.clip_rect_excluding_overlay_scrollbars->ToString());
}
if (state_.clip_path) {
json->SetBoolean("hasClipPath", true);
}
if (state_.direct_compositing_reasons != CompositingReason::kNone) {
json->SetString(
"directCompositingReasons",
CompositingReason::ToString(state_.direct_compositing_reasons));
}
return json;
}
CWE ID:
Target: 1
Example 2:
Code: OMX::buffer_id OMXNodeInstance::findBufferID(OMX_BUFFERHEADERTYPE *bufferHeader) {
if (bufferHeader == NULL) {
return 0;
}
Mutex::Autolock autoLock(mBufferIDLock);
return mBufferHeaderToBufferID.valueFor(bufferHeader);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ChangeInputMethodViaIBus(const std::string& input_method_id) {
if (!initialized_successfully_)
return false;
std::string input_method_id_to_switch = input_method_id;
if (!InputMethodIsActivated(input_method_id)) {
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
DCHECK(!input_methods->empty());
if (!input_methods->empty()) {
input_method_id_to_switch = input_methods->at(0).id;
LOG(INFO) << "Can't change the current input method to "
<< input_method_id << " since the engine is not preloaded. "
<< "Switch to " << input_method_id_to_switch << " instead.";
}
}
if (chromeos::ChangeInputMethod(input_method_status_connection_,
input_method_id_to_switch.c_str())) {
return true;
}
LOG(ERROR) << "Can't switch input method to " << input_method_id_to_switch;
return false;
}
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: rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
{
struct vendor_attribute *attr;
attr = (struct vendor_attribute *)*data;
*vendor = ntohl(attr->vendor_value);
*data = attr->attrib_data;
*len = attr->attrib_len - 2;
return (attr->attrib_type);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int ret;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
avio_wl32(pb, track->tag); // store it byteswapped
track->par->codec_tag = av_bswap16(track->tag >> 16);
if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
return ret;
return update_size(pb, pos);
}
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: InstallVerifyFrame::InstallVerifyFrame(const wxString& lDmodFilePath)
: InstallVerifyFrame_Base(NULL, wxID_ANY, _T(""))
{
mConfig = Config::GetConfig();
prepareDialog();
int flags = wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_REMAINING_TIME;
wxProgressDialog lPrepareProgress(_("Preparing"),
_("The D-Mod archive is being decompressed in a temporary file."), 100, this, flags);
BZip lBZip(lDmodFilePath);
mTarFilePath = lBZip.Extract(&lPrepareProgress);
if (mTarFilePath.Len() != 0)
{
Tar lTar(mTarFilePath);
lTar.ReadHeaders();
wxString lDmodDescription = lTar.getmDmodDescription();
"\n"
"The D-Mod will be installed in subdirectory '%s'."),
lTar.getInstalledDmodDirectory().c_str());
}
else
{
int lBreakChar = lDmodDescription.Find( '\r' );
if ( lBreakChar <= 0 )
{
lBreakChar = lDmodDescription.Find( '\n' );
}
mDmodName = lDmodDescription.SubString( 0, lBreakChar - 1 );
this->SetTitle(_("DFArc - Install D-Mod - ") + mDmodName);
}
mDmodDescription->SetValue(lDmodDescription);
mInstallButton->Enable(true);
}
CWE ID: CWE-22
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void cJSON_Delete( cJSON *c )
{
cJSON *next;
while ( c ) {
next = c->next;
if ( ! ( c->type & cJSON_IsReference ) && c->child )
cJSON_Delete( c->child );
if ( ! ( c->type & cJSON_IsReference ) && c->valuestring )
cJSON_free( c->valuestring );
if ( c->string )
cJSON_free( c->string );
cJSON_free( c );
c = next;
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: synth_body(const char *len, int rnd)
{
int i, j, k, l;
char *b;
AN(len);
i = strtoul(len, NULL, 0);
assert(i > 0);
b = malloc(i + 1L);
AN(b);
l = k = '!';
for (j = 0; j < i; j++) {
if ((j % 64) == 63) {
b[j] = '\n';
k++;
if (k == '~')
k = '!';
l = k;
} else if (rnd) {
b[j] = (random() % 95) + ' ';
} else {
b[j] = (char)l;
if (++l == '~')
l = '!';
}
}
b[i - 1] = '\n';
b[i] = '\0';
return (b);
}
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: setdevicecolor_cont(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
es_ptr ep = esp, pstage;
int code = 0, stage, base;
pstage = ep;
base = (int)ep[-1].value.intval;
stage = (int)pstage->value.intval;
/* If we get a continuation from a sub-procedure, we will want to come back
* here afterward, to do any remaining stages. We need to set up for that now.
* so that our continuation is ahead of the sub-proc's continuation.
*/
check_estack(1);
/* May need to push a /Device... name on the stack so make sure we have space */
check_ostack(1);
/* The push_op_estack macro increments esp before use, so we don't need to */
push_op_estack(setdevicecolor_cont);
do {
switch(stage) {
case 0:
make_int(pstage, ++stage);
push(1);
switch(base) {
case 0: /* DeviceGray */
code = name_enter_string(imemory, "DeviceGray", op);
break;
case 1: /* DeviceRGB */
code = name_enter_string(imemory, "DeviceRGB", op);
break;
case 2: /* DeviceCMYK */
code = name_enter_string(imemory, "DeviceCMYK", op);
break;
}
if (code < 0)
return code;
code = zsetcolorspace(i_ctx_p);
if (code != 0)
return code;
break;
case 1:
make_int(pstage, ++stage);
code = zsetcolor(i_ctx_p);
if (code != 0)
return code;
break;
case 2:
esp -= 3;
return o_pop_estack;
break;
}
}while(1);
return 0;
}
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: error::Error GLES2DecoderPassthroughImpl::DoBeginQueryEXT(
GLenum target,
GLuint id,
int32_t sync_shm_id,
uint32_t sync_shm_offset) {
GLuint service_id = GetQueryServiceID(id, &query_id_map_);
QueryInfo* query_info = &query_info_map_[service_id];
scoped_refptr<gpu::Buffer> buffer = GetSharedMemoryBuffer(sync_shm_id);
if (!buffer)
return error::kInvalidArguments;
QuerySync* sync = static_cast<QuerySync*>(
buffer->GetDataAddress(sync_shm_offset, sizeof(QuerySync)));
if (!sync)
return error::kOutOfBounds;
if (IsEmulatedQueryTarget(target)) {
if (active_queries_.find(target) != active_queries_.end()) {
InsertError(GL_INVALID_OPERATION, "Query already active on target.");
return error::kNoError;
}
if (id == 0) {
InsertError(GL_INVALID_OPERATION, "Query id is 0.");
return error::kNoError;
}
if (query_info->type != GL_NONE && query_info->type != target) {
InsertError(GL_INVALID_OPERATION,
"Query type does not match the target.");
return error::kNoError;
}
} else {
CheckErrorCallbackState();
api()->glBeginQueryFn(target, service_id);
if (CheckErrorCallbackState()) {
return error::kNoError;
}
}
query_info->type = target;
RemovePendingQuery(service_id);
ActiveQuery query;
query.service_id = service_id;
query.shm = std::move(buffer);
query.sync = sync;
active_queries_[target] = std::move(query);
return error::kNoError;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: virtual ~FadeOutAnimationDelegate() {}
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 inline enum ib_qp_state to_ib_qp_state(enum mlx5_qp_state mlx5_state)
{
switch (mlx5_state) {
case MLX5_QP_STATE_RST: return IB_QPS_RESET;
case MLX5_QP_STATE_INIT: return IB_QPS_INIT;
case MLX5_QP_STATE_RTR: return IB_QPS_RTR;
case MLX5_QP_STATE_RTS: return IB_QPS_RTS;
case MLX5_QP_STATE_SQ_DRAINING:
case MLX5_QP_STATE_SQD: return IB_QPS_SQD;
case MLX5_QP_STATE_SQER: return IB_QPS_SQE;
case MLX5_QP_STATE_ERR: return IB_QPS_ERR;
default: 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: decode_bundle(bool load, const struct nx_action_bundle *nab,
const struct vl_mff_map *vl_mff_map, uint64_t *tlv_bitmap,
struct ofpbuf *ofpacts)
{
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
struct ofpact_bundle *bundle;
uint32_t slave_type;
size_t slaves_size, i;
enum ofperr error;
bundle = ofpact_put_BUNDLE(ofpacts);
bundle->n_slaves = ntohs(nab->n_slaves);
bundle->basis = ntohs(nab->basis);
bundle->fields = ntohs(nab->fields);
bundle->algorithm = ntohs(nab->algorithm);
slave_type = ntohl(nab->slave_type);
slaves_size = ntohs(nab->len) - sizeof *nab;
error = OFPERR_OFPBAC_BAD_ARGUMENT;
if (!flow_hash_fields_valid(bundle->fields)) {
VLOG_WARN_RL(&rl, "unsupported fields %d", (int) bundle->fields);
} else if (bundle->n_slaves > BUNDLE_MAX_SLAVES) {
VLOG_WARN_RL(&rl, "too many slaves");
} else if (bundle->algorithm != NX_BD_ALG_HRW
&& bundle->algorithm != NX_BD_ALG_ACTIVE_BACKUP) {
VLOG_WARN_RL(&rl, "unsupported algorithm %d", (int) bundle->algorithm);
} else if (slave_type != mf_nxm_header(MFF_IN_PORT)) {
VLOG_WARN_RL(&rl, "unsupported slave type %"PRIu16, slave_type);
} else {
error = 0;
}
if (!is_all_zeros(nab->zero, sizeof nab->zero)) {
VLOG_WARN_RL(&rl, "reserved field is nonzero");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
if (load) {
bundle->dst.ofs = nxm_decode_ofs(nab->ofs_nbits);
bundle->dst.n_bits = nxm_decode_n_bits(nab->ofs_nbits);
error = mf_vl_mff_mf_from_nxm_header(ntohl(nab->dst), vl_mff_map,
&bundle->dst.field, tlv_bitmap);
if (error) {
return error;
}
if (bundle->dst.n_bits < 16) {
VLOG_WARN_RL(&rl, "bundle_load action requires at least 16 bit "
"destination.");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
} else {
if (nab->ofs_nbits || nab->dst) {
VLOG_WARN_RL(&rl, "bundle action has nonzero reserved fields");
error = OFPERR_OFPBAC_BAD_ARGUMENT;
}
}
if (slaves_size < bundle->n_slaves * sizeof(ovs_be16)) {
VLOG_WARN_RL(&rl, "Nicira action %s only has %"PRIuSIZE" bytes "
"allocated for slaves. %"PRIuSIZE" bytes are required "
"for %"PRIu16" slaves.",
load ? "bundle_load" : "bundle", slaves_size,
bundle->n_slaves * sizeof(ovs_be16), bundle->n_slaves);
error = OFPERR_OFPBAC_BAD_LEN;
}
for (i = 0; i < bundle->n_slaves; i++) {
ofp_port_t ofp_port = u16_to_ofp(ntohs(((ovs_be16 *)(nab + 1))[i]));
ofpbuf_put(ofpacts, &ofp_port, sizeof ofp_port);
bundle = ofpacts->header;
}
ofpact_finish_BUNDLE(ofpacts, &bundle);
if (!error) {
error = bundle_check(bundle, OFPP_MAX, NULL);
}
return error;
}
CWE ID:
Target: 1
Example 2:
Code: static void activityLoggedInIsolatedWorldsAttrAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
V8PerContextData* contextData = V8PerContextData::from(info.GetIsolate()->GetCurrentContext());
if (contextData && contextData->activityLogger()) {
v8::Handle<v8::Value> loggerArg[] = { jsValue };
contextData->activityLogger()->log("TestObject.activityLoggedInIsolatedWorldsAttr", 1, &loggerArg[0], "Setter");
}
TestObjectV8Internal::activityLoggedInIsolatedWorldsAttrAttributeSetter(jsValue, 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 WebGLRenderingContextBase::TexImageHelperImageData(
TexImageFunctionID function_id,
GLenum target,
GLint level,
GLint internalformat,
GLint border,
GLenum format,
GLenum type,
GLsizei depth,
GLint xoffset,
GLint yoffset,
GLint zoffset,
ImageData* pixels,
const IntRect& source_image_rect,
GLint unpack_image_height) {
const char* func_name = GetTexImageFunctionName(function_id);
if (isContextLost())
return;
DCHECK(pixels);
if (pixels->data()->BufferBase()->IsNeutered()) {
SynthesizeGLError(GL_INVALID_VALUE, func_name,
"The source data has been neutered.");
return;
}
if (!ValidateTexImageBinding(func_name, function_id, target))
return;
TexImageFunctionType function_type;
if (function_id == kTexImage2D || function_id == kTexImage3D)
function_type = kTexImage;
else
function_type = kTexSubImage;
if (!ValidateTexFunc(func_name, function_type, kSourceImageData, target,
level, internalformat, pixels->width(), pixels->height(),
depth, border, format, type, xoffset, yoffset, zoffset))
return;
bool selecting_sub_rectangle = false;
if (!ValidateTexImageSubRectangle(
func_name, function_id, pixels, source_image_rect, depth,
unpack_image_height, &selecting_sub_rectangle)) {
return;
}
IntRect adjusted_source_image_rect = source_image_rect;
if (unpack_flip_y_) {
adjusted_source_image_rect.SetY(pixels->height() -
adjusted_source_image_rect.MaxY());
}
Vector<uint8_t> data;
bool need_conversion = true;
if (!unpack_flip_y_ && !unpack_premultiply_alpha_ && format == GL_RGBA &&
type == GL_UNSIGNED_BYTE && !selecting_sub_rectangle && depth == 1) {
need_conversion = false;
} else {
if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) {
type = GL_FLOAT;
}
if (!WebGLImageConversion::ExtractImageData(
pixels->data()->Data(),
WebGLImageConversion::DataFormat::kDataFormatRGBA8, pixels->Size(),
adjusted_source_image_rect, depth, unpack_image_height, format,
type, unpack_flip_y_, unpack_premultiply_alpha_, data)) {
SynthesizeGLError(GL_INVALID_VALUE, func_name, "bad image data");
return;
}
}
ScopedUnpackParametersResetRestore temporary_reset_unpack(this);
const uint8_t* bytes = need_conversion ? data.data() : pixels->data()->Data();
if (function_id == kTexImage2D) {
DCHECK_EQ(unpack_image_height, 0);
TexImage2DBase(
target, level, internalformat, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), border, format, type, bytes);
} else if (function_id == kTexSubImage2D) {
DCHECK_EQ(unpack_image_height, 0);
ContextGL()->TexSubImage2D(
target, level, xoffset, yoffset, adjusted_source_image_rect.Width(),
adjusted_source_image_rect.Height(), format, type, bytes);
} else {
GLint upload_height = adjusted_source_image_rect.Height();
if (unpack_image_height) {
upload_height = unpack_image_height;
}
if (function_id == kTexImage3D) {
ContextGL()->TexImage3D(target, level, internalformat,
adjusted_source_image_rect.Width(), upload_height,
depth, border, format, type, bytes);
} else {
DCHECK_EQ(function_id, kTexSubImage3D);
ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset,
adjusted_source_image_rect.Width(),
upload_height, depth, format, type, bytes);
}
}
}
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 js_RegExp_prototype_exec(js_State *J, js_Regexp *re, const char *text)
{
int i;
int opts;
Resub m;
opts = 0;
if (re->flags & JS_REGEXP_G) {
if (re->last > strlen(text)) {
re->last = 0;
js_pushnull(J);
return;
}
if (re->last > 0) {
text += re->last;
opts |= REG_NOTBOL;
}
}
if (!js_regexec(re->prog, text, &m, opts)) {
js_newarray(J);
js_pushstring(J, text);
js_setproperty(J, -2, "input");
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
js_setproperty(J, -2, "index");
for (i = 0; i < m.nsub; ++i) {
js_pushlstring(J, m.sub[i].sp, m.sub[i].ep - m.sub[i].sp);
js_setindex(J, -2, i);
}
if (re->flags & JS_REGEXP_G)
re->last = re->last + (m.sub[0].ep - text);
return;
}
if (re->flags & JS_REGEXP_G)
re->last = 0;
js_pushnull(J);
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: void AddDefaultBrowserStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"defaultBrowser", IDS_SETTINGS_DEFAULT_BROWSER},
{"defaultBrowserDefault", IDS_SETTINGS_DEFAULT_BROWSER_DEFAULT},
{"defaultBrowserMakeDefault", IDS_SETTINGS_DEFAULT_BROWSER_MAKE_DEFAULT},
{"defaultBrowserMakeDefaultButton",
IDS_SETTINGS_DEFAULT_BROWSER_MAKE_DEFAULT_BUTTON},
{"defaultBrowserError", IDS_SETTINGS_DEFAULT_BROWSER_ERROR},
{"defaultBrowserSecondary", IDS_SETTINGS_DEFAULT_BROWSER_SECONDARY},
};
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
}
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: append_quoted (struct stringbuf *sb, const unsigned char *value, size_t length,
int skip)
{
unsigned char tmp[4];
const unsigned char *s = value;
size_t n = 0;
for (;;)
{
for (value = s; n+skip < length; n++, s++)
{
s += skip;
n += skip;
if (*s < ' ' || *s > 126 || strchr (",+\"\\<>;", *s) )
break;
}
if (s != value)
put_stringbuf_mem_skip (sb, value, s-value, skip);
if (n+skip >= length)
return; /* ready */
s += skip;
n += skip;
if ( *s < ' ' || *s > 126 )
{
sprintf (tmp, "\\%02X", *s);
put_stringbuf_mem (sb, tmp, 3);
}
else
{
tmp[0] = '\\';
tmp[1] = *s;
put_stringbuf_mem (sb, tmp, 2);
}
n++; s++;
}
}
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 struct dentry *proc_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
int err;
struct super_block *sb;
struct pid_namespace *ns;
char *options;
if (flags & MS_KERNMOUNT) {
ns = (struct pid_namespace *)data;
options = NULL;
} else {
ns = task_active_pid_ns(current);
options = data;
/* Does the mounter have privilege over the pid namespace? */
if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
return ERR_PTR(-EPERM);
}
sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns);
if (IS_ERR(sb))
return ERR_CAST(sb);
if (!proc_parse_options(options, ns)) {
deactivate_locked_super(sb);
return ERR_PTR(-EINVAL);
}
if (!sb->s_root) {
err = proc_fill_super(sb);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
/* User space would break if executables appear on proc */
sb->s_iflags |= SB_I_NOEXEC;
}
return dget(sb->s_root);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int kvm_arch_init(void *opaque)
{
int r;
struct kvm_x86_ops *ops = (struct kvm_x86_ops *)opaque;
if (kvm_x86_ops) {
printk(KERN_ERR "kvm: already loaded the other module\n");
r = -EEXIST;
goto out;
}
if (!ops->cpu_has_kvm_support()) {
printk(KERN_ERR "kvm: no hardware support\n");
r = -EOPNOTSUPP;
goto out;
}
if (ops->disabled_by_bios()) {
printk(KERN_ERR "kvm: disabled by bios\n");
r = -EOPNOTSUPP;
goto out;
}
r = kvm_mmu_module_init();
if (r)
goto out;
kvm_init_msr_list();
kvm_x86_ops = ops;
kvm_mmu_set_nonpresent_ptes(0ull, 0ull);
kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
PT_DIRTY_MASK, PT64_NX_MASK, 0);
kvm_timer_init();
perf_register_guest_info_callbacks(&kvm_guest_cbs);
if (cpu_has_xsave)
host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
return 0;
out:
return r;
}
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: V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context,
Dispatcher* dispatcher)
: ObjectBackedNativeHandler(context),
context_(context),
dispatcher_(dispatcher) {
RouteFunction("GetAvailability",
base::Bind(&V8ContextNativeHandler::GetAvailability,
base::Unretained(this)));
RouteFunction("GetModuleSystem",
base::Bind(&V8ContextNativeHandler::GetModuleSystem,
base::Unretained(this)));
RouteFunction(
"RunWithNativesEnabledModuleSystem",
base::Bind(&V8ContextNativeHandler::RunWithNativesEnabledModuleSystem,
base::Unretained(this)));
}
CWE ID: CWE-79
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 PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder, v8::Local<v8::Value> v8Value)
{
v8::Isolate* isolate = scriptState->isolate();
v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className);
v8::Local<v8::Value> descriptor;
if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) {
fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
v8::Local<v8::Value> setter;
if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "set")).ToLocal(&setter) || !setter->IsFunction()) {
fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName);
RELEASE_NOTREACHED();
}
initializeHolderIfNeeded(scriptState, classObject, holder);
v8::Local<v8::Value> argv[] = { v8Value };
v8::TryCatch block(isolate);
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(setter), scriptState->getExecutionContext(), holder, WTF_ARRAY_LENGTH(argv), argv, isolate).ToLocal(&result)) {
rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::SetterContext, attributeName, className);
block.ReThrow();
return false;
}
return true;
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
int nr_pages)
{
unsigned long addr;
gfn_t entry;
addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
if (kvm_is_error_hva(addr))
return -1;
if (entry < nr_pages)
return 0;
return __get_user_pages_fast(addr, nr_pages, 1, pages);
}
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: xps_select_font_encoding(xps_font_t *font, int idx)
{
byte *cmapdata, *entry;
int pid, eid;
if (idx < 0 || idx >= font->cmapsubcount)
return;
cmapdata = font->data + font->cmaptable;
entry = cmapdata + 4 + idx * 8;
pid = u16(entry + 0);
eid = u16(entry + 2);
font->cmapsubtable = font->cmaptable + u32(entry + 4);
font->usepua = (pid == 3 && eid == 0);
}
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: int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
{
void **ptrptr = ptr;
*ptrptr = av_realloc_f(*ptrptr, nmemb, size);
if (!*ptrptr && !(nmemb && size))
return AVERROR(ENOMEM);
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
{
int delta;
WARN_ON(skb->sk != NULL);
delta = skb->end - skb->tail;
if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
return skb;
if (skb_shared(skb)) {
struct sk_buff *nskb = skb_clone(skb, allocation);
if (!nskb)
return skb;
consume_skb(skb);
skb = nskb;
}
if (!pskb_expand_head(skb, 0, -delta, allocation))
skb->truesize -= delta;
return skb;
}
CWE ID: CWE-415
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int muscle_select_file(sc_card_t *card, const sc_path_t *path_in,
sc_file_t **file_out)
{
int r;
assert(card != NULL && path_in != NULL);
switch (path_in->type) {
case SC_PATH_TYPE_FILE_ID:
r = select_item(card, path_in, file_out, 1);
break;
case SC_PATH_TYPE_DF_NAME:
r = select_item(card, path_in, file_out, 0);
break;
case SC_PATH_TYPE_PATH:
r = select_item(card, path_in, file_out, -1);
break;
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS);
}
if(r > 0) r = 0;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,r);
}
CWE ID: CWE-415
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int read_fragment_table(long long *directory_table_end)
{
int res, i;
int bytes = SQUASHFS_FRAGMENT_BYTES(sBlk.s.fragments);
int indexes = SQUASHFS_FRAGMENT_INDEXES(sBlk.s.fragments);
long long fragment_table_index[indexes];
TRACE("read_fragment_table: %d fragments, reading %d fragment indexes "
"from 0x%llx\n", sBlk.s.fragments, indexes,
sBlk.s.fragment_table_start);
if(sBlk.s.fragments == 0) {
*directory_table_end = sBlk.s.fragment_table_start;
return TRUE;
}
fragment_table = malloc(bytes);
if(fragment_table == NULL)
EXIT_UNSQUASH("read_fragment_table: failed to allocate "
"fragment table\n");
res = read_fs_bytes(fd, sBlk.s.fragment_table_start,
SQUASHFS_FRAGMENT_INDEX_BYTES(sBlk.s.fragments),
fragment_table_index);
if(res == FALSE) {
ERROR("read_fragment_table: failed to read fragment table "
"index\n");
return FALSE;
}
SQUASHFS_INSWAP_FRAGMENT_INDEXES(fragment_table_index, indexes);
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
int length = read_block(fd, fragment_table_index[i], NULL,
expected, ((char *) fragment_table) + (i *
SQUASHFS_METADATA_SIZE));
TRACE("Read fragment table block %d, from 0x%llx, length %d\n",
i, fragment_table_index[i], length);
if(length == FALSE) {
ERROR("read_fragment_table: failed to read fragment "
"table index\n");
return FALSE;
}
}
for(i = 0; i < sBlk.s.fragments; i++)
SQUASHFS_INSWAP_FRAGMENT_ENTRY(&fragment_table[i]);
*directory_table_end = fragment_table_index[0];
return TRUE;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void PlatformSensorProviderLinux::GetAllSensorDevices() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
NOTIMPLEMENTED();
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SetState(MediaStreamType stream_type, MediaRequestState new_state) {
if (stream_type == NUM_MEDIA_TYPES) {
for (int i = MEDIA_NO_SERVICE + 1; i < NUM_MEDIA_TYPES; ++i) {
state_[static_cast<MediaStreamType>(i)] = new_state;
}
} else {
state_[stream_type] = new_state;
}
MediaObserver* media_observer =
GetContentClient()->browser()->GetMediaObserver();
if (!media_observer)
return;
media_observer->OnMediaRequestStateChanged(
target_process_id_, target_frame_id_, page_request_id,
security_origin.GetURL(), stream_type, new_state);
}
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: ExtensionTtsPlatformImpl* ExtensionTtsController::GetPlatformImpl() {
if (!platform_impl_)
platform_impl_ = ExtensionTtsPlatformImpl::GetInstance();
return platform_impl_;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static struct ipddp_route* __ipddp_find_route(struct ipddp_route *rt)
{
struct ipddp_route *f;
for(f = ipddp_route_list; f != NULL; f = f->next)
{
if(f->ip == rt->ip &&
f->at.s_net == rt->at.s_net &&
f->at.s_node == rt->at.s_node)
return f;
}
return NULL;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::string LayerTreeHostImpl::LayerTreeAsJson() const {
std::string str;
if (active_tree_->root_layer_for_testing()) {
std::unique_ptr<base::Value> json(
active_tree_->root_layer_for_testing()->LayerTreeAsJson());
base::JSONWriter::WriteWithOptions(
*json, base::JSONWriter::OPTIONS_PRETTY_PRINT, &str);
}
return str;
}
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: NavigateParams::NavigateParams(Browser* a_browser,
TabContentsWrapper* a_target_contents)
: target_contents(a_target_contents),
source_contents(NULL),
disposition(CURRENT_TAB),
transition(content::PAGE_TRANSITION_LINK),
tabstrip_index(-1),
tabstrip_add_types(TabStripModel::ADD_ACTIVE),
window_action(NO_ACTION),
user_gesture(true),
path_behavior(RESPECT),
ref_behavior(IGNORE_REF),
browser(a_browser),
profile(NULL) {
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void Document::setDomain(const String& raw_domain,
ExceptionState& exception_state) {
UseCounter::Count(*this, WebFeature::kDocumentSetDomain);
const String feature_policy_error =
"Setting `document.domain` is disabled by Feature Policy.";
if (!IsFeatureEnabled(mojom::FeaturePolicyFeature::kDocumentDomain,
ReportOptions::kReportOnFailure,
feature_policy_error)) {
exception_state.ThrowSecurityError(feature_policy_error);
return;
}
if (!frame_) {
exception_state.ThrowSecurityError(
"A browsing context is required to set a domain.");
return;
}
if (IsSandboxed(kSandboxDocumentDomain)) {
exception_state.ThrowSecurityError(
"Assignment is forbidden for sandboxed iframes.");
return;
}
if (SchemeRegistry::IsDomainRelaxationForbiddenForURLScheme(
GetSecurityOrigin()->Protocol())) {
exception_state.ThrowSecurityError("Assignment is forbidden for the '" +
GetSecurityOrigin()->Protocol() +
"' scheme.");
return;
}
bool success = false;
String new_domain = SecurityOrigin::CanonicalizeHost(raw_domain, &success);
if (!success) {
exception_state.ThrowSecurityError("'" + raw_domain +
"' could not be parsed properly.");
return;
}
if (new_domain.IsEmpty()) {
exception_state.ThrowSecurityError("'" + new_domain +
"' is an empty domain.");
return;
}
OriginAccessEntry access_entry(
GetSecurityOrigin()->Protocol(), new_domain,
network::mojom::CorsOriginAccessMatchMode::kAllowSubdomains);
network::cors::OriginAccessEntry::MatchResult result =
access_entry.MatchesOrigin(*GetSecurityOrigin());
if (result == network::cors::OriginAccessEntry::kDoesNotMatchOrigin) {
exception_state.ThrowSecurityError(
"'" + new_domain + "' is not a suffix of '" + domain() + "'.");
return;
}
if (result ==
network::cors::OriginAccessEntry::kMatchesOriginButIsPublicSuffix) {
exception_state.ThrowSecurityError("'" + new_domain +
"' is a top-level domain.");
return;
}
if (frame_) {
UseCounter::Count(*this,
GetSecurityOrigin()->Port() == 0
? WebFeature::kDocumentDomainSetWithDefaultPort
: WebFeature::kDocumentDomainSetWithNonDefaultPort);
bool was_cross_domain = frame_->IsCrossOriginSubframe();
GetMutableSecurityOrigin()->SetDomainFromDOM(new_domain);
if (View() && (was_cross_domain != frame_->IsCrossOriginSubframe()))
View()->CrossOriginStatusChanged();
frame_->GetScriptController().UpdateSecurityOrigin(GetSecurityOrigin());
}
}
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: send_cancel(struct TCP_Server_Info *server, void *buf, struct mid_q_entry *mid)
{
return server->ops->send_cancel ?
server->ops->send_cancel(server, buf, mid) : 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: long do_io_submit(aio_context_t ctx_id, long nr,
struct iocb __user *__user *iocbpp, bool compat)
{
struct kioctx *ctx;
long ret = 0;
int i = 0;
struct blk_plug plug;
struct kiocb_batch batch;
if (unlikely(nr < 0))
return -EINVAL;
if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
nr = LONG_MAX/sizeof(*iocbpp);
if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
return -EFAULT;
ctx = lookup_ioctx(ctx_id);
if (unlikely(!ctx)) {
pr_debug("EINVAL: io_submit: invalid context id\n");
return -EINVAL;
}
kiocb_batch_init(&batch, nr);
blk_start_plug(&plug);
/*
* AKPM: should this return a partial result if some of the IOs were
* successfully submitted?
*/
for (i=0; i<nr; i++) {
struct iocb __user *user_iocb;
struct iocb tmp;
if (unlikely(__get_user(user_iocb, iocbpp + i))) {
ret = -EFAULT;
break;
}
if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
ret = -EFAULT;
break;
}
ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat);
if (ret)
break;
}
blk_finish_plug(&plug);
kiocb_batch_free(&batch);
put_ioctx(ctx);
return i ? i : ret;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: secret_blinded (gcry_mpi_t output, gcry_mpi_t input,
RSA_secret_key *sk, unsigned int nbits)
{
gcry_mpi_t r; /* Random number needed for blinding. */
gcry_mpi_t ri; /* Modular multiplicative inverse of r. */
gcry_mpi_t bldata; /* Blinded data to decrypt. */
/* First, we need a random number r between 0 and n - 1, which is
* relatively prime to n (i.e. it is neither p nor q). The random
* number needs to be only unpredictable, thus we employ the
* gcry_create_nonce function by using GCRY_WEAK_RANDOM with
* gcry_mpi_randomize. */
r = mpi_snew (nbits);
ri = mpi_snew (nbits);
bldata = mpi_snew (nbits);
do
{
_gcry_mpi_randomize (r, nbits, GCRY_WEAK_RANDOM);
mpi_mod (r, r, sk->n);
}
while (!mpi_invm (ri, r, sk->n));
/* Do blinding. We calculate: y = (x * r^e) mod n, where r is the
* random number, e is the public exponent, x is the non-blinded
* input data and n is the RSA modulus. */
mpi_powm (bldata, r, sk->e, sk->n);
mpi_mulm (bldata, bldata, input, sk->n);
/* Perform decryption. */
secret (output, bldata, sk);
_gcry_mpi_release (bldata);
/* Undo blinding. Here we calculate: y = (x * r^-1) mod n, where x
* is the blinded decrypted data, ri is the modular multiplicative
* inverse of r and n is the RSA modulus. */
mpi_mulm (output, output, ri, sk->n);
_gcry_mpi_release (r);
_gcry_mpi_release (ri);
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, j, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < le32_to_cpu(lvd->mapTableLength);
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
uint32_t loc;
struct sparingTable *st;
struct sparablePartitionMap *spm =
(struct sparablePartitionMap *)gpm;
map->s_partition_type = UDF_SPARABLE_MAP15;
map->s_type_specific.s_sparing.s_packet_len =
le16_to_cpu(spm->packetLength);
for (j = 0; j < spm->numSparingTables; j++) {
struct buffer_head *bh2;
loc = le32_to_cpu(
spm->locSparingTable[j]);
bh2 = udf_read_tagged(sb, loc, loc,
&ident);
map->s_type_specific.s_sparing.
s_spar_map[j] = bh2;
if (bh2 == NULL)
continue;
st = (struct sparingTable *)bh2->b_data;
if (ident != 0 || strncmp(
st->sparingIdent.ident,
UDF_ID_SPARING,
strlen(UDF_ID_SPARING))) {
brelse(bh2);
map->s_type_specific.s_sparing.
s_spar_map[j] = NULL;
}
}
map->s_partition_func = udf_get_pblock_spar15;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static v8::Handle<v8::Value> overloadedMethod3Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod3");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
imp->overloadedMethod(strArg);
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: static void rpng2_x_reload_bg_image(void)
{
char *dest;
uch r1, r2, g1, g2, b1, b2;
uch r1_inv, r2_inv, g1_inv, g2_inv, b1_inv, b2_inv;
int k, hmax, max;
int xidx, yidx, yidx_max;
int even_odd_vert, even_odd_horiz, even_odd;
int invert_gradient2 = (bg[pat].type & 0x08);
int invert_column;
ulg i, row;
bgscale = (pat == 0)? 8 : bgscale_default;
yidx_max = bgscale - 1;
/*---------------------------------------------------------------------------
Vertical gradients (ramps) in NxN squares, alternating direction and
colors (N == bgscale).
---------------------------------------------------------------------------*/
if ((bg[pat].type & 0x07) == 0) {
uch r1_min = rgb[bg[pat].rgb1_min].r;
uch g1_min = rgb[bg[pat].rgb1_min].g;
uch b1_min = rgb[bg[pat].rgb1_min].b;
uch r2_min = rgb[bg[pat].rgb2_min].r;
uch g2_min = rgb[bg[pat].rgb2_min].g;
uch b2_min = rgb[bg[pat].rgb2_min].b;
int r1_diff = rgb[bg[pat].rgb1_max].r - r1_min;
int g1_diff = rgb[bg[pat].rgb1_max].g - g1_min;
int b1_diff = rgb[bg[pat].rgb1_max].b - b1_min;
int r2_diff = rgb[bg[pat].rgb2_max].r - r2_min;
int g2_diff = rgb[bg[pat].rgb2_max].g - g2_min;
int b2_diff = rgb[bg[pat].rgb2_max].b - b2_min;
for (row = 0; row < rpng2_info.height; ++row) {
yidx = (int)(row % bgscale);
even_odd_vert = (int)((row / bgscale) & 1);
r1 = r1_min + (r1_diff * yidx) / yidx_max;
g1 = g1_min + (g1_diff * yidx) / yidx_max;
b1 = b1_min + (b1_diff * yidx) / yidx_max;
r1_inv = r1_min + (r1_diff * (yidx_max-yidx)) / yidx_max;
g1_inv = g1_min + (g1_diff * (yidx_max-yidx)) / yidx_max;
b1_inv = b1_min + (b1_diff * (yidx_max-yidx)) / yidx_max;
r2 = r2_min + (r2_diff * yidx) / yidx_max;
g2 = g2_min + (g2_diff * yidx) / yidx_max;
b2 = b2_min + (b2_diff * yidx) / yidx_max;
r2_inv = r2_min + (r2_diff * (yidx_max-yidx)) / yidx_max;
g2_inv = g2_min + (g2_diff * (yidx_max-yidx)) / yidx_max;
b2_inv = b2_min + (b2_diff * (yidx_max-yidx)) / yidx_max;
dest = (char *)bg_data + row*bg_rowbytes;
for (i = 0; i < rpng2_info.width; ++i) {
even_odd_horiz = (int)((i / bgscale) & 1);
even_odd = even_odd_vert ^ even_odd_horiz;
invert_column =
(even_odd_horiz && (bg[pat].type & 0x10));
if (even_odd == 0) { /* gradient #1 */
if (invert_column) {
*dest++ = r1_inv;
*dest++ = g1_inv;
*dest++ = b1_inv;
} else {
*dest++ = r1;
*dest++ = g1;
*dest++ = b1;
}
} else { /* gradient #2 */
if ((invert_column && invert_gradient2) ||
(!invert_column && !invert_gradient2))
{
*dest++ = r2; /* not inverted or */
*dest++ = g2; /* doubly inverted */
*dest++ = b2;
} else {
*dest++ = r2_inv;
*dest++ = g2_inv; /* singly inverted */
*dest++ = b2_inv;
}
}
}
}
/*---------------------------------------------------------------------------
Soft gradient-diamonds with scale = bgscale. Code contributed by Adam
M. Costello.
---------------------------------------------------------------------------*/
} else if ((bg[pat].type & 0x07) == 1) {
hmax = (bgscale-1)/2; /* half the max weight of a color */
max = 2*hmax; /* the max weight of a color */
r1 = rgb[bg[pat].rgb1_max].r;
g1 = rgb[bg[pat].rgb1_max].g;
b1 = rgb[bg[pat].rgb1_max].b;
r2 = rgb[bg[pat].rgb2_max].r;
g2 = rgb[bg[pat].rgb2_max].g;
b2 = rgb[bg[pat].rgb2_max].b;
for (row = 0; row < rpng2_info.height; ++row) {
yidx = (int)(row % bgscale);
if (yidx > hmax)
yidx = bgscale-1 - yidx;
dest = (char *)bg_data + row*bg_rowbytes;
for (i = 0; i < rpng2_info.width; ++i) {
xidx = (int)(i % bgscale);
if (xidx > hmax)
xidx = bgscale-1 - xidx;
k = xidx + yidx;
*dest++ = (k*r1 + (max-k)*r2) / max;
*dest++ = (k*g1 + (max-k)*g2) / max;
*dest++ = (k*b1 + (max-k)*b2) / max;
}
}
/*---------------------------------------------------------------------------
Radial "starburst" with azimuthal sinusoids; [eventually number of sinu-
soids will equal bgscale?]. This one is slow but very cool. Code con-
tributed by Pieter S. van der Meulen (originally in Smalltalk).
---------------------------------------------------------------------------*/
} else if ((bg[pat].type & 0x07) == 2) {
uch ch;
int ii, x, y, hw, hh, grayspot;
double freq, rotate, saturate, gray, intensity;
double angle=0.0, aoffset=0.0, maxDist, dist;
double red=0.0, green=0.0, blue=0.0, hue, s, v, f, p, q, t;
hh = (int)(rpng2_info.height / 2);
hw = (int)(rpng2_info.width / 2);
/* variables for radial waves:
* aoffset: number of degrees to rotate hue [CURRENTLY NOT USED]
* freq: number of color beams originating from the center
* grayspot: size of the graying center area (anti-alias)
* rotate: rotation of the beams as a function of radius
* saturate: saturation of beams' shape azimuthally
*/
angle = CLIP(angle, 0.0, 360.0);
grayspot = CLIP(bg[pat].bg_gray, 1, (hh + hw));
freq = MAX((double)bg[pat].bg_freq, 0.0);
saturate = (double)bg[pat].bg_bsat * 0.1;
rotate = (double)bg[pat].bg_brot * 0.1;
gray = 0.0;
intensity = 0.0;
maxDist = (double)((hw*hw) + (hh*hh));
for (row = 0; row < rpng2_info.height; ++row) {
y = (int)(row - hh);
dest = (char *)bg_data + row*bg_rowbytes;
for (i = 0; i < rpng2_info.width; ++i) {
x = (int)(i - hw);
angle = (x == 0)? PI_2 : atan((double)y / (double)x);
gray = (double)MAX(ABS(y), ABS(x)) / grayspot;
gray = MIN(1.0, gray);
dist = (double)((x*x) + (y*y)) / maxDist;
intensity = cos((angle+(rotate*dist*PI)) * freq) *
gray * saturate;
intensity = (MAX(MIN(intensity,1.0),-1.0) + 1.0) * 0.5;
hue = (angle + PI) * INV_PI_360 + aoffset;
s = gray * ((double)(ABS(x)+ABS(y)) / (double)(hw + hh));
s = MIN(MAX(s,0.0), 1.0);
v = MIN(MAX(intensity,0.0), 1.0);
if (s == 0.0) {
ch = (uch)(v * 255.0);
*dest++ = ch;
*dest++ = ch;
*dest++ = ch;
} else {
if ((hue < 0.0) || (hue >= 360.0))
hue -= (((int)(hue / 360.0)) * 360.0);
hue /= 60.0;
ii = (int)hue;
f = hue - (double)ii;
p = (1.0 - s) * v;
q = (1.0 - (s * f)) * v;
t = (1.0 - (s * (1.0 - f))) * v;
if (ii == 0) { red = v; green = t; blue = p; }
else if (ii == 1) { red = q; green = v; blue = p; }
else if (ii == 2) { red = p; green = v; blue = t; }
else if (ii == 3) { red = p; green = q; blue = v; }
else if (ii == 4) { red = t; green = p; blue = v; }
else if (ii == 5) { red = v; green = p; blue = q; }
*dest++ = (uch)(red * 255.0);
*dest++ = (uch)(green * 255.0);
*dest++ = (uch)(blue * 255.0);
}
}
}
}
} /* end function rpng2_x_reload_bg_image() */
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 PHP_FUNCTION(session_set_save_handler)
{
zval ***args = NULL;
int i, num_args, argc = ZEND_NUM_ARGS();
char *name;
if (PS(session_status) != php_session_none) {
RETURN_FALSE;
}
if (argc > 0 && argc <= 2) {
zval *obj = NULL, *callback = NULL;
zend_uint func_name_len;
char *func_name;
HashPosition pos;
zend_function *default_mptr, *current_mptr;
ulong func_index;
php_shutdown_function_entry shutdown_function_entry;
zend_bool register_shutdown = 1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|b", &obj, php_session_iface_entry, ®ister_shutdown) == FAILURE) {
RETURN_FALSE;
}
/* Find implemented methods - SessionHandlerInterface */
zend_hash_internal_pointer_reset_ex(&php_session_iface_entry->function_table, &pos);
i = 0;
while (zend_hash_get_current_data_ex(&php_session_iface_entry->function_table, (void **) &default_mptr, &pos) == SUCCESS) {
zend_hash_get_current_key_ex(&php_session_iface_entry->function_table, &func_name, &func_name_len, &func_index, 0, &pos);
if (zend_hash_find(&Z_OBJCE_P(obj)->function_table, func_name, func_name_len, (void **)¤t_mptr) == SUCCESS) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
MAKE_STD_ZVAL(callback);
array_init_size(callback, 2);
Z_ADDREF_P(obj);
add_next_index_zval(callback, obj);
add_next_index_stringl(callback, func_name, func_name_len - 1, 1);
PS(mod_user_names).names[i] = callback;
} else {
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Session handler's function table is corrupt");
RETURN_FALSE;
}
zend_hash_move_forward_ex(&php_session_iface_entry->function_table, &pos);
++i;
}
/* Find implemented methods - SessionIdInterface (optional) */
zend_hash_internal_pointer_reset_ex(&php_session_id_iface_entry->function_table, &pos);
while (zend_hash_get_current_data_ex(&php_session_id_iface_entry->function_table, (void **) &default_mptr, &pos) == SUCCESS) {
zend_hash_get_current_key_ex(&php_session_id_iface_entry->function_table, &func_name, &func_name_len, &func_index, 0, &pos);
if (zend_hash_find(&Z_OBJCE_P(obj)->function_table, func_name, func_name_len, (void **)¤t_mptr) == SUCCESS) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
MAKE_STD_ZVAL(callback);
array_init_size(callback, 2);
Z_ADDREF_P(obj);
add_next_index_zval(callback, obj);
add_next_index_stringl(callback, func_name, func_name_len - 1, 1);
PS(mod_user_names).names[i] = callback;
}
zend_hash_move_forward_ex(&php_session_id_iface_entry->function_table, &pos);
++i;
}
if (register_shutdown) {
/* create shutdown function */
shutdown_function_entry.arg_count = 1;
shutdown_function_entry.arguments = (zval **) safe_emalloc(sizeof(zval *), 1, 0);
MAKE_STD_ZVAL(callback);
ZVAL_STRING(callback, "session_register_shutdown", 1);
shutdown_function_entry.arguments[0] = callback;
/* add shutdown function, removing the old one if it exists */
if (!register_user_shutdown_function("session_shutdown", sizeof("session_shutdown"), &shutdown_function_entry TSRMLS_CC)) {
zval_ptr_dtor(&callback);
efree(shutdown_function_entry.arguments);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to register session shutdown function");
RETURN_FALSE;
}
} else {
/* remove shutdown function */
remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") TSRMLS_CC);
}
if (PS(mod) && PS(session_status) == php_session_none && PS(mod) != &ps_mod_user) {
zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), "user", sizeof("user")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
RETURN_TRUE;
}
if (argc != 6 && argc != 7) {
WRONG_PARAM_COUNT;
}
if (zend_parse_parameters(argc TSRMLS_CC, "+", &args, &num_args) == FAILURE) {
return;
}
/* remove shutdown function */
remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") TSRMLS_CC);
/* at this point argc can only be 6 or 7 */
for (i = 0; i < argc; i++) {
if (!zend_is_callable(*args[i], 0, &name TSRMLS_CC)) {
efree(args);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Argument %d is not a valid callback", i+1);
efree(name);
RETURN_FALSE;
}
efree(name);
}
if (PS(mod) && PS(mod) != &ps_mod_user) {
zend_alter_ini_entry("session.save_handler", sizeof("session.save_handler"), "user", sizeof("user")-1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
for (i = 0; i < argc; i++) {
if (PS(mod_user_names).names[i] != NULL) {
zval_ptr_dtor(&PS(mod_user_names).names[i]);
}
Z_ADDREF_PP(args[i]);
PS(mod_user_names).names[i] = *args[i];
}
efree(args);
RETURN_TRUE;
}
CWE ID: CWE-416
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)
{
int i;
int j;
if (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=
mat1->numcols_) {
return 1;
}
for (i = 0; i < mat0->numrows_; i++) {
for (j = 0; j < mat0->numcols_; j++) {
if (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {
return 1;
}
}
}
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static ssize_t khugepaged_defrag_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
return single_flag_store(kobj, attr, buf, count,
TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);
}
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: virtual ~FakeURLFetcher() {
}
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 virtqueue_map_desc(unsigned int *p_num_sg, hwaddr *addr, struct iovec *iov,
unsigned int max_num_sg, bool is_write,
hwaddr pa, size_t sz)
{
unsigned num_sg = *p_num_sg;
assert(num_sg <= max_num_sg);
while (sz) {
hwaddr len = sz;
iov[num_sg].iov_base = cpu_physical_memory_map(pa, &len, is_write);
iov[num_sg].iov_len = len;
addr[num_sg] = pa;
sz -= len;
pa += len;
num_sg++;
}
*p_num_sg = num_sg;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: GF_Err pmax_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_PMAXBox *ptr = (GF_PMAXBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->maxSize);
return GF_OK;
}
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: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡვဒ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
CWE ID: CWE-20
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 MaintainContentLengthPrefsForDateChange(
base::ListValue* original_update,
base::ListValue* received_update,
int days_since_last_update) {
if (days_since_last_update == -1) {
days_since_last_update = 0;
} else if (days_since_last_update < -1) {
original_update->Clear();
received_update->Clear();
days_since_last_update = kNumDaysInHistory;
//// DailyContentLengthUpdate maintains a data saving pref. The pref is a list
//// of |kNumDaysInHistory| elements of daily total content lengths for the past
//// |kNumDaysInHistory| days.
}
DCHECK_GE(days_since_last_update, 0);
for (int i = 0;
i < days_since_last_update && i < static_cast<int>(kNumDaysInHistory);
++i) {
original_update->AppendString(base::Int64ToString(0));
received_update->AppendString(base::Int64ToString(0));
}
MaintainContentLengthPrefsWindow(original_update, kNumDaysInHistory);
MaintainContentLengthPrefsWindow(received_update, kNumDaysInHistory);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static X509 * php_openssl_x509_from_zval(zval ** val, int makeresource, long * resourceval TSRMLS_DC)
{
X509 *cert = NULL;
if (resourceval) {
*resourceval = -1;
}
if (Z_TYPE_PP(val) == IS_RESOURCE) {
/* is it an x509 resource ? */
void * what;
int type;
what = zend_fetch_resource(val TSRMLS_CC, -1, "OpenSSL X.509", &type, 1, le_x509);
if (!what) {
return NULL;
}
/* this is so callers can decide if they should free the X509 */
if (resourceval) {
*resourceval = Z_LVAL_PP(val);
}
if (type == le_x509) {
return (X509*)what;
}
/* other types could be used here - eg: file pointers and read in the data from them */
return NULL;
}
if (!(Z_TYPE_PP(val) == IS_STRING || Z_TYPE_PP(val) == IS_OBJECT)) {
return NULL;
}
/* force it to be a string and check if it refers to a file */
convert_to_string_ex(val);
if (Z_STRLEN_PP(val) > 7 && memcmp(Z_STRVAL_PP(val), "file://", sizeof("file://") - 1) == 0) {
/* read cert from the named file */
BIO *in;
if (php_openssl_safe_mode_chk(Z_STRVAL_PP(val) + (sizeof("file://") - 1) TSRMLS_CC)) {
return NULL;
}
in = BIO_new_file(Z_STRVAL_PP(val) + (sizeof("file://") - 1), "r");
if (in == NULL) {
return NULL;
}
cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
BIO_free(in);
} else {
BIO *in;
in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
if (in == NULL) {
return NULL;
}
#ifdef TYPEDEF_D2I_OF
cert = (X509 *) PEM_ASN1_read_bio((d2i_of_void *)d2i_X509, PEM_STRING_X509, in, NULL, NULL, NULL);
#else
cert = (X509 *) PEM_ASN1_read_bio((char *(*)())d2i_X509, PEM_STRING_X509, in, NULL, NULL, NULL);
#endif
BIO_free(in);
}
if (cert && makeresource && resourceval) {
*resourceval = zend_list_insert(cert, le_x509);
}
return cert;
}
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 From2iToMono_32( const LVM_INT32 *src,
LVM_INT32 *dst,
LVM_INT16 n)
{
LVM_INT16 ii;
LVM_INT32 Temp;
for (ii = n; ii != 0; ii--)
{
Temp = (*src>>1);
src++;
Temp +=(*src>>1);
src++;
*dst = Temp;
dst++;
}
return;
}
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: daemon_msg_findallif_req(uint8 ver, struct daemon_slpars *pars, uint32 plen)
{
char errbuf[PCAP_ERRBUF_SIZE]; // buffer for network errors
char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client
char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered
int sendbufidx = 0; // index which keeps the number of bytes currently buffered
pcap_if_t *alldevs = NULL; // pointer to the header of the interface chain
pcap_if_t *d; // temp pointer needed to scan the interface chain
struct pcap_addr *address; // pcap structure that keeps a network address of an interface
struct rpcap_findalldevs_if *findalldevs_if;// rpcap structure that packet all the data of an interface together
uint16 nif = 0; // counts the number of interface listed
if (rpcapd_discard(pars->sockctrl, plen) == -1)
{
return -1;
}
if (pcap_findalldevs(&alldevs, errmsgbuf) == -1)
goto error;
if (alldevs == NULL)
{
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_NOREMOTEIF,
"No interfaces found! Make sure libpcap/WinPcap is properly installed"
" and you have the right to access to the remote device.",
errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
for (d = alldevs; d != NULL; d = d->next)
{
nif++;
if (d->description)
plen+= strlen(d->description);
if (d->name)
plen+= strlen(d->name);
plen+= sizeof(struct rpcap_findalldevs_if);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
plen+= (sizeof(struct rpcap_sockaddr) * 4);
break;
default:
break;
}
}
}
if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
rpcap_createhdr((struct rpcap_header *) sendbuf, ver,
RPCAP_MSG_FINDALLIF_REPLY, nif, plen);
for (d = alldevs; d != NULL; d = d->next)
{
uint16 lname, ldescr;
findalldevs_if = (struct rpcap_findalldevs_if *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_findalldevs_if), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
memset(findalldevs_if, 0, sizeof(struct rpcap_findalldevs_if));
if (d->description) ldescr = (short) strlen(d->description);
else ldescr = 0;
if (d->name) lname = (short) strlen(d->name);
else lname = 0;
findalldevs_if->desclen = htons(ldescr);
findalldevs_if->namelen = htons(lname);
findalldevs_if->flags = htonl(d->flags);
for (address = d->addresses; address != NULL; address = address->next)
{
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
findalldevs_if->naddr++;
break;
default:
break;
}
}
findalldevs_if->naddr = htons(findalldevs_if->naddr);
if (sock_bufferize(d->name, lname, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
if (sock_bufferize(d->description, ldescr, sendbuf, &sendbufidx,
RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errmsgbuf,
PCAP_ERRBUF_SIZE) == -1)
goto error;
for (address = d->addresses; address != NULL; address = address->next)
{
struct rpcap_sockaddr *sockaddr;
/*
* Send only IPv4 and IPv6 addresses over the wire.
*/
switch (address->addr->sa_family)
{
case AF_INET:
#ifdef AF_INET6
case AF_INET6:
#endif
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->addr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->netmask, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->broadaddr, sockaddr);
sockaddr = (struct rpcap_sockaddr *) &sendbuf[sendbufidx];
if (sock_bufferize(NULL, sizeof(struct rpcap_sockaddr), NULL,
&sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errmsgbuf, PCAP_ERRBUF_SIZE) == -1)
goto error;
daemon_seraddr((struct sockaddr_storage *) address->dstaddr, sockaddr);
break;
default:
break;
}
}
}
pcap_freealldevs(alldevs);
if (sock_send(pars->sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
error:
if (alldevs)
pcap_freealldevs(alldevs);
if (rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_FINDALLIF,
errmsgbuf, errbuf) == -1)
{
rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf);
return -1;
}
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void CrostiniUpgrader::OnUpgradeContainerProgress(
const ContainerId& container_id,
UpgradeContainerProgressStatus status,
const std::vector<std::string>& messages) {
if (container_id != container_id_) {
return;
}
switch (status) {
case UpgradeContainerProgressStatus::UPGRADING:
for (auto& observer : upgrader_observers_) {
observer.OnUpgradeProgress(messages);
}
break;
case UpgradeContainerProgressStatus::SUCCEEDED:
for (auto& observer : upgrader_observers_) {
observer.OnUpgradeSucceeded();
}
break;
case UpgradeContainerProgressStatus::FAILED:
for (auto& observer : upgrader_observers_) {
observer.OnUpgradeFailed();
}
break;
}
}
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: error::Error GLES2DecoderImpl::HandleDrawElements(
uint32 immediate_data_size, const gles2::DrawElements& c) {
if (!bound_element_array_buffer_ ||
bound_element_array_buffer_->IsDeleted()) {
SetGLError(GL_INVALID_OPERATION,
"glDrawElements: No element array buffer bound");
return error::kNoError;
}
GLenum mode = c.mode;
GLsizei count = c.count;
GLenum type = c.type;
int32 offset = c.index_offset;
if (count < 0) {
SetGLError(GL_INVALID_VALUE, "glDrawElements: count < 0");
return error::kNoError;
}
if (offset < 0) {
SetGLError(GL_INVALID_VALUE, "glDrawElements: offset < 0");
return error::kNoError;
}
if (!validators_->draw_mode.IsValid(mode)) {
SetGLError(GL_INVALID_ENUM, "glDrawElements: mode GL_INVALID_ENUM");
return error::kNoError;
}
if (!validators_->index_type.IsValid(type)) {
SetGLError(GL_INVALID_ENUM, "glDrawElements: type GL_INVALID_ENUM");
return error::kNoError;
}
if (!CheckFramebufferComplete("glDrawElements")) {
return error::kNoError;
}
if (count == 0) {
return error::kNoError;
}
GLuint max_vertex_accessed;
if (!bound_element_array_buffer_->GetMaxValueForRange(
offset, count, type, &max_vertex_accessed)) {
SetGLError(GL_INVALID_OPERATION,
"glDrawElements: range out of bounds for buffer");
return error::kNoError;
}
if (IsDrawValid(max_vertex_accessed)) {
bool simulated_attrib_0 = SimulateAttrib0(max_vertex_accessed);
bool simulated_fixed_attribs = false;
if (SimulateFixedAttribs(max_vertex_accessed, &simulated_fixed_attribs)) {
bool textures_set = SetBlackTextureForNonRenderableTextures();
ApplyDirtyState();
const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset);
glDrawElements(mode, count, type, indices);
if (textures_set) {
RestoreStateForNonRenderableTextures();
}
if (simulated_fixed_attribs) {
RestoreStateForSimulatedFixedAttribs();
}
}
if (simulated_attrib_0) {
RestoreStateForSimulatedAttrib0();
}
if (WasContextLost()) {
LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements.";
return error::kLostContext;
}
}
return error::kNoError;
}
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: char **XGetFontPath(
register Display *dpy,
int *npaths) /* RETURN */
{
xGetFontPathReply rep;
unsigned long nbytes = 0;
char **flist = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
LockDisplay(dpy);
GetEmptyReq (GetFontPath, req);
(void) _XReply (dpy, (xReply *) &rep, 0, xFalse);
if (rep.nPaths) {
flist = Xmalloc(rep.nPaths * sizeof (char *));
if (rep.length < (INT_MAX >> 2)) {
nbytes = (unsigned long) rep.length << 2;
ch = Xmalloc (nbytes + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, nbytes);
/*
* unpack into null terminated strings.
*/
chend = ch + nbytes;
length = *ch;
for (i = 0; i < rep.nPaths; i++) {
if (ch + length < chend) {
flist[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
flist[i] = NULL;
}
}
*npaths = count;
UnlockDisplay(dpy);
SyncHandle();
return (flist);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
unsigned int to, struct ts_config *config,
struct ts_state *state)
{
unsigned int ret;
config->get_next_block = skb_ts_get_next_block;
config->finish = skb_ts_finish;
skb_prepare_seq_read(skb, from, to, TS_SKB_CB(state));
ret = textsearch_find(config, state);
return (ret <= to - from ? ret : UINT_MAX);
}
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 MemBackendImpl::SetMaxSize(int max_bytes) {
static_assert(sizeof(max_bytes) == sizeof(max_size_),
"unsupported int model");
if (max_bytes < 0)
return false;
if (!max_bytes)
return true;
max_size_ = max_bytes;
return true;
}
CWE ID: CWE-416
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(PharFileInfo, __construct)
{
char *fname, *arch, *entry, *error;
size_t fname_len;
int arch_len, entry_len;
phar_entry_object *entry_obj;
phar_entry_info *entry_info;
phar_archive_data *phar_data;
zval *zobj = getThis(), arg1;
if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
return;
}
entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset);
if (entry_obj->entry) {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice");
return;
}
if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0,
"'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname);
return;
}
if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) {
efree(arch);
efree(entry);
if (error) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0,
"Cannot open phar file '%s': %s", fname, error);
efree(error);
} else {
zend_throw_exception_ex(spl_ce_RuntimeException, 0,
"Cannot open phar file '%s'", fname);
}
return;
}
if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0,
"Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : "");
efree(arch);
efree(entry);
return;
}
efree(arch);
efree(entry);
entry_obj->entry = entry_info;
ZVAL_STRINGL(&arg1, fname, fname_len);
zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj),
&spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1);
zval_ptr_dtor(&arg1);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void vmx_enable_intercept_msr_read_x2apic(u32 msr)
{
__vmx_enable_intercept_for_msr(vmx_msr_bitmap_legacy_x2apic,
msr, MSR_TYPE_R);
__vmx_enable_intercept_for_msr(vmx_msr_bitmap_longmode_x2apic,
msr, MSR_TYPE_R);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: unsigned long long Track::GetCodecDelay() const
{
return m_info.codecDelay;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void php_snmp_getvalue(struct variable_list *vars, zval *snmpval TSRMLS_DC, int valueretrieval)
{
zval *val;
char sbuf[512];
char *buf = &(sbuf[0]);
char *dbuf = (char *)NULL;
int buflen = sizeof(sbuf) - 1;
int val_len = vars->val_len;
/* use emalloc() for large values, use static array otherwize */
/* There is no way to know the size of buffer snprint_value() needs in order to print a value there.
* So we are forced to probe it
*/
while ((valueretrieval & SNMP_VALUE_PLAIN) == 0) {
*buf = '\0';
if (snprint_value(buf, buflen, vars->name, vars->name_length, vars) == -1) {
if (val_len > 512*1024) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "snprint_value() asks for a buffer more than 512k, Net-SNMP bug?");
break;
}
/* buffer is not long enough to hold full output, double it */
val_len *= 2;
} else {
break;
}
if (buf == dbuf) {
dbuf = (char *)erealloc(dbuf, val_len + 1);
} else {
dbuf = (char *)emalloc(val_len + 1);
}
if (!dbuf) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
buf = &(sbuf[0]);
buflen = sizeof(sbuf) - 1;
break;
}
buf = dbuf;
buflen = val_len;
}
if((valueretrieval & SNMP_VALUE_PLAIN) && val_len > buflen){
if ((dbuf = (char *)emalloc(val_len + 1))) {
buf = dbuf;
buflen = val_len;
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno));
}
}
MAKE_STD_ZVAL(val);
if (valueretrieval & SNMP_VALUE_PLAIN) {
*buf = 0;
switch (vars->type) {
case ASN_BIT_STR: /* 0x03, asn1.h */
ZVAL_STRINGL(val, (char *)vars->val.bitstring, vars->val_len, 1);
break;
case ASN_OCTET_STR: /* 0x04, asn1.h */
case ASN_OPAQUE: /* 0x44, snmp_impl.h */
ZVAL_STRINGL(val, (char *)vars->val.string, vars->val_len, 1);
break;
case ASN_NULL: /* 0x05, asn1.h */
ZVAL_NULL(val);
break;
case ASN_OBJECT_ID: /* 0x06, asn1.h */
snprint_objid(buf, buflen, vars->val.objid, vars->val_len / sizeof(oid));
ZVAL_STRING(val, buf, 1);
break;
case ASN_IPADDRESS: /* 0x40, snmp_impl.h */
snprintf(buf, buflen, "%d.%d.%d.%d",
(vars->val.string)[0], (vars->val.string)[1],
(vars->val.string)[2], (vars->val.string)[3]);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_COUNTER: /* 0x41, snmp_impl.h */
case ASN_GAUGE: /* 0x42, snmp_impl.h */
/* ASN_UNSIGNED is the same as ASN_GAUGE */
case ASN_TIMETICKS: /* 0x43, snmp_impl.h */
case ASN_UINTEGER: /* 0x47, snmp_impl.h */
snprintf(buf, buflen, "%lu", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
case ASN_INTEGER: /* 0x02, asn1.h */
snprintf(buf, buflen, "%ld", *vars->val.integer);
buf[buflen]=0;
ZVAL_STRING(val, buf, 1);
break;
#if defined(NETSNMP_WITH_OPAQUE_SPECIAL_TYPES) || defined(OPAQUE_SPECIAL_TYPES)
case ASN_OPAQUE_FLOAT: /* 0x78, asn1.h */
snprintf(buf, buflen, "%f", *vars->val.floatVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_DOUBLE: /* 0x79, asn1.h */
snprintf(buf, buflen, "%Lf", *vars->val.doubleVal);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_I64: /* 0x80, asn1.h */
printI64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
case ASN_OPAQUE_U64: /* 0x81, asn1.h */
#endif
case ASN_COUNTER64: /* 0x46, snmp_impl.h */
printU64(buf, vars->val.counter64);
ZVAL_STRING(val, buf, 1);
break;
default:
ZVAL_STRING(val, "Unknown value type", 1);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown value type: %u", vars->type);
break;
}
} else /* use Net-SNMP value translation */ {
/* we have desired string in buffer, just use it */
ZVAL_STRING(val, buf, 1);
}
if (valueretrieval & SNMP_VALUE_OBJECT) {
object_init(snmpval);
add_property_long(snmpval, "type", vars->type);
add_property_zval(snmpval, "value", val);
} else {
*snmpval = *val;
zval_copy_ctor(snmpval);
}
zval_ptr_dtor(&val);
if(dbuf){ /* malloc was used to store value */
efree(dbuf);
}
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void RenderFrameImpl::PepperCaretPositionChanged(
PepperPluginInstanceImpl* instance) {
if (instance != focused_pepper_plugin_)
return;
GetLocalRootRenderWidget()->UpdateSelectionBounds();
}
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: ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
{
connmgr_set_fail_mode(p->connmgr, fail_mode);
}
CWE ID: CWE-617
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BluetoothDeviceChromeOS::OnRegisterAgent(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Agent registered, now pairing";
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
Pair(object_path_,
base::Bind(&BluetoothDeviceChromeOS::OnPair,
weak_ptr_factory_.GetWeakPtr(),
callback, error_callback),
base::Bind(&BluetoothDeviceChromeOS::OnPairError,
weak_ptr_factory_.GetWeakPtr(),
error_callback));
}
CWE ID:
Target: 1
Example 2:
Code: static void mem_cgroup_move_task(struct cgroup_subsys *ss,
struct cgroup *cont,
struct cgroup_taskset *tset)
{
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void internal_cleaned_up_handler(wifi_handle handle)
{
hal_info *info = getHalInfo(handle);
wifi_cleaned_up_handler cleaned_up_handler = info->cleaned_up_handler;
if (info->cmd_sock != 0) {
close(info->cleanup_socks[0]);
close(info->cleanup_socks[1]);
nl_socket_free(info->cmd_sock);
nl_socket_free(info->event_sock);
info->cmd_sock = NULL;
info->event_sock = NULL;
}
(*cleaned_up_handler)(handle);
pthread_mutex_destroy(&info->cb_lock);
free(info);
ALOGI("Internal cleanup completed");
}
CWE ID: CWE-264
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void sig_server_connect_copy(SERVER_CONNECT_REC **dest,
IRC_SERVER_CONNECT_REC *src)
{
IRC_SERVER_CONNECT_REC *rec;
g_return_if_fail(dest != NULL);
if (!IS_IRC_SERVER_CONNECT(src))
return;
rec = g_new0(IRC_SERVER_CONNECT_REC, 1);
rec->chat_type = IRC_PROTOCOL;
rec->max_cmds_at_once = src->max_cmds_at_once;
rec->cmd_queue_speed = src->cmd_queue_speed;
rec->max_query_chans = src->max_query_chans;
rec->max_kicks = src->max_kicks;
rec->max_modes = src->max_modes;
rec->max_msgs = src->max_msgs;
rec->max_whois = src->max_whois;
rec->usermode = g_strdup(src->usermode);
rec->alternate_nick = g_strdup(src->alternate_nick);
rec->sasl_mechanism = src->sasl_mechanism;
rec->sasl_username = src->sasl_username;
rec->sasl_password = src->sasl_password;
*dest = (SERVER_CONNECT_REC *) rec;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void ScriptController::collectGarbage()
{
v8::HandleScope handleScope;
v8::Persistent<v8::Context> v8Context = v8::Context::New();
if (v8Context.IsEmpty())
return;
{
v8::Context::Scope scope(v8Context);
v8::Local<v8::String> source = v8::String::New("if (gc) gc();");
v8::Local<v8::String> name = v8::String::New("gc");
v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
if (!script.IsEmpty()) {
V8RecursionScope::MicrotaskSuppression scope;
script->Run();
}
}
v8Context.Dispose();
}
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: person_get_offset(const person_t* person)
{
return mk_point2(person->x_offset, person->y_offset);
}
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: ikev2_ke_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_ke ke;
const struct ikev2_ke *k;
k = (const struct ikev2_ke *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&ke, ext, sizeof(ke));
ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical);
ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8,
STR_OR_ID(ntohs(ke.ke_group), dh_p_map)));
if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8))
goto trunc;
}
return (const u_char *)ext + ntohs(ke.h.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void withScriptStateAttributeRaisesAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectV8Internal::withScriptStateAttributeRaisesAttributeGetter(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 gdImageGifCtx(gdImagePtr im, gdIOCtxPtr out)
{
gdImagePtr pim = 0, tim = im;
int interlace, BitsPerPixel;
interlace = im->interlace;
if (im->trueColor) {
/* Expensive, but the only way that produces an
acceptable result: mix down to a palette
based temporary image. */
pim = gdImageCreatePaletteFromTrueColor(im, 1, 256);
if (!pim) {
return;
}
tim = pim;
}
BitsPerPixel = colorstobpp(tim->colorsTotal);
/* All set, let's do it. */
GIFEncode(
out, tim->sx, tim->sy, tim->interlace, 0, tim->transparent, BitsPerPixel,
tim->red, tim->green, tim->blue, tim);
if (pim) {
/* Destroy palette based temporary image. */
gdImageDestroy( pim);
}
}
CWE ID: CWE-415
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GDataDirectory::GDataDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service)
: GDataEntry(parent, directory_service) {
file_info_.is_directory = true;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void udp4_proc_exit(void)
{
unregister_pernet_subsys(&udp4_net_ops);
}
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: virtual InputMethodDescriptor current_input_method() const {
return current_input_method_;
}
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: stringprep_strerror (Stringprep_rc rc)
{
const char *p;
bindtextdomain (PACKAGE, LOCALEDIR);
switch (rc)
{
case STRINGPREP_OK:
p = _("Success");
break;
case STRINGPREP_CONTAINS_UNASSIGNED:
p = _("Forbidden unassigned code points in input");
break;
case STRINGPREP_CONTAINS_PROHIBITED:
p = _("Prohibited code points in input");
break;
case STRINGPREP_BIDI_BOTH_L_AND_RAL:
p = _("Conflicting bidirectional properties in input");
break;
case STRINGPREP_BIDI_LEADTRAIL_NOT_RAL:
p = _("Malformed bidirectional string");
break;
case STRINGPREP_BIDI_CONTAINS_PROHIBITED:
p = _("Prohibited bidirectional code points in input");
break;
case STRINGPREP_TOO_SMALL_BUFFER:
p = _("Output would exceed the buffer space provided");
break;
case STRINGPREP_PROFILE_ERROR:
p = _("Error in stringprep profile definition");
break;
case STRINGPREP_FLAG_ERROR:
p = _("Flag conflict with profile");
break;
case STRINGPREP_UNKNOWN_PROFILE:
case STRINGPREP_UNKNOWN_PROFILE:
p = _("Unknown profile");
break;
case STRINGPREP_NFKC_FAILED:
p = _("Unicode normalization failed (internal error)");
break;
default:
p = _("Unknown error");
break;
}
return p;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void release_tty(struct tty_struct *tty, int idx)
{
/* This should always be true but check for the moment */
WARN_ON(tty->index != idx);
WARN_ON(!mutex_is_locked(&tty_mutex));
if (tty->ops->shutdown)
tty->ops->shutdown(tty);
tty_free_termios(tty);
tty_driver_remove_tty(tty->driver, tty);
tty->port->itty = NULL;
if (tty->link)
tty->link->port->itty = NULL;
tty_buffer_cancel_work(tty->port);
tty_kref_put(tty->link);
tty_kref_put(tty);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool RenderFrameHostManager::CanSubframeSwapProcess(
const GURL& dest_url,
SiteInstance* source_instance,
SiteInstance* dest_instance,
bool was_server_redirect) {
DCHECK(!source_instance || !dest_instance);
GURL resolved_url = dest_url;
if (url::Origin::Create(resolved_url).unique()) {
if (source_instance) {
resolved_url = source_instance->GetSiteURL();
} else if (dest_instance) {
resolved_url = dest_instance->GetSiteURL();
} else {
if (!was_server_redirect)
return false;
}
}
if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(),
resolved_url)) {
DCHECK(!dest_instance ||
dest_instance == render_frame_host_->GetSiteInstance());
return false;
}
return true;
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Huff_Compress(msg_t *mbuf, int offset) {
int i, ch, size;
byte seq[65536];
byte* buffer;
huff_t huff;
size = mbuf->cursize - offset;
buffer = mbuf->data+ + offset;
if (size<=0) {
return;
}
Com_Memset(&huff, 0, sizeof(huff_t));
huff.tree = huff.lhead = huff.loc[NYT] = &(huff.nodeList[huff.blocNode++]);
huff.tree->symbol = NYT;
huff.tree->weight = 0;
huff.lhead->next = huff.lhead->prev = NULL;
huff.tree->parent = huff.tree->left = huff.tree->right = NULL;
seq[0] = (size>>8);
seq[1] = size&0xff;
bloc = 16;
for (i=0; i<size; i++ ) {
ch = buffer[i];
Huff_transmit(&huff, ch, seq); /* Transmit symbol */
Huff_addRef(&huff, (byte)ch); /* Do update */
}
bloc += 8; // next byte
mbuf->cursize = (bloc>>3) + offset;
Com_Memcpy(mbuf->data+offset, seq, (bloc>>3));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: v8::Persistent<v8::FunctionTemplate> V8TestInterface::GetTemplate()
{
V8BindingPerIsolateData* data = V8BindingPerIsolateData::current();
V8BindingPerIsolateData::TemplateMap::iterator result = data->templateMap().find(&info);
if (result != data->templateMap().end())
return result->second;
v8::HandleScope handleScope;
v8::Persistent<v8::FunctionTemplate> templ =
ConfigureV8TestInterfaceTemplate(GetRawTemplate());
data->templateMap().add(&info, templ);
return templ;
}
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: ofpact_put_reg_load(struct ofpbuf *ofpacts, const struct mf_field *field,
const void *value, const void *mask)
{
struct ofpact_set_field *sf = ofpact_put_set_field(ofpacts, field, value,
mask);
sf->ofpact.raw = NXAST_RAW_REG_LOAD;
return sf;
}
CWE ID:
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: set_store_for_write(png_store *ps, png_infopp ppi,
PNG_CONST char * volatile name)
{
anon_context(ps);
Try
{
if (ps->pwrite != NULL)
png_error(ps->pwrite, "write store already in use");
store_write_reset(ps);
safecat(ps->wname, sizeof ps->wname, 0, name);
/* Don't do the slow memory checks if doing a speed test, also if user
* memory is not supported we can't do it anyway.
*/
# ifdef PNG_USER_MEM_SUPPORTED
if (!ps->speed)
ps->pwrite = png_create_write_struct_2(PNG_LIBPNG_VER_STRING,
ps, store_error, store_warning, &ps->write_memory_pool,
store_malloc, store_free);
else
# endif
ps->pwrite = png_create_write_struct(PNG_LIBPNG_VER_STRING,
ps, store_error, store_warning);
png_set_write_fn(ps->pwrite, ps, store_write, store_flush);
# ifdef PNG_SET_OPTION_SUPPORTED
{
int opt;
for (opt=0; opt<ps->noptions; ++opt)
if (png_set_option(ps->pwrite, ps->options[opt].option,
ps->options[opt].setting) == PNG_OPTION_INVALID)
png_error(ps->pwrite, "png option invalid");
}
# endif
if (ppi != NULL)
*ppi = ps->piwrite = png_create_info_struct(ps->pwrite);
}
Catch_anonymous
return NULL;
return ps->pwrite;
}
CWE ID:
Target: 1
Example 2:
Code: static RBinFile *r_bin_file_create_append(RBin *bin, const char *file,
const ut8 *bytes, ut64 sz,
ut64 file_sz, int rawstr, int fd,
const char *xtrname, bool steal_ptr) {
RBinFile *bf = r_bin_file_new (bin, file, bytes, sz, file_sz, rawstr,
fd, xtrname, bin->sdb, steal_ptr);
if (bf) {
r_list_append (bin->binfiles, bf);
}
return bf;
}
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: SProcPseudoramiXQueryScreens(ClientPtr client)
{
REQUEST(xXineramaQueryScreensReq);
TRACE;
swaps(&stuff->length);
REQUEST_SIZE_MATCH(xXineramaQueryScreensReq);
return ProcPseudoramiXQueryScreens(client);
}
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 read_request_line(request_rec *r, apr_bucket_brigade *bb)
{
const char *ll;
const char *uri;
const char *pro;
unsigned int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
char http[5];
apr_size_t len;
int num_blank_lines = 0;
int max_blank_lines = r->server->limit_req_fields;
core_server_config *conf = ap_get_core_module_config(r->server->module_config);
int strict = conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT;
int enforce_strict = !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY);
if (max_blank_lines <= 0) {
max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS;
}
/* Read past empty lines until we get a real request line,
* a read error, the connection closes (EOF), or we timeout.
*
* We skip empty lines because browsers have to tack a CRLF on to the end
* of POSTs to support old CERN webservers. But note that we may not
* have flushed any previous response completely to the client yet.
* We delay the flush as long as possible so that we can improve
* performance for clients that are pipelining requests. If a request
* is pipelined then we won't block during the (implicit) read() below.
* If the requests aren't pipelined, then the client is still waiting
* for the final buffer flush from us, and we will block in the implicit
* read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
* have to block during a read.
*/
do {
apr_status_t rv;
/* ensure ap_rgetline allocates memory each time thru the loop
* if there are empty lines
*/
r->the_request = NULL;
rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),
&len, r, 0, bb);
if (rv != APR_SUCCESS) {
r->request_time = apr_time_now();
/* ap_rgetline returns APR_ENOSPC if it fills up the
* buffer before finding the end-of-line. This is only going to
* happen if it exceeds the configured limit for a request-line.
*/
if (APR_STATUS_IS_ENOSPC(rv)) {
r->status = HTTP_REQUEST_URI_TOO_LARGE;
r->proto_num = HTTP_VERSION(1,0);
r->protocol = apr_pstrdup(r->pool, "HTTP/1.0");
}
else if (APR_STATUS_IS_TIMEUP(rv)) {
r->status = HTTP_REQUEST_TIME_OUT;
}
else if (APR_STATUS_IS_EINVAL(rv)) {
r->status = HTTP_BAD_REQUEST;
}
return 0;
}
} while ((len <= 0) && (++num_blank_lines < max_blank_lines));
if (APLOGrtrace5(r)) {
ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r,
"Request received from client: %s",
ap_escape_logitem(r->pool, r->the_request));
}
r->request_time = apr_time_now();
ll = r->the_request;
r->method = ap_getword_white(r->pool, &ll);
uri = ap_getword_white(r->pool, &ll);
/* Provide quick information about the request method as soon as known */
r->method_number = ap_method_number_of(r->method);
if (r->method_number == M_GET && r->method[0] == 'H') {
r->header_only = 1;
}
ap_parse_uri(r, uri);
if (ll[0]) {
r->assbackwards = 0;
pro = ll;
len = strlen(ll);
} else {
r->assbackwards = 1;
pro = "HTTP/0.9";
len = 8;
if (conf->http09_enable == AP_HTTP09_DISABLE) {
r->status = HTTP_VERSION_NOT_SUPPORTED;
r->protocol = apr_pstrmemdup(r->pool, pro, len);
/* If we deny 0.9, send error message with 1.x */
r->assbackwards = 0;
r->proto_num = HTTP_VERSION(0, 9);
r->connection->keepalive = AP_CONN_CLOSE;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401)
"HTTP/0.9 denied by server configuration");
return 0;
}
}
r->protocol = apr_pstrmemdup(r->pool, pro, len);
/* Avoid sscanf in the common case */
if (len == 8
&& pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P'
&& pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.'
&& apr_isdigit(pro[7])) {
r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
}
else {
if (strict) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418)
"Invalid protocol '%s'", r->protocol);
if (enforce_strict) {
r->status = HTTP_BAD_REQUEST;
return 0;
}
}
if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor)
&& (strcasecmp("http", http) == 0)
&& (minor < HTTP_VERSION(1, 0)) ) { /* don't allow HTTP/0.1000 */
r->proto_num = HTTP_VERSION(major, minor);
}
else {
r->proto_num = HTTP_VERSION(1, 0);
}
}
if (strict) {
int err = 0;
if (ap_has_cntrl(r->the_request)) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02420)
"Request line must not contain control characters");
err = HTTP_BAD_REQUEST;
}
if (r->parsed_uri.fragment) {
/* RFC3986 3.5: no fragment */
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421)
"URI must not contain a fragment");
err = HTTP_BAD_REQUEST;
}
else if (r->parsed_uri.user || r->parsed_uri.password) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422)
"URI must not contain a username/password");
err = HTTP_BAD_REQUEST;
}
else if (r->method_number == M_INVALID) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423)
"Invalid HTTP method string: %s", r->method);
err = HTTP_NOT_IMPLEMENTED;
}
else if (r->assbackwards == 0 && r->proto_num < HTTP_VERSION(1, 0)) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02424)
"HTTP/0.x does not take a protocol");
err = HTTP_BAD_REQUEST;
}
if (err && enforce_strict) {
r->status = err;
return 0;
}
}
return 1;
}
CWE ID:
Target: 1
Example 2:
Code: void Launcher::UpdateBackground(int alpha) {
ui::Layer* layer = widget_->GetNativeView()->layer();
layer->SetColor(SkColorSetARGB(alpha, 0, 0, 0));
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,
struct vsock_sock *vsk,
struct msghdr *msg, size_t len,
int flags)
{
int err;
int noblock;
struct vmci_datagram *dg;
size_t payload_len;
struct sk_buff *skb;
noblock = flags & MSG_DONTWAIT;
if (flags & MSG_OOB || flags & MSG_ERRQUEUE)
return -EOPNOTSUPP;
msg->msg_namelen = 0;
/* Retrieve the head sk_buff from the socket's receive queue. */
err = 0;
skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);
if (err)
return err;
if (!skb)
return -EAGAIN;
dg = (struct vmci_datagram *)skb->data;
if (!dg)
/* err is 0, meaning we read zero bytes. */
goto out;
payload_len = dg->payload_size;
/* Ensure the sk_buff matches the payload size claimed in the packet. */
if (payload_len != skb->len - sizeof(*dg)) {
err = -EINVAL;
goto out;
}
if (payload_len > len) {
payload_len = len;
msg->msg_flags |= MSG_TRUNC;
}
/* Place the datagram payload in the user's iovec. */
err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov,
payload_len);
if (err)
goto out;
if (msg->msg_name) {
struct sockaddr_vm *vm_addr;
/* Provide the address of the sender. */
vm_addr = (struct sockaddr_vm *)msg->msg_name;
vsock_addr_init(vm_addr, dg->src.context, dg->src.resource);
msg->msg_namelen = sizeof(*vm_addr);
}
err = payload_len;
out:
skb_free_datagram(&vsk->sk, skb);
return err;
}
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: PrintPreviewUI::~PrintPreviewUI() {
print_preview_data_service()->RemoveEntry(preview_ui_addr_str_);
g_print_preview_request_id_map.Get().Erase(preview_ui_addr_str_);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
{
int be;
if (get_user(be, argp))
return -EFAULT;
if (be)
tun->flags |= TUN_VNET_BE;
else
tun->flags &= ~TUN_VNET_BE;
return 0;
}
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: long long Cluster::GetPosition() const
{
const long long pos = m_element_start - m_pSegment->m_start;
assert(pos >= 0);
return pos;
}
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: jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate)
{
jpc_ms_t *ms;
jpc_mstabent_t *mstabent;
jas_stream_t *tmpstream;
if (!(ms = jpc_ms_create(0))) {
return 0;
}
/* Get the marker type. */
if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN ||
ms->id > JPC_MS_MAX) {
jpc_ms_destroy(ms);
return 0;
}
mstabent = jpc_mstab_lookup(ms->id);
ms->ops = &mstabent->ops;
/* Get the marker segment length and parameters if present. */
/* Note: It is tacitly assumed that a marker segment cannot have
parameters unless it has a length field. That is, there cannot
be a parameters field without a length field and vice versa. */
if (JPC_MS_HASPARMS(ms->id)) {
/* Get the length of the marker segment. */
if (jpc_getuint16(in, &ms->len) || ms->len < 3) {
jpc_ms_destroy(ms);
return 0;
}
/* Calculate the length of the marker segment parameters. */
ms->len -= 2;
/* Create and prepare a temporary memory stream from which to
read the marker segment parameters. */
/* Note: This approach provides a simple way of ensuring that
we never read beyond the end of the marker segment (even if
the marker segment length is errantly set too small). */
if (!(tmpstream = jas_stream_memopen(0, 0))) {
jpc_ms_destroy(ms);
return 0;
}
if (jas_stream_copy(tmpstream, in, ms->len) ||
jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) {
jas_stream_close(tmpstream);
jpc_ms_destroy(ms);
return 0;
}
/* Get the marker segment parameters. */
if ((*ms->ops->getparms)(ms, cstate, tmpstream)) {
ms->ops = 0;
jpc_ms_destroy(ms);
jas_stream_close(tmpstream);
return 0;
}
if (jas_getdbglevel() > 0) {
jpc_ms_dump(ms, stderr);
}
if (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) {
jas_eprintf(
"warning: trailing garbage in marker segment (%ld bytes)\n",
ms->len - jas_stream_tell(tmpstream));
}
/* Close the temporary stream. */
jas_stream_close(tmpstream);
} else {
/* There are no marker segment parameters. */
ms->len = 0;
if (jas_getdbglevel() > 0) {
jpc_ms_dump(ms, stderr);
}
}
/* Update the code stream state information based on the type of
marker segment read. */
/* Note: This is a bit of a hack, but I'm not going to define another
type of virtual function for this one special case. */
if (ms->id == JPC_MS_SIZ) {
cstate->numcomps = ms->parms.siz.numcomps;
}
return ms;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void DiskCacheBackendTest::BackendEviction() {
const int kMaxSize = 200 * 1024;
const int kMaxEntryCount = 20;
const int kWriteSize = kMaxSize / kMaxEntryCount;
const int kWriteEntryCount = kMaxEntryCount * 2;
static_assert(kWriteEntryCount * kWriteSize > kMaxSize,
"must write more than MaxSize");
SetMaxSize(kMaxSize);
InitSparseCache(nullptr, nullptr);
scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(kWriteSize));
CacheTestFillBuffer(buffer->data(), kWriteSize, false);
std::string key_prefix("prefix");
for (int i = 0; i < kWriteEntryCount; ++i) {
AddDelay();
disk_cache::Entry* entry = NULL;
ASSERT_THAT(CreateEntry(key_prefix + base::IntToString(i), &entry), IsOk());
disk_cache::ScopedEntryPtr entry_closer(entry);
EXPECT_EQ(kWriteSize,
WriteData(entry, 1, 0, buffer.get(), kWriteSize, false));
}
int size = CalculateSizeOfAllEntries();
EXPECT_GT(kMaxSize, 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: static bool parse_signature(struct MACH0_(obj_t) *bin, ut64 off) {
int i,len;
ut32 data;
bin->signature = NULL;
struct linkedit_data_command link = {};
ut8 lit[sizeof (struct linkedit_data_command)] = {0};
struct blob_index_t idx = {};
struct super_blob_t super = {};
if (off > bin->size || off + sizeof (struct linkedit_data_command) > bin->size) {
return false;
}
len = r_buf_read_at (bin->b, off, lit, sizeof (struct linkedit_data_command));
if (len != sizeof (struct linkedit_data_command)) {
bprintf ("Failed to get data while parsing LC_CODE_SIGNATURE command\n");
return false;
}
link.cmd = r_read_ble32 (&lit[0], bin->big_endian);
link.cmdsize = r_read_ble32 (&lit[4], bin->big_endian);
link.dataoff = r_read_ble32 (&lit[8], bin->big_endian);
link.datasize = r_read_ble32 (&lit[12], bin->big_endian);
data = link.dataoff;
if (data > bin->size || data + sizeof (struct super_blob_t) > bin->size) {
bin->signature = (ut8 *)strdup ("Malformed entitlement");
return true;
}
super.blob.magic = r_read_ble32 (bin->b->buf + data, little_);
super.blob.length = r_read_ble32 (bin->b->buf + data + 4, little_);
super.count = r_read_ble32 (bin->b->buf + data + 8, little_);
for (i = 0; i < super.count; ++i) {
if ((ut8 *)(bin->b->buf + data + i) > (ut8 *)(bin->b->buf + bin->size)) {
bin->signature = (ut8 *)strdup ("Malformed entitlement");
break;
}
struct blob_index_t bi;
if (r_buf_read_at (bin->b, data + 12 + (i * sizeof (struct blob_index_t)),
(ut8*)&bi, sizeof (struct blob_index_t)) < sizeof (struct blob_index_t)) {
break;
}
idx.type = r_read_ble32 (&bi.type, little_);
idx.offset = r_read_ble32 (&bi.offset, little_);
if (idx.type == CSSLOT_ENTITLEMENTS) {
ut64 off = data + idx.offset;
if (off > bin->size || off + sizeof (struct blob_t) > bin->size) {
bin->signature = (ut8 *)strdup ("Malformed entitlement");
break;
}
struct blob_t entitlements = {};
entitlements.magic = r_read_ble32 (bin->b->buf + off, little_);
entitlements.length = r_read_ble32 (bin->b->buf + off + 4, little_);
len = entitlements.length - sizeof(struct blob_t);
if (len <= bin->size && len > 1) {
bin->signature = calloc (1, len + 1);
if (bin->signature) {
ut8 *src = bin->b->buf + off + sizeof (struct blob_t);
if (off + sizeof (struct blob_t) + len < bin->b->length) {
memcpy (bin->signature, src, len);
bin->signature[len] = '\0';
return true;
}
bin->signature = (ut8 *)strdup ("Malformed entitlement");
return true;
}
} else {
bin->signature = (ut8 *)strdup ("Malformed entitlement");
}
}
}
if (!bin->signature) {
bin->signature = (ut8 *)strdup ("No entitlement found");
}
return true;
}
CWE ID: CWE-416
Output:
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.