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 PlatformSensorProviderBase::FreeResourcesIfNeeded() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (sensor_map_.empty() && requests_map_.empty()) {
FreeResources();
shared_buffer_handle_.reset();
}
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
{
CacheView
*image_view;
MagickBooleanType
status;
register ssize_t
i;
size_t
depth;
if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
return(FloydSteinbergDither(image,cube_info));
/*
Distribute quantization error along a Hilbert curve.
*/
(void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
sizeof(*cube_info->error));
cube_info->x=0;
cube_info->y=0;
i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
for (depth=1; i != 0; depth++)
i>>=1;
if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
depth++;
cube_info->offset=0;
cube_info->span=(MagickSizeType) image->columns*image->rows;
image_view=AcquireAuthenticCacheView(image,&image->exception);
if (depth > 1)
Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
image_view=DestroyCacheView(image_view);
return(status);
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
/* Throw away the key data if the key is instantiated */
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags) &&
!test_bit(KEY_FLAG_NEGATIVE, &key->flags) &&
key->type->destroy)
key->type->destroy(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
kfree(key->description);
memzero_explicit(key, sizeof(*key));
kmem_cache_free(key_jar, key);
}
}
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: status_t MPEG4Extractor::readMetaData() {
if (mInitCheck != NO_INIT) {
return mInitCheck;
}
off64_t offset = 0;
status_t err;
bool sawMoovOrSidx = false;
while (!(sawMoovOrSidx && (mMdatFound || mMoofFound))) {
off64_t orig_offset = offset;
err = parseChunk(&offset, 0);
if (err != OK && err != UNKNOWN_ERROR) {
break;
} else if (offset <= orig_offset) {
ALOGE("did not advance: %lld->%lld", (long long)orig_offset, (long long)offset);
err = ERROR_MALFORMED;
break;
} else if (err == UNKNOWN_ERROR) {
sawMoovOrSidx = true;
}
}
if (mInitCheck == OK) {
if (mHasVideo) {
mFileMetaData->setCString(
kKeyMIMEType, MEDIA_MIMETYPE_CONTAINER_MPEG4);
} else {
mFileMetaData->setCString(kKeyMIMEType, "audio/mp4");
}
} else {
mInitCheck = err;
}
CHECK_NE(err, (status_t)NO_INIT);
uint64_t psshsize = 0;
for (size_t i = 0; i < mPssh.size(); i++) {
psshsize += 20 + mPssh[i].datalen;
}
if (psshsize > 0 && psshsize <= UINT32_MAX) {
char *buf = (char*)malloc(psshsize);
char *ptr = buf;
for (size_t i = 0; i < mPssh.size(); i++) {
memcpy(ptr, mPssh[i].uuid, 20); // uuid + length
memcpy(ptr + 20, mPssh[i].data, mPssh[i].datalen);
ptr += (20 + mPssh[i].datalen);
}
mFileMetaData->setData(kKeyPssh, 'pssh', buf, psshsize);
free(buf);
}
return mInitCheck;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: server_check_dh(krb5_context context,
pkinit_plg_crypto_context cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_data *dh_params,
int minbits)
{
DH *dh = NULL;
const BIGNUM *p;
int dh_prime_bits;
krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
dh = decode_dh_params((uint8_t *)dh_params->data, dh_params->length);
if (dh == NULL) {
pkiDebug("failed to decode dhparams\n");
goto cleanup;
}
/* KDC SHOULD check to see if the key parameters satisfy its policy */
DH_get0_pqg(dh, &p, NULL, NULL);
dh_prime_bits = BN_num_bits(p);
if (minbits && dh_prime_bits < minbits) {
pkiDebug("client sent dh params with %d bits, we require %d\n",
dh_prime_bits, minbits);
goto cleanup;
}
if (check_dh_wellknown(cryptoctx, dh, dh_prime_bits))
retval = 0;
cleanup:
if (retval == 0)
req_cryptoctx->dh = dh;
else
DH_free(dh);
return retval;
}
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: MODRET set_timeoutsession(cmd_rec *cmd) {
int timeout = 0, precedence = 0;
config_rec *c = NULL;
int ctxt = (cmd->config && cmd->config->config_type != CONF_PARAM ?
cmd->config->config_type : cmd->server->config_type ?
cmd->server->config_type : CONF_ROOT);
/* this directive must have either 1 or 3 arguments */
if (cmd->argc-1 != 1 &&
cmd->argc-1 != 3) {
CONF_ERROR(cmd, "missing parameters");
}
CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON);
/* Set the precedence for this config_rec based on its configuration
* context.
*/
if (ctxt & CONF_GLOBAL) {
precedence = 1;
/* These will never appear simultaneously */
} else if ((ctxt & CONF_ROOT) ||
(ctxt & CONF_VIRTUAL)) {
precedence = 2;
} else if (ctxt & CONF_ANON) {
precedence = 3;
}
if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '",
cmd->argv[1], "': ", strerror(errno), NULL));
}
if (timeout == 0) {
/* do nothing */
return PR_HANDLED(cmd);
}
if (cmd->argc-1 == 3) {
if (strncmp(cmd->argv[2], "user", 5) == 0 ||
strncmp(cmd->argv[2], "group", 6) == 0 ||
strncmp(cmd->argv[2], "class", 6) == 0) {
/* no op */
} else {
CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0],
": unknown classifier used: '", cmd->argv[2], "'", NULL));
}
}
if (cmd->argc-1 == 1) {
c = add_config_param(cmd->argv[0], 2, NULL);
c->argv[0] = pcalloc(c->pool, sizeof(int));
*((int *) c->argv[0]) = timeout;
c->argv[1] = pcalloc(c->pool, sizeof(unsigned int));
*((unsigned int *) c->argv[1]) = precedence;
} else if (cmd->argc-1 == 3) {
array_header *acl = NULL;
unsigned int argc;
void **argv;
argc = cmd->argc - 3;
argv = cmd->argv + 2;
acl = pr_expr_create(cmd->tmp_pool, &argc, (char **) argv);
c = add_config_param(cmd->argv[0], 0);
c->argc = argc + 2;
/* Add 3 to argc for the argv of the config_rec: one for the
* seconds value, one for the precedence, one for the classifier,
* and one for the terminating NULL.
*/
c->argv = pcalloc(c->pool, ((argc + 4) * sizeof(void *)));
/* Capture the config_rec's argv pointer for doing the by-hand
* population.
*/
argv = c->argv;
/* Copy in the seconds. */
*argv = pcalloc(c->pool, sizeof(int));
*((int *) *argv++) = timeout;
/* Copy in the precedence. */
*argv = pcalloc(c->pool, sizeof(unsigned int));
*((unsigned int *) *argv++) = precedence;
/* Copy in the classifier. */
*argv++ = pstrdup(c->pool, cmd->argv[2]);
/* now, copy in the expression arguments */
if (argc && acl) {
while (argc--) {
*argv++ = pstrdup(c->pool, *((char **) acl->elts));
acl->elts = ((char **) acl->elts) + 1;
}
}
/* don't forget the terminating NULL */
*argv = NULL;
} else {
/* Should never reach here. */
CONF_ERROR(cmd, "wrong number of parameters");
}
c->flags |= CF_MERGEDOWN_MULTI;
return PR_HANDLED(cmd);
}
CWE ID: CWE-59
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long Cluster::GetEntryCount() const
{
return m_entries_count;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void LockScreenMediaControlsView::GetAccessibleNodeData(
ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kListItem;
node_data->AddStringAttribute(
ax::mojom::StringAttribute::kRoleDescription,
l10n_util::GetStringUTF8(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACCESSIBLE_NAME));
if (!accessible_name_.empty())
node_data->SetName(accessible_name_);
}
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 BrowserView::MaybeShowInfoBar(TabContents* contents) {
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 ChromeMockRenderThread::OnCheckForCancel(
const std::string& preview_ui_addr,
int preview_request_id,
bool* cancel) {
*cancel =
(print_preview_pages_remaining_ == print_preview_cancel_page_number_);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void WebGLRenderingContextBase::drawElements(GLenum mode,
GLsizei count,
GLenum type,
int64_t offset) {
if (!ValidateDrawElements("drawElements", type, offset))
return;
if (!bound_vertex_array_object_->IsAllEnabledAttribBufferBound()) {
SynthesizeGLError(GL_INVALID_OPERATION, "drawElements",
"no buffer is bound to enabled attribute");
return;
}
ScopedRGBEmulationColorMask emulation_color_mask(this, color_mask_,
drawing_buffer_.get());
OnBeforeDrawCall();
ContextGL()->DrawElements(
mode, count, type,
reinterpret_cast<void*>(static_cast<intptr_t>(offset)));
}
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: gst_asf_demux_get_buffer (GstBuffer ** p_buf, guint num_bytes_to_read,
guint8 ** p_data, guint64 * p_size)
{
*p_buf = NULL;
if (*p_size < num_bytes_to_read)
return FALSE;
*p_buf = gst_buffer_new_and_alloc (num_bytes_to_read);
gst_buffer_fill (*p_buf, 0, *p_data, num_bytes_to_read);
*p_data += num_bytes_to_read;
*p_size -= num_bytes_to_read;
return TRUE;
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct bio *bio_map_user_iov(struct request_queue *q,
const struct iov_iter *iter,
gfp_t gfp_mask)
{
int j;
int nr_pages = 0;
struct page **pages;
struct bio *bio;
int cur_page = 0;
int ret, offset;
struct iov_iter i;
struct iovec iov;
iov_for_each(iov, i, *iter) {
unsigned long uaddr = (unsigned long) iov.iov_base;
unsigned long len = iov.iov_len;
unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
unsigned long start = uaddr >> PAGE_SHIFT;
/*
* Overflow, abort
*/
if (end < start)
return ERR_PTR(-EINVAL);
nr_pages += end - start;
/*
* buffer must be aligned to at least logical block size for now
*/
if (uaddr & queue_dma_alignment(q))
return ERR_PTR(-EINVAL);
}
if (!nr_pages)
return ERR_PTR(-EINVAL);
bio = bio_kmalloc(gfp_mask, nr_pages);
if (!bio)
return ERR_PTR(-ENOMEM);
ret = -ENOMEM;
pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask);
if (!pages)
goto out;
iov_for_each(iov, i, *iter) {
unsigned long uaddr = (unsigned long) iov.iov_base;
unsigned long len = iov.iov_len;
unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
unsigned long start = uaddr >> PAGE_SHIFT;
const int local_nr_pages = end - start;
const int page_limit = cur_page + local_nr_pages;
ret = get_user_pages_fast(uaddr, local_nr_pages,
(iter->type & WRITE) != WRITE,
&pages[cur_page]);
if (ret < local_nr_pages) {
ret = -EFAULT;
goto out_unmap;
}
offset = offset_in_page(uaddr);
for (j = cur_page; j < page_limit; j++) {
unsigned int bytes = PAGE_SIZE - offset;
if (len <= 0)
break;
if (bytes > len)
bytes = len;
/*
* sorry...
*/
if (bio_add_pc_page(q, bio, pages[j], bytes, offset) <
bytes)
break;
len -= bytes;
offset = 0;
}
cur_page = j;
/*
* release the pages we didn't map into the bio, if any
*/
while (j < page_limit)
put_page(pages[j++]);
}
kfree(pages);
bio_set_flag(bio, BIO_USER_MAPPED);
/*
* subtle -- if bio_map_user_iov() ended up bouncing a bio,
* it would normally disappear when its bi_end_io is run.
* however, we need it for the unmap, so grab an extra
* reference to it
*/
bio_get(bio);
return bio;
out_unmap:
for (j = 0; j < nr_pages; j++) {
if (!pages[j])
break;
put_page(pages[j]);
}
out:
kfree(pages);
bio_put(bio);
return ERR_PTR(ret);
}
CWE ID: CWE-772
Target: 1
Example 2:
Code: bool AutocompleteEditModel::OnAfterPossibleChange(
const string16& old_text,
const string16& new_text,
size_t selection_start,
size_t selection_end,
bool selection_differs,
bool text_differs,
bool just_deleted_text,
bool allow_keyword_ui_change) {
if (paste_state_ == PASTING)
paste_state_ = PASTED;
else if (text_differs)
paste_state_ = NONE;
const bool user_text_changed =
text_differs || (selection_differs && !inline_autocomplete_text_.empty());
if ((text_differs || selection_differs) &&
(control_key_state_ == DOWN_WITHOUT_CHANGE)) {
control_key_state_ = DOWN_WITH_CHANGE;
if (!text_differs && !popup_->IsOpen())
return false; // Don't open the popup for no reason.
} else if (!user_text_changed) {
return false;
}
if (user_text_changed) {
InternalSetUserText(UserTextFromDisplayText(new_text));
has_temporary_text_ = false;
just_deleted_text_ = just_deleted_text;
}
const bool no_selection = selection_start == selection_end;
allow_exact_keyword_match_ = text_differs && allow_keyword_ui_change &&
!just_deleted_text && no_selection &&
CreatedKeywordSearchByInsertingSpaceInMiddle(old_text, user_text_,
selection_start);
view_->UpdatePopup();
allow_exact_keyword_match_ = false;
return !(text_differs && allow_keyword_ui_change && !just_deleted_text &&
no_selection && (selection_start == user_text_.length()) &&
MaybeAcceptKeywordBySpace(user_text_));
}
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 ecdsa_sign_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret, key_tries, sign_tries;
int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
mbedtls_mpi *pk = &k, *pr = r;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
ECDSA_RS_ENTER( sig );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
{
/* redirect to our context */
p_sign_tries = &rs_ctx->sig->sign_tries;
p_key_tries = &rs_ctx->sig->key_tries;
pk = &rs_ctx->sig->k;
pr = &rs_ctx->sig->r;
/* jump to current step */
if( rs_ctx->sig->state == ecdsa_sig_mul )
goto mul;
if( rs_ctx->sig->state == ecdsa_sig_modn )
goto modn;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
*p_sign_tries = 0;
do
{
if( *p_sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
*p_key_tries = 0;
do
{
if( *p_key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_mul;
mul:
#endif
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G,
f_rng, p_rng, ECDSA_RS_ECP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
rs_ctx->sig->state = ecdsa_sig_modn;
modn:
#endif
/*
* Accounting for everything up to the end of the loop
* (step 6, but checking now avoids saving e and t)
*/
ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng, p_rng ) );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->sig != NULL )
mbedtls_mpi_copy( r, pr );
#endif
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
ECDSA_RS_LEAVE( sig );
return( ret );
}
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 InspectorController::initializeDeferredAgents()
{
if (m_deferredAgentsInitialized)
return;
m_deferredAgentsInitialized = true;
InjectedScriptManager* injectedScriptManager = m_injectedScriptManager.get();
InspectorOverlay* overlay = m_overlay.get();
OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_pageAgent, m_inspectorClient));
InspectorResourceAgent* resourceAgent = resourceAgentPtr.get();
m_agents.append(resourceAgentPtr.release());
m_agents.append(InspectorCSSAgent::create(m_domAgent, m_pageAgent, resourceAgent));
m_agents.append(InspectorDOMStorageAgent::create(m_pageAgent));
m_agents.append(InspectorMemoryAgent::create());
m_agents.append(InspectorApplicationCacheAgent::create(m_pageAgent));
PageScriptDebugServer* pageScriptDebugServer = &PageScriptDebugServer::shared();
OwnPtr<InspectorDebuggerAgent> debuggerAgentPtr(PageDebuggerAgent::create(pageScriptDebugServer, m_pageAgent, injectedScriptManager, overlay));
InspectorDebuggerAgent* debuggerAgent = debuggerAgentPtr.get();
m_agents.append(debuggerAgentPtr.release());
m_agents.append(InspectorDOMDebuggerAgent::create(m_domAgent, debuggerAgent));
m_agents.append(InspectorProfilerAgent::create(injectedScriptManager, overlay));
m_agents.append(InspectorHeapProfilerAgent::create(injectedScriptManager));
m_agents.append(InspectorCanvasAgent::create(m_pageAgent, injectedScriptManager));
m_agents.append(InspectorInputAgent::create(m_page, m_inspectorClient));
}
CWE ID:
Target: 1
Example 2:
Code: gdImagePtr gdImageCreateFromJpegCtx (gdIOCtx * infile)
{
return gdImageCreateFromJpegCtxEx(infile, 1);
}
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: OMX_ERRORTYPE omx_video::send_command(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_COMMANDTYPE cmd,
OMX_IN OMX_U32 param1,
OMX_IN OMX_PTR cmdData
)
{
(void)hComp;
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("ERROR: Send Command in Invalid State");
return OMX_ErrorInvalidState;
}
if (cmd == OMX_CommandFlush || cmd == OMX_CommandPortDisable || cmd == OMX_CommandPortEnable) {
if ((param1 != (OMX_U32)PORT_INDEX_IN) && (param1 != (OMX_U32)PORT_INDEX_OUT) && (param1 != (OMX_U32)PORT_INDEX_BOTH)) {
DEBUG_PRINT_ERROR("ERROR: omx_video::send_command-->bad port index");
return OMX_ErrorBadPortIndex;
}
}
if (cmd == OMX_CommandMarkBuffer) {
if (param1 != PORT_INDEX_IN) {
DEBUG_PRINT_ERROR("ERROR: omx_video::send_command-->bad port index");
return OMX_ErrorBadPortIndex;
}
if (!cmdData) {
DEBUG_PRINT_ERROR("ERROR: omx_video::send_command-->param is null");
return OMX_ErrorBadParameter;
}
}
post_event((unsigned long)cmd,(unsigned long)param1,OMX_COMPONENT_GENERATE_COMMAND);
sem_wait(&m_cmd_lock);
return OMX_ErrorNone;
}
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 __init sit_init(void)
{
int err;
printk(KERN_INFO "IPv6 over IPv4 tunneling driver\n");
if (xfrm4_tunnel_register(&sit_handler, AF_INET6) < 0) {
printk(KERN_INFO "sit init: Can't add protocol\n");
return -EAGAIN;
}
err = register_pernet_device(&sit_net_ops);
if (err < 0)
xfrm4_tunnel_deregister(&sit_handler, AF_INET6);
return err;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int read_from_url(struct playlist *pls, struct segment *seg,
uint8_t *buf, int buf_size,
enum ReadFromURLMode mode)
{
int ret;
/* limit read if the segment was only a part of a file */
if (seg->size >= 0)
buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
if (mode == READ_COMPLETE) {
ret = avio_read(pls->input, buf, buf_size);
if (ret != buf_size)
av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n");
} else
ret = avio_read(pls->input, buf, buf_size);
if (ret > 0)
pls->cur_seg_offset += ret;
return ret;
}
CWE ID: CWE-835
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 GpuVideoDecodeAccelerator::OnDecode(
base::SharedMemoryHandle handle, int32 id, int32 size) {
DCHECK(video_decode_accelerator_.get());
video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size));
}
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 CreateSymbolicLink(const FilePath& target, const FilePath& symlink) {
ASSERT_TRUE(file_util::CreateSymbolicLink(target, symlink))
<< ": " << target.value() << ": " << symlink.value();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void TagToModuleName(const char *tag,const char *format,char *module)
{
char
name[MaxTextExtent];
assert(tag != (const char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",tag);
assert(format != (const char *) NULL);
assert(module != (char *) NULL);
(void) CopyMagickString(name,tag,MaxTextExtent);
LocaleUpper(name);
#if !defined(MAGICKCORE_NAMESPACE_PREFIX)
(void) FormatLocaleString(module,MaxTextExtent,format,name);
#else
{
char
prefix_format[MaxTextExtent];
(void) FormatLocaleString(prefix_format,MaxTextExtent,"%s%s",
MAGICKCORE_NAMESPACE_PREFIX,format);
(void) FormatLocaleString(module,MaxTextExtent,prefix_format,name);
}
#endif
}
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 v8::Handle<v8::Value> methodThatRequiresAllArgsAndThrowsCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodThatRequiresAllArgsAndThrows");
if (args.Length() < 2)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
ExceptionCode ec = 0;
{
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))) : 0);
RefPtr<TestObj> result = imp->methodThatRequiresAllArgsAndThrows(strArg, objArg, ec);
if (UNLIKELY(ec))
goto fail;
return toV8(result.release(), args.GetIsolate());
}
fail:
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool KeyMap::Press(const scoped_refptr<WindowProxy>& window,
const ui::KeyboardCode key_code,
const wchar_t& key) {
if (key_code == ui::VKEY_SHIFT) {
shift_ = !shift_;
} else if (key_code == ui::VKEY_CONTROL) {
control_ = !control_;
} else if (key_code == ui::VKEY_MENU) { // ALT
alt_ = !alt_;
} else if (key_code == ui::VKEY_COMMAND) {
command_ = !command_;
}
int modifiers = 0;
if (shift_ || shifted_keys_.find(key) != shifted_keys_.end()) {
modifiers = modifiers | ui::EF_SHIFT_DOWN;
}
if (control_) {
modifiers = modifiers | ui::EF_CONTROL_DOWN;
}
if (alt_) {
modifiers = modifiers | ui::EF_ALT_DOWN;
}
if (command_) {
VLOG(1) << "Pressing command key on linux!!";
modifiers = modifiers | ui::EF_COMMAND_DOWN;
}
window->SimulateOSKeyPress(key_code, modifiers);
return true;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: uint64_t GLES2Implementation::ShareGroupTracingGUID() const {
return share_group_->TracingGUID();
}
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: ft_smooth_get_cbox( FT_Renderer render,
FT_GlyphSlot slot,
FT_BBox* cbox )
{
FT_MEM_ZERO( cbox, sizeof ( *cbox ) );
if ( slot->format == render->glyph_format )
FT_Outline_Get_CBox( &slot->outline, cbox );
}
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: gimp_write_and_read_file (Gimp *gimp,
gboolean with_unusual_stuff,
gboolean compat_paths,
gboolean use_gimp_2_8_features)
{
GimpImage *image;
GimpImage *loaded_image;
GimpPlugInProcedure *proc;
gchar *filename;
GFile *file;
/* Create the image */
image = gimp_create_mainimage (gimp,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Assert valid state */
gimp_assert_mainimage (image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
/* Write to file */
filename = g_build_filename (g_get_tmp_dir (), "gimp-test.xcf", NULL);
file = g_file_new_for_path (filename);
g_free (filename);
proc = gimp_plug_in_manager_file_procedure_find (image->gimp->plug_in_manager,
GIMP_FILE_PROCEDURE_GROUP_SAVE,
file,
NULL /*error*/);
file_save (gimp,
image,
NULL /*progress*/,
file,
proc,
GIMP_RUN_NONINTERACTIVE,
FALSE /*change_saved_state*/,
FALSE /*export_backward*/,
FALSE /*export_forward*/,
NULL /*error*/);
/* Load from file */
loaded_image = gimp_test_load_image (image->gimp, file);
/* Assert on the loaded file. If success, it means that there is no
* significant information loss when we wrote the image to a file
* and loaded it again
*/
gimp_assert_mainimage (loaded_image,
with_unusual_stuff,
compat_paths,
use_gimp_2_8_features);
g_file_delete (file, NULL, NULL);
g_object_unref (file);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool ShellContentBrowserClient::IsHandledURL(const GURL& url) {
if (!url.is_valid())
return false;
DCHECK_EQ(url.scheme(), base::StringToLowerASCII(url.scheme()));
static const char* const kProtocolList[] = {
url::kBlobScheme,
url::kFileSystemScheme,
kChromeUIScheme,
kChromeDevToolsScheme,
url::kDataScheme,
url::kFileScheme,
};
for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
if (url.scheme() == kProtocolList[i])
return true;
}
return false;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int add_remove_audio_effect(const struct audio_stream *stream,
effect_handle_t effect,
bool enable)
{
struct stream_in *in = (struct stream_in *)stream;
struct audio_device *adev = in->dev;
int status = 0;
effect_descriptor_t desc;
#ifdef PREPROCESSING_ENABLED
int i;
#endif
status = (*effect)->get_descriptor(effect, &desc);
if (status != 0)
return status;
ALOGI("add_remove_audio_effect(), effect type: %08x, enable: %d ", desc.type.timeLow, enable);
pthread_mutex_lock(&adev->lock_inputs);
lock_input_stream(in);
pthread_mutex_lock(&in->dev->lock);
#ifndef PREPROCESSING_ENABLED
if ((in->source == AUDIO_SOURCE_VOICE_COMMUNICATION) &&
in->enable_aec != enable &&
(memcmp(&desc.type, FX_IID_AEC, sizeof(effect_uuid_t)) == 0)) {
in->enable_aec = enable;
if (!in->standby)
select_devices(in->dev, in->usecase);
}
#else
if (enable) {
if (in->num_preprocessors >= MAX_PREPROCESSORS) {
status = -ENOSYS;
goto exit;
}
in->preprocessors[in->num_preprocessors].effect_itfe = effect;
in->num_preprocessors ++;
/* check compatibility between main channel supported and possible auxiliary channels */
in_update_aux_channels(in, effect);//wesley crash
in->aux_channels_changed = true;
} else {
/* if ( enable == false ) */
if (in->num_preprocessors <= 0) {
status = -ENOSYS;
goto exit;
}
status = -EINVAL;
for (i = 0; i < in->num_preprocessors && status != 0; i++) {
if ( in->preprocessors[i].effect_itfe == effect ) {
ALOGV("add_remove_audio_effect found fx at index %d", i);
free(in->preprocessors[i].channel_configs);
in->num_preprocessors--;
memcpy(in->preprocessors + i,
in->preprocessors + i + 1,
(in->num_preprocessors - i) * sizeof(in->preprocessors[0]));
memset(in->preprocessors + in->num_preprocessors,
0,
sizeof(in->preprocessors[0]));
status = 0;
}
}
if (status != 0)
goto exit;
in->aux_channels_changed = false;
ALOGV("%s: enable(%d), in->aux_channels_changed(%d)",
__func__, enable, in->aux_channels_changed);
}
ALOGI("%s: num_preprocessors = %d", __func__, in->num_preprocessors);
exit:
#endif
ALOGW_IF(status != 0, "add_remove_audio_effect() error %d", status);
pthread_mutex_unlock(&in->dev->lock);
pthread_mutex_unlock(&in->lock);
pthread_mutex_unlock(&adev->lock_inputs);
return status;
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void HTMLFormControlElement::updateVisibleValidationMessage() {
Page* page = document().page();
if (!page)
return;
String message;
if (layoutObject() && willValidate())
message = validationMessage().stripWhiteSpace();
m_hasValidationMessage = true;
ValidationMessageClient* client = &page->validationMessageClient();
TextDirection messageDir = LTR;
TextDirection subMessageDir = LTR;
String subMessage = validationSubMessage().stripWhiteSpace();
if (message.isEmpty())
client->hideValidationMessage(*this);
else
findCustomValidationMessageTextDirection(message, messageDir, subMessage,
subMessageDir);
client->showValidationMessage(*this, message, messageDir, subMessage,
subMessageDir);
}
CWE ID: CWE-1021
Target: 1
Example 2:
Code: int ExtensionPrefs::GetAppLaunchIndex(const std::string& extension_id) {
int value;
if (ReadExtensionPrefInteger(extension_id, kPrefAppLaunchIndex, &value))
return value;
return -1;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: CommonNavigationParams MakeCommonNavigationParams(
blink::WebURLRequest* request,
bool should_replace_current_entry) {
const RequestExtraData kEmptyData;
const RequestExtraData* extra_data =
static_cast<RequestExtraData*>(request->extraData());
if (!extra_data)
extra_data = &kEmptyData;
Referrer referrer(
GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
request->referrerPolicy());
base::TimeTicks ui_timestamp =
base::TimeTicks() + base::TimeDelta::FromSecondsD(request->uiStartTime());
FrameMsg_UILoadMetricsReportType::Value report_type =
static_cast<FrameMsg_UILoadMetricsReportType::Value>(
request->inputPerfMetricReportPolicy());
return CommonNavigationParams(
request->url(), referrer, extra_data->transition_type(),
FrameMsg_Navigate_Type::NORMAL, true, should_replace_current_entry,
ui_timestamp, report_type, GURL(), GURL());
}
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: Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA,
PDFRectangle *box, PDFRectangle *cropBox,
GBool (*abortCheckCbkA)(void *data),
void *abortCheckCbkDataA)
#ifdef USE_CMS
: iccColorSpaceCache(5)
#endif
{
int i;
xref = xrefA;
catalog = catalogA;
subPage = gTrue;
printCommands = globalParams->getPrintCommands();
profileCommands = globalParams->getProfileCommands();
textHaveCSPattern = gFalse;
drawText = gFalse;
drawText = gFalse;
maskHaveCSPattern = gFalse;
mcStack = NULL;
res = new GfxResources(xref, resDict, NULL);
out = outA;
state = new GfxState(72, 72, box, 0, gFalse);
stackHeight = 1;
pushStateGuard();
fontChanged = gFalse;
clip = clipNone;
ignoreUndef = 0;
for (i = 0; i < 6; ++i) {
baseMatrix[i] = state->getCTM()[i];
}
formDepth = 0;
abortCheckCbk = abortCheckCbkA;
abortCheckCbkData = abortCheckCbkDataA;
if (cropBox) {
state->moveTo(cropBox->x1, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y1);
state->lineTo(cropBox->x2, cropBox->y2);
state->lineTo(cropBox->x1, cropBox->y2);
state->closePath();
state->clip();
out->clip(state);
state->clearPath();
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
unsigned long len)
{
int r;
unsigned long addr;
gfn_t gfn = gpa >> PAGE_SHIFT;
int offset = offset_in_page(gpa);
addr = gfn_to_hva_prot(kvm, gfn, NULL);
if (kvm_is_error_hva(addr))
return -EFAULT;
pagefault_disable();
r = kvm_read_hva_atomic(data, (void __user *)addr + offset, len);
pagefault_enable();
if (r)
return -EFAULT;
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void sctp_generate_heartbeat_event(unsigned long data)
{
int error = 0;
struct sctp_transport *transport = (struct sctp_transport *) data;
struct sctp_association *asoc = transport->asoc;
struct net *net = sock_net(asoc->base.sk);
bh_lock_sock(asoc->base.sk);
if (sock_owned_by_user(asoc->base.sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->hb_timer, jiffies + (HZ/20)))
sctp_transport_hold(transport);
goto out_unlock;
}
/* Is this structure just waiting around for us to actually
* get destroyed?
*/
if (transport->dead)
goto out_unlock;
error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT,
SCTP_ST_TIMEOUT(SCTP_EVENT_TIMEOUT_HEARTBEAT),
asoc->state, asoc->ep, asoc,
transport, GFP_ATOMIC);
if (error)
asoc->base.sk->sk_err = -error;
out_unlock:
bh_unlock_sock(asoc->base.sk);
sctp_transport_put(transport);
}
CWE ID: CWE-362
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int http_connect(URLContext *h, const char *path, const char *local_path,
const char *hoststr, const char *auth,
const char *proxyauth, int *new_location)
{
HTTPContext *s = h->priv_data;
int post, err;
char headers[HTTP_HEADERS_SIZE] = "";
char *authstr = NULL, *proxyauthstr = NULL;
int64_t off = s->off;
int len = 0;
const char *method;
int send_expect_100 = 0;
/* send http header */
post = h->flags & AVIO_FLAG_WRITE;
if (s->post_data) {
/* force POST method and disable chunked encoding when
* custom HTTP post data is set */
post = 1;
s->chunked_post = 0;
}
if (s->method)
method = s->method;
else
method = post ? "POST" : "GET";
authstr = ff_http_auth_create_response(&s->auth_state, auth,
local_path, method);
proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
local_path, method);
if (post && !s->post_data) {
send_expect_100 = s->send_expect_100;
/* The user has supplied authentication but we don't know the auth type,
* send Expect: 100-continue to get the 401 response including the
* WWW-Authenticate header, or an 100 continue if no auth actually
* is needed. */
if (auth && *auth &&
s->auth_state.auth_type == HTTP_AUTH_NONE &&
s->http_code != 401)
send_expect_100 = 1;
}
#if FF_API_HTTP_USER_AGENT
if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
s->user_agent = av_strdup(s->user_agent_deprecated);
}
#endif
/* set default headers if needed */
if (!has_header(s->headers, "\r\nUser-Agent: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"User-Agent: %s\r\n", s->user_agent);
if (!has_header(s->headers, "\r\nAccept: "))
len += av_strlcpy(headers + len, "Accept: */*\r\n",
sizeof(headers) - len);
if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Range: bytes=%"PRId64"-", s->off);
if (s->end_off)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"%"PRId64, s->end_off - 1);
len += av_strlcpy(headers + len, "\r\n",
sizeof(headers) - len);
}
if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Expect: 100-continue\r\n");
if (!has_header(s->headers, "\r\nConnection: ")) {
if (s->multiple_requests)
len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
sizeof(headers) - len);
else
len += av_strlcpy(headers + len, "Connection: close\r\n",
sizeof(headers) - len);
}
if (!has_header(s->headers, "\r\nHost: "))
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Host: %s\r\n", hoststr);
if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Content-Length: %d\r\n", s->post_datalen);
if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Content-Type: %s\r\n", s->content_type);
if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
char *cookies = NULL;
if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Cookie: %s\r\n", cookies);
av_free(cookies);
}
}
if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
len += av_strlcatf(headers + len, sizeof(headers) - len,
"Icy-MetaData: %d\r\n", 1);
/* now add in custom headers */
if (s->headers)
av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
snprintf(s->buffer, sizeof(s->buffer),
"%s %s HTTP/1.1\r\n"
"%s"
"%s"
"%s"
"%s%s"
"\r\n",
method,
path,
post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
headers,
authstr ? authstr : "",
proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
goto done;
if (s->post_data)
if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
goto done;
/* init input buffer */
s->buf_ptr = s->buffer;
s->buf_end = s->buffer;
s->line_count = 0;
s->off = 0;
s->icy_data_read = 0;
s->filesize = -1;
s->willclose = 0;
s->end_chunked_post = 0;
s->end_header = 0;
if (post && !s->post_data && !send_expect_100) {
/* Pretend that it did work. We didn't read any header yet, since
* we've still to send the POST data, but the code calling this
* function will check http_code after we return. */
s->http_code = 200;
err = 0;
goto done;
}
/* wait for header */
err = http_read_header(h, new_location);
if (err < 0)
goto done;
if (*new_location)
s->off = off;
err = (off == s->off) ? 0 : -1;
done:
av_freep(&authstr);
av_freep(&proxyauthstr);
return err;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void PrintingMessageFilter::CreatePrintDialogForFile(int render_view_id,
const FilePath& path) {
content::WebContents* wc = GetWebContentsForRenderView(render_view_id);
print_dialog_cloud::CreatePrintDialogForFile(
wc->GetBrowserContext(),
wc->GetView()->GetTopLevelNativeWindow(),
path,
string16(),
string16(),
std::string("application/pdf"),
false);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct ip_sf_list *igmp_mcf_get_idx(struct seq_file *seq, loff_t pos)
{
struct ip_sf_list *psf = igmp_mcf_get_first(seq);
if (psf)
while (pos && (psf = igmp_mcf_get_next(seq, psf)) != NULL)
--pos;
return pos ? NULL : psf;
}
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: void assertObjectHasGCInfo(const void* payload, size_t gcInfoIndex) {
ASSERT(HeapObjectHeader::fromPayload(payload)->checkHeader());
#if !defined(COMPONENT_BUILD)
ASSERT(HeapObjectHeader::fromPayload(payload)->gcInfoIndex() == gcInfoIndex);
#endif
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ScaleRect(float scale, pp::Rect* rect) {
int left = static_cast<int>(floorf(rect->x() * scale));
int top = static_cast<int>(floorf(rect->y() * scale));
int right = static_cast<int>(ceilf((rect->x() + rect->width()) * scale));
int bottom = static_cast<int>(ceilf((rect->y() + rect->height()) * scale));
rect->SetRect(left, top, right - left, bottom - top);
}
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: vrrp_rt_priority_handler(vector_t *strvec)
{
int priority = get_realtime_priority(strvec, "vrrp");
if (priority >= 0)
global_data->vrrp_realtime_priority = priority;
}
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 __init int sctp_init(void)
{
int i;
int status = -EINVAL;
unsigned long goal;
unsigned long limit;
int max_share;
int order;
sock_skb_cb_check_size(sizeof(struct sctp_ulpevent));
/* Allocate bind_bucket and chunk caches. */
status = -ENOBUFS;
sctp_bucket_cachep = kmem_cache_create("sctp_bind_bucket",
sizeof(struct sctp_bind_bucket),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!sctp_bucket_cachep)
goto out;
sctp_chunk_cachep = kmem_cache_create("sctp_chunk",
sizeof(struct sctp_chunk),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!sctp_chunk_cachep)
goto err_chunk_cachep;
status = percpu_counter_init(&sctp_sockets_allocated, 0, GFP_KERNEL);
if (status)
goto err_percpu_counter_init;
/* Implementation specific variables. */
/* Initialize default stream count setup information. */
sctp_max_instreams = SCTP_DEFAULT_INSTREAMS;
sctp_max_outstreams = SCTP_DEFAULT_OUTSTREAMS;
/* Initialize handle used for association ids. */
idr_init(&sctp_assocs_id);
limit = nr_free_buffer_pages() / 8;
limit = max(limit, 128UL);
sysctl_sctp_mem[0] = limit / 4 * 3;
sysctl_sctp_mem[1] = limit;
sysctl_sctp_mem[2] = sysctl_sctp_mem[0] * 2;
/* Set per-socket limits to no more than 1/128 the pressure threshold*/
limit = (sysctl_sctp_mem[1]) << (PAGE_SHIFT - 7);
max_share = min(4UL*1024*1024, limit);
sysctl_sctp_rmem[0] = SK_MEM_QUANTUM; /* give each asoc 1 page min */
sysctl_sctp_rmem[1] = 1500 * SKB_TRUESIZE(1);
sysctl_sctp_rmem[2] = max(sysctl_sctp_rmem[1], max_share);
sysctl_sctp_wmem[0] = SK_MEM_QUANTUM;
sysctl_sctp_wmem[1] = 16*1024;
sysctl_sctp_wmem[2] = max(64*1024, max_share);
/* Size and allocate the association hash table.
* The methodology is similar to that of the tcp hash tables.
*/
if (totalram_pages >= (128 * 1024))
goal = totalram_pages >> (22 - PAGE_SHIFT);
else
goal = totalram_pages >> (24 - PAGE_SHIFT);
for (order = 0; (1UL << order) < goal; order++)
;
do {
sctp_assoc_hashsize = (1UL << order) * PAGE_SIZE /
sizeof(struct sctp_hashbucket);
if ((sctp_assoc_hashsize > (64 * 1024)) && order > 0)
continue;
sctp_assoc_hashtable = (struct sctp_hashbucket *)
__get_free_pages(GFP_ATOMIC|__GFP_NOWARN, order);
} while (!sctp_assoc_hashtable && --order > 0);
if (!sctp_assoc_hashtable) {
pr_err("Failed association hash alloc\n");
status = -ENOMEM;
goto err_ahash_alloc;
}
for (i = 0; i < sctp_assoc_hashsize; i++) {
rwlock_init(&sctp_assoc_hashtable[i].lock);
INIT_HLIST_HEAD(&sctp_assoc_hashtable[i].chain);
}
/* Allocate and initialize the endpoint hash table. */
sctp_ep_hashsize = 64;
sctp_ep_hashtable =
kmalloc(64 * sizeof(struct sctp_hashbucket), GFP_KERNEL);
if (!sctp_ep_hashtable) {
pr_err("Failed endpoint_hash alloc\n");
status = -ENOMEM;
goto err_ehash_alloc;
}
for (i = 0; i < sctp_ep_hashsize; i++) {
rwlock_init(&sctp_ep_hashtable[i].lock);
INIT_HLIST_HEAD(&sctp_ep_hashtable[i].chain);
}
/* Allocate and initialize the SCTP port hash table. */
do {
sctp_port_hashsize = (1UL << order) * PAGE_SIZE /
sizeof(struct sctp_bind_hashbucket);
if ((sctp_port_hashsize > (64 * 1024)) && order > 0)
continue;
sctp_port_hashtable = (struct sctp_bind_hashbucket *)
__get_free_pages(GFP_ATOMIC|__GFP_NOWARN, order);
} while (!sctp_port_hashtable && --order > 0);
if (!sctp_port_hashtable) {
pr_err("Failed bind hash alloc\n");
status = -ENOMEM;
goto err_bhash_alloc;
}
for (i = 0; i < sctp_port_hashsize; i++) {
spin_lock_init(&sctp_port_hashtable[i].lock);
INIT_HLIST_HEAD(&sctp_port_hashtable[i].chain);
}
pr_info("Hash tables configured (established %d bind %d)\n",
sctp_assoc_hashsize, sctp_port_hashsize);
sctp_sysctl_register();
INIT_LIST_HEAD(&sctp_address_families);
sctp_v4_pf_init();
sctp_v6_pf_init();
status = sctp_v4_protosw_init();
if (status)
goto err_protosw_init;
status = sctp_v6_protosw_init();
if (status)
goto err_v6_protosw_init;
status = register_pernet_subsys(&sctp_net_ops);
if (status)
goto err_register_pernet_subsys;
status = sctp_v4_add_protocol();
if (status)
goto err_add_protocol;
/* Register SCTP with inet6 layer. */
status = sctp_v6_add_protocol();
if (status)
goto err_v6_add_protocol;
out:
return status;
err_v6_add_protocol:
sctp_v4_del_protocol();
err_add_protocol:
unregister_pernet_subsys(&sctp_net_ops);
err_register_pernet_subsys:
sctp_v6_protosw_exit();
err_v6_protosw_init:
sctp_v4_protosw_exit();
err_protosw_init:
sctp_v4_pf_exit();
sctp_v6_pf_exit();
sctp_sysctl_unregister();
free_pages((unsigned long)sctp_port_hashtable,
get_order(sctp_port_hashsize *
sizeof(struct sctp_bind_hashbucket)));
err_bhash_alloc:
kfree(sctp_ep_hashtable);
err_ehash_alloc:
free_pages((unsigned long)sctp_assoc_hashtable,
get_order(sctp_assoc_hashsize *
sizeof(struct sctp_hashbucket)));
err_ahash_alloc:
percpu_counter_destroy(&sctp_sockets_allocated);
err_percpu_counter_init:
kmem_cache_destroy(sctp_chunk_cachep);
err_chunk_cachep:
kmem_cache_destroy(sctp_bucket_cachep);
goto out;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg,
struct msghdr *msg_sys, unsigned int flags,
struct used_address *used_address)
{
struct compat_msghdr __user *msg_compat =
(struct compat_msghdr __user *)msg;
struct sockaddr_storage address;
struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
unsigned char ctl[sizeof(struct cmsghdr) + 20]
__attribute__ ((aligned(sizeof(__kernel_size_t))));
/* 20 is size of ipv6_pktinfo */
unsigned char *ctl_buf = ctl;
int ctl_len, total_len;
ssize_t err;
msg_sys->msg_name = &address;
if (MSG_CMSG_COMPAT & flags)
err = get_compat_msghdr(msg_sys, msg_compat, NULL, &iov);
else
err = copy_msghdr_from_user(msg_sys, msg, NULL, &iov);
if (err < 0)
goto out_freeiov;
total_len = err;
err = -ENOBUFS;
if (msg_sys->msg_controllen > INT_MAX)
goto out_freeiov;
ctl_len = msg_sys->msg_controllen;
if ((MSG_CMSG_COMPAT & flags) && ctl_len) {
err =
cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl,
sizeof(ctl));
if (err)
goto out_freeiov;
ctl_buf = msg_sys->msg_control;
ctl_len = msg_sys->msg_controllen;
} else if (ctl_len) {
if (ctl_len > sizeof(ctl)) {
ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL);
if (ctl_buf == NULL)
goto out_freeiov;
}
err = -EFAULT;
/*
* Careful! Before this, msg_sys->msg_control contains a user pointer.
* Afterwards, it will be a kernel pointer. Thus the compiler-assisted
* checking falls down on this.
*/
if (copy_from_user(ctl_buf,
(void __user __force *)msg_sys->msg_control,
ctl_len))
goto out_freectl;
msg_sys->msg_control = ctl_buf;
}
msg_sys->msg_flags = flags;
if (sock->file->f_flags & O_NONBLOCK)
msg_sys->msg_flags |= MSG_DONTWAIT;
/*
* If this is sendmmsg() and current destination address is same as
* previously succeeded address, omit asking LSM's decision.
* used_address->name_len is initialized to UINT_MAX so that the first
* destination address never matches.
*/
if (used_address && msg_sys->msg_name &&
used_address->name_len == msg_sys->msg_namelen &&
!memcmp(&used_address->name, msg_sys->msg_name,
used_address->name_len)) {
err = sock_sendmsg_nosec(sock, msg_sys, total_len);
goto out_freectl;
}
err = sock_sendmsg(sock, msg_sys, total_len);
/*
* If this is sendmmsg() and sending to current destination address was
* successful, remember it.
*/
if (used_address && err >= 0) {
used_address->name_len = msg_sys->msg_namelen;
if (msg_sys->msg_name)
memcpy(&used_address->name, msg_sys->msg_name,
used_address->name_len);
}
out_freectl:
if (ctl_buf != ctl)
sock_kfree_s(sock->sk, ctl_buf, ctl_len);
out_freeiov:
if (iov != iovstack)
kfree(iov);
return err;
}
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 virtqueue_map_sg(struct iovec *sg, hwaddr *addr,
size_t num_sg, int is_write)
{
unsigned int i;
hwaddr len;
for (i = 0; i < num_sg; i++) {
len = sg[i].iov_len;
sg[i].iov_base = cpu_physical_memory_map(addr[i], &len, is_write);
if (sg[i].iov_base == NULL || len != sg[i].iov_len) {
error_report("virtio: trying to map MMIO memory");
exit(1);
}
}
}
CWE ID: CWE-94
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: OmniboxPopupViewGtk::~OmniboxPopupViewGtk() {
model_.reset();
g_object_unref(layout_);
gtk_widget_destroy(window_);
for (ImageMap::iterator it = images_.begin(); it != images_.end(); ++it)
delete it->second;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int isofs_iget5_set(struct inode *ino, void *data)
{
struct iso_inode_info *i = ISOFS_I(ino);
struct isofs_iget5_callback_data *d =
(struct isofs_iget5_callback_data*)data;
i->i_iget5_block = d->block;
i->i_iget5_offset = d->offset;
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
{
AVFilterContext *ctx = inlink->dst;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
uint32_t plane_checksum[4] = {0}, checksum = 0;
int i, plane, vsub = desc->log2_chroma_h;
for (plane = 0; plane < 4 && frame->data[plane]; plane++) {
int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane);
uint8_t *data = frame->data[plane];
int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h;
if (linesize < 0)
return linesize;
for (i = 0; i < h; i++) {
plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize);
checksum = av_adler32_update(checksum, data, linesize);
data += frame->linesize[plane];
}
}
av_log(ctx, AV_LOG_INFO,
"n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" "
"fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c "
"checksum:%08X plane_checksum:[%08X",
inlink->frame_count,
av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame),
desc->name,
frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den,
frame->width, frame->height,
!frame->interlaced_frame ? 'P' : /* Progressive */
frame->top_field_first ? 'T' : 'B', /* Top / Bottom */
frame->key_frame,
av_get_picture_type_char(frame->pict_type),
checksum, plane_checksum[0]);
for (plane = 1; plane < 4 && frame->data[plane]; plane++)
av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]);
av_log(ctx, AV_LOG_INFO, "]\n");
return ff_filter_frame(inlink->dst->outputs[0], frame);
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static unsigned int ssh_tty_parse_specchar(char *s)
{
unsigned int ret;
if (*s) {
char *next = NULL;
ret = ctrlparse(s, &next);
if (!next) ret = s[0];
} else {
ret = 255; /* special value meaning "don't set" */
}
return ret;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: dump_icc_buffer(int buffersize, char filename[],byte *Buffer)
{
char full_file_name[50];
FILE *fid;
gs_sprintf(full_file_name,"%d)%s_debug.icc",global_icc_index,filename);
fid = gp_fopen(full_file_name,"wb");
fwrite(Buffer,sizeof(unsigned char),buffersize,fid);
fclose(fid);
}
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 BnCrypto::readVector(const Parcel &data, Vector<uint8_t> &vector) const {
uint32_t size = data.readInt32();
vector.insertAt((size_t)0, size);
data.read(vector.editArray(), size);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static inline double SaneStrokeWidth(const Image *image,
const DrawInfo *draw_info)
{
return(MagickMin((double) draw_info->stroke_width,
(2.0*sqrt(2.0)+MagickEpsilon)*MagickMax(image->columns,image->rows)));
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void ccid3_hc_tx_packet_sent(struct sock *sk, unsigned int len)
{
struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk);
ccid3_hc_tx_update_s(hc, len);
if (tfrc_tx_hist_add(&hc->tx_hist, dccp_sk(sk)->dccps_gss))
DCCP_CRIT("packet history - out of memory!");
}
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 Image *ReadLABELImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent],
*property;
const char
*label;
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
TypeMetric
metrics;
size_t
height,
width;
/*
Initialize Image structure.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
(void) ResetImagePage(image,"0x0+0+0");
property=InterpretImageProperties(image_info,image,image_info->filename);
(void) SetImageProperty(image,"label",property);
property=DestroyString(property);
label=GetImageProperty(image,"label");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->text=ConstantString(label);
metrics.width=0;
metrics.ascent=0.0;
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if ((image->columns == 0) && (image->rows == 0))
{
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
}
else
if ((strlen(label) > 0) &&
(((image->columns == 0) || (image->rows == 0)) ||
(fabs(image_info->pointsize) < MagickEpsilon)))
{
double
high,
low;
/*
Auto fit text into bounding box.
*/
for ( ; ; draw_info->pointsize*=2.0)
{
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width >= image->columns) && (height >= image->rows))
break;
}
else
if (((image->columns != 0) && (width >= image->columns)) ||
((image->rows != 0) && (height >= image->rows)))
break;
}
high=draw_info->pointsize;
for (low=1.0; (high-low) > 0.5; )
{
draw_info->pointsize=(low+high)/2.0;
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
-metrics.bounds.x1,metrics.ascent);
if (draw_info->gravity == UndefinedGravity)
(void) CloneString(&draw_info->geometry,geometry);
(void) GetMultilineTypeMetrics(image,draw_info,&metrics);
width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5);
if ((image->columns != 0) && (image->rows != 0))
{
if ((width < image->columns) && (height < image->rows))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
else
if (((image->columns != 0) && (width < image->columns)) ||
((image->rows != 0) && (height < image->rows)))
low=draw_info->pointsize+0.5;
else
high=draw_info->pointsize-0.5;
}
draw_info->pointsize=(low+high)/2.0-0.5;
}
status=GetMultilineTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image->columns == 0)
image->columns=(size_t) floor(metrics.width+draw_info->stroke_width+0.5);
if (image->columns == 0)
image->columns=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
if (image->rows == 0)
image->rows=(size_t) floor(metrics.ascent-metrics.descent+
draw_info->stroke_width+0.5);
if (image->rows == 0)
image->rows=(size_t) floor(draw_info->pointsize+draw_info->stroke_width+
0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
draw_info=DestroyDrawInfo(draw_info);
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Draw label.
*/
(void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",
draw_info->direction == RightToLeftDirection ? image->columns-
metrics.bounds.x2 : 0.0,draw_info->gravity == UndefinedGravity ?
metrics.ascent : 0.0);
draw_info->geometry=AcquireString(geometry);
status=AnnotateImage(image,draw_info);
if (image_info->pointsize == 0.0)
{
char
pointsize[MaxTextExtent];
(void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g",
draw_info->pointsize);
(void) SetImageProperty(image,"label:pointsize",pointsize);
}
draw_info=DestroyDrawInfo(draw_info);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
return(GetFirstImageInList(image));
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void SetFixedFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->SetFixedFontFamily(WebString::FromUTF16(font), script);
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void enforcedRangeUnsignedLongLongAttrAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectV8Internal::enforcedRangeUnsignedLongLongAttrAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int snd_compr_allocate_buffer(struct snd_compr_stream *stream,
struct snd_compr_params *params)
{
unsigned int buffer_size;
void *buffer;
buffer_size = params->buffer.fragment_size * params->buffer.fragments;
if (stream->ops->copy) {
buffer = NULL;
/* if copy is defined the driver will be required to copy
* the data from core
*/
} else {
buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
}
stream->runtime->fragment_size = params->buffer.fragment_size;
stream->runtime->fragments = params->buffer.fragments;
stream->runtime->buffer = buffer;
stream->runtime->buffer_size = buffer_size;
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: static int walk_component(struct nameidata *nd, int flags)
{
struct path path;
struct inode *inode;
unsigned seq;
int err;
/*
* "." and ".." are special - ".." especially so because it has
* to be able to know about the current root directory and
* parent relationships.
*/
if (unlikely(nd->last_type != LAST_NORM)) {
err = handle_dots(nd, nd->last_type);
if (flags & WALK_PUT)
put_link(nd);
return err;
}
err = lookup_fast(nd, &path, &inode, &seq);
if (unlikely(err)) {
if (err < 0)
return err;
err = lookup_slow(nd, &path);
if (err < 0)
return err;
inode = d_backing_inode(path.dentry);
seq = 0; /* we are already out of RCU mode */
err = -ENOENT;
if (d_is_negative(path.dentry))
goto out_path_put;
}
if (flags & WALK_PUT)
put_link(nd);
err = should_follow_link(nd, &path, flags & WALK_GET, inode, seq);
if (unlikely(err))
return err;
path_to_nameidata(&path, nd);
nd->inode = inode;
nd->seq = seq;
return 0;
out_path_put:
path_to_nameidata(&path, nd);
return err;
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int LayerTreeHost::ScheduleMicroBenchmark(
const std::string& benchmark_name,
std::unique_ptr<base::Value> value,
const MicroBenchmark::DoneCallback& callback) {
return micro_benchmark_controller_.ScheduleRun(benchmark_name,
std::move(value), callback);
}
CWE ID: CWE-362
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void smp_proc_master_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
uint8_t* p = p_data->p_data;
tBTM_LE_PENC_KEYS le_key;
SMP_TRACE_DEBUG("%s", __func__);
smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, true);
STREAM_TO_UINT16(le_key.ediv, p);
STREAM_TO_ARRAY(le_key.rand, p, BT_OCTET8_LEN);
/* store the encryption keys from peer device */
memcpy(le_key.ltk, p_cb->ltk, BT_OCTET16_LEN);
le_key.sec_level = p_cb->sec_level;
le_key.key_size = p_cb->loc_enc_size;
if ((p_cb->peer_auth_req & SMP_AUTH_BOND) &&
(p_cb->loc_auth_req & SMP_AUTH_BOND))
btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC,
(tBTM_LE_KEY_VALUE*)&le_key, true);
smp_key_distribution(p_cb, NULL);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int __meminit save_mr(struct map_range *mr, int nr_range,
unsigned long start_pfn, unsigned long end_pfn,
unsigned long page_size_mask)
{
if (start_pfn < end_pfn) {
if (nr_range >= NR_RANGE_MR)
panic("run out of range for init_memory_mapping\n");
mr[nr_range].start = start_pfn<<PAGE_SHIFT;
mr[nr_range].end = end_pfn<<PAGE_SHIFT;
mr[nr_range].page_size_mask = page_size_mask;
nr_range++;
}
return nr_range;
}
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: IMkvReader::~IMkvReader() {}
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: e1000e_write_packet_to_guest(E1000ECore *core, struct NetRxPkt *pkt,
const E1000E_RxRing *rxr,
const E1000E_RSSInfo *rss_info)
{
PCIDevice *d = core->owner;
dma_addr_t base;
uint8_t desc[E1000_MAX_RX_DESC_LEN];
size_t desc_size;
size_t desc_offset = 0;
size_t iov_ofs = 0;
struct iovec *iov = net_rx_pkt_get_iovec(pkt);
size_t size = net_rx_pkt_get_total_len(pkt);
size_t total_size = size + e1000x_fcs_len(core->mac);
const E1000E_RingInfo *rxi;
size_t ps_hdr_len = 0;
bool do_ps = e1000e_do_ps(core, pkt, &ps_hdr_len);
bool is_first = true;
rxi = rxr->i;
do {
hwaddr ba[MAX_PS_BUFFERS];
e1000e_ba_state bastate = { { 0 } };
bool is_last = false;
desc_size = total_size - desc_offset;
if (desc_size > core->rx_desc_buf_size) {
desc_size = core->rx_desc_buf_size;
desc_size = core->rx_desc_buf_size;
}
base = e1000e_ring_head_descr(core, rxi);
pci_dma_read(d, base, &desc, core->rx_desc_len);
if (ba[0]) {
if (desc_offset < size) {
static const uint32_t fcs_pad;
size_t iov_copy;
size_t copy_size = size - desc_offset;
if (copy_size > core->rx_desc_buf_size) {
copy_size = core->rx_desc_buf_size;
}
/* For PS mode copy the packet header first */
if (do_ps) {
if (is_first) {
size_t ps_hdr_copied = 0;
do {
iov_copy = MIN(ps_hdr_len - ps_hdr_copied,
iov->iov_len - iov_ofs);
e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate,
iov->iov_base, iov_copy);
copy_size -= iov_copy;
ps_hdr_copied += iov_copy;
iov_ofs += iov_copy;
if (iov_ofs == iov->iov_len) {
iov++;
iov_ofs = 0;
}
} while (ps_hdr_copied < ps_hdr_len);
is_first = false;
} else {
/* Leave buffer 0 of each descriptor except first */
/* empty as per spec 7.1.5.1 */
e1000e_write_hdr_to_rx_buffers(core, &ba, &bastate,
NULL, 0);
}
}
/* Copy packet payload */
while (copy_size) {
iov_copy = MIN(copy_size, iov->iov_len - iov_ofs);
e1000e_write_to_rx_buffers(core, &ba, &bastate,
iov->iov_base + iov_ofs, iov_copy);
copy_size -= iov_copy;
iov_ofs += iov_copy;
if (iov_ofs == iov->iov_len) {
iov++;
iov_ofs = 0;
}
}
if (desc_offset + desc_size >= total_size) {
/* Simulate FCS checksum presence in the last descriptor */
e1000e_write_to_rx_buffers(core, &ba, &bastate,
(const char *) &fcs_pad, e1000x_fcs_len(core->mac));
}
}
desc_offset += desc_size;
if (desc_offset >= total_size) {
is_last = true;
}
} else { /* as per intel docs; skip descriptors with null buf addr */
trace_e1000e_rx_null_descriptor();
}
e1000e_write_rx_descr(core, desc, is_last ? core->rx_pkt : NULL,
rss_info, do_ps ? ps_hdr_len : 0, &bastate.written);
pci_dma_write(d, base, &desc, core->rx_desc_len);
e1000e_ring_advance(core, rxi,
core->rx_desc_len / E1000_MIN_RX_DESC_LEN);
} while (desc_offset < total_size);
e1000e_update_rx_stats(core, size, total_size);
}
CWE ID: CWE-835
Target: 1
Example 2:
Code: bool GesturePoint::DidScroll(const TouchEvent& event, int dist) const {
return abs(last_touch_position_.x() - first_touch_position_.x()) > dist ||
abs(last_touch_position_.y() - first_touch_position_.y()) > dist;
}
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: v8::Handle<v8::Value> V8WebGLRenderingContext::getProgramParameterCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebGLRenderingContext.getProgramParameter()");
if (args.Length() != 2)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLProgram::HasInstance(args[0])) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
WebGLProgram* program = V8WebGLProgram::HasInstance(args[0]) ? V8WebGLProgram::toNative(v8::Handle<v8::Object>::Cast(args[0])) : 0;
unsigned pname = toInt32(args[1]);
WebGLGetInfo info = context->getProgramParameter(program, pname, ec);
if (ec) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
return toV8Object(info, args.GetIsolate());
}
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: char *cJSON_Print( cJSON *item )
{
return print_value( item, 0, 1 );
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void rt_mutex_setprio(struct task_struct *p, int prio)
{
int oldprio, on_rq, running;
struct rq *rq;
const struct sched_class *prev_class;
BUG_ON(prio < 0 || prio > MAX_PRIO);
rq = __task_rq_lock(p);
trace_sched_pi_setprio(p, prio);
oldprio = p->prio;
prev_class = p->sched_class;
on_rq = p->on_rq;
running = task_current(rq, p);
if (on_rq)
dequeue_task(rq, p, 0);
if (running)
p->sched_class->put_prev_task(rq, p);
if (rt_prio(prio))
p->sched_class = &rt_sched_class;
else
p->sched_class = &fair_sched_class;
p->prio = prio;
if (running)
p->sched_class->set_curr_task(rq);
if (on_rq)
enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
check_class_changed(rq, p, prev_class, oldprio);
__task_rq_unlock(rq);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void disk_replace_part_tbl(struct gendisk *disk,
struct disk_part_tbl *new_ptbl)
{
struct disk_part_tbl *old_ptbl = disk->part_tbl;
rcu_assign_pointer(disk->part_tbl, new_ptbl);
if (old_ptbl) {
rcu_assign_pointer(old_ptbl->last_lookup, NULL);
kfree_rcu(old_ptbl, rcu_head);
}
}
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: void HandleCompleteLogin(const base::ListValue* args) {
#if defined(OS_CHROMEOS)
oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui()));
oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher(
oauth2_delegate_.get(), profile_->GetRequestContext()));
oauth2_token_fetcher_->StartExchangeFromCookies();
#elif !defined(OS_ANDROID)
const base::DictionaryValue* dict = NULL;
string16 email;
string16 password;
if (!args->GetDictionary(0, &dict) || !dict ||
!dict->GetString("email", &email) ||
!dict->GetString("password", &password)) {
NOTREACHED();
return;
}
new OneClickSigninSyncStarter(
profile_, NULL, "0" /* session_index 0 for the default user */,
UTF16ToASCII(email), UTF16ToASCII(password),
OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
true /* force_same_tab_navigation */,
OneClickSigninSyncStarter::NO_CONFIRMATION);
web_ui()->CallJavascriptFunction("inline.login.closeDialog");
#endif
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void CameraSourceListener::notify(int32_t msgType, int32_t ext1, int32_t ext2) {
UNUSED_UNLESS_VERBOSE(msgType);
UNUSED_UNLESS_VERBOSE(ext1);
UNUSED_UNLESS_VERBOSE(ext2);
ALOGV("notify(%d, %d, %d)", msgType, ext1, ext2);
}
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 WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
if (!GetAccessibilityMode().is_mode_off()) {
for (RenderFrameHost* rfh : GetAllFrames())
ResetAccessibility(rfh);
} else {
AddAccessibilityMode(ui::kAXModeWebContentsOnly);
}
}
CWE ID: CWE-254
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: new_msg_register_event (u_int32_t seqnum, struct lsa_filter_type *filter)
{
u_char buf[OSPF_API_MAX_MSG_SIZE];
struct msg_register_event *emsg;
int len;
emsg = (struct msg_register_event *) buf;
len = sizeof (struct msg_register_event) +
filter->num_areas * sizeof (struct in_addr);
emsg->filter.typemask = htons (filter->typemask);
emsg->filter.origin = filter->origin;
emsg->filter.num_areas = filter->num_areas;
return msg_new (MSG_REGISTER_EVENT, emsg, seqnum, len);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ScopedModifyPixels::~ScopedModifyPixels() {
if (ref_)
ref_->texture()->OnDidModifyPixels();
}
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: Node* RenderBlock::nodeForHitTest() const
{
return isAnonymousBlockContinuation() ? continuation()->node() : node();
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int cipso_v4_req_setattr(struct request_sock *req,
const struct cipso_v4_doi *doi_def,
const struct netlbl_lsm_secattr *secattr)
{
int ret_val = -EPERM;
unsigned char *buf = NULL;
u32 buf_len;
u32 opt_len;
struct ip_options *opt = NULL;
struct inet_request_sock *req_inet;
/* We allocate the maximum CIPSO option size here so we are probably
* being a little wasteful, but it makes our life _much_ easier later
* on and after all we are only talking about 40 bytes. */
buf_len = CIPSO_V4_OPT_LEN_MAX;
buf = kmalloc(buf_len, GFP_ATOMIC);
if (buf == NULL) {
ret_val = -ENOMEM;
goto req_setattr_failure;
}
ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
if (ret_val < 0)
goto req_setattr_failure;
buf_len = ret_val;
/* We can't use ip_options_get() directly because it makes a call to
* ip_options_get_alloc() which allocates memory with GFP_KERNEL and
* we won't always have CAP_NET_RAW even though we _always_ want to
* set the IPOPT_CIPSO option. */
opt_len = (buf_len + 3) & ~3;
opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
if (opt == NULL) {
ret_val = -ENOMEM;
goto req_setattr_failure;
}
memcpy(opt->__data, buf, buf_len);
opt->optlen = opt_len;
opt->cipso = sizeof(struct iphdr);
kfree(buf);
buf = NULL;
req_inet = inet_rsk(req);
opt = xchg(&req_inet->opt, opt);
kfree(opt);
return 0;
req_setattr_failure:
kfree(buf);
kfree(opt);
return ret_val;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int __init init_inodecache(void)
{
isofs_inode_cachep = kmem_cache_create("isofs_inode_cache",
sizeof(struct iso_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
init_once);
if (isofs_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
int error;
char addrbuf[128];
static const int error_codes[] = {
DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
};
ASSERT_LOCKED(req->base);
ASSERT_VALID_REQUEST(req);
if (flags & 0x020f || !reply || !reply->have_answer) {
/* there was an error */
if (flags & 0x0200) {
error = DNS_ERR_TRUNCATED;
} else if (flags & 0x000f) {
u16 error_code = (flags & 0x000f) - 1;
if (error_code > 4) {
error = DNS_ERR_UNKNOWN;
} else {
error = error_codes[error_code];
}
} else if (reply && !reply->have_answer) {
error = DNS_ERR_NODATA;
} else {
error = DNS_ERR_UNKNOWN;
}
switch (error) {
case DNS_ERR_NOTIMPL:
case DNS_ERR_REFUSED:
/* we regard these errors as marking a bad nameserver */
if (req->reissue_count < req->base->global_max_reissues) {
char msg[64];
evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
error, evdns_err_to_string(error));
nameserver_failed(req->ns, msg);
if (!request_reissue(req)) return;
}
break;
case DNS_ERR_SERVERFAILED:
/* rcode 2 (servfailed) sometimes means "we
* are broken" and sometimes (with some binds)
* means "that request was very confusing."
* Treat this as a timeout, not a failure.
*/
log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
"at %s; will allow the request to time out.",
evutil_format_sockaddr_port_(
(struct sockaddr *)&req->ns->address,
addrbuf, sizeof(addrbuf)));
/* Call the timeout function */
evdns_request_timeout_callback(0, 0, req);
return;
default:
/* we got a good reply from the nameserver: it is up. */
if (req->handle == req->ns->probe_request) {
/* Avoid double-free */
req->ns->probe_request = NULL;
}
nameserver_up(req->ns);
}
if (req->handle->search_state &&
req->request_type != TYPE_PTR) {
/* if we have a list of domains to search in,
* try the next one */
if (!search_try_next(req->handle)) {
/* a new request was issued so this
* request is finished and */
/* the user callback will be made when
* that request (or a */
/* child of it) finishes. */
return;
}
}
/* all else failed. Pass the failure up */
reply_schedule_callback(req, ttl, error, NULL);
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
} else {
/* all ok, tell the user */
reply_schedule_callback(req, ttl, 0, reply);
if (req->handle == req->ns->probe_request)
req->ns->probe_request = NULL; /* Avoid double-free */
nameserver_up(req->ns);
request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
}
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: unset_and_free_gvalue (gpointer val)
{
g_value_unset (val);
g_free (val);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void mddev_put(struct mddev *mddev)
{
struct bio_set *bs = NULL;
if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
return;
if (!mddev->raid_disks && list_empty(&mddev->disks) &&
mddev->ctime == 0 && !mddev->hold_active) {
/* Array is not configured at all, and not held active,
* so destroy it */
list_del_init(&mddev->all_mddevs);
bs = mddev->bio_set;
mddev->bio_set = NULL;
if (mddev->gendisk) {
/* We did a probe so need to clean up. Call
* queue_work inside the spinlock so that
* flush_workqueue() after mddev_find will
* succeed in waiting for the work to be done.
*/
INIT_WORK(&mddev->del_work, mddev_delayed_delete);
queue_work(md_misc_wq, &mddev->del_work);
} else
kfree(mddev);
}
spin_unlock(&all_mddevs_lock);
if (bs)
bioset_free(bs);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
{
BIGNUM *b, *c = NULL, *u = NULL, *v = NULL, *tmp;
int ret = 0;
bn_check_top(a);
bn_check_top(p);
BN_CTX_start(ctx);
if ((b = BN_CTX_get(ctx)) == NULL)
goto err;
if ((c = BN_CTX_get(ctx)) == NULL)
goto err;
if ((u = BN_CTX_get(ctx)) == NULL)
goto err;
if ((v = BN_CTX_get(ctx)) == NULL)
goto err;
if (!BN_GF2m_mod(u, a, p))
goto err;
if (BN_is_zero(u))
goto err;
if (!BN_copy(v, p))
goto err;
# if 0
if (!BN_one(b))
goto err;
while (1) {
while (!BN_is_odd(u)) {
if (BN_is_zero(u))
goto err;
if (!BN_rshift1(u, u))
goto err;
if (BN_is_odd(b)) {
if (!BN_GF2m_add(b, b, p))
goto err;
}
if (!BN_rshift1(b, b))
goto err;
}
if (BN_abs_is_word(u, 1))
break;
if (BN_num_bits(u) < BN_num_bits(v)) {
tmp = u;
u = v;
v = tmp;
tmp = b;
b = c;
c = tmp;
}
if (!BN_GF2m_add(u, u, v))
goto err;
if (!BN_GF2m_add(b, b, c))
goto err;
}
# else
{
int i, ubits = BN_num_bits(u), vbits = BN_num_bits(v), /* v is copy
* of p */
top = p->top;
BN_ULONG *udp, *bdp, *vdp, *cdp;
bn_wexpand(u, top);
udp = u->d;
for (i = u->top; i < top; i++)
udp[i] = 0;
u->top = top;
bn_wexpand(b, top);
bdp = b->d;
bdp[0] = 1;
for (i = 1; i < top; i++)
bdp[i] = 0;
b->top = top;
bn_wexpand(c, top);
cdp = c->d;
for (i = 0; i < top; i++)
cdp[i] = 0;
c->top = top;
vdp = v->d; /* It pays off to "cache" *->d pointers,
* because it allows optimizer to be more
* aggressive. But we don't have to "cache"
* p->d, because *p is declared 'const'... */
while (1) {
while (ubits && !(udp[0] & 1)) {
BN_ULONG u0, u1, b0, b1, mask;
u0 = udp[0];
b0 = bdp[0];
mask = (BN_ULONG)0 - (b0 & 1);
b0 ^= p->d[0] & mask;
for (i = 0; i < top - 1; i++) {
u1 = udp[i + 1];
udp[i] = ((u0 >> 1) | (u1 << (BN_BITS2 - 1))) & BN_MASK2;
u0 = u1;
b1 = bdp[i + 1] ^ (p->d[i + 1] & mask);
bdp[i] = ((b0 >> 1) | (b1 << (BN_BITS2 - 1))) & BN_MASK2;
b0 = b1;
}
udp[i] = u0 >> 1;
bdp[i] = b0 >> 1;
ubits--;
}
if (ubits <= BN_BITS2 && udp[0] == 1)
break;
if (ubits < vbits) {
i = ubits;
ubits = vbits;
vbits = i;
tmp = u;
u = v;
v = tmp;
tmp = b;
b = c;
c = tmp;
udp = vdp;
vdp = v->d;
bdp = cdp;
cdp = c->d;
}
for (i = 0; i < top; i++) {
udp[i] ^= vdp[i];
bdp[i] ^= cdp[i];
}
if (ubits == vbits) {
BN_ULONG ul;
int utop = (ubits - 1) / BN_BITS2;
while ((ul = udp[utop]) == 0 && utop)
utop--;
ubits = utop * BN_BITS2 + BN_num_bits_word(ul);
}
}
bn_correct_top(b);
}
# endif
if (!BN_copy(r, b))
goto err;
bn_check_top(r);
ret = 1;
err:
# ifdef BN_DEBUG /* BN_CTX_end would complain about the
* expanded form */
bn_correct_top(c);
bn_correct_top(u);
bn_correct_top(v);
# endif
BN_CTX_end(ctx);
return ret;
}
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 unsigned int unix_dgram_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk, *other;
unsigned int mask, writable;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR |
(sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if (sk->sk_type == SOCK_SEQPACKET) {
if (sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/* connection hasn't started yet? */
if (sk->sk_state == TCP_SYN_SENT)
return mask;
}
/* No write status requested, avoid expensive OUT tests. */
if (!(poll_requested_events(wait) & (POLLWRBAND|POLLWRNORM|POLLOUT)))
return mask;
writable = unix_writable(sk);
other = unix_peer_get(sk);
if (other) {
if (unix_peer(other) != sk) {
sock_poll_wait(file, &unix_sk(other)->peer_wait, wait);
if (unix_recvq_full(other))
writable = 0;
}
sock_put(other);
}
if (writable)
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
return mask;
}
CWE ID:
Target: 1
Example 2:
Code: void BaseRenderingContext2D::setGlobalAlpha(double alpha) {
if (!(alpha >= 0 && alpha <= 1))
return;
if (GetState().GlobalAlpha() == alpha)
return;
ModifiableState().SetGlobalAlpha(alpha);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,
rpmpsm psm, char ** failedFile)
{
FD_t payload = rpmtePayload(te);
rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE);
rpmfs fs = rpmteGetFileStates(te);
rpmPlugins plugins = rpmtsPlugins(ts);
struct stat sb;
int saveerrno = errno;
int rc = 0;
int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0;
int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0;
int firsthardlink = -1;
int skip;
rpmFileAction action;
char *tid = NULL;
const char *suffix;
char *fpath = NULL;
if (fi == NULL) {
rc = RPMERR_BAD_MAGIC;
goto exit;
}
/* transaction id used for temporary path suffix while installing */
rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts));
/* Detect and create directories not explicitly in package. */
rc = fsmMkdirs(files, fs, plugins);
while (!rc) {
/* Read next payload header. */
rc = rpmfiNext(fi);
if (rc < 0) {
if (rc == RPMERR_ITER_END)
rc = 0;
break;
}
action = rpmfsGetAction(fs, rpmfiFX(fi));
skip = XFA_SKIPPING(action);
suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid;
if (action != FA_TOUCH) {
fpath = fsmFsPath(fi, suffix);
} else {
fpath = fsmFsPath(fi, "");
}
/* Remap file perms, owner, and group. */
rc = rpmfiStat(fi, 1, &sb);
fsmDebug(fpath, action, &sb);
/* Exit on error. */
if (rc)
break;
/* Run fsm file pre hook for all plugins */
rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath,
sb.st_mode, action);
if (rc) {
skip = 1;
} else {
setFileState(fs, rpmfiFX(fi));
}
if (!skip) {
int setmeta = 1;
/* Directories replacing something need early backup */
if (!suffix) {
rc = fsmBackup(fi, action);
}
/* Assume file does't exist when tmp suffix is in use */
if (!suffix) {
rc = fsmVerify(fpath, fi);
} else {
rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT;
}
if (S_ISREG(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmMkfile(fi, fpath, files, psm, nodigest,
&setmeta, &firsthardlink);
}
} else if (S_ISDIR(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
mode_t mode = sb.st_mode;
mode &= ~07777;
mode |= 00700;
rc = fsmMkdir(fpath, mode);
}
} else if (S_ISLNK(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmSymlink(rpmfiFLink(fi), fpath);
}
} else if (S_ISFIFO(sb.st_mode)) {
/* This mimics cpio S_ISSOCK() behavior but probably isn't right */
if (rc == RPMERR_ENOENT) {
rc = fsmMkfifo(fpath, 0000);
}
} else if (S_ISCHR(sb.st_mode) ||
S_ISBLK(sb.st_mode) ||
S_ISSOCK(sb.st_mode))
{
if (rc == RPMERR_ENOENT) {
rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev);
}
} else {
/* XXX Special case /dev/log, which shouldn't be packaged anyways */
if (!IS_DEV_LOG(fpath))
rc = RPMERR_UNKNOWN_FILETYPE;
}
/* Set permissions, timestamps etc for non-hardlink entries */
if (!rc && setmeta) {
rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps);
}
} else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) {
/* we skip the hard linked file containing the content */
/* write the content to the first used instead */
char *fn = rpmfilesFN(files, firsthardlink);
rc = expandRegular(fi, fn, psm, nodigest, 0);
firsthardlink = -1;
free(fn);
}
if (rc) {
if (!skip) {
/* XXX only erase if temp fn w suffix is in use */
if (suffix && (action != FA_TOUCH)) {
(void) fsmRemove(fpath, sb.st_mode);
}
errno = saveerrno;
}
} else {
/* Notify on success. */
rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi));
if (!skip) {
/* Backup file if needed. Directories are handled earlier */
if (suffix)
rc = fsmBackup(fi, action);
if (!rc)
rc = fsmCommit(&fpath, fi, action, suffix);
}
}
if (rc)
*failedFile = xstrdup(fpath);
/* Run fsm file post hook for all plugins */
rpmpluginsCallFsmFilePost(plugins, fi, fpath,
sb.st_mode, action, rc);
fpath = _free(fpath);
}
rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ));
rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST));
exit:
/* No need to bother with close errors on read */
rpmfiArchiveClose(fi);
rpmfiFree(fi);
Fclose(payload);
free(tid);
free(fpath);
return rc;
}
CWE ID: CWE-59
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 DownloadController::StartAndroidDownloadInternal(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download, const DownloadInfo& info, bool allowed) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!allowed)
return;
WebContents* web_contents = wc_getter.Run();
if (!web_contents)
return;
base::string16 filename = net::GetSuggestedFilename(
info.url, info.content_disposition,
std::string(), // referrer_charset
std::string(), // suggested_name
info.original_mime_type,
default_file_name_);
ChromeDownloadDelegate::FromWebContents(web_contents)->RequestHTTPGetDownload(
info.url.spec(), info.user_agent,
info.content_disposition, info.original_mime_type,
info.cookie, info.referer, filename,
info.total_bytes, info.has_user_gesture,
must_download);
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: NavigationEntryImpl::RestoreType ControllerRestoreTypeToEntryType(
NavigationController::RestoreType type) {
switch (type) {
case NavigationController::RESTORE_CURRENT_SESSION:
return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY:
return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY;
case NavigationController::RESTORE_LAST_SESSION_CRASHED:
return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED;
}
NOTREACHED();
return NavigationEntryImpl::RESTORE_CURRENT_SESSION;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool isInt(const std::string &s)
{
for(size_t i = 0; i < s.length(); i++){
if(!isdigit(s[i]))
return false;
}
return true;
}
CWE ID: CWE-93
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long ZEXPORT inflateMark(strm)
z_streamp strm;
{
struct inflate_state FAR *state;
if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;
state = (struct inflate_state FAR *)strm->state;
return ((long)(state->back) << 16) +
(state->mode == COPY ? state->length :
(state->mode == MATCH ? state->was - state->length : 0));
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: dtls1_reset_seq_numbers(SSL *s, int rw)
{
unsigned char *seq;
unsigned int seq_bytes = sizeof(s->s3->read_sequence);
if ( rw & SSL3_CC_READ)
{
seq = s->s3->read_sequence;
s->d1->r_epoch++;
memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
}
else
{
seq = s->s3->write_sequence;
memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
s->d1->w_epoch++;
}
memset(seq, 0x00, seq_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: Strgrow(Str x)
{
char *old = x->ptr;
int newlen;
newlen = x->length * 6 / 5;
if (newlen == x->length)
newlen += 2;
x->ptr = GC_MALLOC_ATOMIC(newlen);
x->area_size = newlen;
bcopy((void *)old, (void *)x->ptr, x->length);
GC_free(old);
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int dex_loadcode(RBinFile *arch, RBinDexObj *bin) {
struct r_bin_t *rbin = arch->rbin;
int i;
int *methods = NULL;
int sym_count = 0;
if (!bin || bin->methods_list) {
return false;
}
bin->code_from = UT64_MAX;
bin->code_to = 0;
bin->methods_list = r_list_newf ((RListFree)free);
if (!bin->methods_list) {
return false;
}
bin->imports_list = r_list_newf ((RListFree)free);
if (!bin->imports_list) {
r_list_free (bin->methods_list);
return false;
}
bin->classes_list = r_list_newf ((RListFree)__r_bin_class_free);
if (!bin->classes_list) {
r_list_free (bin->methods_list);
r_list_free (bin->imports_list);
return false;
}
if (bin->header.method_size>bin->size) {
bin->header.method_size = 0;
return false;
}
/* WrapDown the header sizes to avoid huge allocations */
bin->header.method_size = R_MIN (bin->header.method_size, bin->size);
bin->header.class_size = R_MIN (bin->header.class_size, bin->size);
bin->header.strings_size = R_MIN (bin->header.strings_size, bin->size);
if (bin->header.strings_size > bin->size) {
eprintf ("Invalid strings size\n");
return false;
}
if (bin->classes) {
ut64 amount = sizeof (int) * bin->header.method_size;
if (amount > UT32_MAX || amount < bin->header.method_size) {
return false;
}
methods = calloc (1, amount + 1);
for (i = 0; i < bin->header.class_size; i++) {
char *super_name, *class_name;
struct dex_class_t *c = &bin->classes[i];
class_name = dex_class_name (bin, c);
super_name = dex_class_super_name (bin, c);
if (dexdump) {
rbin->cb_printf ("Class #%d -\n", i);
}
parse_class (arch, bin, c, i, methods, &sym_count);
free (class_name);
free (super_name);
}
}
if (methods) {
int import_count = 0;
int sym_count = bin->methods_list->length;
for (i = 0; i < bin->header.method_size; i++) {
int len = 0;
if (methods[i]) {
continue;
}
if (bin->methods[i].class_id > bin->header.types_size - 1) {
continue;
}
if (is_class_idx_in_code_classes(bin, bin->methods[i].class_id)) {
continue;
}
char *class_name = getstr (
bin, bin->types[bin->methods[i].class_id]
.descriptor_id);
if (!class_name) {
free (class_name);
continue;
}
len = strlen (class_name);
if (len < 1) {
continue;
}
class_name[len - 1] = 0; // remove last char ";"
char *method_name = dex_method_name (bin, i);
char *signature = dex_method_signature (bin, i);
if (method_name && *method_name) {
RBinImport *imp = R_NEW0 (RBinImport);
imp->name = r_str_newf ("%s.method.%s%s", class_name, method_name, signature);
imp->type = r_str_const ("FUNC");
imp->bind = r_str_const ("NONE");
imp->ordinal = import_count++;
r_list_append (bin->imports_list, imp);
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = r_str_newf ("imp.%s", imp->name);
sym->type = r_str_const ("FUNC");
sym->bind = r_str_const ("NONE");
sym->paddr = sym->vaddr = bin->b->base + bin->header.method_offset + (sizeof (struct dex_method_t) * i) ;
sym->ordinal = sym_count++;
r_list_append (bin->methods_list, sym);
sdb_num_set (mdb, sdb_fmt (0, "method.%d", i), sym->paddr, 0);
}
free (method_name);
free (signature);
free (class_name);
}
free (methods);
}
return true;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: acpi_status acpi_os_execute(acpi_execute_type type,
acpi_osd_exec_callback function, void *context)
{
acpi_status status = AE_OK;
struct acpi_os_dpc *dpc;
struct workqueue_struct *queue;
int ret;
ACPI_DEBUG_PRINT((ACPI_DB_EXEC,
"Scheduling function [%p(%p)] for deferred execution.\n",
function, context));
if (type == OSL_DEBUGGER_MAIN_THREAD) {
ret = acpi_debugger_create_thread(function, context);
if (ret) {
pr_err("Call to kthread_create() failed.\n");
status = AE_ERROR;
}
goto out_thread;
}
/*
* Allocate/initialize DPC structure. Note that this memory will be
* freed by the callee. The kernel handles the work_struct list in a
* way that allows us to also free its memory inside the callee.
* Because we may want to schedule several tasks with different
* parameters we can't use the approach some kernel code uses of
* having a static work_struct.
*/
dpc = kzalloc(sizeof(struct acpi_os_dpc), GFP_ATOMIC);
if (!dpc)
return AE_NO_MEMORY;
dpc->function = function;
dpc->context = context;
/*
* To prevent lockdep from complaining unnecessarily, make sure that
* there is a different static lockdep key for each workqueue by using
* INIT_WORK() for each of them separately.
*/
if (type == OSL_NOTIFY_HANDLER) {
queue = kacpi_notify_wq;
INIT_WORK(&dpc->work, acpi_os_execute_deferred);
} else if (type == OSL_GPE_HANDLER) {
queue = kacpid_wq;
INIT_WORK(&dpc->work, acpi_os_execute_deferred);
} else {
pr_err("Unsupported os_execute type %d.\n", type);
status = AE_ERROR;
}
if (ACPI_FAILURE(status))
goto err_workqueue;
/*
* On some machines, a software-initiated SMI causes corruption unless
* the SMI runs on CPU 0. An SMI can be initiated by any AML, but
* typically it's done in GPE-related methods that are run via
* workqueues, so we can avoid the known corruption cases by always
* queueing on CPU 0.
*/
ret = queue_work_on(0, queue, &dpc->work);
if (!ret) {
printk(KERN_ERR PREFIX
"Call to queue_work() failed.\n");
status = AE_ERROR;
}
err_workqueue:
if (ACPI_FAILURE(status))
kfree(dpc);
out_thread:
return status;
}
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: PassRefPtr<AccessibilityTextMarker> AccessibilityUIElement::endTextMarkerForTextMarkerRange(AccessibilityTextMarkerRange* range)
{
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: void GetPreviewDataForIndex(int index,
scoped_refptr<base::RefCountedBytes>* data) {
if (index != printing::COMPLETE_PREVIEW_DOCUMENT_INDEX &&
index < printing::FIRST_PAGE_INDEX) {
return;
}
PreviewPageDataMap::iterator it = page_data_map_.find(index);
if (it != page_data_map_.end())
*data = it->second.get();
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: RenderObject* HTMLInputElement::createRenderer(RenderArena* arena, RenderStyle* style)
{
return m_inputType->createRenderer(arena, style);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebContentsAndroid::OpenURL(JNIEnv* env,
jobject obj,
jstring url,
jboolean user_gesture,
jboolean is_renderer_initiated) {
GURL gurl(base::android::ConvertJavaStringToUTF8(env, url));
OpenURLParams open_params(gurl,
Referrer(),
CURRENT_TAB,
ui::PAGE_TRANSITION_LINK,
is_renderer_initiated);
open_params.user_gesture = user_gesture;
web_contents_->OpenURL(open_params);
}
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 string_check(char *buf, const char *buf2)
{
if(strcmp(buf, buf2)) {
/* they shouldn't differ */
printf("sprintf failed:\nwe '%s'\nsystem: '%s'\n",
buf, buf2);
return 1;
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline int is_callback(u32 proc)
{
return proc == NLMPROC_GRANTED
|| proc == NLMPROC_GRANTED_MSG
|| proc == NLMPROC_TEST_RES
|| proc == NLMPROC_LOCK_RES
|| proc == NLMPROC_CANCEL_RES
|| proc == NLMPROC_UNLOCK_RES
|| proc == NLMPROC_NSM_NOTIFY;
}
CWE ID: CWE-404
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: UINT CSoundFile::GetBestSaveFormat() const
{
if ((!m_nSamples) || (!m_nChannels)) return MOD_TYPE_NONE;
if (!m_nType) return MOD_TYPE_NONE;
if (m_nType & (MOD_TYPE_MOD|MOD_TYPE_OKT))
return MOD_TYPE_MOD;
if (m_nType & (MOD_TYPE_S3M|MOD_TYPE_STM|MOD_TYPE_ULT|MOD_TYPE_FAR|MOD_TYPE_PTM))
return MOD_TYPE_S3M;
if (m_nType & (MOD_TYPE_XM|MOD_TYPE_MED|MOD_TYPE_MTM|MOD_TYPE_MT2))
return MOD_TYPE_XM;
return MOD_TYPE_IT;
}
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 tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb)
{
/* unprotected vars, we dont care of overwrites */
static u32 challenge_timestamp;
static unsigned int challenge_count;
struct tcp_sock *tp = tcp_sk(sk);
u32 now;
/* First check our per-socket dupack rate limit. */
if (tcp_oow_rate_limited(sock_net(sk), skb,
LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
&tp->last_oow_ack_time))
return;
/* Then check the check host-wide RFC 5961 rate limit. */
now = jiffies / HZ;
if (now != challenge_timestamp) {
challenge_timestamp = now;
challenge_count = 0;
}
if (++challenge_count <= sysctl_tcp_challenge_ack_limit) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK);
tcp_send_ack(sk);
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: int regulator_unregister_notifier(struct regulator *regulator,
struct notifier_block *nb)
{
return blocking_notifier_chain_unregister(®ulator->rdev->notifier,
nb);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct dentry *trace_options_init_dentry(struct trace_array *tr)
{
struct dentry *d_tracer;
if (tr->options)
return tr->options;
d_tracer = tracing_get_dentry(tr);
if (IS_ERR(d_tracer))
return NULL;
tr->options = tracefs_create_dir("options", d_tracer);
if (!tr->options) {
pr_warn("Could not create tracefs directory 'options'\n");
return NULL;
}
return tr->options;
}
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: static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns)
{
struct mnt_namespace *new_ns;
struct ucounts *ucounts;
int ret;
ucounts = inc_mnt_namespaces(user_ns);
if (!ucounts)
return ERR_PTR(-ENOSPC);
new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL);
if (!new_ns) {
dec_mnt_namespaces(ucounts);
return ERR_PTR(-ENOMEM);
}
ret = ns_alloc_inum(&new_ns->ns);
if (ret) {
kfree(new_ns);
dec_mnt_namespaces(ucounts);
return ERR_PTR(ret);
}
new_ns->ns.ops = &mntns_operations;
new_ns->seq = atomic64_add_return(1, &mnt_ns_seq);
atomic_set(&new_ns->count, 1);
new_ns->root = NULL;
INIT_LIST_HEAD(&new_ns->list);
init_waitqueue_head(&new_ns->poll);
new_ns->event = 0;
new_ns->user_ns = get_user_ns(user_ns);
new_ns->ucounts = ucounts;
return new_ns;
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: GF_Err infe_dump(GF_Box *a, FILE * trace)
{
GF_ItemInfoEntryBox *p = (GF_ItemInfoEntryBox *)a;
gf_isom_box_dump_start(a, "ItemInfoEntryBox", trace);
fprintf(trace, "item_ID=\"%d\" item_protection_index=\"%d\" item_name=\"%s\" content_type=\"%s\" content_encoding=\"%s\" item_type=\"%s\">\n", p->item_ID, p->item_protection_index, p->item_name, p->content_type, p->content_encoding, gf_4cc_to_str(p->item_type));
gf_isom_box_dump_done("ItemInfoEntryBox", a, trace);
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: static int raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
ret = copy_to_user(param, ptr, sizeof(*ptr));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
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: pipe_iov_copy_from_user(void *to, struct iovec *iov, unsigned long len,
int atomic)
{
unsigned long copy;
while (len > 0) {
while (!iov->iov_len)
iov++;
copy = min_t(unsigned long, len, iov->iov_len);
if (atomic) {
if (__copy_from_user_inatomic(to, iov->iov_base, copy))
return -EFAULT;
} else {
if (copy_from_user(to, iov->iov_base, copy))
return -EFAULT;
}
to += copy;
len -= copy;
iov->iov_base += copy;
iov->iov_len -= copy;
}
return 0;
}
CWE ID: CWE-17
Target: 1
Example 2:
Code: static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image,ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(option) != MagickFalse)
return(MagickTrue);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
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: virDomainRestoreFlags(virConnectPtr conn, const char *from, const char *dxml,
unsigned int flags)
{
VIR_DEBUG("conn=%p, from=%s, dxml=%s, flags=%x",
conn, NULLSTR(from), NULLSTR(dxml), flags);
virResetLastError();
virCheckConnectReturn(conn, -1);
virCheckReadOnlyGoto(conn->flags, error);
virCheckNonNullArgGoto(from, error);
VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING,
VIR_DOMAIN_SAVE_PAUSED,
error);
if (conn->driver->domainRestoreFlags) {
int ret;
char *absolute_from;
/* We must absolutize the file path as the restore is done out of process */
if (virFileAbsPath(from, &absolute_from) < 0) {
virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
_("could not build absolute input file path"));
goto error;
}
ret = conn->driver->domainRestoreFlags(conn, absolute_from, dxml,
flags);
VIR_FREE(absolute_from);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(conn);
return -1;
}
CWE ID: CWE-254
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach)
{
ASSERT(refCount() || parentOrHostNode());
RefPtr<Node> protect(this);
ec = 0;
if (oldChild == newChild) // nothing to do
return true;
checkReplaceChild(newChild.get(), oldChild, ec);
if (ec)
return false;
if (!oldChild || oldChild->parentNode() != this) {
ec = NOT_FOUND_ERR;
return false;
}
#if ENABLE(MUTATION_OBSERVERS)
ChildListMutationScope mutation(this);
#endif
RefPtr<Node> next = oldChild->nextSibling();
RefPtr<Node> removedChild = oldChild;
removeChild(oldChild, ec);
if (ec)
return false;
if (next && (next->previousSibling() == newChild || next == newChild)) // nothing to do
return true;
checkReplaceChild(newChild.get(), oldChild, ec);
if (ec)
return false;
NodeVector targets;
collectChildrenAndRemoveFromOldParent(newChild.get(), targets, ec);
if (ec)
return false;
InspectorInstrumentation::willInsertDOMNode(document(), this);
for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
Node* child = it->get();
if (next && next->parentNode() != this)
break;
if (child->parentNode())
break;
treeScope()->adoptIfNeeded(child);
forbidEventDispatch();
if (next)
insertBeforeCommon(next.get(), child);
else
appendChildToContainer(child, this);
allowEventDispatch();
updateTreeAfterInsertion(this, child, shouldLazyAttach);
}
dispatchSubtreeModifiedEvent();
return true;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void av_max_alloc(size_t max){
max_alloc_size = max;
}
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: dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, int sh_num)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *interp = "";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) == -1) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
break;
default:
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
interp = (const char *)nbuf;
} else
interp = "*empty*";
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const Block* SimpleBlock::GetBlock() const
{
return &m_block;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int f2fs_set_qf_name(struct super_block *sb, int qtype,
substring_t *args)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
char *qname;
int ret = -EINVAL;
if (sb_any_quota_loaded(sb) && !sbi->s_qf_names[qtype]) {
f2fs_msg(sb, KERN_ERR,
"Cannot change journaled "
"quota options when quota turned on");
return -EINVAL;
}
qname = match_strdup(args);
if (!qname) {
f2fs_msg(sb, KERN_ERR,
"Not enough memory for storing quotafile name");
return -EINVAL;
}
if (sbi->s_qf_names[qtype]) {
if (strcmp(sbi->s_qf_names[qtype], qname) == 0)
ret = 0;
else
f2fs_msg(sb, KERN_ERR,
"%s quota file already specified",
QTYPE2NAME(qtype));
goto errout;
}
if (strchr(qname, '/')) {
f2fs_msg(sb, KERN_ERR,
"quotafile must be on filesystem root");
goto errout;
}
sbi->s_qf_names[qtype] = qname;
set_opt(sbi, QUOTA);
return 0;
errout:
kfree(qname);
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: MagickExport void DestroyImagePixels(Image *image)
{
CacheInfo
*restrict cache_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickSignature);
if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL)
{
cache_info->methods.destroy_pixel_handler(image);
return;
}
image->cache=DestroyPixelCache(image->cache);
}
CWE ID: CWE-189
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int dispatch_discard_io(struct xen_blkif *blkif,
struct blkif_request *req)
{
int err = 0;
int status = BLKIF_RSP_OKAY;
struct block_device *bdev = blkif->vbd.bdev;
unsigned long secure;
blkif->st_ds_req++;
xen_blkif_get(blkif);
secure = (blkif->vbd.discard_secure &&
(req->u.discard.flag & BLKIF_DISCARD_SECURE)) ?
BLKDEV_DISCARD_SECURE : 0;
err = blkdev_issue_discard(bdev, req->u.discard.sector_number,
req->u.discard.nr_sectors,
GFP_KERNEL, secure);
if (err == -EOPNOTSUPP) {
pr_debug(DRV_PFX "discard op failed, not supported\n");
status = BLKIF_RSP_EOPNOTSUPP;
} else if (err)
status = BLKIF_RSP_ERROR;
make_response(blkif, req->u.discard.id, req->operation, status);
xen_blkif_put(blkif);
return err;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: ref_param_write_init(iparam_list * plist, const ref * pwanted,
gs_ref_memory_t *imem)
{
gs_param_list_init((gs_param_list *)plist, &ref_write_procs,
(gs_memory_t *)imem);
plist->ref_memory = imem;
if (pwanted == 0)
make_null(&plist->u.w.wanted);
else
plist->u.w.wanted = *pwanted;
plist->results = 0;
plist->int_keys = false;
}
CWE ID: CWE-704
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool TextureManager::TextureInfo::ValidForTexture(
GLint face,
GLint level,
GLint xoffset,
GLint yoffset,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type) const {
size_t face_index = GLTargetToFaceIndex(face);
if (level >= 0 && face_index < level_infos_.size() &&
static_cast<size_t>(level) < level_infos_[face_index].size()) {
const LevelInfo& info = level_infos_[GLTargetToFaceIndex(face)][level];
GLint right;
GLint top;
return SafeAdd(xoffset, width, &right) &&
SafeAdd(yoffset, height, &top) &&
xoffset >= 0 &&
yoffset >= 0 &&
right <= info.width &&
top <= info.height &&
format == info.internal_format &&
type == info.type;
}
return false;
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: jbig2_sd_count_referred(Jbig2Ctx *ctx, Jbig2Segment *segment)
{
int index;
Jbig2Segment *rsegment;
int n_dicts = 0;
for (index = 0; index < segment->referred_to_segment_count; index++) {
rsegment = jbig2_find_segment(ctx, segment->referred_to_segments[index]);
if (rsegment && ((rsegment->flags & 63) == 0) &&
rsegment->result && (((Jbig2SymbolDict *) rsegment->result)->n_symbols > 0) && ((*((Jbig2SymbolDict *) rsegment->result)->glyphs) != NULL))
n_dicts++;
}
return (n_dicts);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline void gen_op_movl_seg_T0_vm(int seg_reg)
{
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
tcg_gen_st32_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,segs[seg_reg].selector));
tcg_gen_shli_tl(cpu_seg_base[seg_reg], cpu_T0, 4);
}
CWE ID: CWE-94
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Profile* SyncTest::verifier() {
if (verifier_ == NULL)
LOG(FATAL) << "SetupClients() has not yet been called.";
return verifier_;
}
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: bool BluetoothDeviceChromeOS::ExpectingConfirmation() const {
return !confirmation_callback_.is_null();
}
CWE ID:
Target: 1
Example 2:
Code: struct in6_addr *fl6_update_dst(struct flowi6 *fl6,
const struct ipv6_txoptions *opt,
struct in6_addr *orig)
{
if (!opt || !opt->srcrt)
return NULL;
*orig = fl6->daddr;
fl6->daddr = *((struct rt0_hdr *)opt->srcrt)->addr;
return orig;
}
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 unsigned int variance_ref(const uint8_t *ref, const uint8_t *src,
int l2w, int l2h, unsigned int *sse_ptr) {
int se = 0;
unsigned int sse = 0;
const int w = 1 << l2w, h = 1 << l2h;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int diff = ref[w * y + x] - src[w * y + x];
se += diff;
sse += diff * diff;
}
//// Truncate high bit depth results by downshifting (with rounding) by:
//// 2 * (bit_depth - 8) for sse
//// (bit_depth - 8) for se
}
*sse_ptr = sse;
return sse - (((int64_t) se * se) >> (l2w + l2h));
}
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 AutofillManager::OnQueryFormFieldAutofillImpl(
int query_id,
const FormData& form,
const FormFieldData& field,
const gfx::RectF& transformed_box,
bool autoselect_first_suggestion) {
external_delegate_->OnQuery(query_id, form, field, transformed_box);
std::vector<Suggestion> suggestions;
SuggestionsContext context;
GetAvailableSuggestions(form, field, &suggestions, &context);
if (context.is_autofill_available) {
switch (context.suppress_reason) {
case SuppressReason::kNotSuppressed:
break;
case SuppressReason::kCreditCardsAblation:
enable_ablation_logging_ = true;
autocomplete_history_manager_->CancelPendingQuery();
external_delegate_->OnSuggestionsReturned(query_id, suggestions,
autoselect_first_suggestion);
return;
case SuppressReason::kAutocompleteOff:
return;
}
if (!suggestions.empty()) {
if (context.is_filling_credit_card) {
AutofillMetrics::LogIsQueriedCreditCardFormSecure(
context.is_context_secure);
}
if (!has_logged_address_suggestions_count_ &&
!context.section_has_autofilled_field) {
AutofillMetrics::LogAddressSuggestionsCount(suggestions.size());
has_logged_address_suggestions_count_ = true;
}
}
}
if (suggestions.empty() && !ShouldShowCreditCardSigninPromo(form, field) &&
field.should_autocomplete &&
!(context.focused_field &&
(IsCreditCardExpirationType(
context.focused_field->Type().GetStorableType()) ||
context.focused_field->Type().html_type() == HTML_TYPE_UNRECOGNIZED ||
context.focused_field->Type().GetStorableType() ==
CREDIT_CARD_NUMBER ||
context.focused_field->Type().GetStorableType() ==
CREDIT_CARD_VERIFICATION_CODE))) {
autocomplete_history_manager_->OnGetAutocompleteSuggestions(
query_id, field.name, field.value, field.form_control_type);
return;
}
autocomplete_history_manager_->CancelPendingQuery();
external_delegate_->OnSuggestionsReturned(query_id, suggestions,
autoselect_first_suggestion,
context.is_all_server_suggestions);
}
CWE ID:
Target: 1
Example 2:
Code: static void virtio_notify_vector(VirtIODevice *vdev, uint16_t vector)
{
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->notify) {
k->notify(qbus->parent, vector);
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ChromeMetricsServiceClient::SetNotificationListenerSetupFailedForTesting(
bool simulate_failure) {
g_notification_listeners_failed = simulate_failure;
}
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: void WebContentsImpl::RunBeforeUnloadConfirm(
RenderFrameHost* render_frame_host,
bool is_reload,
IPC::Message* reply_msg) {
RenderFrameHostImpl* rfhi =
static_cast<RenderFrameHostImpl*>(render_frame_host);
if (delegate_)
delegate_->WillRunBeforeUnloadConfirm();
bool suppress_this_message =
!rfhi->is_active() ||
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (suppress_this_message) {
rfhi->JavaScriptDialogClosed(reply_msg, true, base::string16());
return;
}
is_showing_before_unload_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunBeforeUnloadDialog(
this, is_reload,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
false));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: mrb_local_variables(mrb_state *mrb, mrb_value self)
{
struct RProc *proc;
mrb_irep *irep;
mrb_value vars;
size_t i;
proc = mrb->c->ci[-1].proc;
if (MRB_PROC_CFUNC_P(proc)) {
return mrb_ary_new(mrb);
}
vars = mrb_hash_new(mrb);
while (proc) {
if (MRB_PROC_CFUNC_P(proc)) break;
irep = proc->body.irep;
if (!irep->lv) break;
for (i = 0; i + 1 < irep->nlocals; ++i) {
if (irep->lv[i].name) {
mrb_hash_set(mrb, vars, mrb_symbol_value(irep->lv[i].name), mrb_true_value());
}
}
if (!MRB_PROC_ENV_P(proc)) break;
proc = proc->upper;
if (!proc->c) break;
}
return mrb_hash_keys(mrb, vars);
}
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 InputHandler::handleInputLocaleChanged(bool isRTL)
{
if (!isActiveTextEdit())
return;
ASSERT(m_currentFocusElement->document() && m_currentFocusElement->document()->frame());
RenderObject* renderer = m_currentFocusElement->renderer();
if (!renderer)
return;
Editor* editor = m_currentFocusElement->document()->frame()->editor();
ASSERT(editor);
if ((renderer->style()->direction() == RTL) != isRTL)
editor->setBaseWritingDirection(isRTL ? RightToLeftWritingDirection : LeftToRightWritingDirection);
}
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 __skb_tstamp_tx(struct sk_buff *orig_skb,
struct skb_shared_hwtstamps *hwtstamps,
struct sock *sk, int tstype)
{
struct sk_buff *skb;
bool tsonly;
if (!sk)
return;
tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
if (!skb_may_tx_timestamp(sk, tsonly))
return;
if (tsonly) {
#ifdef CONFIG_INET
if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
skb = tcp_get_timestamping_opt_stats(sk);
else
#endif
skb = alloc_skb(0, GFP_ATOMIC);
} else {
skb = skb_clone(orig_skb, GFP_ATOMIC);
}
if (!skb)
return;
if (tsonly) {
skb_shinfo(skb)->tx_flags = skb_shinfo(orig_skb)->tx_flags;
skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
}
if (hwtstamps)
*skb_hwtstamps(skb) = *hwtstamps;
else
skb->tstamp = ktime_get_real();
__skb_complete_tx_timestamp(skb, sk, tstype);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int ip6mr_forward2(struct net *net, struct mr6_table *mrt,
struct sk_buff *skb, struct mfc6_cache *c, int vifi)
{
struct ipv6hdr *ipv6h;
struct mif_device *vif = &mrt->vif6_table[vifi];
struct net_device *dev;
struct dst_entry *dst;
struct flowi6 fl6;
if (!vif->dev)
goto out_free;
#ifdef CONFIG_IPV6_PIMSM_V2
if (vif->flags & MIFF_REGISTER) {
vif->pkt_out++;
vif->bytes_out += skb->len;
vif->dev->stats.tx_bytes += skb->len;
vif->dev->stats.tx_packets++;
ip6mr_cache_report(mrt, skb, vifi, MRT6MSG_WHOLEPKT);
goto out_free;
}
#endif
ipv6h = ipv6_hdr(skb);
fl6 = (struct flowi6) {
.flowi6_oif = vif->link,
.daddr = ipv6h->daddr,
};
dst = ip6_route_output(net, NULL, &fl6);
if (dst->error) {
dst_release(dst);
goto out_free;
}
skb_dst_drop(skb);
skb_dst_set(skb, dst);
/*
* RFC1584 teaches, that DVMRP/PIM router must deliver packets locally
* not only before forwarding, but after forwarding on all output
* interfaces. It is clear, if mrouter runs a multicasting
* program, it should receive packets not depending to what interface
* program is joined.
* If we will not make it, the program will have to join on all
* interfaces. On the other hand, multihoming host (or router, but
* not mrouter) cannot join to more than one interface - it will
* result in receiving multiple packets.
*/
dev = vif->dev;
skb->dev = dev;
vif->pkt_out++;
vif->bytes_out += skb->len;
/* We are about to write */
/* XXX: extension headers? */
if (skb_cow(skb, sizeof(*ipv6h) + LL_RESERVED_SPACE(dev)))
goto out_free;
ipv6h = ipv6_hdr(skb);
ipv6h->hop_limit--;
IP6CB(skb)->flags |= IP6SKB_FORWARDED;
return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD,
net, NULL, skb, skb->dev, dev,
ip6mr_forward2_finish);
out_free:
kfree_skb(skb);
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool AppCache::AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry) {
std::pair<EntryMap::iterator, bool> ret =
entries_.insert(EntryMap::value_type(url, entry));
if (!ret.second)
ret.first->second.add_types(entry.types());
else
cache_size_ += entry.response_size(); // New entry. Add to cache size.
return ret.second;
}
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: int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
{
struct sctp_association *asoc = sctp_id2assoc(sk, id);
struct sctp_sock *sp = sctp_sk(sk);
struct socket *sock;
int err = 0;
if (!asoc)
return -EINVAL;
/* An association cannot be branched off from an already peeled-off
* socket, nor is this supported for tcp style sockets.
*/
if (!sctp_style(sk, UDP))
return -EINVAL;
/* Create a new socket. */
err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
if (err < 0)
return err;
sctp_copy_sock(sock->sk, sk, asoc);
/* Make peeled-off sockets more like 1-1 accepted sockets.
* Set the daddr and initialize id to something more random
*/
sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);
/* Populate the fields of the newsk from the oldsk and migrate the
* asoc to the newsk.
*/
sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
*sockp = sock;
return err;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: static bool fm10k_set_rss_queues(struct fm10k_intfc *interface)
{
struct fm10k_ring_feature *f;
u16 rss_i;
f = &interface->ring_feature[RING_F_RSS];
rss_i = min_t(u16, interface->hw.mac.max_queues, f->limit);
/* record indices and power of 2 mask for RSS */
f->indices = rss_i;
f->mask = BIT(fls(rss_i - 1)) - 1;
interface->num_rx_queues = rss_i;
interface->num_tx_queues = rss_i;
return true;
}
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 CheckFakeData(uint8* audio_data, int frames_written,
double playback_rate) {
size_t length =
(frames_written * algorithm_.bytes_per_frame())
/ algorithm_.bytes_per_channel();
switch (algorithm_.bytes_per_channel()) {
case 4:
DoCheckFakeData<int32>(audio_data, length);
break;
case 2:
DoCheckFakeData<int16>(audio_data, length);
break;
case 1:
DoCheckFakeData<uint8>(audio_data, length);
break;
default:
NOTREACHED() << "Unsupported audio bit depth in crossfade.";
}
}
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: xfs_attr_rmtval_set(
struct xfs_da_args *args)
{
struct xfs_inode *dp = args->dp;
struct xfs_mount *mp = dp->i_mount;
struct xfs_bmbt_irec map;
xfs_dablk_t lblkno;
xfs_fileoff_t lfileoff = 0;
__uint8_t *src = args->value;
int blkcnt;
int valuelen;
int nmap;
int error;
int offset = 0;
trace_xfs_attr_rmtval_set(args);
/*
* Find a "hole" in the attribute address space large enough for
* us to drop the new attribute's value into. Because CRC enable
* attributes have headers, we can't just do a straight byte to FSB
* conversion and have to take the header space into account.
*/
blkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen);
error = xfs_bmap_first_unused(args->trans, args->dp, blkcnt, &lfileoff,
XFS_ATTR_FORK);
if (error)
return error;
args->rmtblkno = lblkno = (xfs_dablk_t)lfileoff;
args->rmtblkcnt = blkcnt;
/*
* Roll through the "value", allocating blocks on disk as required.
*/
while (blkcnt > 0) {
int committed;
/*
* Allocate a single extent, up to the size of the value.
*/
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_write(args->trans, dp, (xfs_fileoff_t)lblkno,
blkcnt,
XFS_BMAPI_ATTRFORK | XFS_BMAPI_METADATA,
args->firstblock, args->total, &map, &nmap,
args->flist);
if (!error) {
error = xfs_bmap_finish(&args->trans, args->flist,
&committed);
}
if (error) {
ASSERT(committed);
args->trans = NULL;
xfs_bmap_cancel(args->flist);
return(error);
}
/*
* bmap_finish() may have committed the last trans and started
* a new one. We need the inode to be in all transactions.
*/
if (committed)
xfs_trans_ijoin(args->trans, dp, 0);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
/*
* Start the next trans in the chain.
*/
error = xfs_trans_roll(&args->trans, dp);
if (error)
return (error);
}
/*
* Roll through the "value", copying the attribute value to the
* already-allocated blocks. Blocks are written synchronously
* so that we can know they are all on disk before we turn off
* the INCOMPLETE flag.
*/
lblkno = args->rmtblkno;
blkcnt = args->rmtblkcnt;
valuelen = args->valuelen;
while (valuelen > 0) {
struct xfs_buf *bp;
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT(blkcnt > 0);
xfs_bmap_init(args->flist, args->firstblock);
nmap = 1;
error = xfs_bmapi_read(dp, (xfs_fileoff_t)lblkno,
blkcnt, &map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return(error);
ASSERT(nmap == 1);
ASSERT((map.br_startblock != DELAYSTARTBLOCK) &&
(map.br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map.br_startblock),
dblkcnt = XFS_FSB_TO_BB(mp, map.br_blockcount);
bp = xfs_buf_get(mp->m_ddev_targp, dblkno, dblkcnt, 0);
if (!bp)
return ENOMEM;
bp->b_ops = &xfs_attr3_rmt_buf_ops;
xfs_attr_rmtval_copyin(mp, bp, args->dp->i_ino, &offset,
&valuelen, &src);
error = xfs_bwrite(bp); /* GROT: NOTE: synchronous write */
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map.br_blockcount;
blkcnt -= map.br_blockcount;
}
ASSERT(valuelen == 0);
return 0;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: void WebContentsImpl::Stop() {
render_manager_.Stop();
FOR_EACH_OBSERVER(WebContentsObserver, observers_, NavigationStopped());
}
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: aura::Window* CreateNonActivatableWindow(const gfx::Rect& bounds) {
aura::Window* window = CreateWindow(bounds);
::wm::SetActivationDelegate(window, &non_activatable_activation_delegate_);
EXPECT_FALSE(wm::CanActivateWindow(window));
return window;
}
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: error::Error GLES2DecoderPassthroughImpl::ProcessQueries(bool did_finish) {
while (!pending_queries_.empty()) {
const PendingQuery& query = pending_queries_.front();
GLuint result_available = GL_FALSE;
GLuint64 result = 0;
switch (query.target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
DCHECK(query.commands_completed_fence != nullptr);
result_available =
did_finish || query.commands_completed_fence->HasCompleted();
result = result_available;
break;
case GL_COMMANDS_ISSUED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
break;
case GL_LATENCY_QUERY_CHROMIUM:
result_available = GL_TRUE;
result = (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
break;
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
for (const PendingReadPixels& pending_read_pixels :
pending_read_pixels_) {
if (pending_read_pixels.waiting_async_pack_queries.count(
query.service_id) > 0) {
DCHECK(!did_finish);
result_available = GL_FALSE;
result = GL_FALSE;
break;
}
}
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
DCHECK(query.buffer_shadow_update_fence);
if (did_finish || query.buffer_shadow_update_fence->HasCompleted()) {
ReadBackBuffersIntoShadowCopies(query.buffer_shadow_updates);
result_available = GL_TRUE;
result = 0;
}
break;
case GL_GET_ERROR_QUERY_CHROMIUM:
result_available = GL_TRUE;
FlushErrors();
result = PopError();
break;
default:
DCHECK(!IsEmulatedQueryTarget(query.target));
if (did_finish) {
result_available = GL_TRUE;
} else {
api()->glGetQueryObjectuivFn(
query.service_id, GL_QUERY_RESULT_AVAILABLE, &result_available);
}
if (result_available == GL_TRUE) {
if (feature_info_->feature_flags().ext_disjoint_timer_query) {
api()->glGetQueryObjectui64vFn(query.service_id, GL_QUERY_RESULT,
&result);
} else {
GLuint temp_result = 0;
api()->glGetQueryObjectuivFn(query.service_id, GL_QUERY_RESULT,
&temp_result);
result = temp_result;
}
}
break;
}
if (!result_available) {
break;
}
query.sync->result = result;
base::subtle::Release_Store(&query.sync->process_count, query.submit_count);
pending_queries_.pop_front();
}
DCHECK(!did_finish || pending_queries_.empty());
return error::kNoError;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: Skeletons GetSkeletons(const base::string16& host) {
return g_idn_spoof_checker.Get().GetSkeletons(host);
}
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 RenderProcessHostImpl::OnAssociatedInterfaceRequest(
const std::string& interface_name,
mojo::ScopedInterfaceEndpointHandle handle) {
if (associated_interfaces_ &&
associated_interfaces_->CanBindRequest(interface_name)) {
associated_interfaces_->BindRequest(interface_name, std::move(handle));
} else {
LOG(ERROR) << "Request for unknown Channel-associated interface: "
<< interface_name;
}
}
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: DateTimeFieldElement::DateTimeFieldElement(Document* document, FieldOwner& fieldOwner)
: HTMLElement(spanTag, document)
, m_fieldOwner(&fieldOwner)
{
setAttribute(roleAttr, "spinbutton");
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: struct CookieInfo *Curl_cookie_init(struct SessionHandle *data,
const char *file,
struct CookieInfo *inc,
bool newsession)
{
struct CookieInfo *c;
FILE *fp;
bool fromfile=TRUE;
if(NULL == inc) {
/* we didn't get a struct, create one */
c = calloc(1, sizeof(struct CookieInfo));
if(!c)
return NULL; /* failed to get memory */
c->filename = strdup(file?file:"none"); /* copy the name just in case */
}
else {
/* we got an already existing one, use that */
c = inc;
}
c->running = FALSE; /* this is not running, this is init */
if(file && strequal(file, "-")) {
fp = stdin;
fromfile=FALSE;
}
else if(file && !*file) {
/* points to a "" string */
fp = NULL;
}
else
fp = file?fopen(file, "r"):NULL;
c->newsession = newsession; /* new session? */
if(fp) {
char *lineptr;
bool headerline;
char *line = malloc(MAX_COOKIE_LINE);
if(line) {
while(fgets(line, MAX_COOKIE_LINE, fp)) {
if(checkprefix("Set-Cookie:", line)) {
/* This is a cookie line, get it! */
lineptr=&line[11];
headerline=TRUE;
}
else {
lineptr=line;
headerline=FALSE;
}
while(*lineptr && ISBLANK(*lineptr))
lineptr++;
Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL);
}
free(line); /* free the line buffer */
}
if(fromfile)
fclose(fp);
}
c->running = TRUE; /* now, we're running */
return c;
}
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 LoadingStatsCollector::CleanupAbandonedStats() {
base::TimeTicks time_now = base::TimeTicks::Now();
for (auto it = preconnect_stats_.begin(); it != preconnect_stats_.end();) {
if (time_now - it->second->start_time > max_stats_age_) {
ReportPreconnectAccuracy(*it->second,
std::map<GURL, OriginRequestSummary>());
it = preconnect_stats_.erase(it);
} else {
++it;
}
}
}
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 tls1_setup_key_block(SSL *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
SSL_COMP *comp;
int mac_type = NID_undef, mac_secret_size = 0;
int ret = 0;
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp
(s->session, &c, &hash, &mac_type, &mac_secret_size, &comp,
SSL_USE_ETM(s))) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
s->s3->tmp.new_mac_pkey_type = mac_type;
s->s3->tmp.new_mac_secret_size = mac_secret_size;
num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p;
#ifdef SSL_DEBUG
printf("client random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->client_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("server random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->server_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("master key\n");
{
int z;
for (z = 0; z < s->session->master_key_length; z++)
printf("%02X%c", s->session->master_key[z],
((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!tls1_generate_key_block(s, p, num))
goto err;
#ifdef SSL_DEBUG
printf("\nkey block\n");
{
int z;
for (z = 0; z < num; z++)
printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
&& s->method->version <= TLS1_VERSION) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
ret = 1;
err:
return (ret);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: entry_guards_load_guards_from_state(or_state_t *state, int set)
{
const config_line_t *line = state->Guard;
int n_errors = 0;
if (!guard_contexts)
guard_contexts = smartlist_new();
/* Wipe all our existing guard info. (we shouldn't have any, but
* let's be safe.) */
if (set) {
SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
guard_selection_free(gs);
if (curr_guard_context == gs)
curr_guard_context = NULL;
SMARTLIST_DEL_CURRENT(guard_contexts, gs);
} SMARTLIST_FOREACH_END(gs);
}
for ( ; line != NULL; line = line->next) {
entry_guard_t *guard = entry_guard_parse_from_state(line->value);
if (guard == NULL) {
++n_errors;
continue;
}
tor_assert(guard->selection_name);
if (!strcmp(guard->selection_name, "legacy")) {
++n_errors;
entry_guard_free(guard);
continue;
}
if (set) {
guard_selection_t *gs;
gs = get_guard_selection_by_name(guard->selection_name,
GS_TYPE_INFER, 1);
tor_assert(gs);
smartlist_add(gs->sampled_entry_guards, guard);
guard->in_selection = gs;
} else {
entry_guard_free(guard);
}
}
if (set) {
SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
entry_guards_update_all(gs);
} SMARTLIST_FOREACH_END(gs);
}
return n_errors ? -1 : 0;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void IRCView::appendBacklogMessage(const QString& firstColumn,const QString& rawMessage)
{
QString time;
QString message = rawMessage;
QString nick = firstColumn;
QString backlogColor = Preferences::self()->color(Preferences::BacklogMessage).name();
m_tabNotification = Konversation::tnfNone;
int eot = nick.lastIndexOf(' ');
time = nick.left(eot);
nick = nick.mid(eot+1);
if(!nick.isEmpty() && !nick.startsWith('<') && !nick.startsWith('*'))
{
nick = '|' + nick + '|';
}
nick.replace('<',"<");
nick.replace('>',">");
QString line;
QChar::Direction dir;
QString text(filter(message, backlogColor, NULL, false, false, false, &dir));
bool rtl = (dir == QChar::DirR);
if(rtl)
{
line = RLE;
line += LRE;
line += "<font color=\"" + backlogColor + "\">%2 %1" + PDF + " %3</font>";
}
else
{
if (!QApplication::isLeftToRight())
line += LRE;
line += "<font color=\"" + backlogColor + "\">%1 %2 %3</font>";
}
line = line.arg(time, nick, text);
doAppend(line, rtl);
}
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: EffectPaintPropertyNode* EffectPaintPropertyNode::Root() {
DEFINE_STATIC_REF(EffectPaintPropertyNode, root,
(EffectPaintPropertyNode::Create(
nullptr, State{TransformPaintPropertyNode::Root(),
ClipPaintPropertyNode::Root()})));
return root;
}
CWE ID:
Target: 1
Example 2:
Code: rsa_private_key_prepare(struct rsa_private_key *key)
{
mpz_t n;
/* The size of the product is the sum of the sizes of the factors,
* or sometimes one less. It's possible but tricky to compute the
* size without computing the full product. */
mpz_init(n);
mpz_mul(n, key->p, key->q);
key->size = _rsa_check_size(n);
mpz_clear(n);
return (key->size > 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: sctp_disposition_t sctp_sf_eat_fwd_tsn(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
SCTP_DEBUG_PRINTK("%s: TSN 0x%x.\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto discard_noforce;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto discard_noforce;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Count this as receiving DATA. */
if (asoc->autoclose) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* FIXME: For now send a SACK, but DATA processing may
* send another.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE());
return SCTP_DISPOSITION_CONSUME;
discard_noforce:
return SCTP_DISPOSITION_DISCARD;
}
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 NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name)
{
unsigned upper_length;
int len, type, optlen;
char *dest, *ret;
/* option points to OPT_DATA, need to go back to get OPT_LEN */
len = option[-OPT_DATA + OPT_LEN];
type = optflag->flags & OPTION_TYPE_MASK;
optlen = dhcp_option_lengths[type];
upper_length = len_of_option_as_string[type]
* ((unsigned)(len + optlen - 1) / (unsigned)optlen);
dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
dest += sprintf(ret, "%s=", opt_name);
while (len >= optlen) {
switch (type) {
case OPTION_IP:
case OPTION_IP_PAIR:
dest += sprint_nip(dest, "", option);
if (type == OPTION_IP)
break;
dest += sprint_nip(dest, "/", option + 4);
break;
case OPTION_U8:
dest += sprintf(dest, "%u", *option);
break;
case OPTION_U16: {
uint16_t val_u16;
move_from_unaligned16(val_u16, option);
dest += sprintf(dest, "%u", ntohs(val_u16));
break;
}
case OPTION_S32:
case OPTION_U32: {
uint32_t val_u32;
move_from_unaligned32(val_u32, option);
dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32));
break;
}
/* Note: options which use 'return' instead of 'break'
* (for example, OPTION_STRING) skip the code which handles
* the case of list of options.
*/
case OPTION_STRING:
case OPTION_STRING_HOST:
memcpy(dest, option, len);
dest[len] = '\0';
if (type == OPTION_STRING_HOST && !good_hostname(dest))
safe_strncpy(dest, "bad", len);
return ret;
case OPTION_STATIC_ROUTES: {
/* Option binary format:
* mask [one byte, 0..32]
* ip [big endian, 0..4 bytes depending on mask]
* router [big endian, 4 bytes]
* may be repeated
*
* We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2"
*/
const char *pfx = "";
while (len >= 1 + 4) { /* mask + 0-byte ip + router */
uint32_t nip;
uint8_t *p;
unsigned mask;
int bytes;
mask = *option++;
if (mask > 32)
break;
len--;
nip = 0;
p = (void*) &nip;
bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */
while (--bytes >= 0) {
*p++ = *option++;
len--;
}
if (len < 4)
break;
/* print ip/mask */
dest += sprint_nip(dest, pfx, (void*) &nip);
pfx = " ";
dest += sprintf(dest, "/%u ", mask);
/* print router */
dest += sprint_nip(dest, "", option);
option += 4;
len -= 4;
}
return ret;
}
case OPTION_6RD:
/* Option binary format (see RFC 5969):
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 6rdPrefix |
* ... (16 octets) ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* ... 6rdBRIPv4Address(es) ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* We convert it to a string
* "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..."
*
* Sanity check: ensure that our length is at least 22 bytes, that
* IPv4MaskLen <= 32,
* 6rdPrefixLen <= 128,
* 6rdPrefixLen + (32 - IPv4MaskLen) <= 128
* (2nd condition need no check - it follows from 1st and 3rd).
* Else, return envvar with empty value ("optname=")
*/
if (len >= (1 + 1 + 16 + 4)
&& option[0] <= 32
&& (option[1] + 32 - option[0]) <= 128
) {
/* IPv4MaskLen */
dest += sprintf(dest, "%u ", *option++);
/* 6rdPrefixLen */
dest += sprintf(dest, "%u ", *option++);
/* 6rdPrefix */
dest += sprint_nip6(dest, /* "", */ option);
option += 16;
len -= 1 + 1 + 16 + 4;
/* "+ 4" above corresponds to the length of IPv4 addr
* we consume in the loop below */
while (1) {
/* 6rdBRIPv4Address(es) */
dest += sprint_nip(dest, " ", option);
option += 4;
len -= 4; /* do we have yet another 4+ bytes? */
if (len < 0)
break; /* no */
}
}
return ret;
#if ENABLE_FEATURE_UDHCP_RFC3397
case OPTION_DNS_STRING:
/* unpack option into dest; use ret for prefix (i.e., "optname=") */
dest = dname_dec(option, len, ret);
if (dest) {
free(ret);
return dest;
}
/* error. return "optname=" string */
return ret;
case OPTION_SIP_SERVERS:
/* Option binary format:
* type: byte
* type=0: domain names, dns-compressed
* type=1: IP addrs
*/
option++;
len--;
if (option[-1] == 0) {
dest = dname_dec(option, len, ret);
if (dest) {
free(ret);
return dest;
}
} else
if (option[-1] == 1) {
const char *pfx = "";
while (1) {
len -= 4;
if (len < 0)
break;
dest += sprint_nip(dest, pfx, option);
pfx = " ";
option += 4;
}
}
return ret;
#endif
} /* switch */
/* If we are here, try to format any remaining data
* in the option as another, similarly-formatted option
*/
option += optlen;
len -= optlen;
if (len < optlen /* || !(optflag->flags & OPTION_LIST) */)
break;
*dest++ = ' ';
*dest = '\0';
} /* while */
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: MagickExport PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickSignature);
if (cache_info->methods.queue_authentic_pixels_handler !=
(QueueAuthenticPixelsHandler) NULL)
return(cache_info->methods.queue_authentic_pixels_handler(image,x,y,columns,
rows,exception));
assert(id < (int) cache_info->number_threads);
return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse,
cache_info->nexus_info[id],exception));
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
{
if (refcount_dec_and_test(&ctx->refcount)) {
VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
mmdrop(ctx->mm);
kmem_cache_free(userfaultfd_ctx_cachep, ctx);
}
}
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 spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */
{
spl_filesystem_object *intern;
zend_bool use_include_path = 0;
zval *arg1, *arg2;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
switch (source->type) {
case SPL_FS_INFO:
case SPL_FS_FILE:
break;
case SPL_FS_DIR:
if (!source->u.dir.entry.d_name[0]) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file");
zend_restore_error_handling(&error_handling TSRMLS_CC);
return NULL;
}
}
switch (type) {
case SPL_FS_INFO:
ce = ce ? ce : source->info_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
spl_filesystem_object_get_file_name(source TSRMLS_CC);
if (ce->constructor->common.scope != spl_ce_SplFileInfo) {
MAKE_STD_ZVAL(arg1);
ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1);
zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1);
zval_ptr_dtor(&arg1);
} else {
intern->file_name = estrndup(source->file_name, source->file_name_len);
intern->file_name_len = source->file_name_len;
intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC);
intern->_path = estrndup(intern->_path, intern->_path_len);
}
break;
case SPL_FS_FILE:
ce = ce ? ce : source->file_class;
zend_update_class_constants(ce TSRMLS_CC);
return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC);
Z_TYPE_P(return_value) = IS_OBJECT;
spl_filesystem_object_get_file_name(source TSRMLS_CC);
if (ce->constructor->common.scope != spl_ce_SplFileObject) {
MAKE_STD_ZVAL(arg1);
MAKE_STD_ZVAL(arg2);
ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1);
ZVAL_STRINGL(arg2, "r", 1, 1);
zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2);
zval_ptr_dtor(&arg1);
zval_ptr_dtor(&arg2);
} else {
intern->file_name = source->file_name;
intern->file_name_len = source->file_name_len;
intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC);
intern->_path = estrndup(intern->_path, intern->_path_len);
intern->u.file.open_mode = "r";
intern->u.file.open_mode_len = 1;
if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr",
&intern->u.file.open_mode, &intern->u.file.open_mode_len,
&use_include_path, &intern->u.file.zcontext) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
intern->u.file.open_mode = NULL;
intern->file_name = NULL;
zval_dtor(return_value);
Z_TYPE_P(return_value) = IS_NULL;
return NULL;
}
if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
zval_dtor(return_value);
Z_TYPE_P(return_value) = IS_NULL;
return NULL;
}
}
break;
case SPL_FS_DIR:
zend_restore_error_handling(&error_handling TSRMLS_CC);
zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported");
return NULL;
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
return NULL;
} /* }}} */
CWE ID: CWE-190
Target: 1
Example 2:
Code: status_t OMXNodeInstance::updateGraphicBufferInMeta(
OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer,
OMX::buffer_id buffer) {
Mutex::Autolock autoLock(mLock);
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, portIndex);
return updateGraphicBufferInMeta_l(
portIndex, graphicBuffer, buffer, header,
true /* updateCodecBuffer */);
}
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: JSRetainPtr<JSStringRef> AccessibilityUIElement::stringValue()
{
return JSStringCreateWithCharacters(0, 0);
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int ttusbdecfe_dvbs_diseqc_send_master_cmd(struct dvb_frontend* fe, struct dvb_diseqc_master_cmd *cmd)
{
struct ttusbdecfe_state* state = (struct ttusbdecfe_state*) fe->demodulator_priv;
u8 b[] = { 0x00, 0xff, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00 };
memcpy(&b[4], cmd->msg, cmd->msg_len);
state->config->send_command(fe, 0x72,
sizeof(b) - (6 - cmd->msg_len), b,
NULL, NULL);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void S_fromCharCode(js_State *J)
{
int i, top = js_gettop(J);
Rune c;
char *s, *p;
s = p = js_malloc(J, (top-1) * UTFmax + 1);
if (js_try(J)) {
js_free(J, s);
js_throw(J);
}
for (i = 1; i < top; ++i) {
c = js_touint16(J, i);
p += runetochar(p, &c);
}
*p = 0;
js_pushstring(J, s);
js_endtry(J);
js_free(J, s);
}
CWE ID: CWE-400
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __perf_event_enable(void *info)
{
struct perf_event *event = info;
struct perf_event_context *ctx = event->ctx;
struct perf_event *leader = event->group_leader;
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
int err;
if (WARN_ON_ONCE(!ctx->is_active))
return -EINVAL;
raw_spin_lock(&ctx->lock);
update_context_time(ctx);
if (event->state >= PERF_EVENT_STATE_INACTIVE)
goto unlock;
/*
* set current task's cgroup time reference point
*/
perf_cgroup_set_timestamp(current, ctx);
__perf_event_mark_enabled(event);
if (!event_filter_match(event)) {
if (is_cgroup_event(event))
perf_cgroup_defer_enabled(event);
goto unlock;
}
/*
* If the event is in a group and isn't the group leader,
* then don't put it on unless the group is on.
*/
if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
goto unlock;
if (!group_can_go_on(event, cpuctx, 1)) {
err = -EEXIST;
} else {
if (event == leader)
err = group_sched_in(event, cpuctx, ctx);
else
err = event_sched_in(event, cpuctx, ctx);
}
if (err) {
/*
* If this event can't go on and it's part of a
* group, then the whole group has to come off.
*/
if (leader != event)
group_sched_out(leader, cpuctx, ctx);
if (leader->attr.pinned) {
update_group_times(leader);
leader->state = PERF_EVENT_STATE_ERROR;
}
}
unlock:
raw_spin_unlock(&ctx->lock);
return 0;
}
CWE ID: CWE-189
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: struct bio *bio_map_user_iov(struct request_queue *q,
const struct iov_iter *iter,
gfp_t gfp_mask)
{
int j;
int nr_pages = 0;
struct page **pages;
struct bio *bio;
int cur_page = 0;
int ret, offset;
struct iov_iter i;
struct iovec iov;
iov_for_each(iov, i, *iter) {
unsigned long uaddr = (unsigned long) iov.iov_base;
unsigned long len = iov.iov_len;
unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
unsigned long start = uaddr >> PAGE_SHIFT;
/*
* Overflow, abort
*/
if (end < start)
return ERR_PTR(-EINVAL);
nr_pages += end - start;
/*
* buffer must be aligned to at least logical block size for now
*/
if (uaddr & queue_dma_alignment(q))
return ERR_PTR(-EINVAL);
}
if (!nr_pages)
return ERR_PTR(-EINVAL);
bio = bio_kmalloc(gfp_mask, nr_pages);
if (!bio)
return ERR_PTR(-ENOMEM);
ret = -ENOMEM;
pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask);
if (!pages)
goto out;
iov_for_each(iov, i, *iter) {
unsigned long uaddr = (unsigned long) iov.iov_base;
unsigned long len = iov.iov_len;
unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
unsigned long start = uaddr >> PAGE_SHIFT;
const int local_nr_pages = end - start;
const int page_limit = cur_page + local_nr_pages;
ret = get_user_pages_fast(uaddr, local_nr_pages,
(iter->type & WRITE) != WRITE,
&pages[cur_page]);
if (ret < local_nr_pages) {
ret = -EFAULT;
goto out_unmap;
}
offset = offset_in_page(uaddr);
for (j = cur_page; j < page_limit; j++) {
unsigned int bytes = PAGE_SIZE - offset;
unsigned short prev_bi_vcnt = bio->bi_vcnt;
if (len <= 0)
break;
if (bytes > len)
bytes = len;
/*
* sorry...
*/
if (bio_add_pc_page(q, bio, pages[j], bytes, offset) <
bytes)
break;
/*
* check if vector was merged with previous
* drop page reference if needed
*/
if (bio->bi_vcnt == prev_bi_vcnt)
put_page(pages[j]);
len -= bytes;
offset = 0;
}
cur_page = j;
/*
* release the pages we didn't map into the bio, if any
*/
while (j < page_limit)
put_page(pages[j++]);
}
kfree(pages);
bio_set_flag(bio, BIO_USER_MAPPED);
/*
* subtle -- if bio_map_user_iov() ended up bouncing a bio,
* it would normally disappear when its bi_end_io is run.
* however, we need it for the unmap, so grab an extra
* reference to it
*/
bio_get(bio);
return bio;
out_unmap:
for (j = 0; j < nr_pages; j++) {
if (!pages[j])
break;
put_page(pages[j]);
}
out:
kfree(pages);
bio_put(bio);
return ERR_PTR(ret);
}
CWE ID: CWE-772
Target: 1
Example 2:
Code: server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
{
fd_set *fdset;
int i, j, ret, maxfd;
int startups = 0;
int startup_p[2] = { -1 , -1 };
struct sockaddr_storage from;
socklen_t fromlen;
pid_t pid;
/* setup fd set for accept */
fdset = NULL;
maxfd = 0;
for (i = 0; i < num_listen_socks; i++)
if (listen_socks[i] > maxfd)
maxfd = listen_socks[i];
/* pipes connected to unauthenticated childs */
startup_pipes = xcalloc(options.max_startups, sizeof(int));
for (i = 0; i < options.max_startups; i++)
startup_pipes[i] = -1;
/*
* Stay listening for connections until the system crashes or
* the daemon is killed with a signal.
*/
for (;;) {
if (received_sighup)
sighup_restart();
free(fdset);
fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
sizeof(fd_mask));
for (i = 0; i < num_listen_socks; i++)
FD_SET(listen_socks[i], fdset);
for (i = 0; i < options.max_startups; i++)
if (startup_pipes[i] != -1)
FD_SET(startup_pipes[i], fdset);
/* Wait in select until there is a connection. */
ret = select(maxfd+1, fdset, NULL, NULL, NULL);
if (ret < 0 && errno != EINTR)
error("select: %.100s", strerror(errno));
if (received_sigterm) {
logit("Received signal %d; terminating.",
(int) received_sigterm);
close_listen_socks();
if (options.pid_file != NULL)
unlink(options.pid_file);
exit(received_sigterm == SIGTERM ? 0 : 255);
}
if (ret < 0)
continue;
for (i = 0; i < options.max_startups; i++)
if (startup_pipes[i] != -1 &&
FD_ISSET(startup_pipes[i], fdset)) {
/*
* the read end of the pipe is ready
* if the child has closed the pipe
* after successful authentication
* or if the child has died
*/
close(startup_pipes[i]);
startup_pipes[i] = -1;
startups--;
}
for (i = 0; i < num_listen_socks; i++) {
if (!FD_ISSET(listen_socks[i], fdset))
continue;
fromlen = sizeof(from);
*newsock = accept(listen_socks[i],
(struct sockaddr *)&from, &fromlen);
if (*newsock < 0) {
if (errno != EINTR && errno != EWOULDBLOCK &&
errno != ECONNABORTED)
error("accept: %.100s",
strerror(errno));
if (errno == EMFILE || errno == ENFILE)
usleep(100 * 1000);
continue;
}
if (unset_nonblock(*newsock) == -1) {
close(*newsock);
continue;
}
if (drop_connection(startups) == 1) {
debug("drop connection #%d", startups);
close(*newsock);
continue;
}
if (pipe(startup_p) == -1) {
close(*newsock);
continue;
}
if (rexec_flag && socketpair(AF_UNIX,
SOCK_STREAM, 0, config_s) == -1) {
error("reexec socketpair: %s",
strerror(errno));
close(*newsock);
close(startup_p[0]);
close(startup_p[1]);
continue;
}
for (j = 0; j < options.max_startups; j++)
if (startup_pipes[j] == -1) {
startup_pipes[j] = startup_p[0];
if (maxfd < startup_p[0])
maxfd = startup_p[0];
startups++;
break;
}
/*
* Got connection. Fork a child to handle it, unless
* we are in debugging mode.
*/
if (debug_flag) {
/*
* In debugging mode. Close the listening
* socket, and start processing the
* connection without forking.
*/
debug("Server will not fork when running in debugging mode.");
close_listen_socks();
*sock_in = *newsock;
*sock_out = *newsock;
close(startup_p[0]);
close(startup_p[1]);
startup_pipe = -1;
pid = getpid();
if (rexec_flag) {
send_rexec_state(config_s[0],
&cfg);
close(config_s[0]);
}
break;
}
/*
* Normal production daemon. Fork, and have
* the child process the connection. The
* parent continues listening.
*/
if ((pid = fork()) == 0) {
/*
* Child. Close the listening and
* max_startup sockets. Start using
* the accepted socket. Reinitialize
* logging (since our pid has changed).
* We break out of the loop to handle
* the connection.
*/
startup_pipe = startup_p[1];
close_startup_pipes();
close_listen_socks();
*sock_in = *newsock;
*sock_out = *newsock;
log_init(__progname,
options.log_level,
options.log_facility,
log_stderr);
if (rexec_flag)
close(config_s[0]);
break;
}
/* Parent. Stay in the loop. */
if (pid < 0)
error("fork: %.100s", strerror(errno));
else
debug("Forked child %ld.", (long)pid);
close(startup_p[1]);
if (rexec_flag) {
send_rexec_state(config_s[0], &cfg);
close(config_s[0]);
close(config_s[1]);
}
close(*newsock);
}
/* child process check (or debug mode) */
if (num_listen_socks < 0)
break;
}
}
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 SetExperimentEnabled(
PrefService* prefs, const std::string& internal_name, bool enable) {
FlagsState::GetInstance()->SetExperimentEnabled(prefs, internal_name, enable);
}
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: ber_parse_header(STREAM s, int tagval, int *length)
{
int tag, len;
if (tagval > 0xff)
{
in_uint16_be(s, tag);
}
else
{
in_uint8(s, tag);
}
if (tag != tagval)
{
logger(Core, Error, "ber_parse_header(), expected tag %d, got %d", tagval, tag);
return False;
}
in_uint8(s, len);
if (len & 0x80)
{
len &= ~0x80;
*length = 0;
while (len--)
next_be(s, *length);
}
else
*length = len;
return s_check(s);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void strictTypeCheckingTestInterfaceAttributeAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
ExceptionState exceptionState(ExceptionState::SetterContext, "strictTypeCheckingTestInterfaceAttribute", "TestObjectPython", info.Holder(), info.GetIsolate());
if (!isUndefinedOrNull(jsValue) && !V8TestInterface::hasInstance(jsValue, info.GetIsolate())) {
exceptionState.throwTypeError("The provided value is not of type 'TestInterface'.");
exceptionState.throwIfNeeded();
return;
}
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
V8TRYCATCH_VOID(TestInterface*, cppValue, V8TestInterface::toNativeWithTypeCheck(info.GetIsolate(), jsValue));
imp->setStrictTypeCheckingTestInterfaceAttribute(WTF::getPtr(cppValue));
}
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 LauncherView::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) {
FOR_EACH_OBSERVER(LauncherIconObserver, observers_,
OnLauncherIconPositionsChanged());
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int inet_sk_reselect_saddr(struct sock *sk)
{
struct inet_sock *inet = inet_sk(sk);
__be32 old_saddr = inet->inet_saddr;
__be32 daddr = inet->inet_daddr;
struct flowi4 fl4;
struct rtable *rt;
__be32 new_saddr;
if (inet->opt && inet->opt->srr)
daddr = inet->opt->faddr;
/* Query new route. */
rt = ip_route_connect(&fl4, daddr, 0, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if, sk->sk_protocol,
inet->inet_sport, inet->inet_dport, sk, false);
if (IS_ERR(rt))
return PTR_ERR(rt);
sk_setup_caps(sk, &rt->dst);
new_saddr = rt->rt_src;
if (new_saddr == old_saddr)
return 0;
if (sysctl_ip_dynaddr > 1) {
printk(KERN_INFO "%s(): shifting inet->saddr from %pI4 to %pI4\n",
__func__, &old_saddr, &new_saddr);
}
inet->inet_saddr = inet->inet_rcv_saddr = new_saddr;
/*
* XXX The only one ugly spot where we need to
* XXX really change the sockets identity after
* XXX it has entered the hashes. -DaveM
*
* Besides that, it does not check for connection
* uniqueness. Wait for troubles.
*/
__sk_prot_rehash(sk);
return 0;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static png_uint_16 png_exp16bit(png_uint_32 log)
{
return (png_uint_16)floor(.5 + exp(log * -LN2) * 65535);
}
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: stringprep_unichar_to_utf8 (uint32_t c, char *outbuf)
{
return g_unichar_to_utf8 (c, outbuf);
}
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: parse_instruction(
struct translate_ctx *ctx,
boolean has_label )
{
uint i;
uint saturate = 0;
const struct tgsi_opcode_info *info;
struct tgsi_full_instruction inst;
const char *cur;
uint advance;
inst = tgsi_default_full_instruction();
/* Parse predicate.
*/
eat_opt_white( &ctx->cur );
if (*ctx->cur == '(') {
uint file;
int index;
uint swizzle[4];
boolean parsed_swizzle;
inst.Instruction.Predicate = 1;
ctx->cur++;
if (*ctx->cur == '!') {
ctx->cur++;
inst.Predicate.Negate = 1;
}
if (!parse_register_1d( ctx, &file, &index ))
return FALSE;
if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) {
if (parsed_swizzle) {
inst.Predicate.SwizzleX = swizzle[0];
inst.Predicate.SwizzleY = swizzle[1];
inst.Predicate.SwizzleZ = swizzle[2];
inst.Predicate.SwizzleW = swizzle[3];
}
}
if (*ctx->cur != ')') {
report_error( ctx, "Expected `)'" );
return FALSE;
}
ctx->cur++;
}
/* Parse instruction name.
*/
eat_opt_white( &ctx->cur );
for (i = 0; i < TGSI_OPCODE_LAST; i++) {
cur = ctx->cur;
info = tgsi_get_opcode_info( i );
if (match_inst(&cur, &saturate, info)) {
if (info->num_dst + info->num_src + info->is_tex == 0) {
ctx->cur = cur;
break;
}
else if (*cur == '\0' || eat_white( &cur )) {
ctx->cur = cur;
break;
}
}
}
if (i == TGSI_OPCODE_LAST) {
if (has_label)
report_error( ctx, "Unknown opcode" );
else
report_error( ctx, "Expected `DCL', `IMM' or a label" );
return FALSE;
}
inst.Instruction.Opcode = i;
inst.Instruction.Saturate = saturate;
inst.Instruction.NumDstRegs = info->num_dst;
inst.Instruction.NumSrcRegs = info->num_src;
if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) {
/*
* These are not considered tex opcodes here (no additional
* target argument) however we're required to set the Texture
* bit so we can set the number of tex offsets.
*/
inst.Instruction.Texture = 1;
inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN;
}
/* Parse instruction operands.
*/
for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) {
if (i > 0) {
eat_opt_white( &ctx->cur );
if (*ctx->cur != ',') {
report_error( ctx, "Expected `,'" );
return FALSE;
}
ctx->cur++;
eat_opt_white( &ctx->cur );
}
if (i < info->num_dst) {
if (!parse_dst_operand( ctx, &inst.Dst[i] ))
return FALSE;
}
else if (i < info->num_dst + info->num_src) {
if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] ))
return FALSE;
}
else {
uint j;
for (j = 0; j < TGSI_TEXTURE_COUNT; j++) {
if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) {
inst.Instruction.Texture = 1;
inst.Texture.Texture = j;
break;
}
}
if (j == TGSI_TEXTURE_COUNT) {
report_error( ctx, "Expected texture target" );
return FALSE;
}
}
}
cur = ctx->cur;
eat_opt_white( &cur );
for (i = 0; inst.Instruction.Texture && *cur == ','; i++) {
cur++;
eat_opt_white( &cur );
ctx->cur = cur;
if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] ))
return FALSE;
cur = ctx->cur;
eat_opt_white( &cur );
}
inst.Texture.NumOffsets = i;
cur = ctx->cur;
eat_opt_white( &cur );
if (info->is_branch && *cur == ':') {
uint target;
cur++;
eat_opt_white( &cur );
if (!parse_uint( &cur, &target )) {
report_error( ctx, "Expected a label" );
return FALSE;
}
inst.Instruction.Label = 1;
inst.Label.Label = target;
ctx->cur = cur;
}
advance = tgsi_build_full_instruction(
&inst,
ctx->tokens_cur,
ctx->header,
(uint) (ctx->tokens_end - ctx->tokens_cur) );
if (advance == 0)
return FALSE;
ctx->tokens_cur += advance;
return TRUE;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void voidMethodDoubleArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
throwTypeError(ExceptionMessages::failedToExecute("voidMethodDoubleArg", "TestObjectPython", ExceptionMessages::notEnoughArguments(1, info.Length())), info.GetIsolate());
return;
}
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
V8TRYCATCH_VOID(double, doubleArg, static_cast<double>(info[0]->NumberValue()));
imp->voidMethodDoubleArg(doubleArg);
}
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: create_principal3_2_svc(cprinc3_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name, service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_ADD;
log_unauth("kadm5_create_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_create_principal_3((void *)handle,
&arg->rec, arg->mask,
arg->n_ks_tuple,
arg->ks_tuple,
arg->passwd);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_create_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
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 decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req,
size_t *acl_len)
{
__be32 *savep;
uint32_t attrlen,
bitmap[3] = {0};
struct kvec *iov = req->rq_rcv_buf.head;
int status;
*acl_len = 0;
if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0)
goto out;
if ((status = decode_attr_bitmap(xdr, bitmap)) != 0)
goto out;
if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0)
goto out;
if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U)))
return -EIO;
if (likely(bitmap[0] & FATTR4_WORD0_ACL)) {
size_t hdrlen;
u32 recvd;
/* We ignore &savep and don't do consistency checks on
* the attr length. Let userspace figure it out.... */
hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base;
recvd = req->rq_rcv_buf.len - hdrlen;
if (attrlen > recvd) {
dprintk("NFS: server cheating in getattr"
" acl reply: attrlen %u > recvd %u\n",
attrlen, recvd);
return -EINVAL;
}
xdr_read_pages(xdr, attrlen);
*acl_len = attrlen;
} else
status = -EOPNOTSUPP;
out:
return status;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void WebGLRenderingContextBase::vertexAttrib4f(GLuint index,
GLfloat v0,
GLfloat v1,
GLfloat v2,
GLfloat v3) {
if (isContextLost())
return;
ContextGL()->VertexAttrib4f(index, v0, v1, v2, v3);
SetVertexAttribType(index, kFloat32ArrayType);
}
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 _WM_do_note_off_extra(struct _note *nte) {
MIDI_EVENT_DEBUG(__FUNCTION__,0, 0);
nte->is_off = 0;
{
if (!(nte->modes & SAMPLE_ENVELOPE)) {
if (nte->modes & SAMPLE_LOOP) {
nte->modes ^= SAMPLE_LOOP;
}
nte->env_inc = 0;
} else if (nte->hold) {
nte->hold |= HOLD_OFF;
/*
} else if (nte->modes & SAMPLE_SUSTAIN) {
if (nte->env < 3) {
nte->env = 3;
if (nte->env_level > nte->sample->env_target[3]) {
nte->env_inc = -nte->sample->env_rate[3];
} else {
nte->env_inc = nte->sample->env_rate[3];
}
}
*/
} else if (nte->modes & SAMPLE_CLAMPED) {
if (nte->env < 5) {
nte->env = 5;
if (nte->env_level > nte->sample->env_target[5]) {
nte->env_inc = -nte->sample->env_rate[5];
} else {
nte->env_inc = nte->sample->env_rate[5];
}
}
} else if (nte->env < 3) {
nte->env = 3;
if (nte->env_level > nte->sample->env_target[3]) {
nte->env_inc = -nte->sample->env_rate[3];
} else {
nte->env_inc = nte->sample->env_rate[3];
}
}
}
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: double VideoTrack::GetFrameRate() const
{
return m_rate;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bgp_attr_aspath_check (struct peer *const peer, struct attr *const attr)
{
/* These checks were part of bgp_attr_aspath, but with
* as4 we should to check aspath things when
* aspath synthesizing with as4_path has already taken place.
* Otherwise we check ASPATH and use the synthesized thing, and that is
* not right.
* So do the checks later, i.e. here
*/
struct bgp *bgp = peer->bgp;
struct aspath *aspath;
bgp = peer->bgp;
/* Confederation sanity check. */
if ((peer_sort (peer) == BGP_PEER_CONFED && ! aspath_left_confed_check (attr->aspath)) ||
(peer_sort (peer) == BGP_PEER_EBGP && aspath_confed_check (attr->aspath)))
{
zlog (peer->log, LOG_ERR, "Malformed AS path from %s", peer->host);
bgp_notify_send (peer, BGP_NOTIFY_UPDATE_ERR,
BGP_NOTIFY_UPDATE_MAL_AS_PATH);
return BGP_ATTR_PARSE_ERROR;
}
/* First AS check for EBGP. */
if (bgp != NULL && bgp_flag_check (bgp, BGP_FLAG_ENFORCE_FIRST_AS))
{
if (peer_sort (peer) == BGP_PEER_EBGP
&& ! aspath_firstas_check (attr->aspath, peer->as))
{
zlog (peer->log, LOG_ERR,
"%s incorrect first AS (must be %u)", peer->host, peer->as);
bgp_notify_send (peer, BGP_NOTIFY_UPDATE_ERR,
BGP_NOTIFY_UPDATE_MAL_AS_PATH);
return BGP_ATTR_PARSE_ERROR;
}
}
/* local-as prepend */
if (peer->change_local_as &&
! CHECK_FLAG (peer->flags, PEER_FLAG_LOCAL_AS_NO_PREPEND))
{
aspath = aspath_dup (attr->aspath);
aspath = aspath_add_seq (aspath, peer->change_local_as);
aspath_unintern (&attr->aspath);
attr->aspath = aspath_intern (aspath);
}
return BGP_ATTR_PARSE_PROCEED;
}
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 Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
CWE ID: CWE-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: PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s)
{
static const char module[] = "PredictorEncodeTile";
TIFFPredictorState *sp = PredictorState(tif);
uint8 *working_copy;
tmsize_t cc = cc0, rowsize;
unsigned char* bp;
int result_code;
assert(sp != NULL);
assert(sp->encodepfunc != NULL);
assert(sp->encodetile != NULL);
/*
* Do predictor manipulation in a working buffer to avoid altering
* the callers buffer. http://trac.osgeo.org/gdal/ticket/1965
*/
working_copy = (uint8*) _TIFFmalloc(cc0);
if( working_copy == NULL )
{
TIFFErrorExt(tif->tif_clientdata, module,
"Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.",
cc0 );
return 0;
}
memcpy( working_copy, bp0, cc0 );
bp = working_copy;
rowsize = sp->rowsize;
assert(rowsize > 0);
assert((cc0%rowsize)==0);
while (cc > 0) {
(*sp->encodepfunc)(tif, bp, rowsize);
cc -= rowsize;
bp += rowsize;
}
result_code = (*sp->encodetile)(tif, working_copy, cc0, s);
_TIFFfree( working_copy );
return result_code;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
{
int r = kvm_init_shadow_mmu(vcpu, vcpu->arch.walk_mmu);
vcpu->arch.walk_mmu->set_cr3 = kvm_x86_ops->set_cr3;
vcpu->arch.walk_mmu->get_cr3 = get_cr3;
vcpu->arch.walk_mmu->get_pdptr = kvm_pdptr_read;
vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
return r;
}
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 inline ogg_uint32_t decode_packed_entry_number(codebook *book,
oggpack_buffer *b){
ogg_uint32_t chase=0;
int read=book->dec_maxlength;
long lok = oggpack_look(b,read),i;
while(lok<0 && read>1)
lok = oggpack_look(b, --read);
if(lok<0){
oggpack_adv(b,1); /* force eop */
return -1;
}
/* chase the tree with the bits we got */
switch (book->dec_method)
{
case 0:
{
/* book->dec_nodeb==1, book->dec_leafw==1 */
/* 8/8 - Used */
unsigned char *t=(unsigned char *)book->dec_table;
for(i=0;i<read;i++){
chase=t[chase*2+((lok>>i)&1)];
if(chase&0x80UL)break;
}
chase&=0x7fUL;
break;
}
case 1:
{
/* book->dec_nodeb==1, book->dec_leafw!=1 */
/* 8/16 - Used by infile2 */
unsigned char *t=(unsigned char *)book->dec_table;
for(i=0;i<read;i++){
int bit=(lok>>i)&1;
int next=t[chase+bit];
if(next&0x80){
chase= (next<<8) | t[chase+bit+1+(!bit || t[chase]&0x80)];
break;
}
chase=next;
}
chase&=~0x8000UL;
break;
}
case 2:
{
/* book->dec_nodeb==2, book->dec_leafw==1 */
/* 16/16 - Used */
for(i=0;i<read;i++){
chase=((ogg_uint16_t *)(book->dec_table))[chase*2+((lok>>i)&1)];
if(chase&0x8000UL)break;
}
chase&=~0x8000UL;
break;
}
case 3:
{
/* book->dec_nodeb==2, book->dec_leafw!=1 */
/* 16/32 - Used by infile2 */
ogg_uint16_t *t=(ogg_uint16_t *)book->dec_table;
for(i=0;i<read;i++){
int bit=(lok>>i)&1;
int next=t[chase+bit];
if(next&0x8000){
chase= (next<<16) | t[chase+bit+1+(!bit || t[chase]&0x8000)];
break;
}
chase=next;
}
chase&=~0x80000000UL;
break;
}
case 4:
{
for(i=0;i<read;i++){
chase=((ogg_uint32_t *)(book->dec_table))[chase*2+((lok>>i)&1)];
if(chase&0x80000000UL)break;
}
chase&=~0x80000000UL;
break;
}
}
if(i<read){
oggpack_adv(b,i+1);
return chase;
}
oggpack_adv(b,read+1);
return(-1);
}
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: int ChromeMockRenderThread::print_preview_pages_remaining() {
return print_preview_pages_remaining_;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int function_stat_cmp(void *p1, void *p2)
{
struct ftrace_profile *a = p1;
struct ftrace_profile *b = p2;
if (a->counter < b->counter)
return -1;
if (a->counter > b->counter)
return 1;
else
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int tight_fill_palette(VncState *vs, int x, int y,
size_t count, uint32_t *bg, uint32_t *fg,
VncPalette **palette)
{
int max;
max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor;
if (max < 2 &&
count >= tight_conf[vs->tight.compression].mono_min_rect_size) {
max = 2;
}
if (max >= 256) {
max = 256;
}
switch(vs->clientds.pf.bytes_per_pixel) {
case 4:
return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);
case 2:
return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);
default:
max = 2;
return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);
}
return 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 tmx_check_pretran(sip_msg_t *msg)
{
unsigned int chid;
unsigned int slotid;
int dsize;
struct via_param *vbr;
str scallid;
str scseqmet;
str scseqnum;
str sftag;
str svbranch = {NULL, 0};
pretran_t *it;
if(_tmx_ptran_table==NULL) {
LM_ERR("pretran hash table not initialized yet\n");
return -1;
}
if(get_route_type()!=REQUEST_ROUTE) {
LM_ERR("invalid usage - not in request route\n");
return -1;
}
if(msg->first_line.type!=SIP_REQUEST) {
LM_ERR("invalid usage - not a sip request\n");
return -1;
}
if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) {
LM_ERR("failed to parse required headers\n");
return -1;
}
if(msg->cseq==NULL || msg->cseq->parsed==NULL) {
LM_ERR("failed to parse cseq headers\n");
return -1;
}
if(get_cseq(msg)->method_id==METHOD_ACK
|| get_cseq(msg)->method_id==METHOD_CANCEL) {
LM_DBG("no pre-transaction management for ACK or CANCEL\n");
return -1;
}
if (msg->via1==0) {
LM_ERR("failed to get Via header\n");
return -1;
}
if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) {
LM_ERR("failed to get From header\n");
return -1;
}
if (msg->callid==NULL || msg->callid->body.s==NULL) {
LM_ERR("failed to parse callid headers\n");
return -1;
}
vbr = msg->via1->branch;
scallid = msg->callid->body;
trim(&scallid);
scseqmet = get_cseq(msg)->method;
trim(&scseqmet);
scseqnum = get_cseq(msg)->number;
trim(&scseqnum);
sftag = get_from(msg)->tag_value;
trim(&sftag);
chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len);
slotid = chid & (_tmx_ptran_size-1);
if(unlikely(_tmx_proc_ptran == NULL)) {
_tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t));
if(_tmx_proc_ptran == NULL) {
LM_ERR("not enough memory for pretran structure\n");
return -1;
}
memset(_tmx_proc_ptran, 0, sizeof(pretran_t));
_tmx_proc_ptran->pid = my_pid();
}
dsize = scallid.len + scseqnum.len + scseqmet.len
+ sftag.len + 4;
if(likely(vbr!=NULL)) {
svbranch = vbr->value;
trim(&svbranch);
dsize += svbranch.len;
}
if(dsize<256) dsize = 256;
tmx_pretran_unlink();
if(dsize > _tmx_proc_ptran->dbuf.len) {
if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s);
_tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize);
if(_tmx_proc_ptran->dbuf.s==NULL) {
LM_ERR("not enough memory for pretran data\n");
return -1;
}
_tmx_proc_ptran->dbuf.len = dsize;
}
_tmx_proc_ptran->hid = chid;
_tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id;
_tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s;
memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len);
_tmx_proc_ptran->callid.len = scallid.len;
_tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0';
_tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s
+ _tmx_proc_ptran->callid.len + 1;
memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len);
_tmx_proc_ptran->ftag.len = sftag.len;
_tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0';
_tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s
+ _tmx_proc_ptran->ftag.len + 1;
memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len);
_tmx_proc_ptran->cseqnum.len = scseqnum.len;
_tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0';
_tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s
+ _tmx_proc_ptran->cseqnum.len + 1;
memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len);
_tmx_proc_ptran->cseqmet.len = scseqmet.len;
_tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0';
if(likely(vbr!=NULL)) {
_tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s
+ _tmx_proc_ptran->cseqmet.len + 1;
memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len);
_tmx_proc_ptran->vbranch.len = svbranch.len;
_tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0';
} else {
_tmx_proc_ptran->vbranch.s = NULL;
_tmx_proc_ptran->vbranch.len = 0;
}
lock_get(&_tmx_ptran_table[slotid].lock);
it = _tmx_ptran_table[slotid].plist;
tmx_pretran_link_safe(slotid);
for(; it!=NULL; it=it->next) {
if(_tmx_proc_ptran->hid != it->hid
|| _tmx_proc_ptran->cseqmetid != it->cseqmetid
|| _tmx_proc_ptran->callid.len != it->callid.len
|| _tmx_proc_ptran->ftag.len != it->ftag.len
|| _tmx_proc_ptran->cseqmet.len != it->cseqmet.len
|| _tmx_proc_ptran->cseqnum.len != it->cseqnum.len)
continue;
if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) {
if(_tmx_proc_ptran->vbranch.len != it->vbranch.len)
continue;
/* shortcut - check last char in Via branch
* - kamailio/ser adds there branch index => in case of paralel
* forking by previous hop, catch it here quickly */
if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1]
!= it->vbranch.s[it->vbranch.len-1])
continue;
if(memcmp(_tmx_proc_ptran->vbranch.s,
it->vbranch.s, it->vbranch.len)!=0)
continue;
/* shall stop by matching magic cookie?
* if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN
* && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) {
* LM_DBG("rfc3261 cookie found in Via branch\n");
* }
*/
}
if(memcmp(_tmx_proc_ptran->callid.s,
it->callid.s, it->callid.len)!=0
|| memcmp(_tmx_proc_ptran->ftag.s,
it->ftag.s, it->ftag.len)!=0
|| memcmp(_tmx_proc_ptran->cseqnum.s,
it->cseqnum.s, it->cseqnum.len)!=0)
continue;
if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF)
&& memcmp(_tmx_proc_ptran->cseqmet.s,
it->cseqmet.s, it->cseqmet.len)!=0)
continue;
LM_DBG("matched another pre-transaction by pid %d for [%.*s]\n",
it->pid, it->callid.len, it->callid.s);
lock_release(&_tmx_ptran_table[slotid].lock);
return 1;
}
lock_release(&_tmx_ptran_table[slotid].lock);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderWidgetHostViewGuest::AcceleratedSurfaceSetIOSurface(
gfx::PluginWindowHandle window,
int32 width,
int32 height,
uint64 io_surface_identifier) {
NOTIMPLEMENTED();
}
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: xid_map_enter(netdissect_options *ndo,
const struct sunrpc_msg *rp, const u_char *bp)
{
const struct ip *ip = NULL;
const struct ip6_hdr *ip6 = NULL;
struct xid_map_entry *xmep;
if (!ND_TTEST(rp->rm_call.cb_vers))
return (0);
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
break;
default:
return (1);
}
xmep = &xid_map[xid_map_next];
if (++xid_map_next >= XIDMAPSIZE)
xid_map_next = 0;
UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid));
if (ip) {
xmep->ipver = 4;
UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src));
UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst));
}
else if (ip6) {
xmep->ipver = 6;
UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src));
UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
}
xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers);
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 v8::Handle<v8::Value> overloadedMethod12Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod12");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
TestObj::overloadedMethod1(type);
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: void sched_show_task(struct task_struct *p)
{
unsigned long free = 0;
int ppid;
unsigned long state = p->state;
if (state)
state = __ffs(state) + 1;
printk(KERN_INFO "%-15.15s %c", p->comm,
state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
#if BITS_PER_LONG == 32
if (state == TASK_RUNNING)
printk(KERN_CONT " running ");
else
printk(KERN_CONT " %08lx ", thread_saved_pc(p));
#else
if (state == TASK_RUNNING)
printk(KERN_CONT " running task ");
else
printk(KERN_CONT " %016lx ", thread_saved_pc(p));
#endif
#ifdef CONFIG_DEBUG_STACK_USAGE
free = stack_not_used(p);
#endif
ppid = 0;
rcu_read_lock();
if (pid_alive(p))
ppid = task_pid_nr(rcu_dereference(p->real_parent));
rcu_read_unlock();
printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
task_pid_nr(p), ppid,
(unsigned long)task_thread_info(p)->flags);
print_worker_info(KERN_INFO, p);
show_stack(p, 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 edge_sparse_csr_reader_double( const char* i_csr_file_in,
unsigned int** o_row_idx,
unsigned int** o_column_idx,
double** o_values,
unsigned int* o_row_count,
unsigned int* o_column_count,
unsigned int* o_element_count ) {
FILE *l_csr_file_handle;
const unsigned int l_line_length = 512;
char l_line[512/*l_line_length*/+1];
unsigned int l_header_read = 0;
unsigned int* l_row_idx_id = NULL;
unsigned int l_i = 0;
l_csr_file_handle = fopen( i_csr_file_in, "r" );
if ( l_csr_file_handle == NULL ) {
fprintf( stderr, "cannot open CSR file!\n" );
return;
}
while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) {
if ( strlen(l_line) == l_line_length ) {
fprintf( stderr, "could not read file length!\n" );
return;
}
/* check if we are still reading comments header */
if ( l_line[0] == '%' ) {
continue;
} else {
/* if we are the first line after comment header, we allocate our data structures */
if ( l_header_read == 0 ) {
if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) {
/* allocate CSC datastructure matching mtx file */
*o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count));
*o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1));
*o_values = (double*) malloc(sizeof(double) * (*o_element_count));
l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count));
/* check if mallocs were successful */
if ( ( *o_row_idx == NULL ) ||
( *o_column_idx == NULL ) ||
( *o_values == NULL ) ||
( l_row_idx_id == NULL ) ) {
fprintf( stderr, "could not allocate sp data!\n" );
return;
}
/* set everything to zero for init */
memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1));
memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count));
memset(*o_values, 0, sizeof(double)*(*o_element_count));
memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count));
/* init column idx */
for ( l_i = 0; l_i < (*o_row_count + 1); l_i++)
(*o_row_idx)[l_i] = (*o_element_count);
/* init */
(*o_row_idx)[0] = 0;
l_i = 0;
l_header_read = 1;
} else {
fprintf( stderr, "could not csr description!\n" );
return;
}
/* now we read the actual content */
} else {
unsigned int l_row, l_column;
double l_value;
/* read a line of content */
if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) {
fprintf( stderr, "could not read element!\n" );
return;
}
/* adjust numbers to zero termination */
l_row--;
l_column--;
/* add these values to row and value structure */
(*o_column_idx)[l_i] = l_column;
(*o_values)[l_i] = l_value;
l_i++;
/* handle columns, set id to own for this column, yeah we need to handle empty columns */
l_row_idx_id[l_row] = 1;
(*o_row_idx)[l_row+1] = l_i;
}
}
}
/* close mtx file */
fclose( l_csr_file_handle );
/* check if we read a file which was consistent */
if ( l_i != (*o_element_count) ) {
fprintf( stderr, "we were not able to read all elements!\n" );
return;
}
/* let's handle empty rows */
for ( l_i = 0; l_i < (*o_row_count); l_i++) {
if ( l_row_idx_id[l_i] == 0 ) {
(*o_row_idx)[l_i+1] = (*o_row_idx)[l_i];
}
}
/* free helper data structure */
if ( l_row_idx_id != NULL ) {
free( l_row_idx_id );
}
}
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 bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt)
{
struct iovec *l2_hdr, *l3_hdr;
size_t bytes_read;
size_t full_ip6hdr_len;
uint16_t l3_proto;
assert(pkt);
l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG];
l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG];
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,
ETH_MAX_L2_HDR_LEN);
if (bytes_read < ETH_MAX_L2_HDR_LEN) {
l2_hdr->iov_len = 0;
return false;
} else {
l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base);
}
l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len);
l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);
pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p;
/* copy optional IPv4 header data */
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,
l2_hdr->iov_len + sizeof(struct ip_header),
l3_hdr->iov_base + sizeof(struct ip_header),
l3_hdr->iov_len - sizeof(struct ip_header));
if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {
l3_hdr->iov_len = 0;
return false;
}
break;
case ETH_P_IPV6:
if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
&pkt->l4proto, &full_ip6hdr_len)) {
l3_hdr->iov_len = 0;
return false;
}
l3_hdr->iov_base = g_malloc(full_ip6hdr_len);
bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,
l3_hdr->iov_base, full_ip6hdr_len);
if (bytes_read < full_ip6hdr_len) {
l3_hdr->iov_len = 0;
return false;
} else {
l3_hdr->iov_len = full_ip6hdr_len;
}
break;
default:
l3_hdr->iov_len = 0;
break;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: RuleSet* CSSDefaultStyleSheets::viewSourceStyle()
{
if (!defaultViewSourceStyle) {
defaultViewSourceStyle = RuleSet::create().leakPtr();
defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
}
return defaultViewSourceStyle;
}
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: v8::Handle<v8::Value> V8DataView::getUint8Callback(const v8::Arguments& args)
{
INC_STATS("DOM.DataView.getUint8");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
DataView* imp = V8DataView::toNative(args.Holder());
ExceptionCode ec = 0;
EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0]));
uint8_t result = imp->getUint8(byteOffset, ec);
if (UNLIKELY(ec)) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
return v8::Integer::New(result);
}
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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionSerializedValue(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"));
RefPtr<SerializedScriptValue> serializedArg(SerializedScriptValue::create(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->serializedValue(serializedArg);
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void HighEntropyAttributeWithMeasureAsAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
V8StringResource<> cpp_value = v8_value;
if (!cpp_value.Prepare())
return;
impl->setHighEntropyAttributeWithMeasureAs(cpp_value);
}
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 ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
unsigned int npages = DIV_ROUND_UP(buflen, PAGE_SIZE);
int ret = -ENOMEM, i;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
if (npages > ARRAY_SIZE(pages))
return -ERANGE;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
/* for decoding across pages */
res.acl_scratch = alloc_page(GFP_KERNEL);
if (!res.acl_scratch)
goto out_free;
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
/* Handle the case where the passed-in buffer is too short */
if (res.acl_flags & NFS4_ACL_TRUNC) {
/* Did the user only issue a request for the acl length? */
if (buf == NULL)
goto out_ok;
ret = -ERANGE;
goto out_free;
}
nfs4_write_cached_acl(inode, pages, res.acl_data_offset, res.acl_len);
if (buf)
_copy_from_pages(buf, pages, res.acl_data_offset, res.acl_len);
out_ok:
ret = res.acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (res.acl_scratch)
__free_page(res.acl_scratch);
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: OMX_ERRORTYPE omx_venc::component_deinit(OMX_IN OMX_HANDLETYPE hComp)
{
(void) hComp;
OMX_U32 i = 0;
DEBUG_PRINT_HIGH("omx_venc(): Inside component_deinit()");
if (OMX_StateLoaded != m_state) {
DEBUG_PRINT_ERROR("WARNING:Rxd DeInit,OMX not in LOADED state %d",\
m_state);
}
if (m_out_mem_ptr) {
DEBUG_PRINT_LOW("Freeing the Output Memory");
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++ ) {
free_output_buffer (&m_out_mem_ptr[i]);
}
free(m_out_mem_ptr);
m_out_mem_ptr = NULL;
}
/*Check if the input buffers have to be cleaned up*/
if (m_inp_mem_ptr
#ifdef _ANDROID_ICS_
&& !meta_mode_enable
#endif
) {
DEBUG_PRINT_LOW("Freeing the Input Memory");
for (i=0; i<m_sInPortDef.nBufferCountActual; i++ ) {
free_input_buffer (&m_inp_mem_ptr[i]);
}
free(m_inp_mem_ptr);
m_inp_mem_ptr = NULL;
}
m_ftb_q.m_size=0;
m_cmd_q.m_size=0;
m_etb_q.m_size=0;
m_ftb_q.m_read = m_ftb_q.m_write =0;
m_cmd_q.m_read = m_cmd_q.m_write =0;
m_etb_q.m_read = m_etb_q.m_write =0;
#ifdef _ANDROID_
DEBUG_PRINT_HIGH("Calling m_heap_ptr.clear()");
m_heap_ptr.clear();
#endif // _ANDROID_
DEBUG_PRINT_HIGH("Calling venc_close()");
if (handle) {
handle->venc_close();
DEBUG_PRINT_HIGH("Deleting HANDLE[%p]", handle);
delete (handle);
handle = NULL;
}
DEBUG_PRINT_INFO("Component Deinit");
return OMX_ErrorNone;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void ipgre_tunnel_uninit(struct net_device *dev)
{
struct net *net = dev_net(dev);
struct ipgre_net *ign = net_generic(net, ipgre_net_id);
ipgre_tunnel_unlink(ign, netdev_priv(dev));
dev_put(dev);
}
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: RenderThreadImpl::GetIOMessageLoopProxy() {
return ChildProcess::current()->io_message_loop_proxy();
}
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: int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) {
if (HasTextBeingDragged())
return ui::DragDropTypes::DRAG_NONE;
if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) {
GURL url;
base::string16 title;
if (data.GetURLAndTitle(
ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) {
base::string16 text(
StripJavascriptSchemas(base::UTF8ToUTF16(url.spec())));
if (model()->CanPasteAndGo(text)) {
model()->PasteAndGo(text);
return ui::DragDropTypes::DRAG_COPY;
}
}
} else if (data.HasString()) {
base::string16 text;
if (data.GetString(&text)) {
base::string16 collapsed_text(base::CollapseWhitespace(text, true));
if (model()->CanPasteAndGo(collapsed_text))
model()->PasteAndGo(collapsed_text);
return ui::DragDropTypes::DRAG_COPY;
}
}
return ui::DragDropTypes::DRAG_NONE;
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: person_get_pose(const person_t* person)
{
return person->direction;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type)
{
RingItem *link;
RING_FOREACH(link, &channel->clients) {
red_channel_client_pipe_add_empty_msg(
SPICE_CONTAINEROF(link, RedChannelClient, channel_link),
msg_type);
}
}
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: SSH_PACKET_CALLBACK(ssh_packet_dh_reply){
int rc;
(void)type;
(void)user;
SSH_LOG(SSH_LOG_PROTOCOL,"Received SSH_KEXDH_REPLY");
if(session->session_state!= SSH_SESSION_STATE_DH &&
session->dh_handshake_state != DH_STATE_INIT_SENT){
ssh_set_error(session,SSH_FATAL,"ssh_packet_dh_reply called in wrong state : %d:%d",
session->session_state,session->dh_handshake_state);
goto error;
}
switch(session->next_crypto->kex_type){
case SSH_KEX_DH_GROUP1_SHA1:
case SSH_KEX_DH_GROUP14_SHA1:
rc=ssh_client_dh_reply(session, packet);
break;
#ifdef HAVE_ECDH
case SSH_KEX_ECDH_SHA2_NISTP256:
rc = ssh_client_ecdh_reply(session, packet);
break;
#endif
#ifdef HAVE_CURVE25519
case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG:
rc = ssh_client_curve25519_reply(session, packet);
break;
#endif
default:
ssh_set_error(session,SSH_FATAL,"Wrong kex type in ssh_packet_dh_reply");
goto error;
}
if(rc==SSH_OK) {
session->dh_handshake_state = DH_STATE_NEWKEYS_SENT;
return SSH_PACKET_USED;
}
error:
session->session_state=SSH_SESSION_STATE_ERROR;
return SSH_PACKET_USED;
}
CWE ID:
Target: 1
Example 2:
Code: static void md_end_flush(struct bio *bio, int err)
{
struct md_rdev *rdev = bio->bi_private;
struct mddev *mddev = rdev->mddev;
rdev_dec_pending(rdev, mddev);
if (atomic_dec_and_test(&mddev->flush_pending)) {
/* The pre-request flush has finished */
queue_work(md_wq, &mddev->flush_work);
}
bio_put(bio);
}
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 hugetlbfs_put_super(struct super_block *sb)
{
struct hugetlbfs_sb_info *sbi = HUGETLBFS_SB(sb);
if (sbi) {
sb->s_fs_info = NULL;
kfree(sbi);
}
}
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: virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> descriptors(GetActiveInputMethods());
return descriptors->size();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static bool need_wrongsec_check(struct svc_rqst *rqstp)
{
struct nfsd4_compoundres *resp = rqstp->rq_resp;
struct nfsd4_compoundargs *argp = rqstp->rq_argp;
struct nfsd4_op *this = &argp->ops[resp->opcnt - 1];
struct nfsd4_op *next = &argp->ops[resp->opcnt];
struct nfsd4_operation *thisd;
struct nfsd4_operation *nextd;
thisd = OPDESC(this);
/*
* Most ops check wronsec on our own; only the putfh-like ops
* have special rules.
*/
if (!(thisd->op_flags & OP_IS_PUTFH_LIKE))
return false;
/*
* rfc 5661 2.6.3.1.1.6: don't bother erroring out a
* put-filehandle operation if we're not going to use the
* result:
*/
if (argp->opcnt == resp->opcnt)
return false;
if (next->opnum == OP_ILLEGAL)
return false;
nextd = OPDESC(next);
/*
* Rest of 2.6.3.1.1: certain operations will return WRONGSEC
* errors themselves as necessary; others should check for them
* now:
*/
return !(nextd->op_flags & OP_HANDLES_WRONGSEC);
}
CWE ID: CWE-404
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
struct request *req = REQ_HEAD(base, trans_id);
struct request *const started_at = req;
ASSERT_LOCKED(base);
if (req) {
do {
if (req->trans_id == trans_id) return req;
req = req->next;
} while (req != started_at);
}
return NULL;
}
CWE ID: CWE-125
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr,
unsigned long shmlba)
{
struct shmid_kernel *shp;
unsigned long addr;
unsigned long size;
struct file *file;
int err;
unsigned long flags;
unsigned long prot;
int acc_mode;
struct ipc_namespace *ns;
struct shm_file_data *sfd;
struct path path;
fmode_t f_mode;
unsigned long populate = 0;
err = -EINVAL;
if (shmid < 0)
goto out;
else if ((addr = (ulong)shmaddr)) {
if (addr & (shmlba - 1)) {
if (shmflg & SHM_RND)
addr &= ~(shmlba - 1); /* round down */
else
#ifndef __ARCH_FORCE_SHMLBA
if (addr & ~PAGE_MASK)
#endif
goto out;
}
flags = MAP_SHARED | MAP_FIXED;
} else {
if ((shmflg & SHM_REMAP))
goto out;
flags = MAP_SHARED;
}
if (shmflg & SHM_RDONLY) {
prot = PROT_READ;
acc_mode = S_IRUGO;
f_mode = FMODE_READ;
} else {
prot = PROT_READ | PROT_WRITE;
acc_mode = S_IRUGO | S_IWUGO;
f_mode = FMODE_READ | FMODE_WRITE;
}
if (shmflg & SHM_EXEC) {
prot |= PROT_EXEC;
acc_mode |= S_IXUGO;
}
/*
* We cannot rely on the fs check since SYSV IPC does have an
* additional creator id...
*/
ns = current->nsproxy->ipc_ns;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
err = -EACCES;
if (ipcperms(ns, &shp->shm_perm, acc_mode))
goto out_unlock;
err = security_shm_shmat(shp, shmaddr, shmflg);
if (err)
goto out_unlock;
ipc_lock_object(&shp->shm_perm);
/* check if shm_destroy() is tearing down shp */
if (!ipc_valid_object(&shp->shm_perm)) {
ipc_unlock_object(&shp->shm_perm);
err = -EIDRM;
goto out_unlock;
}
path = shp->shm_file->f_path;
path_get(&path);
shp->shm_nattch++;
size = i_size_read(d_inode(path.dentry));
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
err = -ENOMEM;
sfd = kzalloc(sizeof(*sfd), GFP_KERNEL);
if (!sfd) {
path_put(&path);
goto out_nattch;
}
file = alloc_file(&path, f_mode,
is_file_hugepages(shp->shm_file) ?
&shm_file_operations_huge :
&shm_file_operations);
err = PTR_ERR(file);
if (IS_ERR(file)) {
kfree(sfd);
path_put(&path);
goto out_nattch;
}
file->private_data = sfd;
file->f_mapping = shp->shm_file->f_mapping;
sfd->id = shp->shm_perm.id;
sfd->ns = get_ipc_ns(ns);
sfd->file = shp->shm_file;
sfd->vm_ops = NULL;
err = security_mmap_file(file, prot, flags);
if (err)
goto out_fput;
if (down_write_killable(¤t->mm->mmap_sem)) {
err = -EINTR;
goto out_fput;
}
if (addr && !(shmflg & SHM_REMAP)) {
err = -EINVAL;
if (addr + size < addr)
goto invalid;
if (find_vma_intersection(current->mm, addr, addr + size))
goto invalid;
}
addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate, NULL);
*raddr = addr;
err = 0;
if (IS_ERR_VALUE(addr))
err = (long)addr;
invalid:
up_write(¤t->mm->mmap_sem);
if (populate)
mm_populate(addr, populate);
out_fput:
fput(file);
out_nattch:
down_write(&shm_ids(ns).rwsem);
shp = shm_lock(ns, shmid);
shp->shm_nattch--;
if (shm_may_destroy(ns, shp))
shm_destroy(ns, shp);
else
shm_unlock(shp);
up_write(&shm_ids(ns).rwsem);
return err;
out_unlock:
rcu_read_unlock();
out:
return err;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static inline unsigned xfrm6_tunnel_spi_hash_byspi(u32 spi)
{
return spi % XFRM6_TUNNEL_SPI_BYSPI_HSIZE;
}
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 resume_console(void)
{
if (!console_suspend_enabled)
return;
down(&console_sem);
console_suspended = 0;
console_unlock();
}
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 AddInputMethodNames(const GList* engines, InputMethodDescriptors* out) {
DCHECK(out);
for (; engines; engines = g_list_next(engines)) {
IBusEngineDesc* engine_desc = IBUS_ENGINE_DESC(engines->data);
const gchar* name = ibus_engine_desc_get_name(engine_desc);
const gchar* longname = ibus_engine_desc_get_longname(engine_desc);
const gchar* layout = ibus_engine_desc_get_layout(engine_desc);
const gchar* language = ibus_engine_desc_get_language(engine_desc);
if (InputMethodIdIsWhitelisted(name)) {
out->push_back(CreateInputMethodDescriptor(name,
longname,
layout,
language));
DLOG(INFO) << name << " (preloaded)";
}
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int handle_wbinvd(struct kvm_vcpu *vcpu)
{
return kvm_emulate_wbinvd(vcpu);
}
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: get_rt_rlimit(vector_t *strvec, const char *process)
{
unsigned limit;
rlim_t rlim;
if (!read_unsigned_strvec(strvec, 1, &limit, 1, UINT32_MAX, true)) {
report_config_error(CONFIG_GENERAL_ERROR, "Invalid %s real-time limit - %s", process, FMT_STR_VSLOT(strvec, 1));
return 0;
}
rlim = limit;
return rlim;
}
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: spnego_gss_pseudo_random(OM_uint32 *minor_status,
gss_ctx_id_t context,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
OM_uint32 ret;
ret = gss_pseudo_random(minor_status,
context,
prf_key,
prf_in,
desired_output_len,
prf_out);
return (ret);
}
CWE ID: CWE-18
Target: 1
Example 2:
Code: JSValue jsTestInterfaceConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSTestInterface* domObject = jsCast<JSTestInterface*>(asObject(slotBase));
return JSTestInterface::getConstructor(exec, domObject->globalObject());
}
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 IBusBusDisconnectedCallback(IBusBus* bus, gpointer user_data) {
LOG(WARNING) << "IBus connection is terminated.";
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->MaybeDestroyIBusConfig();
if (self->connection_change_handler_) {
LOG(INFO) << "Notifying Chrome that IBus is terminated.";
self->connection_change_handler_(self->language_library_, 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: P2PQuicTransportImpl::P2PQuicTransportImpl(
P2PQuicTransportConfig p2p_transport_config,
std::unique_ptr<net::QuicChromiumConnectionHelper> helper,
std::unique_ptr<quic::QuicConnection> connection,
const quic::QuicConfig& quic_config,
quic::QuicClock* clock)
: quic::QuicSession(connection.get(),
nullptr /* visitor */,
quic_config,
quic::CurrentSupportedVersions()),
helper_(std::move(helper)),
connection_(std::move(connection)),
perspective_(p2p_transport_config.is_server
? quic::Perspective::IS_SERVER
: quic::Perspective::IS_CLIENT),
packet_transport_(p2p_transport_config.packet_transport),
delegate_(p2p_transport_config.delegate),
clock_(clock) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(delegate_);
DCHECK(clock_);
DCHECK(packet_transport_);
DCHECK_GT(p2p_transport_config.certificates.size(), 0u);
if (p2p_transport_config.can_respond_to_crypto_handshake) {
InitializeCryptoStream();
}
certificate_ = p2p_transport_config.certificates[0];
packet_transport_->SetReceiveDelegate(this);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static int loop_exit_cb(int id, void *ptr, void *data)
{
struct loop_device *lo = ptr;
loop_remove(lo);
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: void PaintLayerScrollableArea::SetHorizontalScrollbarVisualRect(
const LayoutRect& rect) {
horizontal_scrollbar_visual_rect_ = rect;
if (Scrollbar* scrollbar = HorizontalScrollbar())
scrollbar->SetVisualRect(rect);
}
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: void TraceEvent::AppendAsJSON(
std::string* out,
const ArgumentFilterPredicate& argument_filter_predicate) const {
int64 time_int64 = timestamp_.ToInternalValue();
int process_id = TraceLog::GetInstance()->process_id();
const char* category_group_name =
TraceLog::GetCategoryGroupName(category_group_enabled_);
DCHECK(!strchr(name_, '"'));
StringAppendF(out, "{\"pid\":%i,\"tid\":%i,\"ts\":%" PRId64
","
"\"ph\":\"%c\",\"cat\":\"%s\",\"name\":\"%s\",\"args\":",
process_id, thread_id_, time_int64, phase_, category_group_name,
name_);
bool strip_args = arg_names_[0] && !argument_filter_predicate.is_null() &&
!argument_filter_predicate.Run(category_group_name, name_);
if (strip_args) {
*out += "\"__stripped__\"";
} else {
*out += "{";
for (int i = 0; i < kTraceMaxNumArgs && arg_names_[i]; ++i) {
if (i > 0)
*out += ",";
*out += "\"";
*out += arg_names_[i];
*out += "\":";
if (arg_types_[i] == TRACE_VALUE_TYPE_CONVERTABLE)
convertable_values_[i]->AppendAsTraceFormat(out);
else
AppendValueAsJSON(arg_types_[i], arg_values_[i], out);
}
*out += "}";
}
if (phase_ == TRACE_EVENT_PHASE_COMPLETE) {
int64 duration = duration_.ToInternalValue();
if (duration != -1)
StringAppendF(out, ",\"dur\":%" PRId64, duration);
if (!thread_timestamp_.is_null()) {
int64 thread_duration = thread_duration_.ToInternalValue();
if (thread_duration != -1)
StringAppendF(out, ",\"tdur\":%" PRId64, thread_duration);
}
}
if (!thread_timestamp_.is_null()) {
int64 thread_time_int64 = thread_timestamp_.ToInternalValue();
StringAppendF(out, ",\"tts\":%" PRId64, thread_time_int64);
}
if (flags_ & TRACE_EVENT_FLAG_ASYNC_TTS) {
StringAppendF(out, ", \"use_async_tts\":1");
}
if (flags_ & TRACE_EVENT_FLAG_HAS_ID)
StringAppendF(out, ",\"id\":\"0x%" PRIx64 "\"", static_cast<uint64>(id_));
if (flags_ & TRACE_EVENT_FLAG_BIND_TO_ENCLOSING)
StringAppendF(out, ",\"bp\":\"e\"");
if ((flags_ & TRACE_EVENT_FLAG_FLOW_OUT) ||
(flags_ & TRACE_EVENT_FLAG_FLOW_IN)) {
StringAppendF(out, ",\"bind_id\":\"0x%" PRIx64 "\"",
static_cast<uint64>(bind_id_));
}
if (flags_ & TRACE_EVENT_FLAG_FLOW_IN)
StringAppendF(out, ",\"flow_in\":true");
if (flags_ & TRACE_EVENT_FLAG_FLOW_OUT)
StringAppendF(out, ",\"flow_out\":true");
if (flags_ & TRACE_EVENT_FLAG_HAS_CONTEXT_ID)
StringAppendF(out, ",\"cid\":\"0x%" PRIx64 "\"",
static_cast<uint64>(context_id_));
if (phase_ == TRACE_EVENT_PHASE_INSTANT) {
char scope = '?';
switch (flags_ & TRACE_EVENT_FLAG_SCOPE_MASK) {
case TRACE_EVENT_SCOPE_GLOBAL:
scope = TRACE_EVENT_SCOPE_NAME_GLOBAL;
break;
case TRACE_EVENT_SCOPE_PROCESS:
scope = TRACE_EVENT_SCOPE_NAME_PROCESS;
break;
case TRACE_EVENT_SCOPE_THREAD:
scope = TRACE_EVENT_SCOPE_NAME_THREAD;
break;
}
StringAppendF(out, ",\"s\":\"%c\"", scope);
}
*out += "}";
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static unsigned int bt_unused_tags(struct blk_mq_bitmap_tags *bt)
{
unsigned int i, used;
for (i = 0, used = 0; i < bt->map_nr; i++) {
struct blk_align_bitmap *bm = &bt->map[i];
used += bitmap_weight(&bm->word, bm->depth);
}
return bt->depth - used;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int hci_sock_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr;
struct sock *sk = sock->sk;
struct hci_dev *hdev = hci_pi(sk)->hdev;
BT_DBG("sock %p sk %p", sock, sk);
if (!hdev)
return -EBADFD;
lock_sock(sk);
*addr_len = sizeof(*haddr);
haddr->hci_family = AF_BLUETOOTH;
haddr->hci_dev = hdev->id;
release_sock(sk);
return 0;
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool MultibufferDataSource::DidPassCORSAccessCheck() const {
if (url_data()->cors_mode() == UrlData::CORS_UNSPECIFIED)
return false;
if (init_cb_)
return false;
if (failed_)
return false;
return true;
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: static int vfat_cmpi(const struct dentry *parent, const struct inode *pinode,
const struct dentry *dentry, const struct inode *inode,
unsigned int len, const char *str, const struct qstr *name)
{
struct nls_table *t = MSDOS_SB(parent->d_sb)->nls_io;
unsigned int alen, blen;
/* A filename cannot end in '.' or we treat it like it has none */
alen = vfat_striptail_len(name);
blen = __vfat_striptail_len(len, str);
if (alen == blen) {
if (nls_strnicmp(t, name->name, str, alen) == 0)
return 0;
}
return 1;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t tail = (i << 1) + 1;
if (cdf_check_stream_offset(sst, h, p, tail * sizeof(uint32_t),
__LINE__) == -1)
goto out;
size_t ofs = CDF_GETUINT32(p, tail);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
if (nelements == 0) {
DPRINTF(("CDF_VECTOR with nelements == 0\n"));
goto out;
}
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void tty_set_termios_ldisc(struct tty_struct *tty, int num)
{
down_write(&tty->termios_rwsem);
tty->termios.c_line = num;
up_write(&tty->termios_rwsem);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
{
BDRVQcowState *s = bs->opaque;
bdi->unallocated_blocks_are_zero = true;
bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
bdi->cluster_size = s->cluster_size;
bdi->vm_state_offset = qcow2_vm_state_offset(s);
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: void remove_hash_table(struct cache *cache, struct cache_entry *entry)
{
if(entry->hash_prev)
entry->hash_prev->hash_next = entry->hash_next;
else
cache->hash_table[CALCULATE_HASH(entry->block)] =
entry->hash_next;
if(entry->hash_next)
entry->hash_next->hash_prev = entry->hash_prev;
entry->hash_prev = entry->hash_next = NULL;
}
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: Document* LocalDOMWindow::InstallNewDocument(const String& mime_type,
const DocumentInit& init,
bool force_xhtml) {
DCHECK_EQ(init.GetFrame(), GetFrame());
ClearDocument();
document_ = CreateDocument(mime_type, init, force_xhtml);
event_queue_ = DOMWindowEventQueue::Create(document_.Get());
document_->Initialize();
if (!GetFrame())
return document_;
GetFrame()->GetScriptController().UpdateDocument();
document_->UpdateViewportDescription();
if (GetFrame()->GetPage() && GetFrame()->View()) {
GetFrame()->GetPage()->GetChromeClient().InstallSupplements(*GetFrame());
if (ScrollingCoordinator* scrolling_coordinator =
GetFrame()->GetPage()->GetScrollingCoordinator()) {
scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange(
GetFrame()->View(), kHorizontalScrollbar);
scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange(
GetFrame()->View(), kVerticalScrollbar);
scrolling_coordinator->ScrollableAreaScrollLayerDidChange(
GetFrame()->View());
}
}
GetFrame()->Selection().UpdateSecureKeyboardEntryIfActive();
if (GetFrame()->IsCrossOriginSubframe())
document_->RecordDeferredLoadReason(WouldLoadReason::kCreated);
return document_;
}
CWE ID:
Target: 1
Example 2:
Code: bool GLSurfaceEGLSurfaceControl::SupportsPlaneGpuFences() const {
return true;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: XSLStyleSheet::XSLStyleSheet(Node* parentNode, const String& originalURL, const KURL& finalURL, bool embedded)
: m_ownerNode(parentNode)
, m_originalURL(originalURL)
, m_finalURL(finalURL)
, m_isDisabled(false)
, m_embedded(embedded)
, m_processed(true) // The root sheet starts off processed.
, m_stylesheetDoc(0)
, m_stylesheetDocTaken(false)
, m_parentStyleSheet(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: void BaseRenderingContext2D::setStrokeStyle(
const StringOrCanvasGradientOrCanvasPattern& style) {
DCHECK(!style.IsNull());
String color_string;
CanvasStyle* canvas_style = nullptr;
if (style.IsString()) {
color_string = style.GetAsString();
if (color_string == GetState().UnparsedStrokeColor())
return;
Color parsed_color = 0;
if (!ParseColorOrCurrentColor(parsed_color, color_string))
return;
if (GetState().StrokeStyle()->IsEquivalentRGBA(parsed_color.Rgb())) {
ModifiableState().SetUnparsedStrokeColor(color_string);
return;
}
canvas_style = CanvasStyle::CreateFromRGBA(parsed_color.Rgb());
} else if (style.IsCanvasGradient()) {
canvas_style = CanvasStyle::CreateFromGradient(style.GetAsCanvasGradient());
} else if (style.IsCanvasPattern()) {
CanvasPattern* canvas_pattern = style.GetAsCanvasPattern();
if (OriginClean() && !canvas_pattern->OriginClean()) {
SetOriginTainted();
ClearResolvedFilters();
}
canvas_style = CanvasStyle::CreateFromPattern(canvas_pattern);
}
DCHECK(canvas_style);
ModifiableState().SetStrokeStyle(canvas_style);
ModifiableState().SetUnparsedStrokeColor(color_string);
ModifiableState().ClearResolvedFilter();
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: DevToolsDataSource::~DevToolsDataSource() {
for (const auto& pair : pending_) {
delete pair.first;
pair.second.Run(
new base::RefCountedStaticMemory(kHttpNotFound, strlen(kHttpNotFound)));
}
}
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 big_key_describe(const struct key *key, struct seq_file *m)
{
size_t datalen = (size_t)key->payload.data[big_key_len];
seq_puts(m, key->description);
if (key_is_instantiated(key))
seq_printf(m, ": %zu [%s]",
datalen,
datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff");
}
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 DeviceTokenFetcher::SetState(FetcherState state) {
state_ = state;
if (state_ != STATE_TEMPORARY_ERROR)
effective_token_fetch_error_delay_ms_ = kTokenFetchErrorDelayMilliseconds;
base::Time delayed_work_at;
switch (state_) {
case STATE_INACTIVE:
notifier_->Inform(CloudPolicySubsystem::UNENROLLED,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_TOKEN_AVAILABLE:
notifier_->Inform(CloudPolicySubsystem::SUCCESS,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_UNMANAGED:
delayed_work_at = cache_->last_policy_refresh_time() +
base::TimeDelta::FromMilliseconds(
kUnmanagedDeviceRefreshRateMilliseconds);
notifier_->Inform(CloudPolicySubsystem::UNMANAGED,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_TEMPORARY_ERROR:
delayed_work_at = base::Time::Now() +
base::TimeDelta::FromMilliseconds(
effective_token_fetch_error_delay_ms_);
effective_token_fetch_error_delay_ms_ =
std::min(effective_token_fetch_error_delay_ms_ * 2,
kTokenFetchErrorMaxDelayMilliseconds);
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::DMTOKEN_NETWORK_ERROR,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_ERROR:
effective_token_fetch_error_delay_ms_ =
kTokenFetchErrorMaxDelayMilliseconds;
delayed_work_at = base::Time::Now() +
base::TimeDelta::FromMilliseconds(
effective_token_fetch_error_delay_ms_);
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::DMTOKEN_NETWORK_ERROR,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_BAD_AUTH:
notifier_->Inform(CloudPolicySubsystem::BAD_GAIA_TOKEN,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
}
scheduler_->CancelDelayedWork();
if (!delayed_work_at.is_null()) {
base::Time now(base::Time::Now());
int64 delay = std::max<int64>((delayed_work_at - now).InMilliseconds(), 0);
scheduler_->PostDelayedWork(
base::Bind(&DeviceTokenFetcher::DoWork, base::Unretained(this)), delay);
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: virtual WebDevToolsAgent* agent() {
DevToolsAgent* agent = DevToolsAgent::FromHostId(host_id);
if (!agent)
return 0;
return agent->GetWebAgent();
}
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 rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
struct stat buf;
int ret;
ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
if (ret >= 0)
return 0;
/* renameat2() exists since Linux 3.15, btrfs added support for it later.
* If it is not implemented, fallback to another method. */
if (!IN_SET(errno, EINVAL, ENOSYS))
return -errno;
/* The link()/unlink() fallback does not work on directories. But
* renameat() without RENAME_NOREPLACE gives the same semantics on
* directories, except when newpath is an *empty* directory. This is
* good enough. */
ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
if (ret >= 0 && S_ISDIR(buf.st_mode)) {
ret = renameat(olddirfd, oldpath, newdirfd, newpath);
return ret >= 0 ? 0 : -errno;
}
/* If it is not a directory, use the link()/unlink() fallback. */
ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
if (ret < 0)
return -errno;
ret = unlinkat(olddirfd, oldpath, 0);
if (ret < 0) {
/* backup errno before the following unlinkat() alters it */
ret = errno;
(void) unlinkat(newdirfd, newpath, 0);
errno = ret;
return -errno;
}
return 0;
}
CWE ID: CWE-264
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WebRuntimeFeatures::enableSpeechSynthesis(bool enable)
{
RuntimeEnabledFeatures::setSpeechSynthesisEnabled(enable);
}
CWE ID: CWE-94
Target: 1
Example 2:
Code: base::string16 AuthenticatorBlePowerOnAutomaticSheetModel::GetStepTitle()
const {
return l10n_util::GetStringUTF16(IDS_WEBAUTHN_BLUETOOTH_POWER_ON_AUTO_TITLE);
}
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 float HWB_Diff (int r1, int g1, int b1, int r2, int g2, int b2)
{
RGBType RGB1, RGB2;
HWBType HWB1, HWB2;
float diff;
SETUP_RGB(RGB1, r1, g1, b1);
SETUP_RGB(RGB2, r2, g2, b2);
RGB_to_HWB(RGB1, &HWB1);
RGB_to_HWB(RGB2, &HWB2);
/*
* I made this bit up; it seems to produce OK results, and it is certainly
* more visually correct than the current RGB metric. (PJW)
*/
if ((HWB1.H == HWB_UNDEFINED) || (HWB2.H == HWB_UNDEFINED)) {
diff = 0.0f; /* Undefined hues always match... */
} else {
diff = fabsf(HWB1.H - HWB2.H);
if (diff > 3.0f) {
diff = 6.0f - diff; /* Remember, it's a colour circle */
}
}
diff = diff * diff + (HWB1.W - HWB2.W) * (HWB1.W - HWB2.W) + (HWB1.B - HWB2.B) * (HWB1.B - HWB2.B);
return diff;
}
CWE ID: CWE-190
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
int width, int height, int bandpos)
{
int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
int clnpass_cnt = 0;
int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
for (y = 0; y < height; y++)
memset(t1->data[y], 0, width * sizeof(**t1->data));
/* If code-block contains no compressed data: nothing to do. */
if (!cblk->length)
return 0;
for (y = 0; y < height + 2; y++)
memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
cblk->data[cblk->length] = 0xff;
cblk->data[cblk->length+1] = 0xff;
ff_mqc_initdec(&t1->mqc, cblk->data);
while (passno--) {
switch(pass_t) {
case 0:
decode_sigpass(t1, width, height, bpno + 1, bandpos,
bpass_csty_symbol && (clnpass_cnt >= 4),
vert_causal_ctx_csty_symbol);
break;
case 1:
decode_refpass(t1, width, height, bpno + 1);
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
case 2:
decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
vert_causal_ctx_csty_symbol);
clnpass_cnt = clnpass_cnt + 1;
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
}
pass_t++;
if (pass_t == 3) {
bpno--;
pass_t = 0;
}
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int __compat_get_timespec64(struct timespec64 *ts64,
const struct compat_timespec __user *cts)
{
struct compat_timespec ts;
int ret;
ret = copy_from_user(&ts, cts, sizeof(ts));
if (ret)
return -EFAULT;
ts64->tv_sec = ts.tv_sec;
ts64->tv_nsec = ts.tv_nsec;
return 0;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct nfs4_state *nfs4_try_open_cached(struct nfs4_opendata *opendata)
{
struct nfs4_state *state = opendata->state;
struct nfs_inode *nfsi = NFS_I(state->inode);
struct nfs_delegation *delegation;
int open_mode = opendata->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL);
nfs4_stateid stateid;
int ret = -EAGAIN;
for (;;) {
if (can_open_cached(state, open_mode)) {
spin_lock(&state->owner->so_lock);
if (can_open_cached(state, open_mode)) {
update_open_stateflags(state, open_mode);
spin_unlock(&state->owner->so_lock);
goto out_return_state;
}
spin_unlock(&state->owner->so_lock);
}
rcu_read_lock();
delegation = rcu_dereference(nfsi->delegation);
if (delegation == NULL ||
!can_open_delegated(delegation, open_mode)) {
rcu_read_unlock();
break;
}
/* Save the delegation */
memcpy(stateid.data, delegation->stateid.data, sizeof(stateid.data));
rcu_read_unlock();
ret = nfs_may_open(state->inode, state->owner->so_cred, open_mode);
if (ret != 0)
goto out;
ret = -EAGAIN;
/* Try to update the stateid using the delegation */
if (update_open_stateid(state, NULL, &stateid, open_mode))
goto out_return_state;
}
out:
return ERR_PTR(ret);
out_return_state:
atomic_inc(&state->count);
return state;
}
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 OneClickSigninSyncStarter::UntrustedSigninConfirmed(
StartSyncMode response) {
if (response == UNDO_SYNC) {
CancelSigninAndDelete();
} else {
if (response == CONFIGURE_SYNC_FIRST)
start_mode_ = response;
SigninManager* signin = SigninManagerFactory::GetForProfile(profile_);
signin->CompletePendingSignin();
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void FakeCentral::SetNextWriteDescriptorResponse(
uint16_t gatt_code,
const std::string& descriptor_id,
const std::string& characteristic_id,
const std::string& service_id,
const std::string& peripheral_address,
SetNextWriteDescriptorResponseCallback callback) {
FakeRemoteGattDescriptor* fake_remote_gatt_descriptor =
GetFakeRemoteGattDescriptor(peripheral_address, service_id,
characteristic_id, descriptor_id);
if (!fake_remote_gatt_descriptor) {
std::move(callback).Run(false);
}
fake_remote_gatt_descriptor->SetNextWriteResponse(gatt_code);
std::move(callback).Run(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 grubfs_free (GrubFS *gf) {
if (gf) {
if (gf->file && gf->file->device)
free (gf->file->device->disk);
free (gf->file);
free (gf);
}
}
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: exit_ext2_xattr(void)
{
mb_cache_destroy(ext2_xattr_cache);
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: _dbus_generate_random_bytes (DBusString *str,
int n_bytes)
{
int old_len;
int fd;
/* FALSE return means "no memory", if it could
* mean something else then we'd need to return
* a DBusError. So we always fall back to pseudorandom
* if the I/O fails.
*/
old_len = _dbus_string_get_length (str);
fd = -1;
/* note, urandom on linux will fall back to pseudorandom */
fd = open ("/dev/urandom", O_RDONLY);
if (fd < 0)
return _dbus_generate_pseudorandom_bytes (str, n_bytes);
_dbus_verbose ("/dev/urandom fd %d opened\n", fd);
if (_dbus_read (fd, str, n_bytes) != n_bytes)
{
_dbus_close (fd, NULL);
_dbus_string_set_length (str, old_len);
return _dbus_generate_pseudorandom_bytes (str, n_bytes);
}
_dbus_verbose ("Read %d bytes from /dev/urandom\n",
n_bytes);
_dbus_close (fd, NULL);
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: long ContentEncoding::ParseCompressionEntry(
long long start,
long long size,
IMkvReader* pReader,
ContentCompression* compression) {
assert(pReader);
assert(compression);
long long pos = start;
const long long stop = start + size;
bool valid = false;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x254) {
long long algo = UnserializeUInt(pReader, pos, size);
if (algo < 0)
return E_FILE_FORMAT_INVALID;
compression->algo = algo;
valid = true;
} else if (id == 0x255) {
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status = pReader->Read(pos, buflen, buf);
if (read_status) {
delete [] buf;
return status;
}
compression->settings = buf;
compression->settings_len = buflen;
}
pos += size; //consume payload
assert(pos <= stop);
}
if (!valid)
return E_FILE_FORMAT_INVALID;
return 0;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static unsigned xen_netbk_tx_build_gops(struct xen_netbk *netbk)
{
struct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop;
struct sk_buff *skb;
int ret;
while (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) &&
!list_empty(&netbk->net_schedule_list)) {
struct xenvif *vif;
struct xen_netif_tx_request txreq;
struct xen_netif_tx_request txfrags[MAX_SKB_FRAGS];
struct page *page;
struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];
u16 pending_idx;
RING_IDX idx;
int work_to_do;
unsigned int data_len;
pending_ring_idx_t index;
/* Get a netif from the list with work to do. */
vif = poll_net_schedule_list(netbk);
if (!vif)
continue;
RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do);
if (!work_to_do) {
xenvif_put(vif);
continue;
}
idx = vif->tx.req_cons;
rmb(); /* Ensure that we see the request before we copy it. */
memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));
/* Credit-based scheduling. */
if (txreq.size > vif->remaining_credit &&
tx_credit_exceeded(vif, txreq.size)) {
xenvif_put(vif);
continue;
}
vif->remaining_credit -= txreq.size;
work_to_do--;
vif->tx.req_cons = ++idx;
memset(extras, 0, sizeof(extras));
if (txreq.flags & XEN_NETTXF_extra_info) {
work_to_do = xen_netbk_get_extras(vif, extras,
work_to_do);
idx = vif->tx.req_cons;
if (unlikely(work_to_do < 0)) {
netbk_tx_err(vif, &txreq, idx);
continue;
}
}
ret = netbk_count_requests(vif, &txreq, txfrags, work_to_do);
if (unlikely(ret < 0)) {
netbk_tx_err(vif, &txreq, idx - ret);
continue;
}
idx += ret;
if (unlikely(txreq.size < ETH_HLEN)) {
netdev_dbg(vif->dev,
"Bad packet size: %d\n", txreq.size);
netbk_tx_err(vif, &txreq, idx);
continue;
}
/* No crossing a page as the payload mustn't fragment. */
if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {
netdev_dbg(vif->dev,
"txreq.offset: %x, size: %u, end: %lu\n",
txreq.offset, txreq.size,
(txreq.offset&~PAGE_MASK) + txreq.size);
netbk_tx_err(vif, &txreq, idx);
continue;
}
index = pending_index(netbk->pending_cons);
pending_idx = netbk->pending_ring[index];
data_len = (txreq.size > PKT_PROT_LEN &&
ret < MAX_SKB_FRAGS) ?
PKT_PROT_LEN : txreq.size;
skb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN,
GFP_ATOMIC | __GFP_NOWARN);
if (unlikely(skb == NULL)) {
netdev_dbg(vif->dev,
"Can't allocate a skb in start_xmit.\n");
netbk_tx_err(vif, &txreq, idx);
break;
}
/* Packets passed to netif_rx() must have some headroom. */
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
struct xen_netif_extra_info *gso;
gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
if (netbk_set_skb_gso(vif, skb, gso)) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
}
/* XXX could copy straight to head */
page = xen_netbk_alloc_page(netbk, skb, pending_idx);
if (!page) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop->source.u.ref = txreq.gref;
gop->source.domid = vif->domid;
gop->source.offset = txreq.offset;
gop->dest.u.gmfn = virt_to_mfn(page_address(page));
gop->dest.domid = DOMID_SELF;
gop->dest.offset = txreq.offset;
gop->len = txreq.size;
gop->flags = GNTCOPY_source_gref;
gop++;
memcpy(&netbk->pending_tx_info[pending_idx].req,
&txreq, sizeof(txreq));
netbk->pending_tx_info[pending_idx].vif = vif;
*((u16 *)skb->data) = pending_idx;
__skb_put(skb, data_len);
skb_shinfo(skb)->nr_frags = ret;
if (data_len < txreq.size) {
skb_shinfo(skb)->nr_frags++;
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
pending_idx);
} else {
frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
INVALID_PENDING_IDX);
}
netbk->pending_cons++;
request_gop = xen_netbk_get_requests(netbk, vif,
skb, txfrags, gop);
if (request_gop == NULL) {
kfree_skb(skb);
netbk_tx_err(vif, &txreq, idx);
continue;
}
gop = request_gop;
__skb_queue_tail(&netbk->tx_queue, skb);
vif->tx.req_cons = idx;
xen_netbk_check_rx_xenvif(vif);
if ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops))
break;
}
return gop - netbk->tx_copy_ops;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void usbhid_mark_busy(struct usbhid_device *usbhid)
{
struct usb_interface *intf = usbhid->intf;
usb_mark_last_busy(interface_to_usbdev(intf));
}
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: bool ExtensionTtsPlatformImplChromeOs::IsSpeaking() {
if (chromeos::CrosLibrary::Get()->EnsureLoaded()) {
return chromeos::CrosLibrary::Get()->GetSpeechSynthesisLibrary()->
IsSpeaking();
}
set_error(kCrosLibraryNotLoadedError);
return 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 ssize_t snd_timer_user_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct snd_timer_user *tu;
long result = 0, unit;
int qhead;
int err = 0;
tu = file->private_data;
unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read);
spin_lock_irq(&tu->qlock);
while ((long)count - result >= unit) {
while (!tu->qused) {
wait_queue_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto _error;
}
set_current_state(TASK_INTERRUPTIBLE);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tu->qchange_sleep, &wait);
spin_unlock_irq(&tu->qlock);
schedule();
spin_lock_irq(&tu->qlock);
remove_wait_queue(&tu->qchange_sleep, &wait);
if (tu->disconnected) {
err = -ENODEV;
goto _error;
}
if (signal_pending(current)) {
err = -ERESTARTSYS;
goto _error;
}
}
qhead = tu->qhead++;
tu->qhead %= tu->queue_size;
tu->qused--;
spin_unlock_irq(&tu->qlock);
mutex_lock(&tu->ioctl_lock);
if (tu->tread) {
if (copy_to_user(buffer, &tu->tqueue[qhead],
sizeof(struct snd_timer_tread)))
err = -EFAULT;
} else {
if (copy_to_user(buffer, &tu->queue[qhead],
sizeof(struct snd_timer_read)))
err = -EFAULT;
}
mutex_unlock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
if (err < 0)
goto _error;
result += unit;
buffer += unit;
}
_error:
spin_unlock_irq(&tu->qlock);
return result > 0 ? result : err;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: int ssl3_get_certificate_request(SSL *s)
{
int ok, ret = 0;
unsigned long n, nc, l;
unsigned int llen, ctype_num, i;
X509_NAME *xn = NULL;
const unsigned char *p, *q;
unsigned char *d;
STACK_OF(X509_NAME) *ca_sk = NULL;
n = s->method->ssl_get_message(s,
SSL3_ST_CR_CERT_REQ_A,
SSL3_ST_CR_CERT_REQ_B,
-1, s->max_cert_list, &ok);
if (!ok)
return ((int)n);
s->s3->tmp.cert_req = 0;
if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
s->s3->tmp.reuse_message = 1;
/*
* If we get here we don't need any cached handshake records as we
* wont be doing client auth.
*/
if (s->s3->handshake_buffer) {
if (!ssl3_digest_cached_records(s))
goto err;
}
return (1);
}
if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_WRONG_MESSAGE_TYPE);
goto err;
}
/* TLS does not like anon-DH with client cert */
if (s->version > SSL3_VERSION) {
if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
goto err;
}
}
p = d = (unsigned char *)s->init_msg;
if ((ca_sk = sk_X509_NAME_new(ca_dn_cmp)) == NULL) {
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
goto err;
}
/* get the certificate types */
ctype_num = *(p++);
if (s->cert->ctypes) {
OPENSSL_free(s->cert->ctypes);
s->cert->ctypes = NULL;
}
if (ctype_num > SSL3_CT_NUMBER) {
/* If we exceed static buffer copy all to cert structure */
s->cert->ctypes = OPENSSL_malloc(ctype_num);
memcpy(s->cert->ctypes, p, ctype_num);
s->cert->ctype_num = (size_t)ctype_num;
ctype_num = SSL3_CT_NUMBER;
}
for (i = 0; i < ctype_num; i++)
s->s3->tmp.ctype[i] = p[i];
p += p[-1];
if (SSL_USE_SIGALGS(s)) {
n2s(p, llen);
/*
* Check we have enough room for signature algorithms and following
* length value.
*/
if ((unsigned long)(p - d + llen + 2) > n) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
SSL_R_DATA_LENGTH_TOO_LONG);
goto err;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].digest = NULL;
s->cert->pkeys[i].valid_flags = 0;
}
if ((llen & 1) || !tls1_save_sigalgs(s, p, llen)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
SSL_R_SIGNATURE_ALGORITHMS_ERROR);
goto err;
}
if (!tls1_process_sigalgs(s)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
goto err;
}
p += llen;
}
/* get the CA RDNs */
n2s(p, llen);
#if 0
{
FILE *out;
out = fopen("/tmp/vsign.der", "w");
fwrite(p, 1, llen, out);
fclose(out);
}
#endif
if ((unsigned long)(p - d + llen) != n) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_LENGTH_MISMATCH);
goto err;
}
for (nc = 0; nc < llen;) {
n2s(p, l);
if ((l + nc + 2) > llen) {
if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
goto cont; /* netscape bugs */
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG);
goto err;
}
q = p;
if ((xn = d2i_X509_NAME(NULL, &q, l)) == NULL) {
/* If netscape tolerance is on, ignore errors */
if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
goto cont;
else {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_ASN1_LIB);
goto err;
}
}
if (q != (p + l)) {
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,
SSL_R_CA_DN_LENGTH_MISMATCH);
goto err;
}
if (!sk_X509_NAME_push(ca_sk, xn)) {
SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE);
goto err;
}
p += l;
nc += l + 2;
}
if (0) {
cont:
ERR_clear_error();
}
/* we should setup a certificate to return.... */
s->s3->tmp.cert_req = 1;
s->s3->tmp.ctype_num = ctype_num;
if (s->s3->tmp.ca_names != NULL)
sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
s->s3->tmp.ca_names = ca_sk;
ca_sk = NULL;
ret = 1;
goto done;
err:
s->state = SSL_ST_ERR;
done:
if (ca_sk != NULL)
sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
return (ret);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void page_add_file_rmap(struct page *page)
{
bool locked;
unsigned long flags;
mem_cgroup_begin_update_page_stat(page, &locked, &flags);
if (atomic_inc_and_test(&page->_mapcount)) {
__inc_zone_page_state(page, NR_FILE_MAPPED);
mem_cgroup_inc_page_stat(page, MEM_CGROUP_STAT_FILE_MAPPED);
}
mem_cgroup_end_update_page_stat(page, &locked, &flags);
}
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 disk_seqf_stop(struct seq_file *seqf, void *v)
{
struct class_dev_iter *iter = seqf->private;
/* stop is called even after start failed :-( */
if (iter) {
class_dev_iter_exit(iter);
kfree(iter);
}
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void slabs_destroy(struct kmem_cache *cachep, struct list_head *list)
{
struct page *page, *n;
list_for_each_entry_safe(page, n, list, lru) {
list_del(&page->lru);
slab_destroy(cachep, page);
}
}
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: struct file *open_exec(const char *name)
{
struct filename *filename = getname_kernel(name);
struct file *f = ERR_CAST(filename);
if (!IS_ERR(filename)) {
f = do_open_execat(AT_FDCWD, filename, 0);
putname(filename);
}
return f;
}
CWE ID: CWE-362
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void StoreNewGroup() {
PushNextTask(base::BindOnce(&AppCacheStorageImplTest::Verify_StoreNewGroup,
base::Unretained(this)));
group_ =
new AppCacheGroup(storage(), kManifestUrl, storage()->NewGroupId());
cache_ = new AppCache(storage(), storage()->NewCacheId());
cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT, 1,
kDefaultEntrySize));
mock_quota_manager_proxy_->mock_manager_->async_ = true;
storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate());
EXPECT_FALSE(delegate()->stored_group_success_);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void ath_tx_return_buffer(struct ath_softc *sc, struct ath_buf *bf)
{
spin_lock_bh(&sc->tx.txbuflock);
list_add_tail(&bf->list, &sc->tx.txbuf);
spin_unlock_bh(&sc->tx.txbuflock);
}
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: modify_principal_2_svc(mprinc_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth("kadm5_modify_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_modify_principal((void *)handle, &arg->rec,
arg->mask);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_modify_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
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 Location::SetLocation(const String& url,
LocalDOMWindow* current_window,
LocalDOMWindow* entered_window,
ExceptionState* exception_state,
SetLocationPolicy set_location_policy) {
if (!IsAttached())
return;
if (!current_window->GetFrame())
return;
Document* entered_document = entered_window->document();
if (!entered_document)
return;
KURL completed_url = entered_document->CompleteURL(url);
if (completed_url.IsNull())
return;
if (!current_window->GetFrame()->CanNavigate(*dom_window_->GetFrame(),
completed_url)) {
if (exception_state) {
exception_state->ThrowSecurityError(
"The current window does not have permission to navigate the target "
"frame to '" +
url + "'.");
}
return;
}
if (exception_state && !completed_url.IsValid()) {
exception_state->ThrowDOMException(DOMExceptionCode::kSyntaxError,
"'" + url + "' is not a valid URL.");
return;
}
if (dom_window_->IsInsecureScriptAccess(*current_window, completed_url))
return;
V8DOMActivityLogger* activity_logger =
V8DOMActivityLogger::CurrentActivityLoggerIfIsolatedWorld();
if (activity_logger) {
Vector<String> argv;
argv.push_back("LocalDOMWindow");
argv.push_back("url");
argv.push_back(entered_document->Url());
argv.push_back(completed_url);
activity_logger->LogEvent("blinkSetAttribute", argv.size(), argv.data());
}
WebFrameLoadType frame_load_type = WebFrameLoadType::kStandard;
if (set_location_policy == SetLocationPolicy::kReplaceThisFrame)
frame_load_type = WebFrameLoadType::kReplaceCurrentItem;
dom_window_->GetFrame()->ScheduleNavigation(*current_window->document(),
completed_url, frame_load_type,
UserGestureStatus::kNone);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static unsigned HuffmanTree_make2DTree(HuffmanTree* tree)
{
unsigned nodefilled = 0; /*up to which node it is filled*/
unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/
unsigned n, i;
tree->tree2d = (unsigned*)calloc(tree->numcodes * 2, sizeof(unsigned));
if(!tree->tree2d) return 83; /*alloc fail*/
/*
convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means
uninited, a value >= numcodes is an address to another bit, a value < numcodes
is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as
many columns as codes - 1.
A good huffmann tree has N * 2 - 1 nodes, of which N - 1 are internal nodes.
Here, the internal nodes are stored (what their 0 and 1 option point to).
There is only memory for such good tree currently, if there are more nodes
(due to too long length codes), error 55 will happen
*/
for(n = 0; n < tree->numcodes * 2; n++)
{
tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/
}
for(n = 0; n < tree->numcodes; n++) /*the codes*/
{
for(i = 0; i < tree->lengths[n]; i++) /*the bits for this code*/
{
unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1);
if(treepos > tree->numcodes - 2) return 55; /*oversubscribed, see comment in lodepng_error_text*/
if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/
{
if(i + 1 == tree->lengths[n]) /*last bit*/
{
tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/
treepos = 0;
}
else
{
/*put address of the next step in here, first that address has to be found of course
(it's just nodefilled + 1)...*/
nodefilled++;
/*addresses encoded with numcodes added to it*/
tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes;
treepos = nodefilled;
}
}
else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes;
}
}
for(n = 0; n < tree->numcodes * 2; n++)
{
if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/
}
return 0;
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int backupOnePage(
sqlite3_backup *p, /* Backup handle */
Pgno iSrcPg, /* Source database page to backup */
const u8 *zSrcData, /* Source database page data */
int bUpdate /* True for an update, false otherwise */
){
Pager * const pDestPager = sqlite3BtreePager(p->pDest);
const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
const int nCopy = MIN(nSrcPgsz, nDestPgsz);
const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
#ifdef SQLITE_HAS_CODEC
/* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
** guaranteed that the shared-mutex is held by this thread, handle
** p->pSrc may not actually be the owner. */
int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
#endif
int rc = SQLITE_OK;
i64 iOff;
assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
assert( p->bDestLocked );
assert( !isFatalError(p->rc) );
assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
assert( zSrcData );
/* Catch the case where the destination is an in-memory database and the
** page sizes of the source and destination differ.
*/
if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
rc = SQLITE_READONLY;
}
#ifdef SQLITE_HAS_CODEC
/* Backup is not possible if the page size of the destination is changing
** and a codec is in use.
*/
if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
rc = SQLITE_READONLY;
}
/* Backup is not possible if the number of bytes of reserve space differ
** between source and destination. If there is a difference, try to
** fix the destination to agree with the source. If that is not possible,
** then the backup cannot proceed.
*/
if( nSrcReserve!=nDestReserve ){
u32 newPgsz = nSrcPgsz;
rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
}
#endif
/* This loop runs once for each destination page spanned by the source
** page. For each iteration, variable iOff is set to the byte offset
** of the destination page.
*/
for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
DbPage *pDestPg = 0;
Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
&& SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
){
const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
u8 *zDestData = sqlite3PagerGetData(pDestPg);
u8 *zOut = &zDestData[iOff%nDestPgsz];
/* Copy the data from the source page into the destination page.
** Then clear the Btree layer MemPage.isInit flag. Both this module
** and the pager code use this trick (clearing the first byte
** of the page 'extra' space to invalidate the Btree layers
** cached parse of the page). MemPage.isInit is marked
** "MUST BE FIRST" for this purpose.
*/
memcpy(zOut, zIn, nCopy);
((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
if( iOff==0 && bUpdate==0 ){
sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
}
}
sqlite3PagerUnref(pDestPg);
}
return rc;
}
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: vrrp_tfile_end_handler(void)
{
vrrp_tracked_file_t *tfile = LIST_TAIL_DATA(vrrp_data->vrrp_track_files);
struct stat statb;
FILE *tf;
int ret;
if (!tfile->file_path) {
report_config_error(CONFIG_GENERAL_ERROR, "No file set for track_file %s - removing", tfile->fname);
free_list_element(vrrp_data->vrrp_track_files, vrrp_data->vrrp_track_files->tail);
return;
}
if (track_file_init == TRACK_FILE_NO_INIT)
return;
ret = stat(tfile->file_path, &statb);
if (!ret) {
if (track_file_init == TRACK_FILE_CREATE) {
/* The file exists */
return;
}
if ((statb.st_mode & S_IFMT) != S_IFREG) {
/* It is not a regular file */
report_config_error(CONFIG_GENERAL_ERROR, "Cannot initialise track file %s - it is not a regular file", tfile->fname);
return;
}
/* Don't overwrite a file on reload */
if (reload)
return;
}
if (!__test_bit(CONFIG_TEST_BIT, &debug)) {
/* Write the value to the file */
if ((tf = fopen(tfile->file_path, "w"))) {
fprintf(tf, "%d\n", track_file_init_value);
fclose(tf);
}
else
report_config_error(CONFIG_GENERAL_ERROR, "Unable to initialise track file %s", tfile->fname);
}
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: poppler_rectangle_new (void)
{
return g_new0 (PopplerRectangle, 1);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void HttpBridge::MakeAsynchronousPost() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
base::AutoLock lock(fetch_state_lock_);
DCHECK(!fetch_state_.request_completed);
if (fetch_state_.aborted)
return;
fetch_state_.url_poster = new URLFetcher(url_for_request_,
URLFetcher::POST, this);
fetch_state_.url_poster->set_request_context(context_getter_for_request_);
fetch_state_.url_poster->set_upload_data(content_type_, request_content_);
fetch_state_.url_poster->set_extra_request_headers(extra_headers_);
fetch_state_.url_poster->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES);
fetch_state_.url_poster->Start();
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
{
const struct sched_class *class;
if (p->sched_class == rq->curr->sched_class) {
rq->curr->sched_class->check_preempt_curr(rq, p, flags);
} else {
for_each_class(class) {
if (class == rq->curr->sched_class)
break;
if (class == p->sched_class) {
resched_task(rq->curr);
break;
}
}
}
/*
* A queue event has occurred, and we're going to schedule. In
* this case, we can save a useless back to back clock update.
*/
if (test_tsk_need_resched(rq->curr))
rq->skip_clock_update = 1;
}
CWE ID:
Target: 1
Example 2:
Code: static void release_uio_class(void)
{
class_unregister(&uio_class);
uio_major_cleanup();
}
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: WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
: delegate_(NULL),
controller_(this, browser_context),
render_view_host_delegate_view_(NULL),
created_with_opener_(false),
#if defined(OS_WIN)
accessible_parent_(NULL),
#endif
frame_tree_(new NavigatorImpl(&controller_, this),
this,
this,
this,
this),
is_loading_(false),
is_load_to_different_document_(false),
crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
crashed_error_code_(0),
waiting_for_response_(false),
load_state_(net::LOAD_STATE_IDLE, base::string16()),
upload_size_(0),
upload_position_(0),
is_resume_pending_(false),
displayed_insecure_content_(false),
has_accessed_initial_document_(false),
theme_color_(SK_ColorTRANSPARENT),
last_sent_theme_color_(SK_ColorTRANSPARENT),
did_first_visually_non_empty_paint_(false),
capturer_count_(0),
should_normally_be_visible_(true),
is_being_destroyed_(false),
notify_disconnection_(false),
dialog_manager_(NULL),
is_showing_before_unload_dialog_(false),
last_active_time_(base::TimeTicks::Now()),
closed_by_user_gesture_(false),
minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)),
maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)),
zoom_scroll_remainder_(0),
render_view_message_source_(NULL),
render_frame_message_source_(NULL),
fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
fullscreen_widget_had_focus_at_shutdown_(false),
is_subframe_(false),
force_disable_overscroll_content_(false),
last_dialog_suppressed_(false),
geolocation_service_context_(new GeolocationServiceContext()),
accessibility_mode_(
BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
audio_stream_monitor_(this),
virtual_keyboard_requested_(false),
page_scale_factor_is_one_(true),
loading_weak_factory_(this) {
frame_tree_.SetFrameRemoveListener(
base::Bind(&WebContentsImpl::OnFrameRemoved,
base::Unretained(this)));
#if defined(OS_ANDROID)
media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this));
#else
media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
#endif
loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this));
wake_lock_service_context_.reset(new WakeLockServiceContext(this));
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
int utype, char *free_cont, const ASN1_ITEM *it)
{
ASN1_VALUE **opval = NULL;
ASN1_STRING *stmp;
ASN1_TYPE *typ = NULL;
int ret = 0;
const ASN1_PRIMITIVE_FUNCS *pf;
ASN1_INTEGER **tint;
pf = it->funcs;
if (pf && pf->prim_c2i)
return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
/* If ANY type clear type and set pointer to internal value */
if (it->utype == V_ASN1_ANY) {
if (!*pval) {
typ = ASN1_TYPE_new();
if (typ == NULL)
goto err;
*pval = (ASN1_VALUE *)typ;
} else
typ = (ASN1_TYPE *)*pval;
if (utype != typ->type)
ASN1_TYPE_set(typ, utype, NULL);
opval = pval;
pval = &typ->value.asn1_value;
}
switch (utype) {
case V_ASN1_OBJECT:
if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len))
goto err;
break;
case V_ASN1_NULL:
if (len) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_NULL_IS_WRONG_LENGTH);
goto err;
}
*pval = (ASN1_VALUE *)1;
break;
case V_ASN1_BOOLEAN:
if (len != 1) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
goto err;
} else {
ASN1_BOOLEAN *tbool;
tbool = (ASN1_BOOLEAN *)pval;
*tbool = *cont;
}
break;
case V_ASN1_BIT_STRING:
if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len))
goto err;
break;
case V_ASN1_INTEGER:
case V_ASN1_NEG_INTEGER:
case V_ASN1_ENUMERATED:
case V_ASN1_NEG_ENUMERATED:
tint = (ASN1_INTEGER **)pval;
if (!c2i_ASN1_INTEGER(tint, &cont, len))
goto err;
if (!c2i_ASN1_INTEGER(tint, &cont, len))
goto err;
/* Fixup type to match the expected form */
(*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
break;
case V_ASN1_OCTET_STRING:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
case V_ASN1_SET:
case V_ASN1_SEQUENCE:
default:
if (utype == V_ASN1_BMPSTRING && (len & 1)) {
ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BMPSTRING_IS_WRONG_LENGTH);
goto err;
}
if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) {
ASN1err(ASN1_F_ASN1_EX_C2I,
ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH);
goto err;
}
/* All based on ASN1_STRING and handled the same */
if (!*pval) {
stmp = ASN1_STRING_type_new(utype);
if (!stmp) {
ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
goto err;
}
*pval = (ASN1_VALUE *)stmp;
} else {
stmp = (ASN1_STRING *)*pval;
stmp->type = utype;
}
/* If we've already allocated a buffer use it */
if (*free_cont) {
if (stmp->data)
OPENSSL_free(stmp->data);
stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
stmp->length = len;
*free_cont = 0;
} else {
if (!ASN1_STRING_set(stmp, cont, len)) {
ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
ASN1_STRING_free(stmp);
*pval = NULL;
goto err;
}
}
break;
}
/* If ASN1_ANY and NULL type fix up value */
if (typ && (utype == V_ASN1_NULL))
typ->value.ptr = NULL;
ret = 1;
err:
if (!ret) {
ASN1_TYPE_free(typ);
if (opval)
*opval = NULL;
}
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg = stream->seg_list;
for (; seg != NULL &&
((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack));)
{
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
seg = seg->next;
cnt++;
}
return cnt;
}
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: TestJavaScriptDialogManager()
: is_fullscreen_(false), message_loop_runner_(new MessageLoopRunner) {}
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 RunCallbacksWithDisabled(LogoCallbacks callbacks) {
if (callbacks.on_cached_encoded_logo_available) {
std::move(callbacks.on_cached_encoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_cached_decoded_logo_available) {
std::move(callbacks.on_cached_decoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_fresh_encoded_logo_available) {
std::move(callbacks.on_fresh_encoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
if (callbacks.on_fresh_decoded_logo_available) {
std::move(callbacks.on_fresh_decoded_logo_available)
.Run(LogoCallbackReason::DISABLED, base::nullopt);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static size_t DestroyEdge(PolygonInfo *polygon_info,
const size_t edge)
{
assert(edge < polygon_info->number_edges);
polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(
polygon_info->edges[edge].points);
polygon_info->number_edges--;
if (edge < polygon_info->number_edges)
(void) memmove(polygon_info->edges+edge,polygon_info->edges+edge+1,
(size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));
return(polygon_info->number_edges);
}
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 ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)
{
u16 offset = sizeof(struct ipv6hdr);
struct ipv6_opt_hdr *exthdr =
(struct ipv6_opt_hdr *)(ipv6_hdr(skb) + 1);
unsigned int packet_len = skb_tail_pointer(skb) -
skb_network_header(skb);
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset + 1 <= packet_len) {
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
#if IS_ENABLED(CONFIG_IPV6_MIP6)
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
break;
#endif
if (found_rhdr)
return offset;
break;
default:
return offset;
}
offset += ipv6_optlen(exthdr);
*nexthdr = &exthdr->nexthdr;
exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +
offset);
}
return offset;
}
CWE ID: CWE-125
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BluetoothDeviceChromeOS::RejectPairing() {
RunPairingCallbacks(REJECTED);
}
CWE ID:
Target: 1
Example 2:
Code: ProfileImplIOData::Handle::GetMediaRequestContextGetter() const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
LazyInitialize();
if (!media_request_context_getter_) {
media_request_context_getter_ =
ChromeURLRequestContextGetter::CreateOriginalForMedia(
profile_, io_data_);
}
return media_request_context_getter_;
}
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 dtls1_clear_queues(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
dtls1_hm_fragment_free(frag);
pitem_free(item);
}
while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
frag = (hm_fragment *)item->data;
pqueue_free(s->d1->buffered_messages);
}
}
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: void UsbFindDevicesFunction::OnGetDevicesComplete(
const std::vector<scoped_refptr<UsbDevice>>& devices) {
result_.reset(new base::ListValue());
barrier_ = base::BarrierClosure(
devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this));
for (const scoped_refptr<UsbDevice>& device : devices) {
if (device->vendor_id() != vendor_id_ ||
device->product_id() != product_id_) {
barrier_.Run();
} else {
device->OpenInterface(
interface_id_,
base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this));
}
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: PHPAPI void php_set_session_var(char *name, size_t namelen, zval *state_val, php_unserialize_data_t *var_hash TSRMLS_DC) /* {{{ */
{
IF_SESSION_VARS() {
zend_set_hash_symbol(state_val, name, namelen, PZVAL_IS_REF(state_val), 1, Z_ARRVAL_P(PS(http_session_vars)));
}
}
/* }}} */
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: guard_selection_have_enough_dir_info_to_build_circuits(guard_selection_t *gs)
{
if (!gs->primary_guards_up_to_date)
entry_guards_update_primary(gs);
int n_missing_descriptors = 0;
int n_considered = 0;
int num_primary_to_check;
/* We want to check for the descriptor of at least the first two primary
* guards in our list, since these are the guards that we typically use for
* circuits. */
num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
num_primary_to_check++;
SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
entry_guard_consider_retry(guard);
if (guard->is_reachable == GUARD_REACHABLE_NO)
continue;
n_considered++;
if (!guard_has_descriptor(guard))
n_missing_descriptors++;
if (n_considered >= num_primary_to_check)
break;
} SMARTLIST_FOREACH_END(guard);
return n_missing_descriptors == 0;
}
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: tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
PrintOutParsingResult(res, 1, caller);
return res;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void V8TestObject::SetterRaisesExceptionLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_setterRaisesExceptionLongAttribute_Getter");
test_object_v8_internal::SetterRaisesExceptionLongAttributeAttributeGetter(info);
}
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 cJSON_InitHooks(cJSON_Hooks* hooks)
{
if ( ! hooks ) {
/* Reset hooks. */
cJSON_malloc = malloc;
cJSON_free = free;
return;
}
cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;
cJSON_free = (hooks->free_fn) ? hooks->free_fn : free;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long Cluster::CreateBlock(long long id,
long long pos, // absolute pos of payload
long long size, long long discard_padding) {
assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock
if (m_entries_count < 0) { // haven't parsed anything yet
assert(m_entries == NULL);
assert(m_entries_size == 0);
m_entries_size = 1024;
m_entries = new BlockEntry* [m_entries_size];
m_entries_count = 0;
} else {
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count <= m_entries_size);
if (m_entries_count >= m_entries_size) {
const long entries_size = 2 * m_entries_size;
BlockEntry** const entries = new BlockEntry* [entries_size];
assert(entries);
BlockEntry** src = m_entries;
BlockEntry** const src_end = src + m_entries_count;
BlockEntry** dst = entries;
while (src != src_end)
*dst++ = *src++;
delete[] m_entries;
m_entries = entries;
m_entries_size = entries_size;
}
}
if (id == 0x20) // BlockGroup ID
return CreateBlockGroup(pos, size, discard_padding);
else // SimpleBlock ID
return CreateSimpleBlock(pos, size);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: find_xml_comment(xmlNode * root, xmlNode * search_comment)
{
xmlNode *a_child = NULL;
CRM_CHECK(search_comment->type == XML_COMMENT_NODE, return NULL);
for (a_child = __xml_first_child(root); a_child != NULL; a_child = __xml_next(a_child)) {
if (a_child->type != XML_COMMENT_NODE) {
continue;
}
if (safe_str_eq((const char *)a_child->content, (const char *)search_comment->content)) {
return a_child;
}
}
return NULL;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: local int log_show(void)
{
struct log *me;
struct timeval diff;
if (log_tail == NULL)
return 0;
#ifndef NOTHREAD
possess(log_lock);
#endif
me = log_head;
if (me == NULL) {
#ifndef NOTHREAD
release(log_lock);
#endif
return 0;
}
log_head = me->next;
if (me->next == NULL)
log_tail = &log_head;
#ifndef NOTHREAD
twist(log_lock, BY, -1);
#endif
diff.tv_usec = me->when.tv_usec - start.tv_usec;
diff.tv_sec = me->when.tv_sec - start.tv_sec;
if (diff.tv_usec < 0) {
diff.tv_usec += 1000000L;
diff.tv_sec--;
}
fprintf(stderr, "trace %ld.%06ld %s\n",
(long)diff.tv_sec, (long)diff.tv_usec, me->msg);
fflush(stderr);
FREE(me->msg);
FREE(me);
return 1;
}
CWE ID: CWE-22
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 PassRefPtr<StaticBitmapImage> cropImage(
Image* image,
const ParsedOptions& parsedOptions,
AlphaDisposition imageFormat = PremultiplyAlpha,
ImageDecoder::ColorSpaceOption colorSpaceOp =
ImageDecoder::ColorSpaceApplied) {
ASSERT(image);
IntRect imgRect(IntPoint(), IntSize(image->width(), image->height()));
const IntRect srcRect = intersection(imgRect, parsedOptions.cropRect);
if (srcRect.isEmpty() && !parsedOptions.premultiplyAlpha) {
SkImageInfo info =
SkImageInfo::Make(parsedOptions.resizeWidth, parsedOptions.resizeHeight,
kN32_SkColorType, kUnpremul_SkAlphaType);
RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(
static_cast<size_t>(info.width()) * info.height(),
info.bytesPerPixel());
if (!dstBuffer)
return nullptr;
RefPtr<Uint8Array> dstPixels =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
return StaticBitmapImage::create(newSkImageFromRaster(
info, std::move(dstPixels),
static_cast<size_t>(info.width()) * info.bytesPerPixel()));
}
sk_sp<SkImage> skiaImage = image->imageForCurrentFrame();
if ((((!parsedOptions.premultiplyAlpha && !skiaImage->isOpaque()) ||
!skiaImage) &&
image->data() && imageFormat == PremultiplyAlpha) ||
colorSpaceOp == ImageDecoder::ColorSpaceIgnored) {
std::unique_ptr<ImageDecoder> decoder(ImageDecoder::create(
image->data(), true,
parsedOptions.premultiplyAlpha ? ImageDecoder::AlphaPremultiplied
: ImageDecoder::AlphaNotPremultiplied,
colorSpaceOp));
if (!decoder)
return nullptr;
skiaImage = ImageBitmap::getSkImageFromDecoder(std::move(decoder));
if (!skiaImage)
return nullptr;
}
if (parsedOptions.cropRect == srcRect && !parsedOptions.shouldScaleInput) {
sk_sp<SkImage> croppedSkImage = skiaImage->makeSubset(srcRect);
if (parsedOptions.flipY)
return StaticBitmapImage::create(flipSkImageVertically(
croppedSkImage.get(), parsedOptions.premultiplyAlpha
? PremultiplyAlpha
: DontPremultiplyAlpha));
if (parsedOptions.premultiplyAlpha && imageFormat == DontPremultiplyAlpha)
return StaticBitmapImage::create(
unPremulSkImageToPremul(croppedSkImage.get()));
croppedSkImage->preroll();
return StaticBitmapImage::create(std::move(croppedSkImage));
}
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(
parsedOptions.resizeWidth, parsedOptions.resizeHeight);
if (!surface)
return nullptr;
if (srcRect.isEmpty())
return StaticBitmapImage::create(surface->makeImageSnapshot());
SkScalar dstLeft = std::min(0, -parsedOptions.cropRect.x());
SkScalar dstTop = std::min(0, -parsedOptions.cropRect.y());
if (parsedOptions.cropRect.x() < 0)
dstLeft = -parsedOptions.cropRect.x();
if (parsedOptions.cropRect.y() < 0)
dstTop = -parsedOptions.cropRect.y();
if (parsedOptions.flipY) {
surface->getCanvas()->translate(0, surface->height());
surface->getCanvas()->scale(1, -1);
}
if (parsedOptions.shouldScaleInput) {
SkRect drawSrcRect = SkRect::MakeXYWH(
parsedOptions.cropRect.x(), parsedOptions.cropRect.y(),
parsedOptions.cropRect.width(), parsedOptions.cropRect.height());
SkRect drawDstRect = SkRect::MakeXYWH(0, 0, parsedOptions.resizeWidth,
parsedOptions.resizeHeight);
SkPaint paint;
paint.setFilterQuality(parsedOptions.resizeQuality);
surface->getCanvas()->drawImageRect(skiaImage, drawSrcRect, drawDstRect,
&paint);
} else {
surface->getCanvas()->drawImage(skiaImage, dstLeft, dstTop);
}
skiaImage = surface->makeImageSnapshot();
if (parsedOptions.premultiplyAlpha) {
if (imageFormat == DontPremultiplyAlpha)
return StaticBitmapImage::create(
unPremulSkImageToPremul(skiaImage.get()));
return StaticBitmapImage::create(std::move(skiaImage));
}
return StaticBitmapImage::create(premulSkImageToUnPremul(skiaImage.get()));
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
{
if (!m_focusedNode || this->inPageCache()) // If the document is in the page cache, then we don't need to clear out the focused node.
return;
Node* focusedNode = node->treeScope()->focusedNode();
if (!focusedNode)
return;
bool nodeInSubtree = false;
if (amongChildrenOnly)
nodeInSubtree = focusedNode->isDescendantOf(node);
else
nodeInSubtree = (focusedNode == node) || focusedNode->isDescendantOf(node);
if (nodeInSubtree)
document()->focusedNodeRemoved();
}
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 BrowserViewRenderer::SetTotalRootLayerScrollOffset(
gfx::Vector2dF scroll_offset_dip) {
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2d scroll_offset;
if (max_scroll_offset_dip_.x()) {
scroll_offset.set_x((scroll_offset_dip.x() * max_offset.x()) /
max_scroll_offset_dip_.x());
}
if (max_scroll_offset_dip_.y()) {
scroll_offset.set_y((scroll_offset_dip.y() * max_offset.y()) /
max_scroll_offset_dip_.y());
}
DCHECK_LE(0, scroll_offset.x());
DCHECK_LE(0, scroll_offset.y());
DCHECK_LE(scroll_offset.x(), max_offset.x());
DCHECK_LE(scroll_offset.y(), max_offset.y());
client_->ScrollContainerViewTo(scroll_offset);
}
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: xsltFindTemplate(xsltTransformContextPtr ctxt, const xmlChar *name,
const xmlChar *nameURI) {
xsltTemplatePtr cur;
xsltStylesheetPtr style;
if ((ctxt == NULL) || (name == NULL))
return(NULL);
style = ctxt->style;
while (style != NULL) {
cur = style->templates;
while (cur != NULL) {
if (xmlStrEqual(name, cur->name)) {
if (((nameURI == NULL) && (cur->nameURI == NULL)) ||
((nameURI != NULL) && (cur->nameURI != NULL) &&
(xmlStrEqual(nameURI, cur->nameURI)))) {
return(cur);
}
}
cur = cur->next;
}
style = xsltNextImport(style);
}
return(NULL);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: request_trans_id_set(struct request *const req, const u16 trans_id) {
req->trans_id = trans_id;
*((u16 *) req->request) = htons(trans_id);
}
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: set_mdic(E1000State *s, int index, uint32_t val)
{
uint32_t data = val & E1000_MDIC_DATA_MASK;
uint32_t addr = ((val & E1000_MDIC_REG_MASK) >> E1000_MDIC_REG_SHIFT);
if ((val & E1000_MDIC_PHY_MASK) >> E1000_MDIC_PHY_SHIFT != 1) // phy #
val = s->mac_reg[MDIC] | E1000_MDIC_ERROR;
else if (val & E1000_MDIC_OP_READ) {
DBGOUT(MDIC, "MDIC read reg 0x%x\n", addr);
if (!(phy_regcap[addr] & PHY_R)) {
DBGOUT(MDIC, "MDIC read reg %x unhandled\n", addr);
val |= E1000_MDIC_ERROR;
} else
val = (val ^ data) | s->phy_reg[addr];
} else if (val & E1000_MDIC_OP_WRITE) {
DBGOUT(MDIC, "MDIC write reg 0x%x, value 0x%x\n", addr, data);
if (!(phy_regcap[addr] & PHY_W)) {
DBGOUT(MDIC, "MDIC write reg %x unhandled\n", addr);
val |= E1000_MDIC_ERROR;
} else {
if (addr < NPHYWRITEOPS && phyreg_writeops[addr]) {
phyreg_writeops[addr](s, index, data);
}
s->phy_reg[addr] = data;
}
}
s->mac_reg[MDIC] = val | E1000_MDIC_READY;
if (val & E1000_MDIC_INT_EN) {
set_ics(s, 0, E1000_ICR_MDAC);
}
}
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 handle_pxe_menu(cmd_tbl_t *cmdtp, struct pxe_menu *cfg)
{
void *choice;
struct menu *m;
int err;
#ifdef CONFIG_CMD_BMP
/* display BMP if available */
if (cfg->bmp) {
if (get_relfile(cmdtp, cfg->bmp, image_load_addr)) {
run_command("cls", 0);
bmp_display(image_load_addr,
BMP_ALIGN_CENTER, BMP_ALIGN_CENTER);
} else {
printf("Skipping background bmp %s for failure\n",
cfg->bmp);
}
}
#endif
m = pxe_menu_to_menu(cfg);
if (!m)
return;
err = menu_get_choice(m, &choice);
menu_destroy(m);
/*
* err == 1 means we got a choice back from menu_get_choice.
*
* err == -ENOENT if the menu was setup to select the default but no
* default was set. in that case, we should continue trying to boot
* labels that haven't been attempted yet.
*
* otherwise, the user interrupted or there was some other error and
* we give up.
*/
if (err == 1) {
err = label_boot(cmdtp, choice);
if (!err)
return;
} else if (err != -ENOENT) {
return;
}
boot_unattempted_labels(cmdtp, cfg);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int pick_link(struct nameidata *nd, struct path *link,
struct inode *inode, unsigned seq)
{
int error;
struct saved *last;
if (unlikely(nd->total_link_count++ >= MAXSYMLINKS)) {
path_to_nameidata(link, nd);
return -ELOOP;
}
if (!(nd->flags & LOOKUP_RCU)) {
if (link->mnt == nd->path.mnt)
mntget(link->mnt);
}
error = nd_alloc_stack(nd);
if (unlikely(error)) {
if (error == -ECHILD) {
if (unlikely(!legitimize_path(nd, link, seq))) {
drop_links(nd);
nd->depth = 0;
nd->flags &= ~LOOKUP_RCU;
nd->path.mnt = NULL;
nd->path.dentry = NULL;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
rcu_read_unlock();
} else if (likely(unlazy_walk(nd)) == 0)
error = nd_alloc_stack(nd);
}
if (error) {
path_put(link);
return error;
}
}
last = nd->stack + nd->depth++;
last->link = *link;
clear_delayed_call(&last->done);
nd->link_inode = inode;
last->seq = seq;
return 1;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: dbus_g_proxy_manager_filter (DBusConnection *connection,
DBusMessage *message,
void *user_data)
{
DBusGProxyManager *manager;
if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
manager = user_data;
dbus_g_proxy_manager_ref (manager);
LOCK_MANAGER (manager);
if (dbus_message_is_signal (message,
DBUS_INTERFACE_LOCAL,
"Disconnected"))
{
/* Destroy all the proxies, quite possibly resulting in unreferencing
* the proxy manager and the connection as well.
*/
GSList *all;
GSList *tmp;
all = dbus_g_proxy_manager_list_all (manager);
tmp = all;
while (tmp != NULL)
{
DBusGProxy *proxy;
proxy = DBUS_G_PROXY (tmp->data);
UNLOCK_MANAGER (manager);
dbus_g_proxy_destroy (proxy);
g_object_unref (G_OBJECT (proxy));
LOCK_MANAGER (manager);
tmp = tmp->next;
}
g_slist_free (all);
#ifndef G_DISABLE_CHECKS
if (manager->proxy_lists != NULL)
g_warning ("Disconnection emitted \"destroy\" on all DBusGProxy, but somehow new proxies were created in response to one of those destroy signals. This will cause a memory leak.");
#endif
}
else
{
char *tri;
GSList *full_list;
GSList *owned_names;
GSList *tmp;
const char *sender;
/* First we handle NameOwnerChanged internally */
if (dbus_message_is_signal (message,
DBUS_INTERFACE_DBUS,
"NameOwnerChanged"))
{
DBusError derr;
dbus_error_init (&derr);
if (!dbus_message_get_args (message,
&derr,
DBUS_TYPE_STRING,
&name,
DBUS_TYPE_STRING,
&prev_owner,
DBUS_TYPE_STRING,
&new_owner,
DBUS_TYPE_INVALID))
{
/* Ignore this error */
dbus_error_free (&derr);
}
else if (manager->owner_names != NULL)
{
dbus_g_proxy_manager_replace_name_owner (manager, name, prev_owner, new_owner);
}
}
}
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool HeapAllocator::backingShrink(void* address,
size_t quantizedCurrentSize,
size_t quantizedShrunkSize) {
if (!address || quantizedShrunkSize == quantizedCurrentSize)
return true;
ASSERT(quantizedShrunkSize < quantizedCurrentSize);
ThreadState* state = ThreadState::current();
if (state->sweepForbidden())
return false;
ASSERT(!state->isInGC());
ASSERT(state->isAllocationAllowed());
DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap());
BasePage* page = pageFromObject(address);
if (page->isLargeObjectPage() || page->arena()->getThreadState() != state)
return false;
HeapObjectHeader* header = HeapObjectHeader::fromPayload(address);
ASSERT(header->checkHeader());
NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage();
if (quantizedCurrentSize <=
quantizedShrunkSize + sizeof(HeapObjectHeader) + sizeof(void*) * 32 &&
!arena->isObjectAllocatedAtAllocationPoint(header))
return true;
bool succeededAtAllocationPoint =
arena->shrinkObject(header, quantizedShrunkSize);
if (succeededAtAllocationPoint)
state->allocationPointAdjusted(arena->arenaIndex());
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int cx24116_sleep(struct dvb_frontend *fe)
{
struct cx24116_state *state = fe->demodulator_priv;
struct cx24116_cmd cmd;
int ret;
dprintk("%s()\n", __func__);
/* Firmware CMD 36: Power config */
cmd.args[0x00] = CMD_TUNERSLEEP;
cmd.args[0x01] = 1;
cmd.len = 0x02;
ret = cx24116_cmd_execute(fe, &cmd);
if (ret != 0)
return ret;
/* Power off (Shutdown clocks) */
cx24116_writereg(state, 0xea, 0xff);
cx24116_writereg(state, 0xe1, 1);
cx24116_writereg(state, 0xe0, 1);
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: PHP_FUNCTION(pg_untrace)
{
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) {
return;
}
if (argc == 0) {
id = FETCH_DEFAULT_LINK();
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
PQuntrace(pgsql);
RETURN_TRUE;
}
CWE ID:
Output:
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.