prompt
stringlengths 799
20.4k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long Track::ParseContentEncodingsEntry(long long start, long long size) {
IMkvReader* const pReader = m_pSegment->m_pReader;
assert(pReader);
long long pos = start;
const long long stop = start + size;
int count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x2240) // ContentEncoding ID
++count;
pos += size; // consume payload
assert(pos <= stop);
}
if (count <= 0)
return -1;
content_encoding_entries_ = new (std::nothrow) ContentEncoding* [count];
if (!content_encoding_entries_)
return -1;
content_encoding_entries_end_ = content_encoding_entries_;
pos = start;
while (pos < stop) {
long long id, size;
long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x2240) { // ContentEncoding ID
ContentEncoding* const content_encoding =
new (std::nothrow) ContentEncoding();
if (!content_encoding)
return -1;
status = content_encoding->ParseContentEncodingEntry(pos, size, pReader);
if (status) {
delete content_encoding;
return status;
}
*content_encoding_entries_end_++ = content_encoding;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: GF_Err ccst_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_int(bs, ptr->all_ref_pics_intra, 1);
gf_bs_write_int(bs, ptr->intra_pred_used, 1);
gf_bs_write_int(bs, ptr->max_ref_per_pic, 4);
gf_bs_write_int(bs, 0, 26);
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: nsPop(xmlParserCtxtPtr ctxt, int nr)
{
int i;
if (ctxt->nsTab == NULL) return(0);
if (ctxt->nsNr < nr) {
xmlGenericError(xmlGenericErrorContext, "Pbm popping %d NS\n", nr);
nr = ctxt->nsNr;
}
if (ctxt->nsNr <= 0)
return (0);
for (i = 0;i < nr;i++) {
ctxt->nsNr--;
ctxt->nsTab[ctxt->nsNr] = NULL;
}
return(nr);
}
CWE ID: CWE-611
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void QuicTransportHost::Initialize(
IceTransportHost* ice_transport_host,
quic::Perspective perspective,
const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates) {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
DCHECK(ice_transport_host);
DCHECK(!ice_transport_host_);
ice_transport_host_ = ice_transport_host;
P2PQuicTransportConfig config(
this, ice_transport_host->ConnectConsumer(this)->packet_transport(),
certificates);
config.is_server = (perspective == quic::Perspective::IS_SERVER);
quic_transport_ =
quic_transport_factory_->CreateQuicTransport(std::move(config));
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void pdf_run_SC_pattern(fz_context *ctx, pdf_processor *proc, const char *name, pdf_pattern *pat, int n, float *color)
{
pdf_run_processor *pr = (pdf_run_processor *)proc;
pr->dev->flags &= ~FZ_DEVFLAG_STROKECOLOR_UNDEFINED;
pdf_set_pattern(ctx, pr, PDF_STROKE, pat, color);
}
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 PHP_FUNCTION(session_id)
{
char *name = NULL;
int name_len, argc = ZEND_NUM_ARGS();
if (zend_parse_parameters(argc TSRMLS_CC, "|s", &name, &name_len) == FAILURE) {
return;
}
if (PS(id)) {
RETVAL_STRING(PS(id), 1);
} else {
RETVAL_EMPTY_STRING();
}
if (name) {
if (PS(id)) {
efree(PS(id));
}
PS(id) = estrndup(name, name_len);
}
}
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 snd_pcm_period_elapsed(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime;
unsigned long flags;
if (PCM_RUNTIME_CHECK(substream))
return;
runtime = substream->runtime;
snd_pcm_stream_lock_irqsave(substream, flags);
if (!snd_pcm_running(substream) ||
snd_pcm_update_hw_ptr0(substream, 1) < 0)
goto _end;
#ifdef CONFIG_SND_PCM_TIMER
if (substream->timer_running)
snd_timer_interrupt(substream->timer, 1);
#endif
_end:
snd_pcm_stream_unlock_irqrestore(substream, flags);
kill_fasync(&runtime->fasync, SIGIO, POLL_IN);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void WebGL2RenderingContextBase::UpdateBuffersToAutoClear(
WebGL2RenderingContextBase::ClearBufferCaller caller,
GLenum buffer,
GLint drawbuffer) {
if (framebuffer_binding_)
return;
if (scissor_enabled_)
return;
if (drawbuffer != 0)
return;
switch (caller) {
case kClearBufferiv:
if (buffer != GL_STENCIL)
return;
break;
case kClearBufferfv:
if (buffer != GL_COLOR && buffer != GL_DEPTH)
return;
break;
case kClearBufferuiv:
return;
case kClearBufferfi:
if (buffer != GL_DEPTH_STENCIL)
return;
break;
}
GLbitfield buffers_to_clear = 0;
switch (buffer) {
case GL_COLOR:
buffers_to_clear = GL_COLOR_BUFFER_BIT;
break;
case GL_DEPTH:
buffers_to_clear = GL_DEPTH_BUFFER_BIT;
break;
case GL_STENCIL:
buffers_to_clear = GL_STENCIL_BUFFER_BIT;
break;
case GL_DEPTH_STENCIL:
buffers_to_clear = GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT;
break;
default:
return;
}
GetDrawingBuffer()->SetBuffersToAutoClear(
GetDrawingBuffer()->GetBuffersToAutoClear() & (~buffers_to_clear));
}
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: struct sk_buff *napi_get_frags(struct napi_struct *napi)
{
struct sk_buff *skb = napi->skb;
if (!skb) {
skb = netdev_alloc_skb_ip_align(napi->dev, GRO_MAX_HEAD);
if (skb)
napi->skb = skb;
}
return skb;
}
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 struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root,
struct btrfs_path *path,
const char *name, int name_len)
{
struct btrfs_dir_item *dir_item;
unsigned long name_ptr;
u32 total_len;
u32 cur = 0;
u32 this_len;
struct extent_buffer *leaf;
leaf = path->nodes[0];
dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
if (verify_dir_item(root, leaf, dir_item))
return NULL;
total_len = btrfs_item_size_nr(leaf, path->slots[0]);
while (cur < total_len) {
this_len = sizeof(*dir_item) +
btrfs_dir_name_len(leaf, dir_item) +
btrfs_dir_data_len(leaf, dir_item);
name_ptr = (unsigned long)(dir_item + 1);
if (btrfs_dir_name_len(leaf, dir_item) == name_len &&
memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0)
return dir_item;
cur += this_len;
dir_item = (struct btrfs_dir_item *)((char *)dir_item +
this_len);
}
return NULL;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: void Gfx::opClosePath(Object args[], int numArgs) {
if (!state->isCurPt()) {
error(getPos(), "No current point in closepath");
return;
}
state->closePath();
}
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 mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos,
long long size_, double& result) {
assert(pReader);
assert(pos >= 0);
if ((size_ != 4) && (size_ != 8))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) // error
return status;
if (size == 4) {
union {
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;) {
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
} else {
assert(size == 8);
union {
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;) {
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
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: void usage()
{
fprintf (stderr, "PNG2PNM\n");
fprintf (stderr, " by Willem van Schaik, 1999\n");
#ifdef __TURBOC__
fprintf (stderr, " for Turbo-C and Borland-C compilers\n");
#else
fprintf (stderr, " for Linux (and Unix) compilers\n");
#endif
fprintf (stderr, "Usage: png2pnm [options] <file>.png [<file>.pnm]\n");
fprintf (stderr, " or: ... | png2pnm [options]\n");
fprintf (stderr, "Options:\n");
fprintf (stderr, " -r[aw] write pnm-file in binary format (P4/P5/P6) (default)\n");
fprintf (stderr, " -n[oraw] write pnm-file in ascii format (P1/P2/P3)\n");
fprintf (stderr, " -a[lpha] <file>.pgm write PNG alpha channel as pgm-file\n");
fprintf (stderr, " -h | -? print this help-information\n");
}
CWE ID:
Target: 1
Example 2:
Code: void AutomationProvider::Cut(int tab_handle) {
RenderViewHost* view = GetViewForTab(tab_handle);
if (!view) {
NOTREACHED();
return;
}
view->Cut();
}
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: _exsltDateAdd (exsltDateValPtr dt, exsltDateValPtr dur)
{
exsltDateValPtr ret;
long carry, tempdays, temp;
exsltDateValDatePtr r, d;
exsltDateValDurationPtr u;
if ((dt == NULL) || (dur == NULL))
return NULL;
ret = exsltDateCreateDate(dt->type);
if (ret == NULL)
return NULL;
r = &(ret->value.date);
d = &(dt->value.date);
u = &(dur->value.dur);
/* normalization */
if (d->mon == 0)
d->mon = 1;
/* normalize for time zone offset */
u->sec -= (d->tzo * 60); /* changed from + to - (bug 153000) */
d->tzo = 0;
/* normalization */
if (d->day == 0)
d->day = 1;
/* month */
carry = d->mon + u->mon;
r->mon = (unsigned int)MODULO_RANGE(carry, 1, 13);
carry = (long)FQUOTIENT_RANGE(carry, 1, 13);
/* year (may be modified later) */
r->year = d->year + carry;
if (r->year == 0) {
if (d->year > 0)
r->year--;
else
r->year++;
}
/* time zone */
r->tzo = d->tzo;
r->tz_flag = d->tz_flag;
/* seconds */
r->sec = d->sec + u->sec;
carry = (long)FQUOTIENT((long)r->sec, 60);
if (r->sec != 0.0) {
r->sec = MODULO(r->sec, 60.0);
}
/* minute */
carry += d->min;
r->min = (unsigned int)MODULO(carry, 60);
carry = (long)FQUOTIENT(carry, 60);
/* hours */
carry += d->hour;
r->hour = (unsigned int)MODULO(carry, 24);
carry = (long)FQUOTIENT(carry, 24);
/*
* days
* Note we use tempdays because the temporary values may need more
* than 5 bits
*/
if ((VALID_YEAR(r->year)) && (VALID_MONTH(r->mon)) &&
(d->day > MAX_DAYINMONTH(r->year, r->mon)))
tempdays = MAX_DAYINMONTH(r->year, r->mon);
else if (d->day < 1)
tempdays = 1;
else
tempdays = d->day;
tempdays += u->day + carry;
while (1) {
if (tempdays < 1) {
long tmon = (long)MODULO_RANGE((int)r->mon-1, 1, 13);
long tyr = r->year + (long)FQUOTIENT_RANGE((int)r->mon-1, 1, 13);
if (tyr == 0)
tyr--;
/*
* Coverity detected an overrun in daysInMonth
* of size 12 at position 12 with index variable "((r)->mon - 1)"
*/
if (tmon < 0)
tmon = 0;
if (tmon > 12)
tmon = 12;
tempdays += MAX_DAYINMONTH(tyr, tmon);
carry = -1;
} else if (tempdays > (long)MAX_DAYINMONTH(r->year, r->mon)) {
tempdays = tempdays - MAX_DAYINMONTH(r->year, r->mon);
carry = 1;
} else
break;
temp = r->mon + carry;
r->mon = (unsigned int)MODULO_RANGE(temp, 1, 13);
r->year = r->year + (long)FQUOTIENT_RANGE(temp, 1, 13);
if (r->year == 0) {
if (temp < 1)
r->year--;
else
r->year++;
}
}
r->day = tempdays;
/*
* adjust the date/time type to the date values
*/
if (ret->type != XS_DATETIME) {
if ((r->hour) || (r->min) || (r->sec))
ret->type = XS_DATETIME;
else if (ret->type != XS_DATE) {
if (r->day != 1)
ret->type = XS_DATE;
else if ((ret->type != XS_GYEARMONTH) && (r->mon != 1))
ret->type = XS_GYEARMONTH;
}
}
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 struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx,
struct vrend_shader *vs,
struct vrend_shader *fs,
struct vrend_shader *gs)
{
struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program);
char name[16];
int i;
GLuint prog_id;
GLint lret;
int id;
int last_shader;
if (!sprog)
return NULL;
/* need to rewrite VS code to add interpolation params */
if ((gs && gs->compiled_fs_id != fs->id) ||
(!gs && vs->compiled_fs_id != fs->id)) {
bool ret;
if (gs)
vrend_patch_vertex_shader_interpolants(gs->glsl_prog,
&gs->sel->sinfo,
&fs->sel->sinfo, true, fs->key.flatshade);
else
vrend_patch_vertex_shader_interpolants(vs->glsl_prog,
&vs->sel->sinfo,
&fs->sel->sinfo, false, fs->key.flatshade);
ret = vrend_compile_shader(ctx, gs ? gs : vs);
if (ret == false) {
glDeleteShader(gs ? gs->id : vs->id);
free(sprog);
return NULL;
}
if (gs)
gs->compiled_fs_id = fs->id;
else
vs->compiled_fs_id = fs->id;
}
prog_id = glCreateProgram();
glAttachShader(prog_id, vs->id);
if (gs) {
if (gs->id > 0)
glAttachShader(prog_id, gs->id);
set_stream_out_varyings(prog_id, &gs->sel->sinfo);
}
else
set_stream_out_varyings(prog_id, &vs->sel->sinfo);
glAttachShader(prog_id, fs->id);
if (fs->sel->sinfo.num_outputs > 1) {
if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1");
sprog->dual_src_linked = true;
} else {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1");
sprog->dual_src_linked = false;
}
} else
sprog->dual_src_linked = false;
if (vrend_state.have_vertex_attrib_binding) {
uint32_t mask = vs->sel->sinfo.attrib_input_mask;
while (mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "in_%d", i);
glBindAttribLocation(prog_id, i, name);
}
}
glLinkProgram(prog_id);
glGetProgramiv(prog_id, GL_LINK_STATUS, &lret);
if (lret == GL_FALSE) {
char infolog[65536];
int len;
glGetProgramInfoLog(prog_id, 65536, &len, infolog);
fprintf(stderr,"got error linking\n%s\n", infolog);
/* dump shaders */
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0);
fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog);
if (gs)
fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog);
fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog);
glDeleteProgram(prog_id);
return NULL;
}
sprog->ss[PIPE_SHADER_FRAGMENT] = fs;
sprog->ss[PIPE_SHADER_GEOMETRY] = gs;
list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs);
list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs);
if (gs)
list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs);
last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT;
sprog->id = prog_id;
list_addtail(&sprog->head, &ctx->sub->programs);
if (fs->key.pstipple_tex)
sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler");
else
sprog->fs_stipple_loc = -1;
sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust");
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.samplers_used_mask) {
uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask;
int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask);
int index;
sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask;
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) {
sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t));
sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t));
} else {
sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL;
}
sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t));
if (sprog->samp_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
index = 0;
while(mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "%ssamp%d", prefix, i);
sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name);
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) {
snprintf(name, 14, "%sshadmask%d", prefix, i);
sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name);
snprintf(name, 14, "%sshadadd%d", prefix, i);
sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name);
}
index++;
}
}
} else {
sprog->samp_locs[id] = NULL;
sprog->shadow_samp_mask_locs[id] = NULL;
sprog->shadow_samp_add_locs[id] = NULL;
sprog->shadow_samp_mask[id] = 0;
}
sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_consts) {
sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t));
if (sprog->const_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) {
snprintf(name, 16, "%sconst0[%d]", prefix, i);
sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name);
}
}
} else
sprog->const_locs[id] = NULL;
}
if (!vrend_state.have_vertex_attrib_binding) {
if (vs->sel->sinfo.num_inputs) {
sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t));
if (sprog->attrib_locs) {
for (i = 0; i < vs->sel->sinfo.num_inputs; i++) {
snprintf(name, 10, "in_%d", i);
sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name);
}
}
} else
sprog->attrib_locs = NULL;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_ubos) {
const char *prefix = pipe_shader_to_prefix(id);
sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t));
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) {
snprintf(name, 16, "%subo%d", prefix, i + 1);
sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name);
}
} else
sprog->ubo_locs[id] = NULL;
}
if (vs->sel->sinfo.num_ucp) {
for (i = 0; i < vs->sel->sinfo.num_ucp; i++) {
snprintf(name, 10, "clipp[%d]", i);
sprog->clip_locs[i] = glGetUniformLocation(prog_id, name);
}
}
return sprog;
}
CWE ID: CWE-772
Target: 1
Example 2:
Code: static u32 vlan_dev_fix_features(struct net_device *dev, u32 features)
{
struct net_device *real_dev = vlan_dev_info(dev)->real_dev;
u32 old_features = features;
features &= real_dev->features;
features &= real_dev->vlan_features;
features |= old_features & NETIF_F_SOFT_FEATURES;
if (dev_ethtool_get_rx_csum(real_dev))
features |= NETIF_F_RXCSUM;
features |= NETIF_F_LLTX;
return features;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void ptrace_hbptriggered(struct perf_event *bp, int unused,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp);
long num;
int i;
siginfo_t info;
for (i = 0; i < ARM_MAX_HBP_SLOTS; ++i)
if (current->thread.debug.hbp[i] == bp)
break;
num = (i == ARM_MAX_HBP_SLOTS) ? 0 : ptrace_hbp_idx_to_num(i);
info.si_signo = SIGTRAP;
info.si_errno = (int)num;
info.si_code = TRAP_HWBKPT;
info.si_addr = (void __user *)(bkpt->trigger);
force_sig_info(SIGTRAP, &info, current);
}
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: OMX_ERRORTYPE SoftG711::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
if (pcmParams->nPortIndex == 0) {
pcmParams->ePCMMode = mIsMLaw ? OMX_AUDIO_PCMModeMULaw
: OMX_AUDIO_PCMModeALaw;
} else {
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
}
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mNumChannels;
pcmParams->nSamplingRate = mSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void add_assoc_name_entry(zval * val, char * key, X509_NAME * name, int shortname TSRMLS_DC) /* {{{ */
{
zval *subitem, *subentries;
int i, j = -1, last = -1, obj_cnt = 0;
char *sname;
int nid;
X509_NAME_ENTRY * ne;
ASN1_STRING * str = NULL;
ASN1_OBJECT * obj;
if (key != NULL) {
MAKE_STD_ZVAL(subitem);
array_init(subitem);
} else {
subitem = val;
}
for (i = 0; i < X509_NAME_entry_count(name); i++) {
unsigned char *to_add;
int to_add_len;
ne = X509_NAME_get_entry(name, i);
obj = X509_NAME_ENTRY_get_object(ne);
nid = OBJ_obj2nid(obj);
obj_cnt = 0;
if (shortname) {
sname = (char *) OBJ_nid2sn(nid);
} else {
sname = (char *) OBJ_nid2ln(nid);
}
MAKE_STD_ZVAL(subentries);
array_init(subentries);
last = -1;
for (;;) {
j = X509_NAME_get_index_by_OBJ(name, obj, last);
if (j < 0) {
if (last != -1) break;
} else {
obj_cnt++;
ne = X509_NAME_get_entry(name, j);
str = X509_NAME_ENTRY_get_data(ne);
if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) {
to_add_len = ASN1_STRING_to_UTF8(&to_add, str);
if (to_add_len != -1) {
add_next_index_stringl(subentries, (char *)to_add, to_add_len, 1);
}
} else {
to_add = ASN1_STRING_data(str);
to_add_len = ASN1_STRING_length(str);
add_next_index_stringl(subentries, (char *)to_add, to_add_len, 1);
}
}
last = j;
}
i = last;
if (obj_cnt > 1) {
add_assoc_zval_ex(subitem, sname, strlen(sname) + 1, subentries);
} else {
zval_dtor(subentries);
FREE_ZVAL(subentries);
if (obj_cnt && str && to_add_len > -1) {
add_assoc_stringl(subitem, sname, (char *)to_add, to_add_len, 1);
}
}
}
if (key != NULL) {
zend_hash_update(HASH_OF(val), key, strlen(key) + 1, (void *)&subitem, sizeof(subitem), NULL);
}
}
/* }}} */
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
int ret, retries = 0;
struct page *page;
pgoff_t index;
struct inode *inode = mapping->host;
handle_t *handle;
index = pos >> PAGE_CACHE_SHIFT;
if (ext4_nonda_switch(inode->i_sb)) {
*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
return ext4_write_begin(file, mapping, pos,
len, flags, pagep, fsdata);
}
*fsdata = (void *)0;
trace_ext4_da_write_begin(inode, pos, len, flags);
if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
ret = ext4_da_write_inline_data_begin(mapping, inode,
pos, len, flags,
pagep, fsdata);
if (ret < 0)
return ret;
if (ret == 1)
return 0;
}
/*
* grab_cache_page_write_begin() can take a long time if the
* system is thrashing due to memory pressure, or if the page
* is being written back. So grab it first before we start
* the transaction handle. This also allows us to allocate
* the page (if needed) without using GFP_NOFS.
*/
retry_grab:
page = grab_cache_page_write_begin(mapping, index, flags);
if (!page)
return -ENOMEM;
unlock_page(page);
/*
* With delayed allocation, we don't log the i_disksize update
* if there is delayed block allocation. But we still need
* to journalling the i_disksize update if writes to the end
* of file which has an already mapped buffer.
*/
retry_journal:
handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
ext4_da_write_credits(inode, pos, len));
if (IS_ERR(handle)) {
page_cache_release(page);
return PTR_ERR(handle);
}
lock_page(page);
if (page->mapping != mapping) {
/* The page got truncated from under us */
unlock_page(page);
page_cache_release(page);
ext4_journal_stop(handle);
goto retry_grab;
}
/* In case writeback began while the page was unlocked */
wait_for_stable_page(page);
#ifdef CONFIG_EXT4_FS_ENCRYPTION
ret = ext4_block_write_begin(page, pos, len,
ext4_da_get_block_prep);
#else
ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
#endif
if (ret < 0) {
unlock_page(page);
ext4_journal_stop(handle);
/*
* block_write_begin may have instantiated a few blocks
* outside i_size. Trim these off again. Don't need
* i_size_read because we hold i_mutex.
*/
if (pos + len > inode->i_size)
ext4_truncate_failed_write(inode);
if (ret == -ENOSPC &&
ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry_journal;
page_cache_release(page);
return ret;
}
*pagep = page;
return ret;
}
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 CreateSession::ExecutePost(Response* const response) {
DictionaryValue *capabilities = NULL;
if (!GetDictionaryParameter("desiredCapabilities", &capabilities)) {
response->SetError(new Error(
kBadRequest, "Missing or invalid 'desiredCapabilities'"));
return;
}
CommandLine command_line_options(CommandLine::NO_PROGRAM);
ListValue* switches = NULL;
const char* kCustomSwitchesKey = "chrome.switches";
if (capabilities->GetListWithoutPathExpansion(kCustomSwitchesKey,
&switches)) {
for (size_t i = 0; i < switches->GetSize(); ++i) {
std::string switch_string;
if (!switches->GetString(i, &switch_string)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
size_t separator_index = switch_string.find("=");
if (separator_index != std::string::npos) {
CommandLine::StringType switch_string_native;
if (!switches->GetString(i, &switch_string_native)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
command_line_options.AppendSwitchNative(
switch_string.substr(0, separator_index),
switch_string_native.substr(separator_index + 1));
} else {
command_line_options.AppendSwitch(switch_string);
}
}
} else if (capabilities->HasKey(kCustomSwitchesKey)) {
response->SetError(new Error(
kBadRequest, "Custom switches must be a list"));
return;
}
FilePath browser_exe;
FilePath::StringType path;
if (capabilities->GetStringWithoutPathExpansion("chrome.binary", &path))
browser_exe = FilePath(path);
Session* session = new Session();
Error* error = session->Init(browser_exe, command_line_options);
if (error) {
response->SetError(error);
return;
}
bool native_events_required = false;
Value* native_events_value = NULL;
if (capabilities->GetWithoutPathExpansion(
"chrome.nativeEvents", &native_events_value)) {
if (native_events_value->GetAsBoolean(&native_events_required)) {
session->set_use_native_events(native_events_required);
}
}
bool screenshot_on_error = false;
if (capabilities->GetBoolean(
"takeScreenshotOnError", &screenshot_on_error)) {
session->set_screenshot_on_error(screenshot_on_error);
}
VLOG(1) << "Created session " << session->id();
std::ostringstream stream;
SessionManager* session_manager = SessionManager::GetInstance();
stream << "http://" << session_manager->GetAddress() << "/session/"
<< session->id();
response->SetStatus(kSeeOther);
response->SetValue(Value::CreateStringValue(stream.str()));
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: sleep_between_retrievals (int count)
{
static bool first_retrieval = true;
if (first_retrieval)
{
/* Don't sleep before the very first retrieval. */
first_retrieval = false;
return;
}
if (opt.waitretry && count > 1)
{
/* If opt.waitretry is specified and this is a retry, wait for
COUNT-1 number of seconds, or for opt.waitretry seconds. */
if (count <= opt.waitretry)
xsleep (count - 1);
else
xsleep (opt.waitretry);
}
else if (opt.wait)
{
if (!opt.random_wait || count > 1)
/* If random-wait is not specified, or if we are sleeping
between retries of the same download, sleep the fixed
interval. */
xsleep (opt.wait);
else
{
/* Sleep a random amount of time averaging in opt.wait
seconds. The sleeping amount ranges from 0.5*opt.wait to
1.5*opt.wait. */
double waitsecs = (0.5 + random_float ()) * opt.wait;
DEBUGP (("sleep_between_retrievals: avg=%f,sleep=%f\n",
opt.wait, waitsecs));
xsleep (waitsecs);
}
}
}
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: ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
const EVP_MD *digest;
VALUE vpass, vsalt, viter, vdigest;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL;
int iter;
rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest);
StringValue(vpass);
if(!NIL_P(vsalt)){
StringValue(vsalt);
if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN)
ossl_raise(eCipherError, "salt must be an 8-octet string");
salt = (unsigned char *)RSTRING_PTR(vsalt);
}
iter = NIL_P(viter) ? 2048 : NUM2INT(viter);
digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest);
GetCipher(self, ctx);
EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt,
(unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv);
if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1)
ossl_raise(eCipherError, NULL);
OPENSSL_cleanse(key, sizeof key);
OPENSSL_cleanse(iv, sizeof iv);
return Qnil;
}
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj, unsigned length)
{
FLAC__uint32 i;
FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
/* read vendor string */
if (length >= 8) {
length -= 8; /* vendor string length + num comments entries alone take 8 bytes */
FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
return false; /* read_callback_ sets the state for us */
if (obj->vendor_string.length > 0) {
if (length < obj->vendor_string.length) {
obj->vendor_string.length = 0;
obj->vendor_string.entry = 0;
goto skip;
}
else
length -= obj->vendor_string.length;
if (0 == (obj->vendor_string.entry = safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
return false;
}
if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
return false; /* read_callback_ sets the state for us */
obj->vendor_string.entry[obj->vendor_string.length] = '\0';
}
else
obj->vendor_string.entry = 0;
/* read num comments */
FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
return false; /* read_callback_ sets the state for us */
/* read comments */
if (obj->num_comments > 100000) {
/* Possibly malicious file. */
obj->num_comments = 0;
return false;
}
if (obj->num_comments > 0) {
if (0 == (obj->comments = safe_malloc_mul_2op_p(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
return false;
}
for (i = 0; i < obj->num_comments; i++) {
/* Initialize here just to make sure. */
obj->comments[i].length = 0;
obj->comments[i].entry = 0;
FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
if (length < 4) {
obj->num_comments = i;
goto skip;
}
else
length -= 4;
if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
return false; /* read_callback_ sets the state for us */
if (obj->comments[i].length > 0) {
if (length < obj->comments[i].length) {
obj->num_comments = i;
goto skip;
}
else
length -= obj->comments[i].length;
if (0 == (obj->comments[i].entry = safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
return false;
}
memset (obj->comments[i].entry, 0, obj->comments[i].length) ;
if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length)) {
obj->num_comments = i;
goto skip;
}
obj->comments[i].entry[obj->comments[i].length] = '\0';
}
else
obj->comments[i].entry = 0;
}
}
else
obj->comments = 0;
}
skip:
if (length > 0) {
/* This will only happen on files with invalid data in comments */
if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
return false; /* read_callback_ sets the state for us */
}
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
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: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
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: TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg,
TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits,
TPM2B_MAX_BUFFER *resultKey )
{
TPM2B_DIGEST tmpResult;
TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2;
UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0];
UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0];
TPM2B_DIGEST *bufferList[8];
UINT32 bitsSwizzled, i_Swizzled;
TPM_RC rval;
int i, j;
UINT16 bytes = bits / 8;
resultKey->t .size = 0;
tpm2b_i_2.t.size = 4;
tpm2bBits.t.size = 4;
bitsSwizzled = string_bytes_endian_convert_32( bits );
*(UINT32 *)tpm2bBitsPtr = bitsSwizzled;
for(i = 0; label[i] != 0 ;i++ );
tpm2bLabel.t.size = i+1;
for( i = 0; i < tpm2bLabel.t.size; i++ )
{
tpm2bLabel.t.buffer[i] = label[i];
}
resultKey->t.size = 0;
i = 1;
while( resultKey->t.size < bytes )
{
i_Swizzled = string_bytes_endian_convert_32( i );
*(UINT32 *)tpm2b_i_2Ptr = i_Swizzled;
j = 0;
bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b);
bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b);
bufferList[j++] = (TPM2B_DIGEST *)contextU;
bufferList[j++] = (TPM2B_DIGEST *)contextV;
bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b);
bufferList[j++] = (TPM2B_DIGEST *)0;
rval = tpm_hmac(sapi_context, hashAlg, key, (TPM2B **)&( bufferList[0] ), &tmpResult );
if( rval != TPM_RC_SUCCESS )
{
return( rval );
}
bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b));
if (!res) {
return TSS2_SYS_RC_BAD_VALUE;
}
}
resultKey->t.size = bytes;
return TPM_RC_SUCCESS;
}
CWE ID: CWE-522
Target: 1
Example 2:
Code: rend_service_parse_intro_for_v2(
rend_intro_cell_t *intro,
const uint8_t *buf,
size_t plaintext_len,
char **err_msg_out)
{
unsigned int klen;
extend_info_t *extend_info = NULL;
ssize_t ver_specific_len;
/*
* We accept version 3 too so that the v3 parser can call this with
* an adjusted buffer for the latter part of a v3 cell, which is
* identical to a v2 cell.
*/
if (!(intro->version == 2 ||
intro->version == 3)) {
if (err_msg_out)
tor_asprintf(err_msg_out,
"rend_service_parse_intro_for_v2() called with "
"bad version %d on INTRODUCE%d cell (this is a bug)",
intro->version,
(int)(intro->type));
goto err;
}
/* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
if (plaintext_len < 7 + DIGEST_LEN + 2) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"truncated plaintext of encrypted parted of "
"version %d INTRODUCE%d cell",
intro->version,
(int)(intro->type));
}
goto err;
}
extend_info = tor_malloc_zero(sizeof(extend_info_t));
tor_addr_from_ipv4n(&extend_info->addr, get_uint32(buf + 1));
extend_info->port = ntohs(get_uint16(buf + 5));
memcpy(extend_info->identity_digest, buf + 7, DIGEST_LEN);
extend_info->nickname[0] = '$';
base16_encode(extend_info->nickname + 1, sizeof(extend_info->nickname) - 1,
extend_info->identity_digest, DIGEST_LEN);
klen = ntohs(get_uint16(buf + 7 + DIGEST_LEN));
/* 7 == version, IP and port, DIGEST_LEN == id, 2 == key length */
if (plaintext_len < 7 + DIGEST_LEN + 2 + klen) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"truncated plaintext of encrypted parted of "
"version %d INTRODUCE%d cell",
intro->version,
(int)(intro->type));
}
goto err;
}
extend_info->onion_key =
crypto_pk_asn1_decode((const char *)(buf + 7 + DIGEST_LEN + 2), klen);
if (!extend_info->onion_key) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"error decoding onion key in version %d "
"INTRODUCE%d cell",
intro->version,
(intro->type));
}
goto err;
}
if (128 != crypto_pk_keysize(extend_info->onion_key)) {
if (err_msg_out) {
tor_asprintf(err_msg_out,
"invalid onion key size in version %d INTRODUCE%d cell",
intro->version,
(intro->type));
}
goto err;
}
ver_specific_len = 7+DIGEST_LEN+2+klen;
if (intro->version == 2) intro->u.v2.extend_info = extend_info;
else intro->u.v3.extend_info = extend_info;
return ver_specific_len;
err:
extend_info_free(extend_info);
return -1;
}
CWE ID: CWE-532
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 l2cap_sock_set_timer(struct sock *sk, long timeout)
{
BT_DBG("sk %p state %d timeout %ld", sk, sk->sk_state, timeout);
sk_reset_timer(sk, &sk->sk_timer, jiffies + timeout);
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void *bpf_obj_do_get(const struct filename *pathname,
enum bpf_type *type)
{
struct inode *inode;
struct path path;
void *raw;
int ret;
ret = kern_path(pathname->name, LOOKUP_FOLLOW, &path);
if (ret)
return ERR_PTR(ret);
inode = d_backing_inode(path.dentry);
ret = inode_permission(inode, MAY_WRITE);
if (ret)
goto out;
ret = bpf_inode_type(inode, type);
if (ret)
goto out;
raw = bpf_any_get(inode->i_private, *type);
touch_atime(&path);
path_put(&path);
return raw;
out:
path_put(&path);
return ERR_PTR(ret);
}
CWE ID:
Target: 1
Example 2:
Code: static int decode_secinfo_gss(struct xdr_stream *xdr, struct nfs4_secinfo_flavor *flavor)
{
__be32 *p;
p = xdr_inline_decode(xdr, 4);
if (unlikely(!p))
goto out_overflow;
flavor->gss.sec_oid4.len = be32_to_cpup(p);
if (flavor->gss.sec_oid4.len > GSS_OID_MAX_LEN)
goto out_err;
p = xdr_inline_decode(xdr, flavor->gss.sec_oid4.len);
if (unlikely(!p))
goto out_overflow;
memcpy(flavor->gss.sec_oid4.data, p, flavor->gss.sec_oid4.len);
p = xdr_inline_decode(xdr, 8);
if (unlikely(!p))
goto out_overflow;
flavor->gss.qop4 = be32_to_cpup(p++);
flavor->gss.service = be32_to_cpup(p);
return 0;
out_overflow:
print_overflow_msg(__func__, xdr);
return -EIO;
out_err:
return -EINVAL;
}
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 DelayedExecutor::delayedExecute(const QString &udi)
{
Solid::Device device(udi);
QString exec = m_service.exec();
MacroExpander mx(device);
mx.expandMacros(exec);
KRun::runCommand(exec, QString(), m_service.icon(), 0);
deleteLater();
}
CWE ID: CWE-78
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ext4_xattr_block_set(handle_t *handle, struct inode *inode,
struct ext4_xattr_info *i,
struct ext4_xattr_block_find *bs)
{
struct super_block *sb = inode->i_sb;
struct buffer_head *new_bh = NULL;
struct ext4_xattr_search *s = &bs->s;
struct mb_cache_entry *ce = NULL;
int error = 0;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
#define header(x) ((struct ext4_xattr_header *)(x))
if (i->value && i->value_len > sb->s_blocksize)
return -ENOSPC;
if (s->base) {
ce = mb_cache_entry_get(ext4_mb_cache, bs->bh->b_bdev,
bs->bh->b_blocknr);
BUFFER_TRACE(bs->bh, "get_write_access");
error = ext4_journal_get_write_access(handle, bs->bh);
if (error)
goto cleanup;
lock_buffer(bs->bh);
if (header(s->base)->h_refcount == cpu_to_le32(1)) {
if (ce) {
mb_cache_entry_free(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "modifying in-place");
error = ext4_xattr_set_entry(i, s);
if (!error) {
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base),
s->here);
ext4_xattr_cache_insert(ext4_mb_cache,
bs->bh);
}
unlock_buffer(bs->bh);
if (error == -EFSCORRUPTED)
goto bad_block;
if (!error)
error = ext4_handle_dirty_xattr_block(handle,
inode,
bs->bh);
if (error)
goto cleanup;
goto inserted;
} else {
int offset = (char *)s->here - bs->bh->b_data;
unlock_buffer(bs->bh);
if (ce) {
mb_cache_entry_release(ce);
ce = NULL;
}
ea_bdebug(bs->bh, "cloning");
s->base = kmalloc(bs->bh->b_size, GFP_NOFS);
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
memcpy(s->base, BHDR(bs->bh), bs->bh->b_size);
s->first = ENTRY(header(s->base)+1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->here = ENTRY(s->base + offset);
s->end = s->base + bs->bh->b_size;
}
} else {
/* Allocate a buffer where we construct the new block. */
s->base = kzalloc(sb->s_blocksize, GFP_NOFS);
/* assert(header == s->base) */
error = -ENOMEM;
if (s->base == NULL)
goto cleanup;
header(s->base)->h_magic = cpu_to_le32(EXT4_XATTR_MAGIC);
header(s->base)->h_blocks = cpu_to_le32(1);
header(s->base)->h_refcount = cpu_to_le32(1);
s->first = ENTRY(header(s->base)+1);
s->here = ENTRY(header(s->base)+1);
s->end = s->base + sb->s_blocksize;
}
error = ext4_xattr_set_entry(i, s);
if (error == -EFSCORRUPTED)
goto bad_block;
if (error)
goto cleanup;
if (!IS_LAST_ENTRY(s->first))
ext4_xattr_rehash(header(s->base), s->here);
inserted:
if (!IS_LAST_ENTRY(s->first)) {
new_bh = ext4_xattr_cache_find(inode, header(s->base), &ce);
if (new_bh) {
/* We found an identical block in the cache. */
if (new_bh == bs->bh)
ea_bdebug(new_bh, "keeping");
else {
/* The old block is released after updating
the inode. */
error = dquot_alloc_block(inode,
EXT4_C2B(EXT4_SB(sb), 1));
if (error)
goto cleanup;
BUFFER_TRACE(new_bh, "get_write_access");
error = ext4_journal_get_write_access(handle,
new_bh);
if (error)
goto cleanup_dquot;
lock_buffer(new_bh);
le32_add_cpu(&BHDR(new_bh)->h_refcount, 1);
ea_bdebug(new_bh, "reusing; refcount now=%d",
le32_to_cpu(BHDR(new_bh)->h_refcount));
unlock_buffer(new_bh);
error = ext4_handle_dirty_xattr_block(handle,
inode,
new_bh);
if (error)
goto cleanup_dquot;
}
mb_cache_entry_release(ce);
ce = NULL;
} else if (bs->bh && s->base == bs->bh->b_data) {
/* We were modifying this block in-place. */
ea_bdebug(bs->bh, "keeping this block");
new_bh = bs->bh;
get_bh(new_bh);
} else {
/* We need to allocate a new block */
ext4_fsblk_t goal, block;
goal = ext4_group_first_block_no(sb,
EXT4_I(inode)->i_block_group);
/* non-extent files can't have physical blocks past 2^32 */
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
block = ext4_new_meta_blocks(handle, inode, goal, 0,
NULL, &error);
if (error)
goto cleanup;
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
BUG_ON(block > EXT4_MAX_BLOCK_FILE_PHYS);
ea_idebug(inode, "creating block %llu",
(unsigned long long)block);
new_bh = sb_getblk(sb, block);
if (unlikely(!new_bh)) {
error = -ENOMEM;
getblk_failed:
ext4_free_blocks(handle, inode, NULL, block, 1,
EXT4_FREE_BLOCKS_METADATA);
goto cleanup;
}
lock_buffer(new_bh);
error = ext4_journal_get_create_access(handle, new_bh);
if (error) {
unlock_buffer(new_bh);
error = -EIO;
goto getblk_failed;
}
memcpy(new_bh->b_data, s->base, new_bh->b_size);
set_buffer_uptodate(new_bh);
unlock_buffer(new_bh);
ext4_xattr_cache_insert(ext4_mb_cache, new_bh);
error = ext4_handle_dirty_xattr_block(handle,
inode, new_bh);
if (error)
goto cleanup;
}
}
/* Update the inode. */
EXT4_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0;
/* Drop the previous xattr block. */
if (bs->bh && bs->bh != new_bh)
ext4_xattr_release_block(handle, inode, bs->bh);
error = 0;
cleanup:
if (ce)
mb_cache_entry_release(ce);
brelse(new_bh);
if (!(bs->bh && s->base == bs->bh->b_data))
kfree(s->base);
return error;
cleanup_dquot:
dquot_free_block(inode, EXT4_C2B(EXT4_SB(sb), 1));
goto cleanup;
bad_block:
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
goto cleanup;
#undef header
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: AudioFlinger::EffectChain::EffectChain(ThreadBase *thread,
audio_session_t sessionId)
: mThread(thread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX), mForceVolume(false)
{
mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
if (thread == NULL) {
return;
}
mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
thread->frameCount();
}
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 bool nl80211_valid_akm_suite(u32 akm)
{
return akm == WLAN_AKM_SUITE_8021X ||
akm == WLAN_AKM_SUITE_PSK;
}
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: const Chapters::Display* Chapters::Atom::GetDisplay(int index) const
{
if (index < 0)
return NULL;
if (index >= m_displays_count)
return NULL;
return m_displays + index;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void prepare_grayscale(struct iw_context *ctx)
{
switch(ctx->grayscale_formula) {
case IW_GSF_STANDARD:
ctx->grayscale_formula = IW_GSF_WEIGHTED;
iw_set_grayscale_weights(ctx,0.212655,0.715158,0.072187);
break;
case IW_GSF_COMPATIBLE:
ctx->grayscale_formula = IW_GSF_WEIGHTED;
iw_set_grayscale_weights(ctx,0.299,0.587,0.114);
break;
}
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: __releases(ping_table.lock)
{
read_unlock_bh(&ping_table.lock);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PageInfo::OnWhitelistPasswordReuseButtonPressed(
content::WebContents* web_contents) {
#if defined(FULL_SAFE_BROWSING)
DCHECK(password_protection_service_);
DCHECK(safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE ||
safe_browsing_status_ ==
SAFE_BROWSING_STATUS_ENTERPRISE_PASSWORD_REUSE);
password_protection_service_->OnUserAction(
web_contents,
safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE
? PasswordReuseEvent::SIGN_IN_PASSWORD
: PasswordReuseEvent::ENTERPRISE_PASSWORD,
safe_browsing::WarningUIType::PAGE_INFO,
safe_browsing::WarningAction::MARK_AS_LEGITIMATE);
#endif
}
CWE ID: CWE-311
Target: 1
Example 2:
Code: bool WebPagePrivate::executeJavaScriptInIsolatedWorld(const ScriptSourceCode& sourceCode, JavaScriptDataType& returnType, BlackBerry::Platform::String& returnValue)
{
if (!m_isolatedWorld)
m_isolatedWorld = m_mainFrame->script()->createWorld();
ScriptValue result = m_mainFrame->script()->evaluateInWorld(sourceCode, m_isolatedWorld.get());
JSC::JSValue value = result.jsValue();
if (!value) {
returnType = JSException;
return false;
}
if (value.isUndefined())
returnType = JSUndefined;
else if (value.isNull())
returnType = JSNull;
else if (value.isBoolean())
returnType = JSBoolean;
else if (value.isNumber())
returnType = JSNumber;
else if (value.isString())
returnType = JSString;
else if (value.isObject())
returnType = JSObject;
else
returnType = JSUndefined;
if (returnType == JSBoolean || returnType == JSNumber || returnType == JSString || returnType == JSObject) {
JSC::ExecState* exec = m_mainFrame->script()->globalObject(mainThreadNormalWorld())->globalExec();
returnValue = result.toString(exec);
}
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: void ShellWindow::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
const extensions::Extension* unloaded_extension =
content::Details<extensions::UnloadedExtensionInfo>(
details)->extension;
if (extension_ == unloaded_extension)
Close();
break;
}
case content::NOTIFICATION_APP_TERMINATING:
Close();
break;
default:
NOTREACHED() << "Received unexpected notification";
}
}
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 decode_frame(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PicContext *s = avctx->priv_data;
AVFrame *frame = data;
uint32_t *palette;
int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;
int i, x, y, plane, tmp, ret, val;
bytestream2_init(&s->g, avpkt->data, avpkt->size);
if (bytestream2_get_bytes_left(&s->g) < 11)
return AVERROR_INVALIDDATA;
if (bytestream2_get_le16u(&s->g) != 0x1234)
return AVERROR_INVALIDDATA;
s->width = bytestream2_get_le16u(&s->g);
s->height = bytestream2_get_le16u(&s->g);
bytestream2_skip(&s->g, 4);
tmp = bytestream2_get_byteu(&s->g);
bits_per_plane = tmp & 0xF;
s->nb_planes = (tmp >> 4) + 1;
bpp = bits_per_plane * s->nb_planes;
if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {
avpriv_request_sample(avctx, "Unsupported bit depth");
return AVERROR_PATCHWELCOME;
}
if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {
bytestream2_skip(&s->g, 2);
etype = bytestream2_get_le16(&s->g);
esize = bytestream2_get_le16(&s->g);
if (bytestream2_get_bytes_left(&s->g) < esize)
return AVERROR_INVALIDDATA;
} else {
etype = -1;
esize = 0;
}
avctx->pix_fmt = AV_PIX_FMT_PAL8;
if (av_image_check_size(s->width, s->height, 0, avctx) < 0)
return -1;
if (s->width != avctx->width && s->height != avctx->height) {
ret = ff_set_dimensions(avctx, s->width, s->height);
if (ret < 0)
return ret;
}
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
memset(frame->data[0], 0, s->height * frame->linesize[0]);
frame->pict_type = AV_PICTURE_TYPE_I;
frame->palette_has_changed = 1;
pos_after_pal = bytestream2_tell(&s->g) + esize;
palette = (uint32_t*)frame->data[1];
if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) {
int idx = bytestream2_get_byte(&s->g);
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];
} else if (etype == 2) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)];
}
} else if (etype == 3) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)];
}
} else if (etype == 4 || etype == 5) {
npal = FFMIN(esize / 3, 256);
for (i = 0; i < npal; i++) {
palette[i] = bytestream2_get_be24(&s->g) << 2;
palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303;
}
} else {
if (bpp == 1) {
npal = 2;
palette[0] = 0xFF000000;
palette[1] = 0xFFFFFFFF;
} else if (bpp == 2) {
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];
} else {
npal = 16;
memcpy(palette, ff_cga_palette, npal * 4);
}
}
memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);
bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);
val = 0;
y = s->height - 1;
if (bytestream2_get_le16(&s->g)) {
x = 0;
plane = 0;
while (bytestream2_get_bytes_left(&s->g) >= 6) {
int stop_size, marker, t1, t2;
t1 = bytestream2_get_bytes_left(&s->g);
t2 = bytestream2_get_le16(&s->g);
stop_size = t1 - FFMIN(t1, t2);
bytestream2_skip(&s->g, 2);
marker = bytestream2_get_byte(&s->g);
while (plane < s->nb_planes &&
bytestream2_get_bytes_left(&s->g) > stop_size) {
int run = 1;
val = bytestream2_get_byte(&s->g);
if (val == marker) {
run = bytestream2_get_byte(&s->g);
if (run == 0)
run = bytestream2_get_le16(&s->g);
val = bytestream2_get_byte(&s->g);
}
if (!bytestream2_get_bytes_left(&s->g))
break;
if (bits_per_plane == 8) {
picmemset_8bpp(s, frame, val, run, &x, &y);
if (y < 0)
goto finish;
} else {
picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane);
}
}
}
if (x < avctx->width) {
int run = (y + 1) * avctx->width - x;
if (bits_per_plane == 8)
picmemset_8bpp(s, frame, val, run, &x, &y);
else
picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);
}
} else {
while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {
memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));
bytestream2_skip(&s->g, avctx->width);
y--;
}
}
finish:
*got_frame = 1;
return avpkt->size;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: long long Cluster::GetFirstTime() const {
const BlockEntry* pEntry;
const long status = GetFirst(pEntry);
if (status < 0) // error
return status;
if (pEntry == NULL) // empty cluster
return GetTime();
const Block* const pBlock = pEntry->GetBlock();
assert(pBlock);
return pBlock->GetTime(this);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int update_queue(struct sem_array *sma, int semnum, struct list_head *pt)
{
struct sem_queue *q;
struct list_head *walk;
struct list_head *pending_list;
int semop_completed = 0;
if (semnum == -1)
pending_list = &sma->sem_pending;
else
pending_list = &sma->sem_base[semnum].sem_pending;
again:
walk = pending_list->next;
while (walk != pending_list) {
int error, restart;
q = container_of(walk, struct sem_queue, list);
walk = walk->next;
/* If we are scanning the single sop, per-semaphore list of
* one semaphore and that semaphore is 0, then it is not
* necessary to scan the "alter" entries: simple increments
* that affect only one entry succeed immediately and cannot
* be in the per semaphore pending queue, and decrements
* cannot be successful if the value is already 0.
*/
if (semnum != -1 && sma->sem_base[semnum].semval == 0 &&
q->alter)
break;
error = try_atomic_semop(sma, q->sops, q->nsops,
q->undo, q->pid);
/* Does q->sleeper still need to sleep? */
if (error > 0)
continue;
unlink_queue(sma, q);
if (error) {
restart = 0;
} else {
semop_completed = 1;
restart = check_restart(sma, q);
}
wake_up_sem_queue_prepare(pt, q, error);
if (restart)
goto again;
}
return semop_completed;
}
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: StorageHandler::StorageHandler()
: DevToolsDomainHandler(Storage::Metainfo::domainName),
process_(nullptr),
weak_ptr_factory_(this) {}
CWE ID: CWE-20
Target: 1
Example 2:
Code: snd_device_t get_output_snd_device(struct audio_device *adev, audio_devices_t devices)
{
audio_mode_t mode = adev->mode;
snd_device_t snd_device = SND_DEVICE_NONE;
ALOGV("%s: enter: output devices(%#x), mode(%d)", __func__, devices, mode);
if (devices == AUDIO_DEVICE_NONE ||
devices & AUDIO_DEVICE_BIT_IN) {
ALOGV("%s: Invalid output devices (%#x)", __func__, devices);
goto exit;
}
if (mode == AUDIO_MODE_IN_CALL) {
if (devices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE ||
devices & AUDIO_DEVICE_OUT_WIRED_HEADSET) {
if (adev->tty_mode == TTY_MODE_FULL)
snd_device = SND_DEVICE_OUT_VOICE_TTY_FULL_HEADPHONES;
else if (adev->tty_mode == TTY_MODE_VCO)
snd_device = SND_DEVICE_OUT_VOICE_TTY_VCO_HEADPHONES;
else if (adev->tty_mode == TTY_MODE_HCO)
snd_device = SND_DEVICE_OUT_VOICE_TTY_HCO_HANDSET;
else
snd_device = SND_DEVICE_OUT_VOICE_HEADPHONES;
} else if (devices & AUDIO_DEVICE_OUT_SPEAKER) {
snd_device = SND_DEVICE_OUT_VOICE_SPEAKER;
} else if (devices & AUDIO_DEVICE_OUT_EARPIECE) {
snd_device = SND_DEVICE_OUT_HANDSET;
}
if (snd_device != SND_DEVICE_NONE) {
goto exit;
}
}
if (popcount(devices) == 2) {
if (devices == (AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
AUDIO_DEVICE_OUT_SPEAKER)) {
snd_device = SND_DEVICE_OUT_SPEAKER_AND_HEADPHONES;
} else if (devices == (AUDIO_DEVICE_OUT_WIRED_HEADSET |
AUDIO_DEVICE_OUT_SPEAKER)) {
snd_device = SND_DEVICE_OUT_SPEAKER_AND_HEADPHONES;
} else {
ALOGE("%s: Invalid combo device(%#x)", __func__, devices);
goto exit;
}
if (snd_device != SND_DEVICE_NONE) {
goto exit;
}
}
if (popcount(devices) != 1) {
ALOGE("%s: Invalid output devices(%#x)", __func__, devices);
goto exit;
}
if (devices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE ||
devices & AUDIO_DEVICE_OUT_WIRED_HEADSET) {
snd_device = SND_DEVICE_OUT_HEADPHONES;
} else if (devices & AUDIO_DEVICE_OUT_SPEAKER) {
snd_device = SND_DEVICE_OUT_SPEAKER;
} else if (devices & AUDIO_DEVICE_OUT_EARPIECE) {
snd_device = SND_DEVICE_OUT_HANDSET;
} else {
ALOGE("%s: Unknown device(s) %#x", __func__, devices);
}
exit:
ALOGV("%s: exit: snd_device(%s)", __func__, device_table[snd_device]);
return snd_device;
}
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 inline void clear_soft_dirty_pmd(struct vm_area_struct *vma,
unsigned long addr, pmd_t *pmdp)
{
pmd_t pmd = *pmdp;
pmd = pmd_wrprotect(pmd);
pmd = pmd_clear_flags(pmd, _PAGE_SOFT_DIRTY);
if (vma->vm_flags & VM_SOFTDIRTY)
vma->vm_flags &= ~VM_SOFTDIRTY;
set_pmd_at(vma->vm_mm, addr, pmdp, pmd);
}
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 v8::Handle<v8::Value> getNamedProperty(HTMLDocument* htmlDocument, const AtomicString& key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
if (!htmlDocument->hasNamedItem(key.impl()) && !htmlDocument->hasExtraNamedItem(key.impl()))
return v8Undefined();
RefPtr<HTMLCollection> items = htmlDocument->documentNamedItems(key);
if (items->isEmpty())
return v8Undefined();
if (items->hasExactlyOneItem()) {
Node* node = items->item(0);
Frame* frame = 0;
if (node->hasTagName(HTMLNames::iframeTag) && (frame = toHTMLIFrameElement(node)->contentFrame()))
return toV8(frame->domWindow(), creationContext, isolate);
return toV8(node, creationContext, isolate);
}
return toV8(items.release(), creationContext, isolate);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
{
struct task_group *tg = css_tg(css);
/*
* Relies on the RCU grace period between css_released() and this.
*/
sched_free_group(tg);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE || pg > 6) {
return -1;
}
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
if (pg == 6) {
return -1; /* avoid page pg + 1 */
}
ptr2 = (itd->bufptr[pg + 1] & ITD_BUFPTR_MASK);
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
}
}
return 0;
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
CWE ID: CWE-674
Target: 1
Example 2:
Code: String Document::compatMode() const {
return InQuirksMode() ? "BackCompat" : "CSS1Compat";
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain == 0) {
/* 2.0.34: EOF is incorrect. We use 0 for
* errors and EOF, just like fileGetbuf,
* which is a simple fread() wrapper.
* TBB. Original bug report: Daniel Cowgill. */
return 0; /* NOT EOF */
}
rlen = remain;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
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: xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix,
const xmlChar *URI, int line, int nsNr, int tlen) {
const xmlChar *name;
GROW;
if ((RAW != '<') || (NXT(1) != '/')) {
xmlFatalErr(ctxt, XML_ERR_LTSLASH_REQUIRED, NULL);
return;
}
SKIP(2);
if ((tlen > 0) && (xmlStrncmp(ctxt->input->cur, ctxt->name, tlen) == 0)) {
if (ctxt->input->cur[tlen] == '>') {
ctxt->input->cur += tlen + 1;
goto done;
}
ctxt->input->cur += tlen;
name = (xmlChar*)1;
} else {
if (prefix == NULL)
name = xmlParseNameAndCompare(ctxt, ctxt->name);
else
name = xmlParseQNameAndCompare(ctxt, ctxt->name, prefix);
}
/*
* We should definitely be at the ending "S? '>'" part
*/
GROW;
SKIP_BLANKS;
if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) {
xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
} else
NEXT1;
/*
* [ WFC: Element Type Match ]
* The Name in an element's end-tag must match the element type in the
* start-tag.
*
*/
if (name != (xmlChar*)1) {
if (name == NULL) name = BAD_CAST "unparseable";
if ((line == 0) && (ctxt->node != NULL))
line = ctxt->node->line;
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NAME_MISMATCH,
"Opening and ending tag mismatch: %s line %d and %s\n",
ctxt->name, line, name);
}
/*
* SAX: End of Tag
*/
done:
if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, ctxt->name, prefix, URI);
spacePop(ctxt);
if (nsNr != 0)
nsPop(ctxt, nsNr);
return;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: LogL16Decode(TIFF* tif, uint8* op, tmsize_t occ, uint16 s)
{
static const char module[] = "LogL16Decode";
LogLuvState* sp = DecoderState(tif);
int shft;
tmsize_t i;
tmsize_t npixels;
unsigned char* bp;
int16* tp;
int16 b;
tmsize_t cc;
int rc;
assert(s == 0);
assert(sp != NULL);
npixels = occ / sp->pixel_size;
if (sp->user_datafmt == SGILOGDATAFMT_16BIT)
tp = (int16*) op;
else {
if(sp->tbuflen < npixels) {
TIFFErrorExt(tif->tif_clientdata, module,
"Translation buffer too short");
return (0);
}
tp = (int16*) sp->tbuf;
}
_TIFFmemset((void*) tp, 0, npixels*sizeof (tp[0]));
bp = (unsigned char*) tif->tif_rawcp;
cc = tif->tif_rawcc;
/* get each byte string */
for (shft = 2*8; (shft -= 8) >= 0; ) {
for (i = 0; i < npixels && cc > 0; ) {
if (*bp >= 128) { /* run */
if( cc < 2 )
break;
rc = *bp++ + (2-128);
b = (int16)(*bp++ << shft);
cc -= 2;
while (rc-- && i < npixels)
tp[i++] |= b;
} else { /* non-run */
rc = *bp++; /* nul is noop */
while (--cc && rc-- && i < npixels)
tp[i++] |= (int16)*bp++ << shft;
}
}
if (i != npixels) {
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at row %lu (short %I64d pixels)",
(unsigned long) tif->tif_row,
(unsigned __int64) (npixels - i));
#else
TIFFErrorExt(tif->tif_clientdata, module,
"Not enough data at row %lu (short %llu pixels)",
(unsigned long) tif->tif_row,
(unsigned long long) (npixels - i));
#endif
tif->tif_rawcp = (uint8*) bp;
tif->tif_rawcc = cc;
return (0);
}
}
(*sp->tfunc)(sp, op, npixels);
tif->tif_rawcp = (uint8*) bp;
tif->tif_rawcc = cc;
return (1);
}
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: PHP_FUNCTION(linkinfo)
{
char *link;
size_t link_len;
zend_stat_t sb;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) {
return;
}
ret = VCWD_STAT(link, &sb);
if (ret == -1) {
php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
RETURN_LONG(Z_L(-1));
}
RETURN_LONG((zend_long) sb.st_dev);
}
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 gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_TRUE;
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void jas_matrix_destroy(jas_matrix_t *matrix)
{
if (matrix->data_) {
assert(!(matrix->flags_ & JAS_MATRIX_REF));
jas_free(matrix->data_);
matrix->data_ = 0;
}
if (matrix->rows_) {
jas_free(matrix->rows_);
matrix->rows_ = 0;
}
jas_free(matrix);
}
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 SendHandwritingStroke(const HandwritingStroke& stroke) {
if (stroke.size() < 2) {
LOG(WARNING) << "Empty stroke data or a single dot is passed.";
return;
}
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
const size_t raw_stroke_size = stroke.size() * 2;
scoped_array<double> raw_stroke(new double[raw_stroke_size]);
for (size_t n = 0; n < stroke.size(); ++n) {
raw_stroke[n * 2] = stroke[n].first; // x
raw_stroke[n * 2 + 1] = stroke[n].second; // y
}
ibus_input_context_process_hand_writing_event(
context, raw_stroke.get(), raw_stroke_size);
g_object_unref(context);
}
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 load_xref_from_plaintext(FILE *fp, xref_t *xref)
{
int i, buf_idx, obj_id, added_entries;
char c, buf[32] = {0};
long start, pos;
start = ftell(fp);
/* Get number of entries */
pos = xref->end;
fseek(fp, pos, SEEK_SET);
while (ftell(fp) != 0)
if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S')))
break;
else
SAFE_E(fseek(fp, --pos, SEEK_SET), 0, "Failed seek to xref /Size.\n");
SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n");
xref->n_entries = atoi(buf + strlen("ize "));
xref->entries = calloc(1, xref->n_entries * sizeof(struct _xref_entry));
/* Load entry data */
obj_id = 0;
fseek(fp, xref->start + strlen("xref"), SEEK_SET);
added_entries = 0;
for (i=0; i<xref->n_entries; i++)
{
/* Advance past newlines. */
c = fgetc(fp);
while (c == '\n' || c == '\r')
c = fgetc(fp);
/* Collect data up until the following newline. */
buf_idx = 0;
while (c != '\n' && c != '\r' && !feof(fp) &&
!ferror(fp) && buf_idx < sizeof(buf))
{
buf[buf_idx++] = c;
c = fgetc(fp);
}
if (buf_idx >= sizeof(buf))
{
ERR("Failed to locate newline character. "
"This might be a corrupt PDF.\n");
exit(EXIT_FAILURE);
}
buf[buf_idx] = '\0';
/* Went to far and hit start of trailer */
if (strchr(buf, 't'))
break;
/* Entry or object id */
if (strlen(buf) > 17)
{
xref->entries[i].obj_id = obj_id++;
xref->entries[i].offset = atol(strtok(buf, " "));
xref->entries[i].gen_num = atoi(strtok(NULL, " "));
xref->entries[i].f_or_n = buf[17];
++added_entries;
}
else
{
obj_id = atoi(buf);
--i;
}
}
xref->n_entries = added_entries;
fseek(fp, start, SEEK_SET);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: ObjectAttributeSetter(AXObjectAttribute attribute) : m_attribute(attribute) {}
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: ossl_cipher_update(int argc, VALUE *argv, VALUE self)
{
EVP_CIPHER_CTX *ctx;
unsigned char *in;
long in_len, out_len;
VALUE data, str;
rb_scan_args(argc, argv, "11", &data, &str);
StringValue(data);
in = (unsigned char *)RSTRING_PTR(data);
if ((in_len = RSTRING_LEN(data)) == 0)
ossl_raise(rb_eArgError, "data must not be empty");
GetCipher(self, ctx);
out_len = in_len+EVP_CIPHER_CTX_block_size(ctx);
if (out_len <= 0) {
ossl_raise(rb_eRangeError,
"data too big to make output buffer: %ld bytes", in_len);
}
if (NIL_P(str)) {
str = rb_str_new(0, out_len);
} else {
StringValue(str);
rb_str_resize(str, out_len);
}
if (!ossl_cipher_update_long(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len))
ossl_raise(eCipherError, NULL);
assert(out_len < RSTRING_LEN(str));
rb_str_set_len(str, out_len);
return str;
}
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: kg_seal_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count,
int toktype)
{
krb5_gss_ctx_id_rec *ctx;
krb5_error_code code;
krb5_context context;
if (qop_req != 0) {
*minor_status = (OM_uint32)G_UNKNOWN_QOP;
return GSS_S_FAILURE;
}
ctx = (krb5_gss_ctx_id_rec *)context_handle;
if (!ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return GSS_S_NO_CONTEXT;
}
if (conf_req_flag && kg_integ_only_iov(iov, iov_count)) {
/* may be more sensible to return an error here */
conf_req_flag = FALSE;
}
context = ctx->k5_context;
switch (ctx->proto) {
case 0:
code = make_seal_token_v1_iov(context, ctx, conf_req_flag,
conf_state, iov, iov_count, toktype);
break;
case 1:
code = gss_krb5int_make_seal_token_v3_iov(context, ctx, conf_req_flag,
conf_state, iov, iov_count, toktype);
break;
default:
code = G_UNKNOWN_QOP;
break;
}
if (code != 0) {
*minor_status = code;
save_error_info(*minor_status, context);
return GSS_S_FAILURE;
}
*minor_status = 0;
return GSS_S_COMPLETE;
}
CWE ID:
Target: 1
Example 2:
Code: static void *create_core_server_config(apr_pool_t *a, server_rec *s)
{
core_server_config *conf;
int is_virtual = s->is_virtual;
conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
/* global-default / global-only settings */
if (!is_virtual) {
conf->ap_document_root = DOCUMENT_LOCATION;
conf->access_name = DEFAULT_ACCESS_FNAME;
/* A mapping only makes sense in the global context */
conf->accf_map = apr_table_make(a, 5);
#if APR_HAS_SO_ACCEPTFILTER
apr_table_setn(conf->accf_map, "http", ACCEPT_FILTER_NAME);
apr_table_setn(conf->accf_map, "https", "dataready");
#elif defined(WIN32)
/* 'data' is disabled on Windows due to a DoS vuln (PR 59970) */
apr_table_setn(conf->accf_map, "http", "connect");
apr_table_setn(conf->accf_map, "https", "connect");
#else
apr_table_setn(conf->accf_map, "http", "data");
apr_table_setn(conf->accf_map, "https", "data");
#endif
}
/* pcalloc'ed - we have NULL's/0's
else ** is_virtual ** {
conf->ap_document_root = NULL;
conf->access_name = NULL;
conf->accf_map = NULL;
}
*/
/* initialization, no special case for global context */
conf->sec_dir = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
/* pcalloc'ed - we have NULL's/0's
conf->gprof_dir = NULL;
** recursion stopper; 0 == unset
conf->redirect_limit = 0;
conf->subreq_limit = 0;
conf->protocol = NULL;
*/
conf->trace_enable = AP_TRACE_UNSET;
conf->protocols = apr_array_make(a, 5, sizeof(const char *));
conf->protocols_honor_order = -1;
conf->async_filter = 0;
return (void *)conf;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void warn_no_space_for_csum(struct inode *inode)
{
ext4_warning(inode->i_sb, "no space in directory inode %lu leaf for "
"checksum. Please run e2fsck -D.", inode->i_ino);
}
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 struct mount *clone_mnt(struct mount *old, struct dentry *root,
int flag)
{
struct super_block *sb = old->mnt.mnt_sb;
struct mount *mnt;
int err;
mnt = alloc_vfsmnt(old->mnt_devname);
if (!mnt)
return ERR_PTR(-ENOMEM);
if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE))
mnt->mnt_group_id = 0; /* not a peer of original */
else
mnt->mnt_group_id = old->mnt_group_id;
if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) {
err = mnt_alloc_group_id(mnt);
if (err)
goto out_free;
}
mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~MNT_WRITE_HOLD;
atomic_inc(&sb->s_active);
mnt->mnt.mnt_sb = sb;
mnt->mnt.mnt_root = dget(root);
mnt->mnt_mountpoint = mnt->mnt.mnt_root;
mnt->mnt_parent = mnt;
br_write_lock(&vfsmount_lock);
list_add_tail(&mnt->mnt_instance, &sb->s_mounts);
br_write_unlock(&vfsmount_lock);
if ((flag & CL_SLAVE) ||
((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) {
list_add(&mnt->mnt_slave, &old->mnt_slave_list);
mnt->mnt_master = old;
CLEAR_MNT_SHARED(mnt);
} else if (!(flag & CL_PRIVATE)) {
if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old))
list_add(&mnt->mnt_share, &old->mnt_share);
if (IS_MNT_SLAVE(old))
list_add(&mnt->mnt_slave, &old->mnt_slave);
mnt->mnt_master = old->mnt_master;
}
if (flag & CL_MAKE_SHARED)
set_mnt_shared(mnt);
/* stick the duplicate mount on the same expiry list
* as the original if that was on one */
if (flag & CL_EXPIRE) {
if (!list_empty(&old->mnt_expire))
list_add(&mnt->mnt_expire, &old->mnt_expire);
}
return mnt;
out_free:
free_vfsmnt(mnt);
return ERR_PTR(err);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: prepare_error_tgs (struct kdc_request_state *state,
krb5_kdc_req *request, krb5_ticket *ticket, int error,
krb5_principal canon_server,
krb5_data **response, const char *status,
krb5_pa_data **e_data)
{
krb5_error errpkt;
krb5_error_code retval = 0;
krb5_data *scratch, *e_data_asn1 = NULL, *fast_edata = NULL;
errpkt.ctime = request->nonce;
errpkt.cusec = 0;
if ((retval = krb5_us_timeofday(kdc_context, &errpkt.stime,
&errpkt.susec)))
return(retval);
errpkt.error = error;
errpkt.server = request->server;
if (ticket && ticket->enc_part2)
errpkt.client = ticket->enc_part2->client;
else
errpkt.client = NULL;
errpkt.text.length = strlen(status);
if (!(errpkt.text.data = strdup(status)))
return ENOMEM;
if (!(scratch = (krb5_data *)malloc(sizeof(*scratch)))) {
free(errpkt.text.data);
return ENOMEM;
}
if (e_data != NULL) {
retval = encode_krb5_padata_sequence(e_data, &e_data_asn1);
if (retval) {
free(scratch);
free(errpkt.text.data);
return retval;
}
errpkt.e_data = *e_data_asn1;
} else
errpkt.e_data = empty_data();
if (state) {
retval = kdc_fast_handle_error(kdc_context, state, request, e_data,
&errpkt, &fast_edata);
}
if (retval) {
free(scratch);
free(errpkt.text.data);
krb5_free_data(kdc_context, e_data_asn1);
return retval;
}
if (fast_edata)
errpkt.e_data = *fast_edata;
retval = krb5_mk_error(kdc_context, &errpkt, scratch);
free(errpkt.text.data);
krb5_free_data(kdc_context, e_data_asn1);
krb5_free_data(kdc_context, fast_edata);
if (retval)
free(scratch);
else
*response = scratch;
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: static int igmp_marksources(struct ip_mc_list *pmc, int nsrcs, __be32 *srcs)
{
struct ip_sf_list *psf;
int i, scount;
if (pmc->sfmode == MCAST_EXCLUDE)
return igmp_xmarksources(pmc, nsrcs, srcs);
/* mark INCLUDE-mode sources */
scount = 0;
for (psf=pmc->sources; psf; psf=psf->sf_next) {
if (scount == nsrcs)
break;
for (i=0; i<nsrcs; i++)
if (srcs[i] == psf->sf_inaddr) {
psf->sf_gsresp = 1;
scount++;
break;
}
}
if (!scount) {
pmc->gsquery = 0;
return 0;
}
pmc->gsquery = 1;
return 1;
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p,
int *got_frame, uint8_t *data_start,
unsigned int data_size)
{
WebPContext *s = avctx->priv_data;
AVPacket pkt;
int ret;
if (!s->initialized) {
ff_vp8_decode_init(avctx);
s->initialized = 1;
if (s->has_alpha)
avctx->pix_fmt = AV_PIX_FMT_YUVA420P;
}
s->lossless = 0;
if (data_size > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n");
return AVERROR_PATCHWELCOME;
}
av_init_packet(&pkt);
pkt.data = data_start;
pkt.size = data_size;
ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt);
if (ret < 0)
return ret;
update_canvas_size(avctx, avctx->width, avctx->height);
if (s->has_alpha) {
ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data,
s->alpha_data_size);
if (ret < 0)
return ret;
}
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool ChromeClientImpl::ShouldReportDetailedMessageForSource(
LocalFrame& local_frame,
const String& url) {
WebLocalFrameImpl* webframe =
WebLocalFrameImpl::FromFrame(&local_frame.LocalFrameRoot());
return webframe && webframe->Client() &&
webframe->Client()->ShouldReportDetailedMessageForSource(url);
}
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 newseg(struct ipc_namespace *ns, struct ipc_params *params)
{
key_t key = params->key;
int shmflg = params->flg;
size_t size = params->u.size;
int error;
struct shmid_kernel *shp;
size_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
struct file *file;
char name[13];
int id;
vm_flags_t acctflag = 0;
if (size < SHMMIN || size > ns->shm_ctlmax)
return -EINVAL;
if (numpages << PAGE_SHIFT < size)
return -ENOSPC;
if (ns->shm_tot + numpages < ns->shm_tot ||
ns->shm_tot + numpages > ns->shm_ctlall)
return -ENOSPC;
shp = ipc_rcu_alloc(sizeof(*shp));
if (!shp)
return -ENOMEM;
shp->shm_perm.key = key;
shp->shm_perm.mode = (shmflg & S_IRWXUGO);
shp->mlock_user = NULL;
shp->shm_perm.security = NULL;
error = security_shm_alloc(shp);
if (error) {
ipc_rcu_putref(shp, ipc_rcu_free);
return error;
}
sprintf(name, "SYSV%08x", key);
if (shmflg & SHM_HUGETLB) {
struct hstate *hs;
size_t hugesize;
hs = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
if (!hs) {
error = -EINVAL;
goto no_file;
}
hugesize = ALIGN(size, huge_page_size(hs));
/* hugetlb_file_setup applies strict accounting */
if (shmflg & SHM_NORESERVE)
acctflag = VM_NORESERVE;
file = hugetlb_file_setup(name, hugesize, acctflag,
&shp->mlock_user, HUGETLB_SHMFS_INODE,
(shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
} else {
/*
* Do not allow no accounting for OVERCOMMIT_NEVER, even
* if it's asked for.
*/
if ((shmflg & SHM_NORESERVE) &&
sysctl_overcommit_memory != OVERCOMMIT_NEVER)
acctflag = VM_NORESERVE;
file = shmem_kernel_file_setup(name, size, acctflag);
}
error = PTR_ERR(file);
if (IS_ERR(file))
goto no_file;
id = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni);
if (id < 0) {
error = id;
goto no_id;
}
shp->shm_cprid = task_tgid_vnr(current);
shp->shm_lprid = 0;
shp->shm_atim = shp->shm_dtim = 0;
shp->shm_ctim = get_seconds();
shp->shm_segsz = size;
shp->shm_nattch = 0;
shp->shm_file = file;
shp->shm_creator = current;
list_add(&shp->shm_clist, ¤t->sysvshm.shm_clist);
/*
* shmid gets reported as "inode#" in /proc/pid/maps.
* proc-ps tools use this. Changing this will break them.
*/
file_inode(file)->i_ino = shp->shm_perm.id;
ns->shm_tot += numpages;
error = shp->shm_perm.id;
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
return error;
no_id:
if (is_file_hugepages(file) && shp->mlock_user)
user_shm_unlock(size, shp->mlock_user);
fput(file);
no_file:
ipc_rcu_putref(shp, shm_rcu_free);
return error;
}
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: void MakeCacheAndGroup(const GURL& manifest_url,
int64_t group_id,
int64_t cache_id,
bool add_to_database) {
AppCacheEntry default_entry(AppCacheEntry::EXPLICIT,
cache_id + kDefaultEntryIdOffset,
kDefaultEntrySize);
group_ = new AppCacheGroup(storage(), manifest_url, group_id);
cache_ = new AppCache(storage(), cache_id);
cache_->AddEntry(kDefaultEntryUrl, default_entry);
cache_->set_complete(true);
group_->AddCache(cache_.get());
url::Origin manifest_origin(url::Origin::Create(manifest_url));
if (add_to_database) {
AppCacheDatabase::GroupRecord group_record;
group_record.group_id = group_id;
group_record.manifest_url = manifest_url;
group_record.origin = manifest_origin;
EXPECT_TRUE(database()->InsertGroup(&group_record));
AppCacheDatabase::CacheRecord cache_record;
cache_record.cache_id = cache_id;
cache_record.group_id = group_id;
cache_record.online_wildcard = false;
cache_record.update_time = kZeroTime;
cache_record.cache_size = kDefaultEntrySize;
EXPECT_TRUE(database()->InsertCache(&cache_record));
AppCacheDatabase::EntryRecord entry_record;
entry_record.cache_id = cache_id;
entry_record.url = kDefaultEntryUrl;
entry_record.flags = default_entry.types();
entry_record.response_id = default_entry.response_id();
entry_record.response_size = default_entry.response_size();
EXPECT_TRUE(database()->InsertEntry(&entry_record));
storage()->usage_map_[manifest_origin] = default_entry.response_size();
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void reclaim_dma_bufs(void)
{
unsigned long flags;
struct port_buffer *buf, *tmp;
LIST_HEAD(tmp_list);
if (list_empty(&pending_free_dma_bufs))
return;
/* Create a copy of the pending_free_dma_bufs while holding the lock */
spin_lock_irqsave(&dma_bufs_lock, flags);
list_cut_position(&tmp_list, &pending_free_dma_bufs,
pending_free_dma_bufs.prev);
spin_unlock_irqrestore(&dma_bufs_lock, flags);
/* Release the dma buffers, without irqs enabled */
list_for_each_entry_safe(buf, tmp, &tmp_list, list) {
list_del(&buf->list);
free_buf(buf, true);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int common_timer_set(struct k_itimer *timr, int flags,
struct itimerspec64 *new_setting,
struct itimerspec64 *old_setting)
{
const struct k_clock *kc = timr->kclock;
bool sigev_none;
ktime_t expires;
if (old_setting)
common_timer_get(timr, old_setting);
/* Prevent rearming by clearing the interval */
timr->it_interval = 0;
/*
* Careful here. On SMP systems the timer expiry function could be
* active and spinning on timr->it_lock.
*/
if (kc->timer_try_to_cancel(timr) < 0)
return TIMER_RETRY;
timr->it_active = 0;
timr->it_requeue_pending = (timr->it_requeue_pending + 2) &
~REQUEUE_PENDING;
timr->it_overrun_last = 0;
/* Switch off the timer when it_value is zero */
if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec)
return 0;
timr->it_interval = timespec64_to_ktime(new_setting->it_interval);
expires = timespec64_to_ktime(new_setting->it_value);
sigev_none = (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE;
kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none);
timr->it_active = !sigev_none;
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: make_transform_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type,
png_byte PNG_CONST bit_depth, unsigned int palette_number,
int interlace_type, png_const_charp name)
{
context(ps, fault);
check_interlace_type(interlace_type);
Try
{
png_infop pi;
png_structp pp = set_store_for_write(ps, &pi, name);
png_uint_32 h;
/* In the event of a problem return control to the Catch statement below
* to do the clean up - it is not possible to 'return' directly from a Try
* block.
*/
if (pp == NULL)
Throw ps;
h = transform_height(pp, colour_type, bit_depth);
png_set_IHDR(pp, pi, transform_width(pp, colour_type, bit_depth), h,
bit_depth, colour_type, interlace_type,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
#ifdef PNG_TEXT_SUPPORTED
# if defined(PNG_READ_zTXt_SUPPORTED) && defined(PNG_WRITE_zTXt_SUPPORTED)
# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_zTXt
# else
# define TEXT_COMPRESSION PNG_TEXT_COMPRESSION_NONE
# endif
{
static char key[] = "image name"; /* must be writeable */
size_t pos;
png_text text;
char copy[FILE_NAME_SIZE];
/* Use a compressed text string to test the correct interaction of text
* compression and IDAT compression.
*/
text.compression = TEXT_COMPRESSION;
text.key = key;
/* Yuck: the text must be writable! */
pos = safecat(copy, sizeof copy, 0, ps->wname);
text.text = copy;
text.text_length = pos;
text.itxt_length = 0;
text.lang = 0;
text.lang_key = 0;
png_set_text(pp, pi, &text, 1);
}
#endif
if (colour_type == 3) /* palette */
init_standard_palette(ps, pp, pi, 1U << bit_depth, 1/*do tRNS*/);
png_write_info(pp, pi);
if (png_get_rowbytes(pp, pi) !=
transform_rowsize(pp, colour_type, bit_depth))
png_error(pp, "row size incorrect");
else
{
/* Somewhat confusingly this must be called *after* png_write_info
* because if it is called before, the information in *pp has not been
* updated to reflect the interlaced image.
*/
int npasses = png_set_interlace_handling(pp);
int pass;
if (npasses != npasses_from_interlace_type(pp, interlace_type))
png_error(pp, "write: png_set_interlace_handling failed");
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
for (y=0; y<h; ++y)
{
png_byte buffer[TRANSFORM_ROWMAX];
transform_row(pp, buffer, colour_type, bit_depth, y);
png_write_row(pp, buffer);
}
}
}
#ifdef PNG_TEXT_SUPPORTED
{
static char key[] = "end marker";
static char comment[] = "end";
png_text text;
/* Use a compressed text string to test the correct interaction of text
* compression and IDAT compression.
*/
text.compression = TEXT_COMPRESSION;
text.key = key;
text.text = comment;
text.text_length = (sizeof comment)-1;
text.itxt_length = 0;
text.lang = 0;
text.lang_key = 0;
png_set_text(pp, pi, &text, 1);
}
#endif
png_write_end(pp, pi);
/* And store this under the appropriate id, then clean up. */
store_storefile(ps, FILEID(colour_type, bit_depth, palette_number,
interlace_type, 0, 0, 0));
store_write_reset(ps);
}
Catch(fault)
{
/* Use the png_store returned by the exception. This may help the compiler
* because 'ps' is not used in this branch of the setjmp. Note that fault
* and ps will always be the same value.
*/
store_write_reset(fault);
}
}
CWE ID:
Target: 1
Example 2:
Code: get_file_flags (const char *filename, int *dt)
{
logprintf (LOG_VERBOSE, _("\
File %s already there; not retrieving.\n\n"), quote (filename));
/* If the file is there, we suppose it's retrieved OK. */
*dt |= RETROKF;
/* #### Bogusness alert. */
/* If its suffix is "html" or "htm" or similar, assume text/html. */
if (has_html_suffix_p (filename))
*dt |= TEXTHTML;
}
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 AXLayoutObject::textChanged() {
if (!m_layoutObject)
return;
Settings* settings = getDocument()->settings();
if (settings && settings->getInlineTextBoxAccessibilityEnabled() &&
roleValue() == StaticTextRole)
childrenChanged();
AXNodeObject::textChanged();
}
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 FakeCentral::IsPowered() const {
switch (state_) {
case mojom::CentralState::POWERED_OFF:
return false;
case mojom::CentralState::POWERED_ON:
return true;
case mojom::CentralState::ABSENT:
NOTREACHED();
return false;
}
NOTREACHED();
return false;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int tecmp0 (const void *_a, const void *_b)
{
struct tree_entry *a = *((struct tree_entry**)_a);
struct tree_entry *b = *((struct tree_entry**)_b);
return base_name_compare(
a->name->str_dat, a->name->str_len, a->versions[0].mode,
b->name->str_dat, b->name->str_len, b->versions[0].mode);
}
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 ExtensionService::AddProviderForTesting(
ExternalExtensionProviderInterface* test_provider) {
CHECK(test_provider);
external_extension_providers_.push_back(
linked_ptr<ExternalExtensionProviderInterface>(test_provider));
}
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 SetManualFallbacks(bool enabled) {
std::vector<std::string> features = {
password_manager::features::kEnableManualFallbacksFilling.name,
password_manager::features::kEnableManualFallbacksFillingStandalone
.name,
password_manager::features::kEnableManualFallbacksGeneration.name};
if (enabled) {
scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","),
std::string());
} else {
scoped_feature_list_.InitFromCommandLine(std::string(),
base::JoinString(features, ","));
}
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void OfflinePageModelImpl::GetPagesMatchingQueryWhenLoadDone(
std::unique_ptr<OfflinePageModelQuery> query,
const MultipleOfflinePageItemCallback& callback) {
DCHECK(query);
DCHECK(is_loaded_);
MultipleOfflinePageItemResult offline_pages_result;
for (const auto& id_page_pair : offline_pages_) {
if (query->Matches(id_page_pair.second))
offline_pages_result.emplace_back(id_page_pair.second);
}
callback.Run(offline_pages_result);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline int imgCoordMungeLower(SplashCoord x) {
return splashFloor(x);
}
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: ext4_xattr_block_list(struct dentry *dentry, char *buffer, size_t buffer_size)
{
struct inode *inode = d_inode(dentry);
struct buffer_head *bh = NULL;
int error;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
ea_idebug(inode, "buffer=%p, buffer_size=%ld",
buffer, (long)buffer_size);
error = 0;
if (!EXT4_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %llu",
(unsigned long long)EXT4_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT4_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(BHDR(bh)->h_refcount));
if (ext4_xattr_check_block(inode, bh)) {
EXT4_ERROR_INODE(inode, "bad block %llu",
EXT4_I(inode)->i_file_acl);
error = -EFSCORRUPTED;
goto cleanup;
}
ext4_xattr_cache_insert(ext4_mb_cache, bh);
error = ext4_xattr_list_entries(dentry, BFIRST(bh), buffer, buffer_size);
cleanup:
brelse(bh);
return error;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: void smp_send_commitment(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) {
SMP_TRACE_DEBUG("%s", __func__);
smp_send_cmd(SMP_OPCODE_PAIR_COMMITM, p_cb);
}
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: image_transform_add(PNG_CONST image_transform **this, unsigned int max,
png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos,
png_byte colour_type, png_byte bit_depth)
{
for (;;) /* until we manage to add something */
{
png_uint_32 mask;
image_transform *list;
/* Find the next counter value, if the counter is zero this is the start
* of the list. This routine always returns the current counter (not the
* next) so it returns 0 at the end and expects 0 at the beginning.
*/
if (counter == 0) /* first time */
{
image_transform_reset_count();
if (max <= 1)
counter = 1;
else
counter = random_32();
}
else /* advance the counter */
{
switch (max)
{
case 0: ++counter; break;
case 1: counter <<= 1; break;
default: counter = random_32(); break;
}
}
/* Now add all these items, if possible */
*this = &image_transform_end;
list = image_transform_first;
mask = 1;
/* Go through the whole list adding anything that the counter selects: */
while (list != &image_transform_end)
{
if ((counter & mask) != 0 && list->enable &&
(max == 0 || list->local_use < max))
{
/* Candidate to add: */
if (list->add(list, this, colour_type, bit_depth) || max == 0)
{
/* Added, so add to the name too. */
*pos = safecat(name, sizeof_name, *pos, " +");
*pos = safecat(name, sizeof_name, *pos, list->name);
}
else
{
/* Not useful and max>0, so remove it from *this: */
*this = list->next;
list->next = 0;
/* And, since we know it isn't useful, stop it being added again
* in this run:
*/
list->local_use = max;
}
}
mask <<= 1;
list = list->list;
}
/* Now if anything was added we have something to do. */
if (*this != &image_transform_end)
return counter;
/* Nothing added, but was there anything in there to add? */
if (!image_transform_test_counter(counter, max))
return 0;
}
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: StorageHandler::GetCacheStorageObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!cache_storage_observer_) {
cache_storage_observer_ = std::make_unique<CacheStorageObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<CacheStorageContextImpl*>(
process_->GetStoragePartition()->GetCacheStorageContext()));
}
return cache_storage_observer_.get();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void SetAudioType(MediaStreamType audio_type) {
DCHECK(IsAudioInputMediaType(audio_type) || audio_type == MEDIA_NO_SERVICE);
audio_type_ = audio_type;
}
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: PluginModule::PluginModule(const std::string& name,
const FilePath& path,
PluginDelegate::ModuleLifetime* lifetime_delegate)
: lifetime_delegate_(lifetime_delegate),
callback_tracker_(new ::ppapi::CallbackTracker),
is_in_destructor_(false),
is_crashed_(false),
broker_(NULL),
library_(NULL),
name_(name),
path_(path),
reserve_instance_id_(NULL),
nacl_ipc_proxy_(false) {
if (!host_globals)
host_globals = new HostGlobals;
memset(&entry_points_, 0, sizeof(entry_points_));
pp_module_ = HostGlobals::Get()->AddModule(this);
GetMainThreadMessageLoop(); // Initialize the main thread message loop.
GetLivePluginSet()->insert(this);
}
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: image_transform_png_set_scale_16_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_scale_16(pp);
this->next->set(this->next, that, pp, pi);
}
CWE ID:
Target: 1
Example 2:
Code: PHP_FUNCTION(pg_client_encoding)
{
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);
/* Just do the same as found in PostgreSQL sources... */
RETURN_STRING((char *) pg_encoding_to_char(PQclientEncoding(pgsql)));
}
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 WebContentsImpl::SetPageScale(float page_scale_factor) {
Send(new ViewMsg_SetPageScale(GetRoutingID(), page_scale_factor));
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool RenderViewHostManager::ShouldSwapProcessesForNavigation(
const NavigationEntry* curr_entry,
const NavigationEntryImpl* new_entry) const {
DCHECK(new_entry);
const GURL& current_url = (curr_entry) ? curr_entry->GetURL() :
render_view_host_->GetSiteInstance()->GetSiteURL();
BrowserContext* browser_context =
delegate_->GetControllerForRenderManager().GetBrowserContext();
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, current_url)) {
if (!WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
browser_context, new_entry->GetURL(), false)) {
return true;
}
} else {
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, new_entry->GetURL())) {
return true;
}
}
if (GetContentClient()->browser()->ShouldSwapProcessesForNavigation(
curr_entry ? curr_entry->GetURL() : GURL(), new_entry->GetURL())) {
return true;
}
if (!curr_entry)
return false;
if (curr_entry->IsViewSourceMode() != new_entry->IsViewSourceMode())
return true;
return false;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
{
int ret;
if ((ret = sem_init(cgsem, 0, 0)))
quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
}
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 change_port_settings(struct tty_struct *tty,
struct edgeport_port *edge_port, struct ktermios *old_termios)
{
struct device *dev = &edge_port->port->dev;
struct ump_uart_config *config;
int baud;
unsigned cflag;
int status;
int port_number = edge_port->port->port_number;
config = kmalloc (sizeof (*config), GFP_KERNEL);
if (!config) {
tty->termios = *old_termios;
return;
}
cflag = tty->termios.c_cflag;
config->wFlags = 0;
/* These flags must be set */
config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT;
config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR;
config->bUartMode = (__u8)(edge_port->bUartMode);
switch (cflag & CSIZE) {
case CS5:
config->bDataBits = UMP_UART_CHAR5BITS;
dev_dbg(dev, "%s - data bits = 5\n", __func__);
break;
case CS6:
config->bDataBits = UMP_UART_CHAR6BITS;
dev_dbg(dev, "%s - data bits = 6\n", __func__);
break;
case CS7:
config->bDataBits = UMP_UART_CHAR7BITS;
dev_dbg(dev, "%s - data bits = 7\n", __func__);
break;
default:
case CS8:
config->bDataBits = UMP_UART_CHAR8BITS;
dev_dbg(dev, "%s - data bits = 8\n", __func__);
break;
}
if (cflag & PARENB) {
if (cflag & PARODD) {
config->wFlags |= UMP_MASK_UART_FLAGS_PARITY;
config->bParity = UMP_UART_ODDPARITY;
dev_dbg(dev, "%s - parity = odd\n", __func__);
} else {
config->wFlags |= UMP_MASK_UART_FLAGS_PARITY;
config->bParity = UMP_UART_EVENPARITY;
dev_dbg(dev, "%s - parity = even\n", __func__);
}
} else {
config->bParity = UMP_UART_NOPARITY;
dev_dbg(dev, "%s - parity = none\n", __func__);
}
if (cflag & CSTOPB) {
config->bStopBits = UMP_UART_STOPBIT2;
dev_dbg(dev, "%s - stop bits = 2\n", __func__);
} else {
config->bStopBits = UMP_UART_STOPBIT1;
dev_dbg(dev, "%s - stop bits = 1\n", __func__);
}
/* figure out the flow control settings */
if (cflag & CRTSCTS) {
config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW;
config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW;
dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__);
} else {
dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__);
restart_read(edge_port);
}
/*
* if we are implementing XON/XOFF, set the start and stop
* character in the device
*/
config->cXon = START_CHAR(tty);
config->cXoff = STOP_CHAR(tty);
/* if we are implementing INBOUND XON/XOFF */
if (I_IXOFF(tty)) {
config->wFlags |= UMP_MASK_UART_FLAGS_IN_X;
dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n",
__func__, config->cXon, config->cXoff);
} else
dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__);
/* if we are implementing OUTBOUND XON/XOFF */
if (I_IXON(tty)) {
config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X;
dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n",
__func__, config->cXon, config->cXoff);
} else
dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__);
tty->termios.c_cflag &= ~CMSPAR;
/* Round the baud rate */
baud = tty_get_baud_rate(tty);
if (!baud) {
/* pick a default, any default... */
baud = 9600;
} else
tty_encode_baud_rate(tty, baud, baud);
edge_port->baud_rate = baud;
config->wBaudRate = (__u16)((461550L + baud/2) / baud);
/* FIXME: Recompute actual baud from divisor here */
dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate);
dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate));
dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags);
dev_dbg(dev, "bDataBits: %d\n", config->bDataBits);
dev_dbg(dev, "bParity: %d\n", config->bParity);
dev_dbg(dev, "bStopBits: %d\n", config->bStopBits);
dev_dbg(dev, "cXon: %d\n", config->cXon);
dev_dbg(dev, "cXoff: %d\n", config->cXoff);
dev_dbg(dev, "bUartMode: %d\n", config->bUartMode);
/* move the word values into big endian mode */
cpu_to_be16s(&config->wFlags);
cpu_to_be16s(&config->wBaudRate);
status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG,
(__u8)(UMPM_UART1_PORT + port_number),
0, (__u8 *)config, sizeof(*config));
if (status)
dev_dbg(dev, "%s - error %d when trying to write config to device\n",
__func__, status);
kfree(config);
}
CWE ID: CWE-369
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(data_reduction_proxy_service_->compression_stats());
if (spdy_proxy_auth_enabled_.GetValue() != enabled) {
spdy_proxy_auth_enabled_.SetValue(enabled);
OnProxyEnabledPrefChange();
#if defined(OS_ANDROID)
data_reduction_proxy_service_->compression_stats()
->SetDataUsageReportingEnabled(enabled);
#endif // defined(OS_ANDROID)
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline void tcp_end_cwnd_reduction(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
/* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
if (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR ||
(tp->undo_marker && tp->snd_ssthresh < TCP_INFINITE_SSTHRESH)) {
tp->snd_cwnd = tp->snd_ssthresh;
tp->snd_cwnd_stamp = tcp_time_stamp;
}
tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
}
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: local unsigned long crc32_big(crc, buf, len)
unsigned long crc;
const unsigned char FAR *buf;
unsigned len;
{
register z_crc_t c;
register const z_crc_t FAR *buf4;
c = ZSWAP32((z_crc_t)crc);
c = ~c;
while (len && ((ptrdiff_t)buf & 3)) {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
len--;
}
buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
buf4--;
while (len >= 32) {
DOBIG32;
len -= 32;
}
while (len >= 4) {
DOBIG4;
len -= 4;
}
buf4++;
buf = (const unsigned char FAR *)buf4;
if (len) do {
c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
} while (--len);
c = ~c;
return (unsigned long)(ZSWAP32(c));
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int propagate_mnt(struct mount *dest_mnt, struct dentry *dest_dentry,
struct mount *source_mnt, struct list_head *tree_list)
{
struct mount *m, *child;
int ret = 0;
struct mount *prev_dest_mnt = dest_mnt;
struct mount *prev_src_mnt = source_mnt;
LIST_HEAD(tmp_list);
LIST_HEAD(umount_list);
for (m = propagation_next(dest_mnt, dest_mnt); m;
m = propagation_next(m, dest_mnt)) {
int type;
struct mount *source;
if (IS_MNT_NEW(m))
continue;
source = get_source(m, prev_dest_mnt, prev_src_mnt, &type);
child = copy_tree(source, source->mnt.mnt_root, type);
if (IS_ERR(child)) {
ret = PTR_ERR(child);
list_splice(tree_list, tmp_list.prev);
goto out;
}
if (is_subdir(dest_dentry, m->mnt.mnt_root)) {
mnt_set_mountpoint(m, dest_dentry, child);
list_add_tail(&child->mnt_hash, tree_list);
} else {
/*
* This can happen if the parent mount was bind mounted
* on some subdirectory of a shared/slave mount.
*/
list_add_tail(&child->mnt_hash, &tmp_list);
}
prev_dest_mnt = m;
prev_src_mnt = child;
}
out:
br_write_lock(&vfsmount_lock);
while (!list_empty(&tmp_list)) {
child = list_first_entry(&tmp_list, struct mount, mnt_hash);
umount_tree(child, 0, &umount_list);
}
br_write_unlock(&vfsmount_lock);
release_mounts(&umount_list);
return ret;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void drop_nlink(struct inode *inode)
{
WARN_ON(inode->i_nlink == 0);
inode->__i_nlink--;
if (!inode->i_nlink)
atomic_long_inc(&inode->i_sb->s_remove_count);
}
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 ProfilingService::DumpProcessesForTracing(
bool keep_small_allocations,
bool strip_path_from_mapped_files,
DumpProcessesForTracingCallback callback) {
memory_instrumentation::MemoryInstrumentation::GetInstance()
->GetVmRegionsForHeapProfiler(base::Bind(
&ProfilingService::OnGetVmRegionsCompleteForDumpProcessesForTracing,
weak_factory_.GetWeakPtr(), keep_small_allocations,
strip_path_from_mapped_files, base::Passed(&callback)));
}
CWE ID: CWE-269
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int process_one_ticket(struct ceph_auth_client *ac,
struct ceph_crypto_key *secret,
void **p, void *end,
void *dbuf, void *ticket_buf)
{
struct ceph_x_info *xi = ac->private;
int type;
u8 tkt_struct_v, blob_struct_v;
struct ceph_x_ticket_handler *th;
void *dp, *dend;
int dlen;
char is_enc;
struct timespec validity;
struct ceph_crypto_key old_key;
void *tp, *tpend;
struct ceph_timespec new_validity;
struct ceph_crypto_key new_session_key;
struct ceph_buffer *new_ticket_blob;
unsigned long new_expires, new_renew_after;
u64 new_secret_id;
int ret;
ceph_decode_need(p, end, sizeof(u32) + 1, bad);
type = ceph_decode_32(p);
dout(" ticket type %d %s\n", type, ceph_entity_type_name(type));
tkt_struct_v = ceph_decode_8(p);
if (tkt_struct_v != 1)
goto bad;
th = get_ticket_handler(ac, type);
if (IS_ERR(th)) {
ret = PTR_ERR(th);
goto out;
}
/* blob for me */
dlen = ceph_x_decrypt(secret, p, end, dbuf,
TEMP_TICKET_BUF_LEN);
if (dlen <= 0) {
ret = dlen;
goto out;
}
dout(" decrypted %d bytes\n", dlen);
dp = dbuf;
dend = dp + dlen;
tkt_struct_v = ceph_decode_8(&dp);
if (tkt_struct_v != 1)
goto bad;
memcpy(&old_key, &th->session_key, sizeof(old_key));
ret = ceph_crypto_key_decode(&new_session_key, &dp, dend);
if (ret)
goto out;
ceph_decode_copy(&dp, &new_validity, sizeof(new_validity));
ceph_decode_timespec(&validity, &new_validity);
new_expires = get_seconds() + validity.tv_sec;
new_renew_after = new_expires - (validity.tv_sec / 4);
dout(" expires=%lu renew_after=%lu\n", new_expires,
new_renew_after);
/* ticket blob for service */
ceph_decode_8_safe(p, end, is_enc, bad);
tp = ticket_buf;
if (is_enc) {
/* encrypted */
dout(" encrypted ticket\n");
dlen = ceph_x_decrypt(&old_key, p, end, ticket_buf,
TEMP_TICKET_BUF_LEN);
if (dlen < 0) {
ret = dlen;
goto out;
}
dlen = ceph_decode_32(&tp);
} else {
/* unencrypted */
ceph_decode_32_safe(p, end, dlen, bad);
ceph_decode_need(p, end, dlen, bad);
ceph_decode_copy(p, ticket_buf, dlen);
}
tpend = tp + dlen;
dout(" ticket blob is %d bytes\n", dlen);
ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad);
blob_struct_v = ceph_decode_8(&tp);
new_secret_id = ceph_decode_64(&tp);
ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend);
if (ret)
goto out;
/* all is well, update our ticket */
ceph_crypto_key_destroy(&th->session_key);
if (th->ticket_blob)
ceph_buffer_put(th->ticket_blob);
th->session_key = new_session_key;
th->ticket_blob = new_ticket_blob;
th->validity = new_validity;
th->secret_id = new_secret_id;
th->expires = new_expires;
th->renew_after = new_renew_after;
dout(" got ticket service %d (%s) secret_id %lld len %d\n",
type, ceph_entity_type_name(type), th->secret_id,
(int)th->ticket_blob->vec.iov_len);
xi->have_keys |= th->service;
out:
return ret;
bad:
ret = -EINVAL;
goto out;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: std::wstring UTF8ToUTF16(const std::string& source) {
if (source.empty() ||
static_cast<int>(source.size()) > std::numeric_limits<int>::max()) {
return std::wstring();
}
int size = ::MultiByteToWideChar(CP_UTF8, 0, &source[0],
static_cast<int>(source.size()), nullptr, 0);
std::wstring result(size, L'\0');
if (::MultiByteToWideChar(CP_UTF8, 0, &source[0],
static_cast<int>(source.size()), &result[0],
size) != size) {
assert(false);
return std::wstring();
}
return result;
}
CWE ID: CWE-77
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void copyMono8(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
}
}
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: SPL_METHOD(RecursiveDirectoryIterator, getSubPath)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (intern->u.dir.sub_path) {
RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1);
} else {
RETURN_STRINGL("", 0, 1);
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void GfxColorSpace::getRGBLine(Guchar *in, unsigned int *out, int length) {
int i, j, n;
GfxColor color;
GfxRGB rgb;
n = getNComps();
for (i = 0; i < length; i++) {
for (j = 0; j < n; j++)
color.c[j] = in[i * n + j] * 256;
getRGB (&color, &rgb);
out[i] =
((int) colToByte(rgb.r) << 16) |
((int) colToByte(rgb.g) << 8) |
((int) colToByte(rgb.b) << 0);
}
}
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: bool AXObject::isPresentationalChild() const {
updateCachedAttributeValuesIfNeeded();
return m_cachedIsPresentationalChild;
}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void common_hrtimer_rearm(struct k_itimer *timr)
{
struct hrtimer *timer = &timr->it.real.timer;
if (!timr->it_interval)
return;
timr->it_overrun += (unsigned int) hrtimer_forward(timer,
timer->base->get_time(),
timr->it_interval);
hrtimer_restart(timer);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: tt_cmap10_get_info( TT_CMap cmap,
TT_CMapInfo *cmap_info )
{
FT_Byte* p = cmap->data + 8;
cmap_info->format = 10;
cmap_info->language = (FT_ULong)TT_PEEK_ULONG( p );
return SFNT_Err_Ok;
}
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: bool ExecuteCodeInTabFunction::HasPermission() {
if (Init() &&
extension_->HasAPIPermissionForTab(execute_tab_id_,
extensions::APIPermission::kTab)) {
return true;
}
return ExtensionFunction::HasPermission();
}
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: int bta_co_rfc_data_outgoing_size(void *user_data, int *size) {
pthread_mutex_lock(&slot_lock);
uint32_t id = (uintptr_t)user_data;
int ret = false;
*size = 0;
rfc_slot_t *slot = find_rfc_slot_by_id(id);
if (!slot)
goto out;
if (ioctl(slot->fd, FIONREAD, size) == 0) {
ret = true;
} else {
LOG_ERROR("%s unable to determine bytes remaining to be read on fd %d: %s", __func__, slot->fd, strerror(errno));
cleanup_rfc_slot(slot);
}
out:;
pthread_mutex_unlock(&slot_lock);
return ret;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: void RunLoop::DisallowNestingOnCurrentThread() {
tls_delegate.Get().Get()->allow_nesting_ = false;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_init_video_state(dec_state_t *ps_dec, e_video_type_t e_video_type)
{
/*-----------------------------------------------------------------------*/
/* Bit Stream that conforms to MPEG-1 <ISO/IEC 11172-2> standard */
/*-----------------------------------------------------------------------*/
if(e_video_type == MPEG_1_VIDEO)
{
ps_dec->u2_is_mpeg2 = 0;
/*-------------------------------------------------------------------*/
/* force MPEG-1 parameters for proper decoder behavior */
/* see ISO/IEC 13818-2 section D.9.14 */
/*-------------------------------------------------------------------*/
ps_dec->u2_progressive_sequence = 1;
ps_dec->u2_intra_dc_precision = 0;
ps_dec->u2_picture_structure = FRAME_PICTURE;
ps_dec->u2_frame_pred_frame_dct = 1;
ps_dec->u2_concealment_motion_vectors = 0;
ps_dec->u2_q_scale_type = 0;
ps_dec->u2_intra_vlc_format = 0;
ps_dec->u2_alternate_scan = 0;
ps_dec->u2_repeat_first_field = 0;
ps_dec->u2_progressive_frame = 1;
ps_dec->u2_frame_rate_extension_n = 0;
ps_dec->u2_frame_rate_extension_d = 0;
ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg1;
/*-------------------------------------------------------------------*/
/* Setting of parameters other than those mentioned in MPEG2 standard*/
/* but used in decoding process. */
/*-------------------------------------------------------------------*/
}
/*-----------------------------------------------------------------------*/
/* Bit Stream that conforms to MPEG-2 */
/*-----------------------------------------------------------------------*/
else
{
ps_dec->u2_is_mpeg2 = 1;
ps_dec->u2_full_pel_forw_vector = 0;
ps_dec->u2_forw_f_code = 7;
ps_dec->u2_full_pel_back_vector = 0;
ps_dec->u2_back_f_code = 7;
ps_dec->pf_vld_inv_quant = impeg2d_vld_inv_quant_mpeg2;
}
impeg2d_init_function_ptr(ps_dec);
/* Set the frame Width and frame Height */
ps_dec->u2_frame_height = ALIGN16(ps_dec->u2_vertical_size);
ps_dec->u2_frame_width = ALIGN16(ps_dec->u2_horizontal_size);
ps_dec->u2_num_horiz_mb = (ps_dec->u2_horizontal_size + 15) >> 4;
if (ps_dec->u2_frame_height > ps_dec->u2_create_max_height || ps_dec->u2_frame_width > ps_dec->u2_create_max_width)
{
return IMPEG2D_PIC_SIZE_NOT_SUPPORTED;
}
ps_dec->u2_num_flds_decoded = 0;
/* Calculate the frame period */
{
UWORD32 numer;
UWORD32 denom;
numer = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][1] *
(UWORD32)(ps_dec->u2_frame_rate_extension_d + 1);
denom = (UWORD32)gau2_impeg2_frm_rate_code[ps_dec->u2_frame_rate_code][0] *
(UWORD32)(ps_dec->u2_frame_rate_extension_n + 1);
ps_dec->u2_framePeriod = (numer * 1000 * 100) / denom;
}
if(VERTICAL_SCAN == ps_dec->u2_alternate_scan)
{
ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_vertical;
}
else
{
ps_dec->pu1_inv_scan_matrix = (UWORD8 *)gau1_impeg2_inv_scan_zig_zag;
}
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
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 nw_buf_free(nw_buf_pool *pool, nw_buf *buf)
{
if (pool->free < pool->free_total) {
pool->free_arr[pool->free++] = buf;
} else {
uint32_t new_free_total = pool->free_total * 2;
void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *));
if (new_arr) {
pool->free_total = new_free_total;
pool->free_arr = new_arr;
pool->free_arr[pool->free++] = buf;
} else {
free(buf);
}
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int hugetlbfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, struct nameidata *nd)
{
return hugetlbfs_mknod(dir, dentry, mode | S_IFREG, 0);
}
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 check_stack_usage(void)
{
static DEFINE_SPINLOCK(low_water_lock);
static int lowest_to_date = THREAD_SIZE;
unsigned long free;
free = stack_not_used(current);
if (free >= lowest_to_date)
return;
spin_lock(&low_water_lock);
if (free < lowest_to_date) {
pr_info("%s (%d) used greatest stack depth: %lu bytes left\n",
current->comm, task_pid_nr(current), free);
lowest_to_date = free;
}
spin_unlock(&low_water_lock);
}
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: void ExtensionContextMenuModel::InitCommonCommands() {
const Extension* extension = GetExtension();
DCHECK(extension);
AddItem(NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItemWithStringId(CONFIGURE, IDS_EXTENSIONS_OPTIONS);
AddItemWithStringId(DISABLE, IDS_EXTENSIONS_DISABLE);
AddItem(UNINSTALL, l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
if (extension->browser_action())
AddItemWithStringId(HIDE, IDS_EXTENSIONS_HIDE_BUTTON);
AddSeparator();
AddItemWithStringId(MANAGE, IDS_MANAGE_EXTENSIONS);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ip_cmsg_recv_offset(struct msghdr *msg, struct sock *sk,
struct sk_buff *skb, int tlen, int offset)
{
struct inet_sock *inet = inet_sk(sk);
unsigned int flags = inet->cmsg_flags;
/* Ordered by supposed usage frequency */
if (flags & IP_CMSG_PKTINFO) {
ip_cmsg_recv_pktinfo(msg, skb);
flags &= ~IP_CMSG_PKTINFO;
if (!flags)
return;
}
if (flags & IP_CMSG_TTL) {
ip_cmsg_recv_ttl(msg, skb);
flags &= ~IP_CMSG_TTL;
if (!flags)
return;
}
if (flags & IP_CMSG_TOS) {
ip_cmsg_recv_tos(msg, skb);
flags &= ~IP_CMSG_TOS;
if (!flags)
return;
}
if (flags & IP_CMSG_RECVOPTS) {
ip_cmsg_recv_opts(msg, skb);
flags &= ~IP_CMSG_RECVOPTS;
if (!flags)
return;
}
if (flags & IP_CMSG_RETOPTS) {
ip_cmsg_recv_retopts(msg, skb);
flags &= ~IP_CMSG_RETOPTS;
if (!flags)
return;
}
if (flags & IP_CMSG_PASSSEC) {
ip_cmsg_recv_security(msg, skb);
flags &= ~IP_CMSG_PASSSEC;
if (!flags)
return;
}
if (flags & IP_CMSG_ORIGDSTADDR) {
ip_cmsg_recv_dstaddr(msg, skb);
flags &= ~IP_CMSG_ORIGDSTADDR;
if (!flags)
return;
}
if (flags & IP_CMSG_CHECKSUM)
ip_cmsg_recv_checksum(msg, skb, tlen, offset);
if (flags & IP_CMSG_RECVFRAGSIZE)
ip_cmsg_recv_fragsize(msg, skb);
}
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: int wvlan_set_station_nickname(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu,
char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC("wvlan_set_station_nickname");
DBG_ENTER(DbgInfo);
wl_lock(lp, &flags);
memset(lp->StationName, 0, sizeof(lp->StationName));
memcpy(lp->StationName, extra, wrqu->data.length);
/* Commit the adapter parameters */
wl_apply(lp);
wl_unlock(lp, &flags);
DBG_LEAVE(DbgInfo);
return ret;
} /* wvlan_set_station_nickname */
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 MagickPixelPacket **AcquirePixelThreadSet(const Image *image)
{
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(image->columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) image->columns; j++)
GetMagickPixelPacket(image,&pixels[i][j]);
}
return(pixels);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void recalc_sigpending_and_wake(struct task_struct *t)
{
if (recalc_sigpending_tsk(t))
signal_wake_up(t, 0);
}
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 sw_perf_event_destroy(struct perf_event *event)
{
u64 event_id = event->attr.config;
WARN_ON(event->parent);
jump_label_dec(&perf_swevent_enabled[event_id]);
swevent_hlist_put(event);
}
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 * calloc(size_t n, size_t lb)
{
if (lb && n > SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: bool XSSAuditor::FilterStartToken(const FilterTokenRequest& request) {
state_ = kFilteringTokens;
bool did_block_script = EraseDangerousAttributesIfInjected(request);
if (HasName(request.token, scriptTag)) {
did_block_script |= FilterScriptToken(request);
DCHECK(request.should_allow_cdata || !script_tag_nesting_level_);
script_tag_nesting_level_++;
} else if (HasName(request.token, objectTag))
did_block_script |= FilterObjectToken(request);
else if (HasName(request.token, paramTag))
did_block_script |= FilterParamToken(request);
else if (HasName(request.token, embedTag))
did_block_script |= FilterEmbedToken(request);
else if (HasName(request.token, iframeTag) ||
HasName(request.token, frameTag))
did_block_script |= FilterFrameToken(request);
else if (HasName(request.token, metaTag))
did_block_script |= FilterMetaToken(request);
else if (HasName(request.token, baseTag))
did_block_script |= FilterBaseToken(request);
else if (HasName(request.token, formTag))
did_block_script |= FilterFormToken(request);
else if (HasName(request.token, inputTag))
did_block_script |= FilterInputToken(request);
else if (HasName(request.token, buttonTag))
did_block_script |= FilterButtonToken(request);
else if (HasName(request.token, linkTag))
did_block_script |= FilterLinkToken(request);
return did_block_script;
}
CWE ID: CWE-79
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void configureV8TestObjectPythonTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "TestObjectPython", v8::Local<v8::FunctionTemplate>(), V8TestObjectPython::internalFieldCount,
V8TestObjectPythonAttributes, WTF_ARRAY_LENGTH(V8TestObjectPythonAttributes),
V8TestObjectPythonAccessors, WTF_ARRAY_LENGTH(V8TestObjectPythonAccessors),
V8TestObjectPythonMethods, WTF_ARRAY_LENGTH(V8TestObjectPythonMethods),
isolate);
v8::Local<v8::ObjectTemplate> ALLOW_UNUSED instanceTemplate = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> ALLOW_UNUSED prototypeTemplate = functionTemplate->PrototypeTemplate();
if (RuntimeEnabledFeatures::featureNameEnabled()) {
static const V8DOMConfiguration::AttributeConfiguration attributeConfiguration =\
{"runtimeEnabledLongAttribute", TestObjectPythonV8Internal::runtimeEnabledLongAttributeAttributeGetterCallback, TestObjectPythonV8Internal::runtimeEnabledLongAttributeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */};
V8DOMConfiguration::installAttribute(instanceTemplate, prototypeTemplate, attributeConfiguration, isolate);
}
#if ENABLE(CONDITION)
if (RuntimeEnabledFeatures::featureNameEnabled()) {
static const V8DOMConfiguration::AttributeConfiguration attributeConfiguration =\
{"conditionalRuntimeEnabledLongAttribute", TestObjectPythonV8Internal::conditionalRuntimeEnabledLongAttributeAttributeGetterCallback, TestObjectPythonV8Internal::conditionalRuntimeEnabledLongAttributeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */};
V8DOMConfiguration::installAttribute(instanceTemplate, prototypeTemplate, attributeConfiguration, isolate);
}
#endif // ENABLE(CONDITION)
static const V8DOMConfiguration::ConstantConfiguration V8TestObjectPythonConstants[] = {
{"CONST_VALUE_0", 0},
{"CONST_VALUE_1", 1},
{"CONST_VALUE_2", 2},
{"CONST_VALUE_4", 4},
{"CONST_VALUE_8", 8},
{"CONST_VALUE_9", -1},
{"CONST_VALUE_10", "my constant string"},
{"CONST_VALUE_11", 0xffffffff},
{"CONST_VALUE_12", 0x01},
{"CONST_VALUE_13", 0X20},
{"CONST_VALUE_14", 0x1abc},
{"CONST_VALUE_15", 010},
{"CONST_VALUE_16", -010},
{"CONST_VALUE_16", -0x1A},
{"CONST_VALUE_17", -0X1a},
{"DEPRECATED_CONSTANT", 1},
{"CONST_JAVASCRIPT", 1},
};
V8DOMConfiguration::installConstants(functionTemplate, prototypeTemplate, V8TestObjectPythonConstants, WTF_ARRAY_LENGTH(V8TestObjectPythonConstants), isolate);
if (RuntimeEnabledFeatures::featureNameEnabled()) {
static const V8DOMConfiguration::ConstantConfiguration constantConfiguration = {"FEATURE_ENABLED_CONST", static_cast<signed int>(1)};
V8DOMConfiguration::installConstants(functionTemplate, prototypeTemplate, &constantConfiguration, 1, isolate);
}
COMPILE_ASSERT(0 == TestObjectPython::CONST_VALUE_0, TheValueOfTestObjectPython_CONST_VALUE_0DoesntMatchWithImplementation);
COMPILE_ASSERT(1 == TestObjectPython::CONST_VALUE_1, TheValueOfTestObjectPython_CONST_VALUE_1DoesntMatchWithImplementation);
COMPILE_ASSERT(2 == TestObjectPython::CONST_VALUE_2, TheValueOfTestObjectPython_CONST_VALUE_2DoesntMatchWithImplementation);
COMPILE_ASSERT(4 == TestObjectPython::CONST_VALUE_4, TheValueOfTestObjectPython_CONST_VALUE_4DoesntMatchWithImplementation);
COMPILE_ASSERT(8 == TestObjectPython::CONST_VALUE_8, TheValueOfTestObjectPython_CONST_VALUE_8DoesntMatchWithImplementation);
COMPILE_ASSERT(-1 == TestObjectPython::CONST_VALUE_9, TheValueOfTestObjectPython_CONST_VALUE_9DoesntMatchWithImplementation);
COMPILE_ASSERT("my constant string" == TestObjectPython::CONST_VALUE_10, TheValueOfTestObjectPython_CONST_VALUE_10DoesntMatchWithImplementation);
COMPILE_ASSERT(0xffffffff == TestObjectPython::CONST_VALUE_11, TheValueOfTestObjectPython_CONST_VALUE_11DoesntMatchWithImplementation);
COMPILE_ASSERT(0x01 == TestObjectPython::CONST_VALUE_12, TheValueOfTestObjectPython_CONST_VALUE_12DoesntMatchWithImplementation);
COMPILE_ASSERT(0X20 == TestObjectPython::CONST_VALUE_13, TheValueOfTestObjectPython_CONST_VALUE_13DoesntMatchWithImplementation);
COMPILE_ASSERT(0x1abc == TestObjectPython::CONST_VALUE_14, TheValueOfTestObjectPython_CONST_VALUE_14DoesntMatchWithImplementation);
COMPILE_ASSERT(010 == TestObjectPython::CONST_VALUE_15, TheValueOfTestObjectPython_CONST_VALUE_15DoesntMatchWithImplementation);
COMPILE_ASSERT(-010 == TestObjectPython::CONST_VALUE_16, TheValueOfTestObjectPython_CONST_VALUE_16DoesntMatchWithImplementation);
COMPILE_ASSERT(-0x1A == TestObjectPython::CONST_VALUE_16, TheValueOfTestObjectPython_CONST_VALUE_16DoesntMatchWithImplementation);
COMPILE_ASSERT(-0X1a == TestObjectPython::CONST_VALUE_17, TheValueOfTestObjectPython_CONST_VALUE_17DoesntMatchWithImplementation);
COMPILE_ASSERT(1 == TestObjectPython::DEPRECATED_CONSTANT, TheValueOfTestObjectPython_DEPRECATED_CONSTANTDoesntMatchWithImplementation);
COMPILE_ASSERT(1 == TestObjectPython::FEATURE_ENABLED_CONST, TheValueOfTestObjectPython_FEATURE_ENABLED_CONSTDoesntMatchWithImplementation);
COMPILE_ASSERT(1 == TestObjectPython::CONST_IMPL, TheValueOfTestObjectPython_CONST_IMPLDoesntMatchWithImplementation);
functionTemplate->Set(v8AtomicString(isolate, "staticVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::staticVoidMethodMethodCallback, v8Undefined(), v8::Local<v8::Signature>(), 0));
functionTemplate->Set(v8AtomicString(isolate, "overloadedStaticMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::overloadedStaticMethodMethodCallback, v8Undefined(), v8::Local<v8::Signature>(), 1));
#if ENABLE(CONDITION)
functionTemplate->Set(v8AtomicString(isolate, "conditionalConditionStaticVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::conditionalConditionStaticVoidMethodMethodCallback, v8Undefined(), v8::Local<v8::Signature>(), 0));
#endif // ENABLE(CONDITION)
prototypeTemplate->Set(v8AtomicString(isolate, "doNotCheckSignatureVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::doNotCheckSignatureVoidMethodMethodCallback, v8Undefined(), v8::Local<v8::Signature>(), 0));
prototypeTemplate->Set(v8AtomicString(isolate, "notEnumerableVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::notEnumerableVoidMethodMethodCallback, v8Undefined(), defaultSignature, 0), static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::DontEnum));
prototypeTemplate->Set(v8AtomicString(isolate, "readOnlyVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::readOnlyVoidMethodMethodCallback, v8Undefined(), defaultSignature, 0), static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly));
prototypeTemplate->Set(v8AtomicString(isolate, "notEnumerableReadOnlyVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::notEnumerableReadOnlyVoidMethodMethodCallback, v8Undefined(), defaultSignature, 0), static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::DontEnum | v8::ReadOnly));
if (RuntimeEnabledFeatures::featureNameEnabled())
prototypeTemplate->Set(v8AtomicString(isolate, "runtimeEnabledVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::runtimeEnabledVoidMethodMethodCallback, v8Undefined(), defaultSignature, 0));
if (DOMWrapperWorld::current(isolate)->isMainWorld()) {
if (RuntimeEnabledFeatures::featureNameEnabled())
prototypeTemplate->Set(v8AtomicString(isolate, "perWorldBindingsRuntimeEnabledVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::perWorldBindingsRuntimeEnabledVoidMethodMethodCallbackForMainWorld, v8Undefined(), defaultSignature, 0));
} else {
if (RuntimeEnabledFeatures::featureNameEnabled())
prototypeTemplate->Set(v8AtomicString(isolate, "perWorldBindingsRuntimeEnabledVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::perWorldBindingsRuntimeEnabledVoidMethodMethodCallback, v8Undefined(), defaultSignature, 0));
}
instanceTemplate->Set(v8AtomicString(isolate, "unforgeableVoidMethod"), v8::FunctionTemplate::New(isolate, TestObjectPythonV8Internal::unforgeableVoidMethodMethodCallback, v8Undefined(), defaultSignature, 0));
functionTemplate->SetNativeDataProperty(v8AtomicString(isolate, "staticStringAttribute"), TestObjectPythonV8Internal::staticStringAttributeAttributeGetterCallback, TestObjectPythonV8Internal::staticStringAttributeAttributeSetterCallback, v8::External::New(isolate, 0), static_cast<v8::PropertyAttribute>(v8::None), v8::Handle<v8::AccessorSignature>(), static_cast<v8::AccessControl>(v8::DEFAULT));
functionTemplate->SetNativeDataProperty(v8AtomicString(isolate, "staticLongAttribute"), TestObjectPythonV8Internal::staticLongAttributeAttributeGetterCallback, TestObjectPythonV8Internal::staticLongAttributeAttributeSetterCallback, v8::External::New(isolate, 0), static_cast<v8::PropertyAttribute>(v8::None), v8::Handle<v8::AccessorSignature>(), static_cast<v8::AccessControl>(v8::DEFAULT));
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::current()->toStringTemplate());
}
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 mount_entry_on_relative_rootfs(struct mntent *mntent,
const char *rootfs)
{
char path[MAXPATHLEN];
int ret;
/* relative to root mount point */
ret = snprintf(path, sizeof(path), "%s/%s", rootfs, mntent->mnt_dir);
if (ret >= sizeof(path)) {
ERROR("path name too long");
return -1;
}
return mount_entry_on_generic(mntent, path);
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: InputEvent::EventIsComposing isComposingFromCommand(
const CompositeEditCommand* command) {
if (command->isTypingCommand() &&
toTypingCommand(command)->compositionType() !=
TypingCommand::TextCompositionNone)
return InputEvent::EventIsComposing::IsComposing;
return InputEvent::EventIsComposing::NotComposing;
}
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 bta_hh_co_close(UINT8 dev_handle, UINT8 app_id)
{
UINT32 i;
btif_hh_device_t *p_dev = NULL;
APPL_TRACE_WARNING("%s: dev_handle = %d, app_id = %d", __FUNCTION__, dev_handle, app_id);
if (dev_handle == BTA_HH_INVALID_HANDLE) {
APPL_TRACE_WARNING("%s: Oops, dev_handle (%d) is invalid...", __FUNCTION__, dev_handle);
return;
}
for (i = 0; i < BTIF_HH_MAX_HID; i++) {
p_dev = &btif_hh_cb.devices[i];
if (p_dev->dev_status != BTHH_CONN_STATE_UNKNOWN && p_dev->dev_handle == dev_handle) {
APPL_TRACE_WARNING("%s: Found an existing device with the same handle "
"dev_status = %d, dev_handle =%d"
,__FUNCTION__,p_dev->dev_status
,p_dev->dev_handle);
btif_hh_close_poll_thread(p_dev);
break;
}
}
}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void WasmCompileStreamingImpl(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
ScriptState* script_state = ScriptState::ForRelevantRealm(args);
v8::Local<v8::Function> compile_callback =
v8::Function::New(isolate, CompileFromResponseCallback);
V8SetReturnValue(args, ScriptPromise::Cast(script_state, args[0])
.Then(compile_callback)
.V8Value());
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: BufferMeta(const sp<GraphicBuffer> &graphicBuffer)
: mGraphicBuffer(graphicBuffer),
mIsBackup(false) {
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void vnc_release_modifiers(VncState *vs)
{
static const int keycodes[] = {
/* shift, control, alt keys, both left & right */
0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
};
int i, keycode;
if (!qemu_console_is_graphic(NULL)) {
return;
}
for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
keycode = keycodes[i];
if (!vs->modifiers_state[keycode]) {
continue;
}
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
}
}
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 Image *ReadRGFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register IndexPacket
*indexes;
register PixelPacket
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
byte;
ssize_t
y;
unsigned char
*data;
/*
Open image file.
*/
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);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read RGF header.
*/
image->columns = (unsigned long) ReadBlobByte(image);
image->rows = (unsigned long) ReadBlobByte(image);
image->depth=8;
image->storage_class=PseudoClass;
image->colors=2;
/*
Initialize image structure.
*/
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize colormap.
*/
image->colormap[0].red=QuantumRange;
image->colormap[0].green=QuantumRange;
image->colormap[0].blue=QuantumRange;
image->colormap[1].red=(Quantum) 0;
image->colormap[1].green=(Quantum) 0;
image->colormap[1].blue=(Quantum) 0;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read hex image data.
*/
data=(unsigned char *) AcquireQuantumMemory(image->rows,image->columns*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) (image->columns * image->rows); i++)
{
*p++=ReadBlobByte(image);
}
/*
Convert RGF image to pixel packets.
*/
p=data;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
byte=(size_t) (*p++);
SetPixelIndex(indexes+x,(Quantum) ((byte & 0x01) != 0 ? 0x01 : 0x00));
bit++;
byte>>=1;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
data=(unsigned char *) RelinquishMagickMemory(data);
(void) SyncImage(image);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void nfs_increment_lock_seqid(int status, struct nfs_seqid *seqid)
{
nfs_increment_seqid(status, seqid);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int add_bound_rdev(struct md_rdev *rdev)
{
struct mddev *mddev = rdev->mddev;
int err = 0;
if (!mddev->pers->hot_remove_disk) {
/* If there is hot_add_disk but no hot_remove_disk
* then added disks for geometry changes,
* and should be added immediately.
*/
super_types[mddev->major_version].
validate_super(mddev, rdev);
err = mddev->pers->hot_add_disk(mddev, rdev);
if (err) {
unbind_rdev_from_array(rdev);
export_rdev(rdev);
return err;
}
}
sysfs_notify_dirent_safe(rdev->sysfs_state);
set_bit(MD_CHANGE_DEVS, &mddev->flags);
if (mddev->degraded)
set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
md_new_event(mddev);
md_wakeup_thread(mddev->thread);
return 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: juniper_mfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
memset(&l2info, 0, sizeof(l2info));
l2info.pictype = DLT_JUNIPER_MFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* child-link ? */
if (l2info.cookie_len == 0) {
mfr_print(ndo, p, l2info.length);
return l2info.header_len;
}
/* first try the LSQ protos */
if (l2info.cookie_len == AS_PIC_COOKIE_LEN) {
switch(l2info.proto) {
case JUNIPER_LSQ_L3_PROTO_IPV4:
ip_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_IPV6:
ip6_print(ndo, p,l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_MPLS:
mpls_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_ISO:
isoclns_print(ndo, p, l2info.length, l2info.caplen);
return l2info.header_len;
default:
break;
}
return l2info.header_len;
}
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLCSAP_ISONS<<8 | LLCSAP_ISONS):
isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: GfxCalGrayColorSpace::GfxCalGrayColorSpace() {
whiteX = whiteY = whiteZ = 1;
blackX = blackY = blackZ = 0;
gamma = 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: base::string16 GetAppForProtocolUsingAssocQuery(const GURL& url) {
base::string16 url_scheme = base::ASCIIToUTF16(url.scheme());
if (url_scheme.empty())
return base::string16();
wchar_t out_buffer[1024];
DWORD buffer_size = arraysize(out_buffer);
HRESULT hr = AssocQueryString(ASSOCF_IS_PROTOCOL,
ASSOCSTR_FRIENDLYAPPNAME,
url_scheme.c_str(),
NULL,
out_buffer,
&buffer_size);
if (FAILED(hr)) {
DLOG(WARNING) << "AssocQueryString failed!";
return base::string16();
}
return base::string16(out_buffer);
}
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 PlatformFontSkia::InitDefaultFont() {
if (g_default_font.Get())
return true;
bool success = false;
std::string family = kFallbackFontFamilyName;
int size_pixels = 12;
int style = Font::NORMAL;
Font::Weight weight = Font::Weight::NORMAL;
FontRenderParams params;
const SkiaFontDelegate* delegate = SkiaFontDelegate::instance();
if (delegate) {
delegate->GetDefaultFontDescription(&family, &size_pixels, &style, &weight,
¶ms);
} else if (default_font_description_) {
#if defined(OS_CHROMEOS)
FontRenderParamsQuery query;
CHECK(FontList::ParseDescription(*default_font_description_,
&query.families, &query.style,
&query.pixel_size, &query.weight))
<< "Failed to parse font description " << *default_font_description_;
params = gfx::GetFontRenderParams(query, &family);
size_pixels = query.pixel_size;
style = query.style;
weight = query.weight;
#else
NOTREACHED();
#endif
}
sk_sp<SkTypeface> typeface =
CreateSkTypeface(style & Font::ITALIC, weight, &family, &success);
if (!success)
return false;
g_default_font.Get() = new PlatformFontSkia(
std::move(typeface), family, size_pixels, style, weight, params);
return true;
}
CWE ID: CWE-862
Target: 1
Example 2:
Code: static int __init pmcraid_init(void)
{
dev_t dev;
int error;
pmcraid_info("%s Device Driver version: %s\n",
PMCRAID_DRIVER_NAME, PMCRAID_DRIVER_VERSION);
error = alloc_chrdev_region(&dev, 0,
PMCRAID_MAX_ADAPTERS,
PMCRAID_DEVFILE);
if (error) {
pmcraid_err("failed to get a major number for adapters\n");
goto out_init;
}
pmcraid_major = MAJOR(dev);
pmcraid_class = class_create(THIS_MODULE, PMCRAID_DEVFILE);
if (IS_ERR(pmcraid_class)) {
error = PTR_ERR(pmcraid_class);
pmcraid_err("failed to register with with sysfs, error = %x\n",
error);
goto out_unreg_chrdev;
}
error = pmcraid_netlink_init();
if (error)
goto out_unreg_chrdev;
error = pci_register_driver(&pmcraid_driver);
if (error == 0)
goto out_init;
pmcraid_err("failed to register pmcraid driver, error = %x\n",
error);
class_destroy(pmcraid_class);
pmcraid_netlink_release();
out_unreg_chrdev:
unregister_chrdev_region(MKDEV(pmcraid_major, 0), PMCRAID_MAX_ADAPTERS);
out_init:
return error;
}
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: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags, uint16_t *notecount)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (*notecount == 0)
return 0;
--*notecount;
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return 0;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return 0;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & FLAGS_DID_OS_NOTE) == 0) {
if (do_os_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_BUILD_ID) == 0) {
if (do_bid_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) {
if (do_pax_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return size;
}
if ((*flags & FLAGS_DID_CORE) == 0) {
if (do_core_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags, size, clazz))
return size;
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
return size;
case NT_NETBSD_MARCH:
if (*flags & FLAGS_DID_NETBSD_MARCH)
return size;
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (*flags & FLAGS_DID_NETBSD_CMODEL)
return size;
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (*flags & FLAGS_DID_NETBSD_UNKNOWN)
return size;
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
return 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: bool RenderMenuList::multiple()
{
return toHTMLSelectElement(node())->multiple();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void reds_mig_target_client_disconnect_all(void)
{
RingItem *now, *next;
RING_FOREACH_SAFE(now, next, &reds->mig_target_clients) {
RedsMigTargetClient *mig_client = SPICE_CONTAINEROF(now, RedsMigTargetClient, link);
reds_client_disconnect(mig_client->client);
}
}
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: MojoResult Core::UnwrapPlatformSharedBufferHandle(
MojoHandle mojo_handle,
MojoPlatformHandle* platform_handle,
size_t* size,
MojoSharedBufferGuid* guid,
MojoPlatformSharedBufferHandleFlags* flags) {
scoped_refptr<Dispatcher> dispatcher;
MojoResult result = MOJO_RESULT_OK;
{
base::AutoLock lock(handles_->GetLock());
result = handles_->GetAndRemoveDispatcher(mojo_handle, &dispatcher);
if (result != MOJO_RESULT_OK)
return result;
}
if (dispatcher->GetType() != Dispatcher::Type::SHARED_BUFFER) {
dispatcher->Close();
return MOJO_RESULT_INVALID_ARGUMENT;
}
SharedBufferDispatcher* shm_dispatcher =
static_cast<SharedBufferDispatcher*>(dispatcher.get());
scoped_refptr<PlatformSharedBuffer> platform_shared_buffer =
shm_dispatcher->PassPlatformSharedBuffer();
DCHECK(platform_shared_buffer);
DCHECK(size);
*size = platform_shared_buffer->GetNumBytes();
base::UnguessableToken token = platform_shared_buffer->GetGUID();
guid->high = token.GetHighForSerialization();
guid->low = token.GetLowForSerialization();
DCHECK(flags);
*flags = MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_NONE;
if (platform_shared_buffer->IsReadOnly())
*flags |= MOJO_PLATFORM_SHARED_BUFFER_HANDLE_FLAG_READ_ONLY;
ScopedPlatformHandle handle = platform_shared_buffer->PassPlatformHandle();
return ScopedPlatformHandleToMojoPlatformHandle(std::move(handle),
platform_handle);
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int em_fxsave(struct x86_emulate_ctxt *ctxt)
{
struct fxregs_state fx_state;
size_t size;
int rc;
rc = check_fxsr(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->ops->get_fpu(ctxt);
rc = asm_safe("fxsave %[fx]", , [fx] "+m"(fx_state));
ctxt->ops->put_fpu(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR)
size = offsetof(struct fxregs_state, xmm_space[8 * 16/4]);
else
size = offsetof(struct fxregs_state, xmm_space[0]);
return segmented_write(ctxt, ctxt->memop.addr.mem, &fx_state, size);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void provideLocalFileSystemTo(LocalFrame& frame, PassOwnPtr<FileSystemClient> client)
{
frame.provideSupplement(LocalFileSystem::supplementName(), LocalFileSystem::create(client));
}
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: cJSON *cJSON_CreateTrue( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_True;
return item;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
struct kvm_memory_slot *memslot, *slot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = check_memory_region_flags(mem);
if (r)
goto out;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if (user_alloc &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE,
(void __user *)(unsigned long)mem->userspace_addr,
mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEM_SLOTS_NUM)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = id_to_memslot(kvm->memslots, mem->slot);
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/*
* Disallow changing a memory slot's size or changing anything about
* zero sized slots that doesn't involve making them non-zero.
*/
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
if (!npages && !old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
kvm_for_each_memslot(slot, kvm->memslots) {
if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot)
continue;
if (!((base_gfn + npages <= slot->base_gfn) ||
(base_gfn >= slot->base_gfn + slot->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/*
* Allocate if a slot is being created. If modifying a slot,
* the userspace_addr cannot change.
*/
if (!old.npages) {
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
if (kvm_arch_create_memslot(&new, npages))
goto out_free;
} else if (npages && mem->userspace_addr != old.userspace_addr) {
r = -EINVAL;
goto out_free;
}
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
if (!npages || base_gfn != old.base_gfn) {
struct kvm_memory_slot *slot;
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
slot = id_to_memslot(slots, mem->slot);
slot->flags |= KVM_MEMSLOT_INVALID;
update_memslots(slots, NULL);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted,
* or moved, memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow_memslot(kvm, slot);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map/unmap the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
} else
kvm_iommu_unmap_pages(kvm, &old);
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.dirty_bitmap = NULL;
memset(&new.arch, 0, sizeof(new.arch));
}
update_memslots(slots, &new);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool HeapAllocator::shrinkVectorBacking(void* address,
size_t quantizedCurrentSize,
size_t quantizedShrunkSize) {
return backingShrink(address, quantizedCurrentSize, quantizedShrunkSize);
}
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 Layer::SetContentsOpaque(bool opaque) {
DCHECK(IsPropertyChangeAllowed());
if (contents_opaque_ == opaque)
return;
contents_opaque_ = opaque;
SetNeedsCommit();
}
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: int hns_nic_net_xmit_hw(struct net_device *ndev,
struct sk_buff *skb,
struct hns_nic_ring_data *ring_data)
{
struct hns_nic_priv *priv = netdev_priv(ndev);
struct hnae_ring *ring = ring_data->ring;
struct device *dev = ring_to_dev(ring);
struct netdev_queue *dev_queue;
struct skb_frag_struct *frag;
int buf_num;
int seg_num;
dma_addr_t dma;
int size, next_to_use;
int i;
switch (priv->ops.maybe_stop_tx(&skb, &buf_num, ring)) {
case -EBUSY:
ring->stats.tx_busy++;
goto out_net_tx_busy;
case -ENOMEM:
ring->stats.sw_err_cnt++;
netdev_err(ndev, "no memory to xmit!\n");
goto out_err_tx_ok;
default:
break;
}
/* no. of segments (plus a header) */
seg_num = skb_shinfo(skb)->nr_frags + 1;
next_to_use = ring->next_to_use;
/* fill the first part */
size = skb_headlen(skb);
dma = dma_map_single(dev, skb->data, size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma)) {
netdev_err(ndev, "TX head DMA map failed\n");
ring->stats.sw_err_cnt++;
goto out_err_tx_ok;
}
priv->ops.fill_desc(ring, skb, size, dma, seg_num == 1 ? 1 : 0,
buf_num, DESC_TYPE_SKB, ndev->mtu);
/* fill the fragments */
for (i = 1; i < seg_num; i++) {
frag = &skb_shinfo(skb)->frags[i - 1];
size = skb_frag_size(frag);
dma = skb_frag_dma_map(dev, frag, 0, size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, dma)) {
netdev_err(ndev, "TX frag(%d) DMA map failed\n", i);
ring->stats.sw_err_cnt++;
goto out_map_frag_fail;
}
priv->ops.fill_desc(ring, skb_frag_page(frag), size, dma,
seg_num - 1 == i ? 1 : 0, buf_num,
DESC_TYPE_PAGE, ndev->mtu);
}
/*complete translate all packets*/
dev_queue = netdev_get_tx_queue(ndev, skb->queue_mapping);
netdev_tx_sent_queue(dev_queue, skb->len);
wmb(); /* commit all data before submit */
assert(skb->queue_mapping < priv->ae_handle->q_num);
hnae_queue_xmit(priv->ae_handle->qs[skb->queue_mapping], buf_num);
ring->stats.tx_pkts++;
ring->stats.tx_bytes += skb->len;
return NETDEV_TX_OK;
out_map_frag_fail:
while (ring->next_to_use != next_to_use) {
unfill_desc(ring);
if (ring->next_to_use != next_to_use)
dma_unmap_page(dev,
ring->desc_cb[ring->next_to_use].dma,
ring->desc_cb[ring->next_to_use].length,
DMA_TO_DEVICE);
else
dma_unmap_single(dev,
ring->desc_cb[next_to_use].dma,
ring->desc_cb[next_to_use].length,
DMA_TO_DEVICE);
}
out_err_tx_ok:
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
out_net_tx_busy:
netif_stop_subqueue(ndev, skb->queue_mapping);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it.
*/
smp_mb();
return NETDEV_TX_BUSY;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: RenderProcessHost* SiteInstanceImpl::GetProcess() {
if (!process_) {
BrowserContext* browser_context = browsing_instance_->browser_context();
bool should_use_process_per_site =
has_site_ &&
RenderProcessHost::ShouldUseProcessPerSite(browser_context, site_);
if (should_use_process_per_site) {
process_reuse_policy_ = ProcessReusePolicy::PROCESS_PER_SITE;
} else if (process_reuse_policy_ == ProcessReusePolicy::PROCESS_PER_SITE) {
process_reuse_policy_ = ProcessReusePolicy::DEFAULT;
}
process_ = RenderProcessHostImpl::GetProcessHostForSiteInstance(this);
CHECK(process_);
process_->AddObserver(this);
if (process_reuse_policy_ == ProcessReusePolicy::PROCESS_PER_SITE &&
has_site_) {
RenderProcessHostImpl::RegisterSoleProcessHostForSite(browser_context,
process_, this);
}
TRACE_EVENT2("navigation", "SiteInstanceImpl::GetProcess",
"site id", id_, "process id", process_->GetID());
GetContentClient()->browser()->SiteInstanceGotProcess(this);
if (has_site_)
LockToOriginIfNeeded();
}
DCHECK(process_);
return process_;
}
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: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr)
{
jas_image_t *image;
bmp_hdr_t hdr;
bmp_info_t *info;
uint_fast16_t cmptno;
jas_image_cmptparm_t cmptparms[3];
jas_image_cmptparm_t *cmptparm;
uint_fast16_t numcmpts;
long n;
if (optstr) {
jas_eprintf("warning: ignoring BMP decoder options\n");
}
jas_eprintf(
"THE BMP FORMAT IS NOT FULLY SUPPORTED!\n"
"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n"
"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n"
"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n"
);
/* Read the bitmap header. */
if (bmp_gethdr(in, &hdr)) {
jas_eprintf("cannot get header\n");
return 0;
}
JAS_DBGLOG(1, (
"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\n",
hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off
));
/* Read the bitmap information. */
if (!(info = bmp_getinfo(in))) {
jas_eprintf("cannot get info\n");
return 0;
}
JAS_DBGLOG(1,
("BMP information: len %d; width %d; height %d; numplanes %d; "
"depth %d; enctype %d; siz %d; hres %d; vres %d; numcolors %d; "
"mincolors %d\n", info->len, info->width, info->height, info->numplanes,
info->depth, info->enctype, info->siz, info->hres, info->vres,
info->numcolors, info->mincolors));
/* Ensure that we support this type of BMP file. */
if (!bmp_issupported(&hdr, info)) {
jas_eprintf("error: unsupported BMP encoding\n");
bmp_info_destroy(info);
return 0;
}
/* Skip over any useless data between the end of the palette
and start of the bitmap data. */
if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) {
jas_eprintf("error: possibly bad bitmap offset?\n");
return 0;
}
if (n > 0) {
jas_eprintf("skipping unknown data in BMP file\n");
if (bmp_gobble(in, n)) {
bmp_info_destroy(info);
return 0;
}
}
/* Get the number of components. */
numcmpts = bmp_numcmpts(info);
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
cmptparm->tlx = 0;
cmptparm->tly = 0;
cmptparm->hstep = 1;
cmptparm->vstep = 1;
cmptparm->width = info->width;
cmptparm->height = info->height;
cmptparm->prec = 8;
cmptparm->sgnd = false;
}
/* Create image object. */
if (!(image = jas_image_create(numcmpts, cmptparms,
JAS_CLRSPC_UNKNOWN))) {
bmp_info_destroy(info);
return 0;
}
if (numcmpts == 3) {
jas_image_setclrspc(image, JAS_CLRSPC_SRGB);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
jas_image_setcmpttype(image, 1,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
jas_image_setcmpttype(image, 2,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
} else {
jas_image_setclrspc(image, JAS_CLRSPC_SGRAY);
jas_image_setcmpttype(image, 0,
JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y));
}
/* Read the bitmap data. */
if (bmp_getdata(in, info, image)) {
bmp_info_destroy(info);
jas_image_destroy(image);
return 0;
}
bmp_info_destroy(info);
return image;
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void serveloop(GArray* servers) {
struct sockaddr_storage addrin;
socklen_t addrinlen=sizeof(addrin);
int i;
int max;
fd_set mset;
fd_set rset;
/*
* Set up the master fd_set. The set of descriptors we need
* to select() for never changes anyway and it buys us a *lot*
* of time to only build this once. However, if we ever choose
* to not fork() for clients anymore, we may have to revisit
* this.
*/
max=0;
FD_ZERO(&mset);
for(i=0;i<servers->len;i++) {
int sock;
if((sock=(g_array_index(servers, SERVER, i)).socket) >= 0) {
FD_SET(sock, &mset);
max=sock>max?sock:max;
}
}
for(i=0;i<modernsocks->len;i++) {
int sock = g_array_index(modernsocks, int, i);
FD_SET(sock, &mset);
max=sock>max?sock:max;
}
for(;;) {
/* SIGHUP causes the root server process to reconfigure
* itself and add new export servers for each newly
* found export configuration group, i.e. spawn new
* server processes for each previously non-existent
* export. This does not alter old runtime configuration
* but just appends new exports. */
if (is_sighup_caught) {
int n;
GError *gerror = NULL;
msg(LOG_INFO, "reconfiguration request received");
is_sighup_caught = 0; /* Reset to allow catching
* it again. */
n = append_new_servers(servers, &gerror);
if (n == -1)
msg(LOG_ERR, "failed to append new servers: %s",
gerror->message);
for (i = servers->len - n; i < servers->len; ++i) {
const SERVER server = g_array_index(servers,
SERVER, i);
if (server.socket >= 0) {
FD_SET(server.socket, &mset);
max = server.socket > max ? server.socket : max;
}
msg(LOG_INFO, "reconfigured new server: %s",
server.servename);
}
}
memcpy(&rset, &mset, sizeof(fd_set));
if(select(max+1, &rset, NULL, NULL, NULL)>0) {
int net;
DEBUG("accept, ");
for(i=0; i < modernsocks->len; i++) {
int sock = g_array_index(modernsocks, int, i);
if(!FD_ISSET(sock, &rset)) {
continue;
}
CLIENT *client;
if((net=accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0) {
err_nonfatal("accept: %m");
continue;
}
client = negotiate(net, NULL, servers, NEG_INIT | NEG_MODERN);
if(!client) {
close(net);
continue;
}
handle_connection(servers, net, client->server, client);
}
for(i=0; i < servers->len; i++) {
SERVER *serve;
serve=&(g_array_index(servers, SERVER, i));
if(serve->socket < 0) {
continue;
}
if(FD_ISSET(serve->socket, &rset)) {
if ((net=accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0) {
err_nonfatal("accept: %m");
continue;
}
handle_connection(servers, net, serve, NULL);
}
}
}
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static u32 veth_get_rx_csum(struct net_device *dev)
{
struct veth_priv *priv;
priv = netdev_priv(dev);
return priv->ip_summed == CHECKSUM_UNNECESSARY;
}
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: HistogramBase* LinearHistogram::DeserializeInfoImpl(PickleIterator* iter) {
std::string histogram_name;
int flags;
int declared_min;
int declared_max;
uint32_t bucket_count;
uint32_t range_checksum;
if (!ReadHistogramArguments(iter, &histogram_name, &flags, &declared_min,
&declared_max, &bucket_count, &range_checksum)) {
return NULL;
}
HistogramBase* histogram = LinearHistogram::FactoryGet(
histogram_name, declared_min, declared_max, bucket_count, flags);
if (!ValidateRangeChecksum(*histogram, range_checksum)) {
return NULL;
}
return histogram;
}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
CWE ID:
Target: 1
Example 2:
Code: static int copy_mm(unsigned long clone_flags, struct task_struct * tsk)
{
struct mm_struct * mm, *oldmm;
int retval;
tsk->min_flt = tsk->maj_flt = 0;
tsk->nvcsw = tsk->nivcsw = 0;
#ifdef CONFIG_DETECT_HUNG_TASK
tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
#endif
tsk->mm = NULL;
tsk->active_mm = NULL;
/*
* Are we cloning a kernel thread?
*
* We need to steal a active VM for that..
*/
oldmm = current->mm;
if (!oldmm)
return 0;
if (clone_flags & CLONE_VM) {
atomic_inc(&oldmm->mm_users);
mm = oldmm;
goto good_mm;
}
retval = -ENOMEM;
mm = dup_mm(tsk);
if (!mm)
goto fail_nomem;
good_mm:
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
if (tsk->signal->oom_score_adj == OOM_SCORE_ADJ_MIN)
atomic_inc(&mm->oom_disable_count);
tsk->mm = mm;
tsk->active_mm = mm;
return 0;
fail_nomem:
return retval;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: smb2_hdr_assemble(struct smb2_sync_hdr *shdr, __le16 smb2_cmd,
const struct cifs_tcon *tcon)
{
shdr->ProtocolId = SMB2_PROTO_NUMBER;
shdr->StructureSize = cpu_to_le16(64);
shdr->Command = smb2_cmd;
if (tcon && tcon->ses && tcon->ses->server) {
struct TCP_Server_Info *server = tcon->ses->server;
spin_lock(&server->req_lock);
/* Request up to 2 credits but don't go over the limit. */
if (server->credits >= server->max_credits)
shdr->CreditRequest = cpu_to_le16(0);
else
shdr->CreditRequest = cpu_to_le16(
min_t(int, server->max_credits -
server->credits, 2));
spin_unlock(&server->req_lock);
} else {
shdr->CreditRequest = cpu_to_le16(2);
}
shdr->ProcessId = cpu_to_le32((__u16)current->tgid);
if (!tcon)
goto out;
/* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
/* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
if ((tcon->ses) && (tcon->ses->server) &&
(tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
shdr->CreditCharge = cpu_to_le16(1);
/* else CreditCharge MBZ */
shdr->TreeId = tcon->tid;
/* Uid is not converted */
if (tcon->ses)
shdr->SessionId = tcon->ses->Suid;
/*
* If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
* to pass the path on the Open SMB prefixed by \\server\share.
* Not sure when we would need to do the augmented path (if ever) and
* setting this flag breaks the SMB2 open operation since it is
* illegal to send an empty path name (without \\server\share prefix)
* when the DFS flag is set in the SMB open header. We could
* consider setting the flag on all operations other than open
* but it is safer to net set it for now.
*/
/* if (tcon->share_flags & SHI1005_FLAGS_DFS)
shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
if (tcon->ses && tcon->ses->server && tcon->ses->server->sign &&
!encryption_required(tcon))
shdr->Flags |= SMB2_FLAGS_SIGNED;
out:
return;
}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AcpiNsTerminate (
void)
{
ACPI_STATUS Status;
ACPI_FUNCTION_TRACE (NsTerminate);
#ifdef ACPI_EXEC_APP
{
ACPI_OPERAND_OBJECT *Prev;
ACPI_OPERAND_OBJECT *Next;
/* Delete any module-level code blocks */
Next = AcpiGbl_ModuleCodeList;
while (Next)
{
Prev = Next;
Next = Next->Method.Mutex;
Prev->Method.Mutex = NULL; /* Clear the Mutex (cheated) field */
AcpiUtRemoveReference (Prev);
}
}
#endif
/*
* Free the entire namespace -- all nodes and all objects
* attached to the nodes
*/
AcpiNsDeleteNamespaceSubtree (AcpiGbl_RootNode);
/* Delete any objects attached to the root node */
Status = AcpiUtAcquireMutex (ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE (Status))
{
return_VOID;
}
AcpiNsDeleteNode (AcpiGbl_RootNode);
(void) AcpiUtReleaseMutex (ACPI_MTX_NAMESPACE);
ACPI_DEBUG_PRINT ((ACPI_DB_INFO, "Namespace freed\n"));
return_VOID;
}
CWE ID: CWE-755
Target: 1
Example 2:
Code: static int magicmouse_setup_input(struct input_dev *input, struct hid_device *hdev)
{
int error;
__set_bit(EV_KEY, input->evbit);
if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) {
__set_bit(BTN_LEFT, input->keybit);
__set_bit(BTN_RIGHT, input->keybit);
if (emulate_3button)
__set_bit(BTN_MIDDLE, input->keybit);
__set_bit(EV_REL, input->evbit);
__set_bit(REL_X, input->relbit);
__set_bit(REL_Y, input->relbit);
if (emulate_scroll_wheel) {
__set_bit(REL_WHEEL, input->relbit);
__set_bit(REL_HWHEEL, input->relbit);
}
} else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */
/* input->keybit is initialized with incorrect button info
* for Magic Trackpad. There really is only one physical
* button (BTN_LEFT == BTN_MOUSE). Make sure we don't
* advertise buttons that don't exist...
*/
__clear_bit(BTN_RIGHT, input->keybit);
__clear_bit(BTN_MIDDLE, input->keybit);
__set_bit(BTN_MOUSE, input->keybit);
__set_bit(BTN_TOOL_FINGER, input->keybit);
__set_bit(BTN_TOOL_DOUBLETAP, input->keybit);
__set_bit(BTN_TOOL_TRIPLETAP, input->keybit);
__set_bit(BTN_TOOL_QUADTAP, input->keybit);
__set_bit(BTN_TOOL_QUINTTAP, input->keybit);
__set_bit(BTN_TOUCH, input->keybit);
__set_bit(INPUT_PROP_POINTER, input->propbit);
__set_bit(INPUT_PROP_BUTTONPAD, input->propbit);
}
__set_bit(EV_ABS, input->evbit);
error = input_mt_init_slots(input, 16, 0);
if (error)
return error;
input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, 255 << 2,
4, 0);
input_set_abs_params(input, ABS_MT_TOUCH_MINOR, 0, 255 << 2,
4, 0);
input_set_abs_params(input, ABS_MT_ORIENTATION, -31, 32, 1, 0);
/* Note: Touch Y position from the device is inverted relative
* to how pointer motion is reported (and relative to how USB
* HID recommends the coordinates work). This driver keeps
* the origin at the same position, and just uses the additive
* inverse of the reported Y.
*/
if (input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE) {
input_set_abs_params(input, ABS_MT_POSITION_X,
MOUSE_MIN_X, MOUSE_MAX_X, 4, 0);
input_set_abs_params(input, ABS_MT_POSITION_Y,
MOUSE_MIN_Y, MOUSE_MAX_Y, 4, 0);
input_abs_set_res(input, ABS_MT_POSITION_X,
MOUSE_RES_X);
input_abs_set_res(input, ABS_MT_POSITION_Y,
MOUSE_RES_Y);
} else { /* USB_DEVICE_ID_APPLE_MAGICTRACKPAD */
input_set_abs_params(input, ABS_X, TRACKPAD_MIN_X,
TRACKPAD_MAX_X, 4, 0);
input_set_abs_params(input, ABS_Y, TRACKPAD_MIN_Y,
TRACKPAD_MAX_Y, 4, 0);
input_set_abs_params(input, ABS_MT_POSITION_X,
TRACKPAD_MIN_X, TRACKPAD_MAX_X, 4, 0);
input_set_abs_params(input, ABS_MT_POSITION_Y,
TRACKPAD_MIN_Y, TRACKPAD_MAX_Y, 4, 0);
input_abs_set_res(input, ABS_X, TRACKPAD_RES_X);
input_abs_set_res(input, ABS_Y, TRACKPAD_RES_Y);
input_abs_set_res(input, ABS_MT_POSITION_X,
TRACKPAD_RES_X);
input_abs_set_res(input, ABS_MT_POSITION_Y,
TRACKPAD_RES_Y);
}
input_set_events_per_packet(input, 60);
if (report_undeciphered) {
__set_bit(EV_MSC, input->evbit);
__set_bit(MSC_RAW, input->mscbit);
}
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: h_conn(const int fd, const short which, conn c)
{
if (fd != c->fd) {
twarnx("Argh! event fd doesn't match conn fd.");
close(fd);
return conn_close(c);
}
switch (which) {
case EV_TIMEOUT:
h_conn_timeout(c);
event_add(&c->evq, NULL); /* seems to be necessary */
break;
case EV_READ:
/* fall through... */
case EV_WRITE:
/* fall through... */
default:
h_conn_data(c);
}
while (cmd_data_ready(c) && (c->cmd_len = cmd_len(c))) do_cmd(c);
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long Cluster::Parse(long long& pos, long& len) const
{
long status = Load(pos, len);
if (status < 0)
return status;
assert(m_pos >= m_element_start);
assert(m_timecode >= 0);
const long long cluster_stop =
(m_element_size < 0) ? -1 : m_element_start + m_element_size;
if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
return 1; //nothing else to do
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
status = pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
pos = m_pos;
for (;;)
{
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((total >= 0) && (pos >= total))
{
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return static_cast<long>(id);
if (id == 0) //weird
return E_FILE_FORMAT_INVALID;
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster or Cues ID
{
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
pos += len; //consume ID field
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; //consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) //weird
continue;
const long long block_stop = pos + size;
if (cluster_stop >= 0)
{
if (block_stop > cluster_stop)
{
if ((id == 0x20) || (id == 0x23))
return E_FILE_FORMAT_INVALID;
pos = cluster_stop;
break;
}
}
else if ((total >= 0) && (block_stop > total))
{
m_element_size = total - m_element_start;
pos = total;
break;
}
else if (block_stop > avail)
{
len = static_cast<long>(size);
return E_BUFFER_NOT_FULL;
}
Cluster* const this_ = const_cast<Cluster*>(this);
if (id == 0x20) //BlockGroup
return this_->ParseBlockGroup(size, pos, len);
if (id == 0x23) //SimpleBlock
return this_->ParseSimpleBlock(size, pos, len);
pos += size; //consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert(m_element_size > 0);
m_pos = pos;
assert((cluster_stop < 0) || (m_pos <= cluster_stop));
if (m_entries_count > 0)
{
const long idx = m_entries_count - 1;
const BlockEntry* const pLast = m_entries[idx];
assert(pLast);
const Block* const pBlock = pLast->GetBlock();
assert(pBlock);
const long long start = pBlock->m_start;
if ((total >= 0) && (start > total))
return -1; //defend against trucated stream
const long long size = pBlock->m_size;
const long long stop = start + size;
assert((cluster_stop < 0) || (stop <= cluster_stop));
if ((total >= 0) && (stop > total))
return -1; //defend against trucated stream
}
return 1; //no more entries
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void EditorClientBlackBerry::toggleGrammarChecking()
{
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: static unsigned int subpel_variance_ref(const uint8_t *ref, const uint8_t *src,
int l2w, int l2h, int xoff, int yoff,
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++) {
const int a1 = ref[(w + 1) * (y + 0) + x + 0];
const int a2 = ref[(w + 1) * (y + 0) + x + 1];
const int b1 = ref[(w + 1) * (y + 1) + x + 0];
const int b2 = ref[(w + 1) * (y + 1) + x + 1];
const int a = a1 + (((a2 - a1) * xoff + 8) >> 4);
const int b = b1 + (((b2 - b1) * xoff + 8) >> 4);
const int r = a + (((b - a) * yoff + 8) >> 4);
int diff = r - src[w * y + x];
se += diff;
sse += diff * diff;
}
}
*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: static int __perf_event_overflow(struct perf_event *event, int nmi,
int throttle, struct perf_sample_data *data,
struct pt_regs *regs)
{
int events = atomic_read(&event->event_limit);
struct hw_perf_event *hwc = &event->hw;
int ret = 0;
/*
* Non-sampling counters might still use the PMI to fold short
* hardware counters, ignore those.
*/
if (unlikely(!is_sampling_event(event)))
return 0;
if (unlikely(hwc->interrupts >= max_samples_per_tick)) {
if (throttle) {
hwc->interrupts = MAX_INTERRUPTS;
perf_log_throttle(event, 0);
ret = 1;
}
} else
hwc->interrupts++;
if (event->attr.freq) {
u64 now = perf_clock();
s64 delta = now - hwc->freq_time_stamp;
hwc->freq_time_stamp = now;
if (delta > 0 && delta < 2*TICK_NSEC)
perf_adjust_period(event, delta, hwc->last_period);
}
/*
* XXX event_limit might not quite work as expected on inherited
* events
*/
event->pending_kill = POLL_IN;
if (events && atomic_dec_and_test(&event->event_limit)) {
ret = 1;
event->pending_kill = POLL_HUP;
if (nmi) {
event->pending_disable = 1;
irq_work_queue(&event->pending);
} else
perf_event_disable(event);
}
if (event->overflow_handler)
event->overflow_handler(event, nmi, data, regs);
else
perf_event_output(event, nmi, data, regs);
if (event->fasync && event->pending_kill) {
if (nmi) {
event->pending_wakeup = 1;
irq_work_queue(&event->pending);
} else
perf_event_wakeup(event);
}
return ret;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void reflectedNameAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectPythonV8Internal::reflectedNameAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: FaviconWebUIHandler::FaviconWebUIHandler() {
}
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: long mkvparser::UnserializeString(
IMkvReader* pReader,
long long pos,
long long size_,
char*& str)
{
delete[] str;
str = NULL;
if (size_ >= LONG_MAX) //we need (size+1) chars
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
str = new (std::nothrow) char[size+1];
if (str == NULL)
return -1;
unsigned char* const buf = reinterpret_cast<unsigned char*>(str);
const long status = pReader->Read(pos, size, buf);
if (status)
{
delete[] str;
str = NULL;
return status;
}
str[size] = '\0';
return 0; //success
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void handle_p_frame_png(PNGDecContext *s, AVFrame *p)
{
int i, j;
uint8_t *pd = p->data[0];
uint8_t *pd_last = s->last_picture.f->data[0];
int ls = FFMIN(av_image_get_linesize(p->format, s->width, 0), s->width * s->bpp);
ff_thread_await_progress(&s->last_picture, INT_MAX, 0);
for (j = 0; j < s->height; j++) {
for (i = 0; i < ls; i++)
pd[i] += pd_last[i];
pd += s->image_linesize;
pd_last += s->image_linesize;
}
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: l2tp_accm_print(netdissect_options *ndo, const u_char *dat)
{
const uint16_t *ptr = (const uint16_t *)dat;
uint16_t val_h, val_l;
ptr++; /* skip "Reserved" */
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "send=%08x ", (val_h<<16) + val_l));
val_h = EXTRACT_16BITS(ptr); ptr++;
val_l = EXTRACT_16BITS(ptr); ptr++;
ND_PRINT((ndo, "recv=%08x ", (val_h<<16) + val_l));
}
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> vertexAttribAndUniformHelperf(const v8::Arguments& args,
FunctionToCall functionToCall) {
if (args.Length() != 2)
return V8Proxy::throwNotEnoughArgumentsError();
bool ok = false;
int index = -1;
WebGLUniformLocation* location = 0;
if (isFunctionToCallForAttribute(functionToCall))
index = toInt32(args[0]);
else {
if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLUniformLocation::HasInstance(args[0])) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
location = toWebGLUniformLocation(args[0], ok);
}
WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder());
if (V8Float32Array::HasInstance(args[1])) {
Float32Array* array = V8Float32Array::toNative(args[1]->ToObject());
ASSERT(array != NULL);
ExceptionCode ec = 0;
switch (functionToCall) {
case kUniform1v: context->uniform1fv(location, array, ec); break;
case kUniform2v: context->uniform2fv(location, array, ec); break;
case kUniform3v: context->uniform3fv(location, array, ec); break;
case kUniform4v: context->uniform4fv(location, array, ec); break;
case kVertexAttrib1v: context->vertexAttrib1fv(index, array); break;
case kVertexAttrib2v: context->vertexAttrib2fv(index, array); break;
case kVertexAttrib3v: context->vertexAttrib3fv(index, array); break;
case kVertexAttrib4v: context->vertexAttrib4fv(index, array); break;
default: ASSERT_NOT_REACHED(); break;
}
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
if (args[1].IsEmpty() || !args[1]->IsArray()) {
V8Proxy::throwTypeError();
return notHandledByInterceptor();
}
v8::Handle<v8::Array> array =
v8::Local<v8::Array>::Cast(args[1]);
uint32_t len = array->Length();
float* data = jsArrayToFloatArray(array, len);
if (!data) {
V8Proxy::setDOMException(SYNTAX_ERR, args.GetIsolate());
return notHandledByInterceptor();
}
ExceptionCode ec = 0;
switch (functionToCall) {
case kUniform1v: context->uniform1fv(location, data, len, ec); break;
case kUniform2v: context->uniform2fv(location, data, len, ec); break;
case kUniform3v: context->uniform3fv(location, data, len, ec); break;
case kUniform4v: context->uniform4fv(location, data, len, ec); break;
case kVertexAttrib1v: context->vertexAttrib1fv(index, data, len); break;
case kVertexAttrib2v: context->vertexAttrib2fv(index, data, len); break;
case kVertexAttrib3v: context->vertexAttrib3fv(index, data, len); break;
case kVertexAttrib4v: context->vertexAttrib4fv(index, data, len); break;
default: ASSERT_NOT_REACHED(); break;
}
fastFree(data);
if (ec)
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Undefined();
}
CWE ID:
Target: 1
Example 2:
Code: int qeth_do_send_packet_fast(struct qeth_card *card,
struct qeth_qdio_out_q *queue, struct sk_buff *skb,
struct qeth_hdr *hdr, int elements_needed,
int offset, int hd_len)
{
struct qeth_qdio_out_buffer *buffer;
int index;
/* spin until we get the queue ... */
while (atomic_cmpxchg(&queue->state, QETH_OUT_Q_UNLOCKED,
QETH_OUT_Q_LOCKED) != QETH_OUT_Q_UNLOCKED);
/* ... now we've got the queue */
index = queue->next_buf_to_fill;
buffer = queue->bufs[queue->next_buf_to_fill];
/*
* check if buffer is empty to make sure that we do not 'overtake'
* ourselves and try to fill a buffer that is already primed
*/
if (atomic_read(&buffer->state) != QETH_QDIO_BUF_EMPTY)
goto out;
queue->next_buf_to_fill = (queue->next_buf_to_fill + 1) %
QDIO_MAX_BUFFERS_PER_Q;
atomic_set(&queue->state, QETH_OUT_Q_UNLOCKED);
qeth_fill_buffer(queue, buffer, skb, hdr, offset, hd_len);
qeth_flush_buffers(queue, index, 1);
return 0;
out:
atomic_set(&queue->state, QETH_OUT_Q_UNLOCKED);
return -EBUSY;
}
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: DidFinishNavigation(NavigationHandle* handle) {
if (handle->GetFrameTreeNodeId() != frame_tree_node_id_)
return;
if (!handle->HasCommitted())
return;
if (handle->GetRenderFrameHost()->GetSiteInstance() != parent_site_instance_)
return;
if (!handle->GetURL().IsAboutBlank())
return;
if (!handle->GetRenderFrameHost()->PrepareForInnerWebContentsAttach()) {
filter_->ResumeAttachOrDestroy(element_instance_id_,
MSG_ROUTING_NONE /* no plugin frame */);
}
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(&ExtensionsGuestViewMessageFilter::ResumeAttachOrDestroy,
filter_, element_instance_id_,
handle->GetRenderFrameHost()->GetRoutingID()));
}
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: SeekHead::~SeekHead()
{
delete[] m_entries;
delete[] m_void_elements;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static __init int veth_init(void)
{
return rtnl_link_register(&veth_link_ops);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int gfs2_block_truncate_page(struct address_space *mapping, loff_t from)
{
struct inode *inode = mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
unsigned long index = from >> PAGE_CACHE_SHIFT;
unsigned offset = from & (PAGE_CACHE_SIZE-1);
unsigned blocksize, iblock, length, pos;
struct buffer_head *bh;
struct page *page;
int err;
page = grab_cache_page(mapping, index);
if (!page)
return 0;
blocksize = inode->i_sb->s_blocksize;
length = blocksize - (offset & (blocksize - 1));
iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
if (!page_has_buffers(page))
create_empty_buffers(page, blocksize, 0);
/* Find the buffer that contains "offset" */
bh = page_buffers(page);
pos = blocksize;
while (offset >= pos) {
bh = bh->b_this_page;
iblock++;
pos += blocksize;
}
err = 0;
if (!buffer_mapped(bh)) {
gfs2_block_map(inode, iblock, bh, 0);
/* unmapped? It's a hole - nothing to do */
if (!buffer_mapped(bh))
goto unlock;
}
/* Ok, it's mapped. Make sure it's up-to-date */
if (PageUptodate(page))
set_buffer_uptodate(bh);
if (!buffer_uptodate(bh)) {
err = -EIO;
ll_rw_block(READ, 1, &bh);
wait_on_buffer(bh);
/* Uhhuh. Read error. Complain and punt. */
if (!buffer_uptodate(bh))
goto unlock;
err = 0;
}
if (!gfs2_is_writeback(ip))
gfs2_trans_add_bh(ip->i_gl, bh, 0);
zero_user(page, offset, length);
mark_buffer_dirty(bh);
unlock:
unlock_page(page);
page_cache_release(page);
return err;
}
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 ManifestUmaUtil::FetchFailed(FetchFailureReason reason) {
ManifestFetchResultType fetch_result_type = MANIFEST_FETCH_RESULT_TYPE_COUNT;
switch (reason) {
case FETCH_EMPTY_URL:
fetch_result_type = MANIFEST_FETCH_ERROR_EMPTY_URL;
break;
case FETCH_UNSPECIFIED_REASON:
fetch_result_type = MANIFEST_FETCH_ERROR_UNSPECIFIED;
break;
}
DCHECK_NE(fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT);
UMA_HISTOGRAM_ENUMERATION(kUMANameFetchResult,
fetch_result_type,
MANIFEST_FETCH_RESULT_TYPE_COUNT);
}
CWE ID:
Target: 1
Example 2:
Code: ZEND_API zend_string *zend_get_executed_filename_ex(void) /* {{{ */
{
zend_execute_data *ex = EG(current_execute_data);
while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) {
ex = ex->prev_execute_data;
}
if (ex) {
return ex->func->op_array.filename;
} else {
return NULL;
}
}
/* }}} */
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int Reverb_command(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData){
android::ReverbContext * pContext = (android::ReverbContext *) self;
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
if (pContext == NULL){
ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
return -EINVAL;
}
switch (cmdCode){
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_INIT: ERROR");
return -EINVAL;
}
*(int *) pReplyData = 0;
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_CONFIG: ERROR");
return -EINVAL;
}
*(int *) pReplyData = android::Reverb_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_CONFIG: ERROR");
return -EINVAL;
}
android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Reverb_setConfig(pContext, &pContext->config);
break;
case EFFECT_CMD_GET_PARAM:{
effect_param_t *p = (effect_param_t *)pCmdData;
if (SIZE_MAX - sizeof(effect_param_t) < (size_t)p->psize) {
android_errorWriteLog(0x534e4554, "26347509");
return -EINVAL;
}
if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
cmdSize < (sizeof(effect_param_t) + p->psize) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (sizeof(effect_param_t) + p->psize)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
p = (effect_param_t *)pReplyData;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Reverb_getParameter(pContext,
(void *)p->data,
&p->vsize,
p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
} break;
case EFFECT_CMD_SET_PARAM:{
if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *) pCmdData;
if (p->psize != sizeof(int32_t)){
ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
return -EINVAL;
}
*(int *)pReplyData = android::Reverb_setParameter(pContext,
(void *)p->data,
p->data + p->psize);
} break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_TRUE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_TRUE;
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
pContext->SamplesToExitCount =
(ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_FALSE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_FALSE;
break;
case EFFECT_CMD_SET_VOLUME:
if (pCmdData == NULL ||
cmdSize != 2 * sizeof(uint32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_VOLUME: ERROR");
return -EINVAL;
}
if (pReplyData != NULL) { // we have volume control
pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
*(uint32_t *)pReplyData = (1 << 24);
*((uint32_t *)pReplyData + 1) = (1 << 24);
if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
}
} else { // we don't have volume control
pContext->leftVolume = REVERB_UNIT_VOLUME;
pContext->rightVolume = REVERB_UNIT_VOLUME;
pContext->volumeMode = android::REVERB_VOLUME_OFF;
}
ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
pContext->leftVolume, pContext->rightVolume, pContext->volumeMode);
break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"DEFAULT start %d ERROR",cmdCode);
return -EINVAL;
}
return 0;
} /* end Reverb_command */
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: XdmcpGenerateKey (XdmAuthKeyPtr key)
{
#ifndef HAVE_ARC4RANDOM_BUF
long lowbits, highbits;
srandom ((int)getpid() ^ time((Time_t *)0));
highbits = random ();
highbits = random ();
getbits (lowbits, key->data);
getbits (highbits, key->data + 4);
#else
arc4random_buf(key->data, 8);
#endif
}
CWE ID: CWE-320
Target: 1
Example 2:
Code: static void __exit ext4_exit_fs(void)
{
ext4_destroy_lazyinit_thread();
unregister_as_ext2();
unregister_as_ext3();
unregister_filesystem(&ext4_fs_type);
destroy_inodecache();
ext4_exit_xattr();
ext4_exit_mballoc();
ext4_exit_feat_adverts();
remove_proc_entry("fs/ext4", NULL);
kset_unregister(ext4_kset);
ext4_exit_system_zone();
ext4_exit_pageio();
}
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: bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
if (!nestable_tasks_allowed_ ||
!SweepDelayedWorkQueueAndReturnTrueIfStillHasWork()) {
recent_time_ = *next_delayed_work_time = TimeTicks();
return false;
}
TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
if (next_run_time > recent_time_) {
recent_time_ = TimeTicks::Now(); // Get a better view of Now();
if (next_run_time > recent_time_) {
*next_delayed_work_time = next_run_time;
return false;
}
}
PendingTask pending_task =
std::move(const_cast<PendingTask&>(delayed_work_queue_.top()));
delayed_work_queue_.pop();
if (SweepDelayedWorkQueueAndReturnTrueIfStillHasWork())
*next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
return DeferOrRunPendingTask(std::move(pending_task));
}
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: rdpsnd_process_training(STREAM in)
{
uint16 tick;
uint16 packsize;
STREAM out;
in_uint16_le(in, tick);
in_uint16_le(in, packsize);
logger(Sound, Debug, "rdpsnd_process_training(), tick=0x%04x", (unsigned) tick);
out = rdpsnd_init_packet(SNDC_TRAINING, 4);
out_uint16_le(out, tick);
out_uint16_le(out, packsize);
s_mark_end(out);
rdpsnd_send(out);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void debugMutexEnter(sqlite3_mutex *pX){
sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
p->cnt++;
}
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 rpng2_win_init()
{
ulg i;
ulg rowbytes = rpng2_info.rowbytes;
Trace((stderr, "beginning rpng2_win_init()\n"))
Trace((stderr, " rowbytes = %d\n", rpng2_info.rowbytes))
Trace((stderr, " width = %ld\n", rpng2_info.width))
Trace((stderr, " height = %ld\n", rpng2_info.height))
rpng2_info.image_data = (uch *)malloc(rowbytes * rpng2_info.height);
if (!rpng2_info.image_data) {
readpng2_cleanup(&rpng2_info);
return;
}
rpng2_info.row_pointers = (uch **)malloc(rpng2_info.height * sizeof(uch *));
if (!rpng2_info.row_pointers) {
free(rpng2_info.image_data);
rpng2_info.image_data = NULL;
readpng2_cleanup(&rpng2_info);
return;
}
for (i = 0; i < rpng2_info.height; ++i)
rpng2_info.row_pointers[i] = rpng2_info.image_data + i*rowbytes;
/*---------------------------------------------------------------------------
Do the basic Windows initialization stuff, make the window, and fill it
with the user-specified, file-specified or default background color.
---------------------------------------------------------------------------*/
if (rpng2_win_create_window()) {
readpng2_cleanup(&rpng2_info);
return;
}
rpng2_info.state = kWindowInit;
}
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 RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderBox::styleDidChange(diff, oldStyle);
RenderStyle* newStyle = style();
if (!isAnonymousBlock()) {
for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
RenderBoxModelObject* nextCont = currCont->continuation();
currCont->setContinuation(0);
currCont->setStyle(newStyle);
currCont->setContinuation(nextCont);
}
}
if (FastTextAutosizer* textAutosizer = document().fastTextAutosizer())
textAutosizer->record(this);
propagateStyleToAnonymousChildren(true);
invalidateLineHeight();
m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
Vector<ImageResource*> images;
appendImagesFromStyle(images, *newStyle);
if (images.isEmpty())
ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
else
ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void OobeUI::GetLocalizedStrings(base::DictionaryValue* localized_strings) {
for (size_t i = 0; i < handlers_.size(); ++i) {
handlers_[i]->GetLocalizedStrings(localized_strings);
}
const std::string& app_locale = g_browser_process->GetApplicationLocale();
webui::SetLoadTimeDataDefaults(app_locale, localized_strings);
kiosk_app_menu_handler_->GetLocalizedStrings(localized_strings);
#if defined(GOOGLE_CHROME_BUILD)
localized_strings->SetString("buildType", "chrome");
#else
localized_strings->SetString("buildType", "chromium");
#endif
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableBootAnimation)) {
localized_strings->SetString("bootIntoWallpaper", "on");
} else {
localized_strings->SetString("bootIntoWallpaper", "off");
}
bool keyboard_driven_oobe =
system::InputDeviceSettings::Get()->ForceKeyboardDrivenUINavigation();
localized_strings->SetString("highlightStrength",
keyboard_driven_oobe ? "strong" : "normal");
bool new_kiosk_ui = KioskAppMenuHandler::EnableNewKioskUI();
localized_strings->SetString("newKioskUI", new_kiosk_ui ? "on" : "off");
}
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 InspectorNetworkAgent::GetResponseBodyBlob(
const String& request_id,
std::unique_ptr<GetResponseBodyCallback> callback) {
NetworkResourcesData::ResourceData const* resource_data =
resources_data_->Data(request_id);
BlobDataHandle* blob = resource_data->DownloadedFileBlob();
InspectorFileReaderLoaderClient* client = new InspectorFileReaderLoaderClient(
blob, resource_data->MimeType(), resource_data->TextEncodingName(),
std::move(callback));
if (worker_global_scope_) {
client->Start(worker_global_scope_);
return;
}
DCHECK(inspected_frames_);
LocalFrame* frame = IdentifiersFactory::FrameById(inspected_frames_,
resource_data->FrameId());
Document* document = frame->GetDocument();
client->Start(document);
}
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: InterstitialPage* WebContentsImpl::GetInterstitialPage() const {
return GetRenderManager()->interstitial_page();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int swap_show(struct seq_file *swap, void *v)
{
struct swap_info_struct *si = v;
struct file *file;
int len;
if (si == SEQ_START_TOKEN) {
seq_puts(swap,"Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
return 0;
}
file = si->swap_file;
len = seq_path(swap, &file->f_path, " \t\n\\");
seq_printf(swap, "%*s%s\t%u\t%u\t%d\n",
len < 40 ? 40 - len : 1, " ",
S_ISBLK(file->f_path.dentry->d_inode->i_mode) ?
"partition" : "file\t",
si->pages << (PAGE_SHIFT - 10),
si->inuse_pages << (PAGE_SHIFT - 10),
si->prio);
return 0;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GDataDirectory::~GDataDirectory() {
RemoveChildren();
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) {
sandbox::ResultCode result;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
sandbox::TargetPolicy::HANDLES_DUP_ANY,
L"Section");
if (result != sandbox::SBOX_ALL_OK) {
NOTREACHED();
return false;
}
policy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0);
sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
if (base::win::GetVersion() > base::win::VERSION_XP) {
initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
}
policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableAltWinstation);
if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) {
DLOG(WARNING) << "Failed to apply desktop security to the renderer";
}
AddGenericDllEvictionPolicy(policy);
return true;
}
CWE ID:
Target: 1
Example 2:
Code: void QQuickWebView::focusInEvent(QFocusEvent* event)
{
Q_D(QQuickWebView);
d->pageView->eventHandler()->handleFocusInEvent(event);
}
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: String Element::nodeNamePreservingCase() const
{
return m_tagName.toString();
}
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: lha_read_file_header_1(struct archive_read *a, struct lha *lha)
{
const unsigned char *p;
size_t extdsize;
int i, err, err2;
int namelen, padding;
unsigned char headersum, sum_calculated;
err = ARCHIVE_OK;
if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)
return (truncated_error(a));
lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;
headersum = p[H1_HEADER_SUM_OFFSET];
/* Note: An extended header size is included in a compsize. */
lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);
lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);
lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);
namelen = p[H1_NAME_LEN_OFFSET];
/* Calculate a padding size. The result will be normally 0 only(?) */
padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;
if (namelen > 230 || padding < 0)
goto invalid;
if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)
return (truncated_error(a));
for (i = 0; i < namelen; i++) {
if (p[i + H1_FILE_NAME_OFFSET] == 0xff)
goto invalid;/* Invalid filename. */
}
archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);
lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);
lha->setflag |= CRC_IS_SET;
sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);
/* Consume used bytes but not include `next header size' data
* since it will be consumed in lha_read_file_extended_header(). */
__archive_read_consume(a, lha->header_size - 2);
/* Read extended headers */
err2 = lha_read_file_extended_header(a, lha, NULL, 2,
(size_t)(lha->compsize + 2), &extdsize);
if (err2 < ARCHIVE_WARN)
return (err2);
if (err2 < err)
err = err2;
/* Get a real compressed file size. */
lha->compsize -= extdsize - 2;
if (sum_calculated != headersum) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"LHa header sum error");
return (ARCHIVE_FATAL);
}
return (err);
invalid:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid LHa header");
return (ARCHIVE_FATAL);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: ExecuteBrowserCommandObserver::ExecuteBrowserCommandObserver(
AutomationProvider* automation,
IPC::Message* reply_message,
bool use_json_interface)
: automation_(automation->AsWeakPtr()),
notification_type_(content::NOTIFICATION_ALL),
reply_message_(reply_message),
use_json_interface_(use_json_interface) {
}
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 GLES2Implementation::DestroyImageCHROMIUMHelper(GLuint image_id) {
helper_->CommandBufferHelper::Flush();
gpu_control_->DestroyImage(image_id);
}
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: const Track* Tracks::GetTrackByNumber(long tn) const
{
if (tn < 0)
return NULL;
Track** i = m_trackEntries;
Track** const j = m_trackEntriesEnd;
while (i != j)
{
Track* const pTrack = *i++;
if (pTrack == NULL)
continue;
if (tn == pTrack->GetNumber())
return pTrack;
}
return NULL; //not found
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
int blocks_to_boundary)
{
unsigned int count = 0;
/*
* Simple case, [t,d]Indirect block(s) has not allocated yet
* then it's clear blocks on that path have not allocated
*/
if (k > 0) {
/* right now we don't handle cross boundary allocation */
if (blks < blocks_to_boundary + 1)
count += blks;
else
count += blocks_to_boundary + 1;
return count;
}
count++;
while (count < blks && count <= blocks_to_boundary &&
le32_to_cpu(*(branch[0].p + count)) == 0) {
count++;
}
return count;
}
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: PlatformTouchPoint::PlatformTouchPoint(const BlackBerry::Platform::TouchPoint& point)
: m_id(point.m_id)
, m_screenPos(point.m_screenPos)
, m_pos(point.m_pos)
{
switch (point.m_state) {
case BlackBerry::Platform::TouchPoint::TouchReleased:
m_state = TouchReleased;
break;
case BlackBerry::Platform::TouchPoint::TouchMoved:
m_state = TouchMoved;
break;
case BlackBerry::Platform::TouchPoint::TouchPressed:
m_state = TouchPressed;
break;
case BlackBerry::Platform::TouchPoint::TouchStationary:
m_state = TouchStationary;
break;
default:
m_state = TouchStationary; // make sure m_state is initialized
BLACKBERRY_ASSERT(false);
break;
}
}
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 llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name;
const int nonblock = flags & MSG_DONTWAIT;
struct sk_buff *skb = NULL;
struct sock *sk = sock->sk;
struct llc_sock *llc = llc_sk(sk);
unsigned long cpu_flags;
size_t copied = 0;
u32 peek_seq = 0;
u32 *seq;
unsigned long used;
int target; /* Read at least this many bytes */
long timeo;
lock_sock(sk);
copied = -ENOTCONN;
if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN))
goto out;
timeo = sock_rcvtimeo(sk, nonblock);
seq = &llc->copied_seq;
if (flags & MSG_PEEK) {
peek_seq = llc->copied_seq;
seq = &peek_seq;
}
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
copied = 0;
do {
u32 offset;
/*
* We need to check signals first, to get correct SIGURG
* handling. FIXME: Need to check this doesn't impact 1003.1g
* and move it down to the bottom of the loop
*/
if (signal_pending(current)) {
if (copied)
break;
copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
break;
}
/* Next get a buffer. */
skb = skb_peek(&sk->sk_receive_queue);
if (skb) {
offset = *seq;
goto found_ok_skb;
}
/* Well, if we have backlog, try to process it now yet. */
if (copied >= target && !sk->sk_backlog.tail)
break;
if (copied) {
if (sk->sk_err ||
sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
!timeo ||
(flags & MSG_PEEK))
break;
} else {
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
copied = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) {
if (!sock_flag(sk, SOCK_DONE)) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
copied = -ENOTCONN;
break;
}
break;
}
if (!timeo) {
copied = -EAGAIN;
break;
}
}
if (copied >= target) { /* Do not sleep, just process backlog. */
release_sock(sk);
lock_sock(sk);
} else
sk_wait_data(sk, &timeo);
if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) {
net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n",
current->comm,
task_pid_nr(current));
peek_seq = llc->copied_seq;
}
continue;
found_ok_skb:
/* Ok so how much can we use? */
used = skb->len - offset;
if (len < used)
used = len;
if (!(flags & MSG_TRUNC)) {
int rc = skb_copy_datagram_iovec(skb, offset,
msg->msg_iov, used);
if (rc) {
/* Exception. Bailout! */
if (!copied)
copied = -EFAULT;
break;
}
}
*seq += used;
copied += used;
len -= used;
/* For non stream protcols we get one packet per recvmsg call */
if (sk->sk_type != SOCK_STREAM)
goto copy_uaddr;
if (!(flags & MSG_PEEK)) {
spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags);
sk_eat_skb(sk, skb, false);
spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags);
*seq = 0;
}
/* Partial read */
if (used + offset < skb->len)
continue;
} while (len > 0);
out:
release_sock(sk);
return copied;
copy_uaddr:
if (uaddr != NULL && skb != NULL) {
memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr));
msg->msg_namelen = sizeof(*uaddr);
}
if (llc_sk(sk)->cmsg_flags)
llc_cmsg_rcv(msg, skb);
if (!(flags & MSG_PEEK)) {
spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags);
sk_eat_skb(sk, skb, false);
spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags);
*seq = 0;
}
goto out;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void UrlStringAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.Holder();
TestObject* impl = V8TestObject::ToImpl(holder);
V8SetReturnValueString(info, impl->GetURLAttribute(html_names::kReflectUrlAttributeAttr), info.GetIsolate());
}
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: delete_policy_2_svc(dpol_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;
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;
}
prime_arg = arg->name;
if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context,
rqst2name(rqstp),
ACL_DELETE, NULL, NULL)) {
log_unauth("kadm5_delete_policy", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_DELETE;
} else {
ret.code = kadm5_delete_policy((void *)handle, arg->name);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_delete_policy",
((prime_arg == NULL) ? "(null)" : prime_arg), errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
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 void ext4_end_io_work(struct work_struct *work)
{
ext4_io_end_t *io = container_of(work, ext4_io_end_t, work);
struct inode *inode = io->inode;
int ret = 0;
mutex_lock(&inode->i_mutex);
ret = ext4_end_io_nolock(io);
if (ret >= 0) {
if (!list_empty(&io->list))
list_del_init(&io->list);
ext4_free_io_end(io);
}
mutex_unlock(&inode->i_mutex);
}
CWE ID:
Target: 1
Example 2:
Code: bool NormalPageArena::PagesToBeSweptContains(Address address) {
for (BasePage* page = first_unswept_page_; page; page = page->Next()) {
if (page->Contains(address))
return true;
}
return false;
}
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 opj_bool pi_next_rlcp(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
res = &comp->resolutions[pi->resno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
if (!pi->tp_on) {
pi->poc.precno1 = res->pw * res->ph;
}
for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
return OPJ_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 int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c);
switch (type) {
case EVP_CTRL_INIT:
cctx->key_set = 0;
cctx->iv_set = 0;
cctx->L = 8;
cctx->M = 12;
cctx->tag_set = 0;
cctx->len_set = 0;
cctx->tls_aad_len = -1;
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
/* Save the AAD for later use */
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
cctx->tls_aad_len = arg;
{
uint16_t len =
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8
| EVP_CIPHER_CTX_buf_noconst(c)[arg - 1];
/* Correct length for explicit IV */
len -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
/* If decrypting correct for tag too */
if (!EVP_CIPHER_CTX_encrypting(c))
len -= cctx->M;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff;
}
/* Extra padding: tag appended to record */
return cctx->M;
case EVP_CTRL_CCM_SET_IV_FIXED:
/* Sanity check length */
if (arg != EVP_CCM_TLS_FIXED_IV_LEN)
return 0;
/* Just copy to first part of IV */
memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg);
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
arg = 15 - arg;
case EVP_CTRL_CCM_SET_L:
if (arg < 2 || arg > 8)
return 0;
cctx->L = arg;
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if ((arg & 1) || arg < 4 || arg > 16)
return 0;
if (EVP_CIPHER_CTX_encrypting(c) && ptr)
return 0;
if (ptr) {
cctx->tag_set = 1;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
}
cctx->M = arg;
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set)
return 0;
if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg))
return 0;
cctx->tag_set = 0;
cctx->iv_set = 0;
cctx->len_set = 0;
return 1;
case EVP_CTRL_COPY:
{
EVP_CIPHER_CTX *out = ptr;
EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out);
if (cctx->ccm.key) {
if (cctx->ccm.key != &cctx->ks)
return 0;
cctx_out->ccm.key = &cctx_out->ks;
}
return 1;
}
default:
return -1;
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: bool SocketStreamDispatcherHost::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(SocketStreamDispatcherHost, message, *message_was_ok)
IPC_MESSAGE_HANDLER(SocketStreamHostMsg_Connect, OnConnect)
IPC_MESSAGE_HANDLER(SocketStreamHostMsg_SendData, OnSendData)
IPC_MESSAGE_HANDLER(SocketStreamHostMsg_Close, OnCloseReq)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int svc_rdma_map_xdr(struct svcxprt_rdma *xprt,
struct xdr_buf *xdr,
struct svc_rdma_req_map *vec,
bool write_chunk_present)
{
int sge_no;
u32 sge_bytes;
u32 page_bytes;
u32 page_off;
int page_no;
if (xdr->len !=
(xdr->head[0].iov_len + xdr->page_len + xdr->tail[0].iov_len)) {
pr_err("svcrdma: %s: XDR buffer length error\n", __func__);
return -EIO;
}
/* Skip the first sge, this is for the RPCRDMA header */
sge_no = 1;
/* Head SGE */
vec->sge[sge_no].iov_base = xdr->head[0].iov_base;
vec->sge[sge_no].iov_len = xdr->head[0].iov_len;
sge_no++;
/* pages SGE */
page_no = 0;
page_bytes = xdr->page_len;
page_off = xdr->page_base;
while (page_bytes) {
vec->sge[sge_no].iov_base =
page_address(xdr->pages[page_no]) + page_off;
sge_bytes = min_t(u32, page_bytes, (PAGE_SIZE - page_off));
page_bytes -= sge_bytes;
vec->sge[sge_no].iov_len = sge_bytes;
sge_no++;
page_no++;
page_off = 0; /* reset for next time through loop */
}
/* Tail SGE */
if (xdr->tail[0].iov_len) {
unsigned char *base = xdr->tail[0].iov_base;
size_t len = xdr->tail[0].iov_len;
u32 xdr_pad = xdr_padsize(xdr->page_len);
if (write_chunk_present && xdr_pad) {
base += xdr_pad;
len -= xdr_pad;
}
if (len) {
vec->sge[sge_no].iov_base = base;
vec->sge[sge_no].iov_len = len;
sge_no++;
}
}
dprintk("svcrdma: %s: sge_no %d page_no %d "
"page_base %u page_len %u head_len %zu tail_len %zu\n",
__func__, sge_no, page_no, xdr->page_base, xdr->page_len,
xdr->head[0].iov_len, xdr->tail[0].iov_len);
vec->count = sge_no;
return 0;
}
CWE ID: CWE-404
Output: | 1 |
Here are some example code snippets. Analyze the following 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_get(
struct xfs_da_args *args)
{
struct xfs_bmbt_irec map[ATTR_RMTVALUE_MAPSIZE];
struct xfs_mount *mp = args->dp->i_mount;
struct xfs_buf *bp;
xfs_dablk_t lblkno = args->rmtblkno;
__uint8_t *dst = args->value;
int valuelen = args->valuelen;
int nmap;
int error;
int blkcnt = args->rmtblkcnt;
int i;
int offset = 0;
trace_xfs_attr_rmtval_get(args);
ASSERT(!(args->flags & ATTR_KERNOVAL));
while (valuelen > 0) {
nmap = ATTR_RMTVALUE_MAPSIZE;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
blkcnt, map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return error;
ASSERT(nmap >= 1);
for (i = 0; (i < nmap) && (valuelen > 0); i++) {
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT((map[i].br_startblock != DELAYSTARTBLOCK) &&
(map[i].br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map[i].br_startblock);
dblkcnt = XFS_FSB_TO_BB(mp, map[i].br_blockcount);
error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,
dblkno, dblkcnt, 0, &bp,
&xfs_attr3_rmt_buf_ops);
if (error)
return error;
error = xfs_attr_rmtval_copyout(mp, bp, args->dp->i_ino,
&offset, &valuelen,
&dst);
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map[i].br_blockcount;
blkcnt -= map[i].br_blockcount;
}
}
ASSERT(valuelen == 0);
return 0;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: static struct ffs_data *ffs_data_new(void)
{
struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
if (unlikely(!ffs))
return NULL;
ENTER();
atomic_set(&ffs->ref, 1);
atomic_set(&ffs->opened, 0);
ffs->state = FFS_READ_DESCRIPTORS;
mutex_init(&ffs->mutex);
spin_lock_init(&ffs->eps_lock);
init_waitqueue_head(&ffs->ev.waitq);
init_completion(&ffs->ep0req_completion);
/* XXX REVISIT need to update it in some places, or do we? */
ffs->ev.can_stall = 1;
return ffs;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int try_read_command(conn *c) {
assert(c != NULL);
assert(c->rcurr <= (c->rbuf + c->rsize));
assert(c->rbytes > 0);
if (c->protocol == negotiating_prot || c->transport == udp_transport) {
if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) {
c->protocol = binary_prot;
} else {
c->protocol = ascii_prot;
}
if (settings.verbose > 1) {
fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd,
prot_text(c->protocol));
}
}
if (c->protocol == binary_prot) {
/* Do we have the complete packet header? */
if (c->rbytes < sizeof(c->binary_header)) {
/* need more data! */
return 0;
} else {
#ifdef NEED_ALIGN
if (((long)(c->rcurr)) % 8 != 0) {
/* must realign input buffer */
memmove(c->rbuf, c->rcurr, c->rbytes);
c->rcurr = c->rbuf;
if (settings.verbose > 1) {
fprintf(stderr, "%d: Realign input buffer\n", c->sfd);
}
}
#endif
protocol_binary_request_header* req;
req = (protocol_binary_request_header*)c->rcurr;
if (settings.verbose > 1) {
/* Dump the packet before we convert it to host order */
int ii;
fprintf(stderr, "<%d Read binary protocol data:", c->sfd);
for (ii = 0; ii < sizeof(req->bytes); ++ii) {
if (ii % 4 == 0) {
fprintf(stderr, "\n<%d ", c->sfd);
}
fprintf(stderr, " 0x%02x", req->bytes[ii]);
}
fprintf(stderr, "\n");
}
c->binary_header = *req;
c->binary_header.request.keylen = ntohs(req->request.keylen);
c->binary_header.request.bodylen = ntohl(req->request.bodylen);
c->binary_header.request.cas = ntohll(req->request.cas);
if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) {
if (settings.verbose) {
fprintf(stderr, "Invalid magic: %x\n",
c->binary_header.request.magic);
}
conn_set_state(c, conn_closing);
return -1;
}
c->msgcurr = 0;
c->msgused = 0;
c->iovused = 0;
if (add_msghdr(c) != 0) {
out_string(c, "SERVER_ERROR out of memory");
return 0;
}
c->cmd = c->binary_header.request.opcode;
c->keylen = c->binary_header.request.keylen;
c->opaque = c->binary_header.request.opaque;
/* clear the returned cas value */
c->cas = 0;
dispatch_bin_command(c);
c->rbytes -= sizeof(c->binary_header);
c->rcurr += sizeof(c->binary_header);
}
} else {
char *el, *cont;
if (c->rbytes == 0)
return 0;
el = memchr(c->rcurr, '\n', c->rbytes);
if (!el) {
if (c->rbytes > 1024) {
/*
* We didn't have a '\n' in the first k. This _has_ to be a
* large multiget, if not we should just nuke the connection.
*/
char *ptr = c->rcurr;
while (*ptr == ' ') { /* ignore leading whitespaces */
++ptr;
}
if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) {
conn_set_state(c, conn_closing);
return 1;
}
}
return 0;
}
cont = el + 1;
if ((el - c->rcurr) > 1 && *(el - 1) == '\r') {
el--;
}
*el = '\0';
assert(cont <= (c->rcurr + c->rbytes));
process_command(c, c->rcurr);
c->rbytes -= (cont - c->rcurr);
c->rcurr = cont;
assert(c->rcurr <= (c->rbuf + c->rsize));
}
return 1;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: u32 secure_ipv6_port_ephemeral(const __be32 *saddr, const __be32 *daddr,
__be16 dport)
{
struct keydata *keyptr = get_keyptr();
u32 hash[12];
memcpy(hash, saddr, 16);
hash[4] = (__force u32)dport;
memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7);
return twothirdsMD4Transform((const __u32 *)daddr, hash);
}
CWE ID:
Target: 1
Example 2:
Code: mISDN_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct mISDN_sock *msk;
msk = container_of(ch, struct mISDN_sock, ch);
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s(%p, %x, %p)\n", __func__, ch, cmd, arg);
switch (cmd) {
case CLOSE_CHANNEL:
msk->sk.sk_state = MISDN_CLOSED;
break;
}
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: md5_state_update (struct md5_state *s, void *data, size_t len)
{
md_ctx_update(&s->ctx, data, len);
}
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: psf_binheader_readf (SF_PRIVATE *psf, char const *format, ...)
{ va_list argptr ;
sf_count_t *countptr, countdata ;
unsigned char *ucptr, sixteen_bytes [16] ;
unsigned int *intptr, intdata ;
unsigned short *shortptr ;
char *charptr ;
float *floatptr ;
double *doubleptr ;
char c ;
int byte_count = 0, count ;
if (! format)
return psf_ftell (psf) ;
va_start (argptr, format) ;
while ((c = *format++))
{ switch (c)
{ case 'e' : /* All conversions are now from LE to host. */
psf->rwf_endian = SF_ENDIAN_LITTLE ;
break ;
case 'E' : /* All conversions are now from BE to host. */
psf->rwf_endian = SF_ENDIAN_BIG ;
break ;
case 'm' : /* 4 byte marker value eg 'RIFF' */
intptr = va_arg (argptr, unsigned int*) ;
ucptr = (unsigned char*) intptr ;
byte_count += header_read (psf, ucptr, sizeof (int)) ;
*intptr = GET_MARKER (ucptr) ;
break ;
case 'h' :
intptr = va_arg (argptr, unsigned int*) ;
ucptr = (unsigned char*) intptr ;
byte_count += header_read (psf, sixteen_bytes, sizeof (sixteen_bytes)) ;
{ int k ;
intdata = 0 ;
for (k = 0 ; k < 16 ; k++)
intdata ^= sixteen_bytes [k] << k ;
}
*intptr = intdata ;
break ;
case '1' :
charptr = va_arg (argptr, char*) ;
*charptr = 0 ;
byte_count += header_read (psf, charptr, sizeof (char)) ;
break ;
case '2' : /* 2 byte value with the current endian-ness */
shortptr = va_arg (argptr, unsigned short*) ;
*shortptr = 0 ;
ucptr = (unsigned char*) shortptr ;
byte_count += header_read (psf, ucptr, sizeof (short)) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
*shortptr = GET_BE_SHORT (ucptr) ;
else
*shortptr = GET_LE_SHORT (ucptr) ;
break ;
case '3' : /* 3 byte value with the current endian-ness */
intptr = va_arg (argptr, unsigned int*) ;
*intptr = 0 ;
byte_count += header_read (psf, sixteen_bytes, 3) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
*intptr = GET_BE_3BYTE (sixteen_bytes) ;
else
*intptr = GET_LE_3BYTE (sixteen_bytes) ;
break ;
case '4' : /* 4 byte value with the current endian-ness */
intptr = va_arg (argptr, unsigned int*) ;
*intptr = 0 ;
ucptr = (unsigned char*) intptr ;
byte_count += header_read (psf, ucptr, sizeof (int)) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
*intptr = psf_get_be32 (ucptr, 0) ;
else
*intptr = psf_get_le32 (ucptr, 0) ;
break ;
case '8' : /* 8 byte value with the current endian-ness */
countptr = va_arg (argptr, sf_count_t *) ;
*countptr = 0 ;
byte_count += header_read (psf, sixteen_bytes, 8) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
countdata = psf_get_be64 (sixteen_bytes, 0) ;
else
countdata = psf_get_le64 (sixteen_bytes, 0) ;
*countptr = countdata ;
break ;
case 'f' : /* Float conversion */
floatptr = va_arg (argptr, float *) ;
*floatptr = 0.0 ;
byte_count += header_read (psf, floatptr, sizeof (float)) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
*floatptr = float32_be_read ((unsigned char*) floatptr) ;
else
*floatptr = float32_le_read ((unsigned char*) floatptr) ;
break ;
case 'd' : /* double conversion */
doubleptr = va_arg (argptr, double *) ;
*doubleptr = 0.0 ;
byte_count += header_read (psf, doubleptr, sizeof (double)) ;
if (psf->rwf_endian == SF_ENDIAN_BIG)
*doubleptr = double64_be_read ((unsigned char*) doubleptr) ;
else
*doubleptr = double64_le_read ((unsigned char*) doubleptr) ;
break ;
case 's' :
psf_log_printf (psf, "Format conversion 's' not implemented yet.\n") ;
/*
strptr = va_arg (argptr, char *) ;
size = strlen (strptr) + 1 ;
size += (size & 1) ;
longdata = H2LE_32 (size) ;
get_int (psf, longdata) ;
memcpy (&(psf->header [psf->headindex]), strptr, size) ;
psf->headindex += size ;
*/
break ;
case 'b' : /* Raw bytes */
charptr = va_arg (argptr, char*) ;
count = va_arg (argptr, size_t) ;
if (count > 0)
byte_count += header_read (psf, charptr, count) ;
break ;
case 'G' :
charptr = va_arg (argptr, char*) ;
count = va_arg (argptr, size_t) ;
if (count > 0)
byte_count += header_gets (psf, charptr, count) ;
break ;
case 'z' :
psf_log_printf (psf, "Format conversion 'z' not implemented yet.\n") ;
/*
size = va_arg (argptr, size_t) ;
while (size)
{ psf->header [psf->headindex] = 0 ;
psf->headindex ++ ;
size -- ;
} ;
*/
break ;
case 'p' :
/* Get the seek position first. */
count = va_arg (argptr, size_t) ;
header_seek (psf, count, SEEK_SET) ;
byte_count = count ;
break ;
case 'j' :
/* Get the seek position first. */
count = va_arg (argptr, size_t) ;
if (count)
{ header_seek (psf, count, SEEK_CUR) ;
byte_count += count ;
} ;
break ;
default :
psf_log_printf (psf, "*** Invalid format specifier `%c'\n", c) ;
psf->error = SFE_INTERNAL ;
break ;
} ;
} ;
va_end (argptr) ;
return byte_count ;
} /* psf_binheader_readf */
CWE ID: CWE-119
Target: 1
Example 2:
Code: void setDeferredMultiBulkLength(client *c, void *node, long length) {
listNode *ln = (listNode*)node;
robj *len, *next;
/* Abort when *node is NULL (see addDeferredMultiBulkLength). */
if (node == NULL) return;
len = listNodeValue(ln);
len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length);
len->encoding = OBJ_ENCODING_RAW; /* in case it was an EMBSTR. */
c->reply_bytes += sdsZmallocSize(len->ptr);
if (ln->next != NULL) {
next = listNodeValue(ln->next);
/* Only glue when the next node is non-NULL (an sds in this case) */
if (next->ptr != NULL) {
c->reply_bytes -= sdsZmallocSize(len->ptr);
c->reply_bytes -= getStringObjectSdsUsedMemory(next);
len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr));
c->reply_bytes += sdsZmallocSize(len->ptr);
listDelNode(c->reply,ln->next);
}
}
asyncCloseClientOnOutputBufferLimitReached(c);
}
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: PHP_FUNCTION( locale_get_region )
{
get_icu_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
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: cJSON *cJSON_DetachItemFromArray( cJSON *array, int which )
{
cJSON *c = array->child;
while ( c && which > 0 ) {
c = c->next;
--which;
}
if ( ! c )
return 0;
if ( c->prev )
c->prev->next = c->next;
if ( c->next ) c->next->prev = c->prev;
if ( c == array->child )
array->child = c->next;
c->prev = c->next = 0;
return c;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: WM_SYMBOL int WildMidi_SetOption(midi * handle, uint16_t options, uint16_t setting) {
struct _mdi *mdi;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (-1);
}
if (handle == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL handle)", 0);
return (-1);
}
mdi = (struct _mdi *) handle;
_WM_Lock(&mdi->lock);
if ((!(options & 0x800F)) || (options & 0x7FF0)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid option)", 0);
_WM_Unlock(&mdi->lock);
return (-1);
}
if (setting & 0x7FF0) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(invalid setting)", 0);
_WM_Unlock(&mdi->lock);
return (-1);
}
mdi->extra_info.mixer_options = ((mdi->extra_info.mixer_options & (0x80FF ^ options))
| (options & setting));
if (options & WM_MO_LOG_VOLUME) {
_WM_AdjustChannelVolumes(mdi, 16); // Settings greater than 15
} else if (options & WM_MO_REVERB) {
_WM_reset_reverb(mdi->reverb);
}
_WM_Unlock(&mdi->lock);
return (0);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ShadowRoot::setInnerHTML(const String& markup, ExceptionCode& ec)
{
RefPtr<DocumentFragment> fragment = createFragmentFromSource(markup, host(), ec);
if (fragment)
replaceChildrenWithFragment(this, fragment.release(), ec);
}
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: crm_recv_remote_msg(void *session, gboolean encrypted)
{
char *reply = NULL;
xmlNode *xml = NULL;
if (encrypted) {
#ifdef HAVE_GNUTLS_GNUTLS_H
reply = cib_recv_tls(session);
#else
CRM_ASSERT(encrypted == FALSE);
#endif
} else {
reply = cib_recv_plaintext(GPOINTER_TO_INT(session));
}
if (reply == NULL || strlen(reply) == 0) {
crm_trace("Empty reply");
} else {
xml = string2xml(reply);
if (xml == NULL) {
crm_err("Couldn't parse: '%.120s'", reply);
}
}
free(reply);
return xml;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void __aac_shutdown(struct aac_dev * aac)
{
if (aac->aif_thread) {
int i;
/* Clear out events first */
for (i = 0; i < (aac->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB); i++) {
struct fib *fib = &aac->fibs[i];
if (!(fib->hw_fib_va->header.XferState & cpu_to_le32(NoResponseExpected | Async)) &&
(fib->hw_fib_va->header.XferState & cpu_to_le32(ResponseExpected)))
up(&fib->event_wait);
}
kthread_stop(aac->thread);
}
aac_send_shutdown(aac);
aac_adapter_disable_int(aac);
free_irq(aac->pdev->irq, aac);
if (aac->msi)
pci_disable_msi(aac->pdev);
}
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: compat_copy_entries_to_user(unsigned int total_size, struct xt_table *table,
void __user *userptr)
{
struct xt_counters *counters;
const struct xt_table_info *private = table->private;
void __user *pos;
unsigned int size;
int ret = 0;
unsigned int i = 0;
struct ipt_entry *iter;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
pos = userptr;
size = total_size;
xt_entry_foreach(iter, private->entries, total_size) {
ret = compat_copy_entry_to_user(iter, &pos,
&size, counters, i++);
if (ret != 0)
break;
}
vfree(counters);
return ret;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ExtensionOptionsGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached()) {
auto guest_zoom_controller =
ui_zoom::ZoomController::FromWebContents(web_contents());
guest_zoom_controller->SetZoomMode(
ui_zoom::ZoomController::ZOOM_MODE_ISOLATED);
SetGuestZoomLevelToMatchEmbedder();
if (params.url.GetOrigin() != options_page_.GetOrigin()) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EOG_BAD_ORIGIN);
}
}
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: status_t CameraClient::setPreviewWindow(const sp<IBinder>& binder,
const sp<ANativeWindow>& window) {
Mutex::Autolock lock(mLock);
status_t result = checkPidAndHardware();
if (result != NO_ERROR) return result;
if (binder == mSurface) {
return NO_ERROR;
}
if (window != 0) {
result = native_window_api_connect(window.get(), NATIVE_WINDOW_API_CAMERA);
if (result != NO_ERROR) {
ALOGE("native_window_api_connect failed: %s (%d)", strerror(-result),
result);
return result;
}
}
if (mHardware->previewEnabled()) {
if (window != 0) {
native_window_set_scaling_mode(window.get(),
NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
native_window_set_buffers_transform(window.get(), mOrientation);
result = mHardware->setPreviewWindow(window);
}
}
if (result == NO_ERROR) {
disconnectWindow(mPreviewWindow);
mSurface = binder;
mPreviewWindow = window;
} else {
disconnectWindow(window);
}
return result;
}
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 ping()
{
CCMainThread::postTask(createMainThreadTask(this, &PingPongTestUsingTasks::pong));
hit = true;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const Track* Tracks::GetTrackByIndex(unsigned long idx) const
{
const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries;
if (idx >= static_cast<unsigned long>(count))
return NULL;
return m_trackEntries[idx];
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: device_luks_unlock_authorized_cb (Daemon *daemon,
Device *device,
DBusGMethodInvocation *context,
const gchar *action_id,
guint num_user_data,
gpointer *user_data_elements)
{
const char *secret = user_data_elements[0];
char **options = user_data_elements[1];
device_luks_unlock_internal (device, secret, options, NULL, NULL, context);
}
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 bool in_subsystem_list(const char *c)
{
int i;
for (i = 0; i < nr_subsystems; i++) {
if (strcmp(c, subsystems[i]) == 0)
return true;
}
return false;
}
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: PatternMatch(char *pat, int patdashes, char *string, int stringdashes)
{
char c,
t;
if (stringdashes < patdashes)
return 0;
for (;;) {
switch (c = *pat++) {
case '*':
if (!(c = *pat++))
return 1;
if (c == XK_minus) {
patdashes--;
for (;;) {
while ((t = *string++) != XK_minus)
if (!t)
return 0;
stringdashes--;
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
if (stringdashes == patdashes)
return 0;
}
} else {
for (;;) {
while ((t = *string++) != c) {
if (!t)
return 0;
if (t == XK_minus) {
if (stringdashes-- < patdashes)
return 0;
}
}
if (PatternMatch(pat, patdashes, string, stringdashes))
return 1;
}
}
case '?':
if (*string++ == XK_minus)
stringdashes--;
break;
case '\0':
return (*string == '\0');
patdashes--;
stringdashes--;
break;
}
return 0;
default:
if (c == *string++)
break;
return 0;
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: MagickExport FILE *GetBlobFileHandle(const Image *image)
{
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
return(image->blob->file_info.file);
}
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 BrowserContextDestroyer::FinishDestroyContext() {
DCHECK_EQ(pending_hosts_, 0U);
delete context_;
context_ = nullptr;
delete this;
}
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 PdfCompositorClient::Composite(
service_manager::Connector* connector,
base::SharedMemoryHandle handle,
size_t data_size,
mojom::PdfCompositor::CompositePdfCallback callback,
scoped_refptr<base::SequencedTaskRunner> callback_task_runner) {
DCHECK(data_size);
if (!compositor_)
Connect(connector);
mojo::ScopedSharedBufferHandle buffer_handle =
mojo::WrapSharedMemoryHandle(handle, data_size, true);
compositor_->CompositePdf(
std::move(buffer_handle),
base::BindOnce(&OnCompositePdf, base::Passed(&compositor_),
std::move(callback), callback_task_runner));
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static void setFileState(rpmfs fs, int i)
{
switch (rpmfsGetAction(fs, i)) {
case FA_SKIPNSTATE:
rpmfsSetState(fs, i, RPMFILE_STATE_NOTINSTALLED);
break;
case FA_SKIPNETSHARED:
rpmfsSetState(fs, i, RPMFILE_STATE_NETSHARED);
break;
case FA_SKIPCOLOR:
rpmfsSetState(fs, i, RPMFILE_STATE_WRONGCOLOR);
break;
case FA_TOUCH:
rpmfsSetState(fs, i, RPMFILE_STATE_NORMAL);
break;
default:
break;
}
}
CWE ID: CWE-59
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CL_ServerStatusResponse( netadr_t from, msg_t *msg ) {
char *s;
char info[MAX_INFO_STRING];
int i, l, score, ping;
int len;
serverStatus_t *serverStatus;
serverStatus = NULL;
for ( i = 0; i < MAX_SERVERSTATUSREQUESTS; i++ ) {
if ( NET_CompareAdr( from, cl_serverStatusList[i].address ) ) {
serverStatus = &cl_serverStatusList[i];
break;
}
}
if ( !serverStatus ) {
return;
}
s = MSG_ReadStringLine( msg );
len = 0;
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "%s", s );
if ( serverStatus->print ) {
Com_Printf( "Server settings:\n" );
while ( *s ) {
for ( i = 0; i < 2 && *s; i++ ) {
if ( *s == '\\' ) {
s++;
}
l = 0;
while ( *s ) {
info[l++] = *s;
if ( l >= MAX_INFO_STRING - 1 ) {
break;
}
s++;
if ( *s == '\\' ) {
break;
}
}
info[l] = '\0';
if ( i ) {
Com_Printf( "%s\n", info );
} else {
Com_Printf( "%-24s", info );
}
}
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
if ( serverStatus->print ) {
Com_Printf( "\nPlayers:\n" );
Com_Printf( "num: score: ping: name:\n" );
}
for ( i = 0, s = MSG_ReadStringLine( msg ); *s; s = MSG_ReadStringLine( msg ), i++ ) {
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\%s", s );
if ( serverStatus->print ) {
score = ping = 0;
sscanf( s, "%d %d", &score, &ping );
s = strchr( s, ' ' );
if ( s ) {
s = strchr( s + 1, ' ' );
}
if ( s ) {
s++;
} else {
s = "unknown";
}
Com_Printf( "%-2d %-3d %-3d %s\n", i, score, ping, s );
}
}
len = strlen( serverStatus->string );
Com_sprintf( &serverStatus->string[len], sizeof( serverStatus->string ) - len, "\\" );
serverStatus->time = Com_Milliseconds();
serverStatus->address = from;
serverStatus->pending = qfalse;
if (serverStatus->print) {
serverStatus->retrieved = qtrue;
}
}
CWE ID: CWE-269
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 dump_completed_IO(struct inode * inode)
{
#ifdef EXT4_DEBUG
struct list_head *cur, *before, *after;
ext4_io_end_t *io, *io0, *io1;
if (list_empty(&EXT4_I(inode)->i_completed_io_list)){
ext4_debug("inode %lu completed_io list is empty\n", inode->i_ino);
return;
}
ext4_debug("Dump inode %lu completed_io list \n", inode->i_ino);
list_for_each_entry(io, &EXT4_I(inode)->i_completed_io_list, list){
cur = &io->list;
before = cur->prev;
io0 = container_of(before, ext4_io_end_t, list);
after = cur->next;
io1 = container_of(after, ext4_io_end_t, list);
ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n",
io, inode->i_ino, io0, io1);
}
#endif
}
CWE ID:
Target: 1
Example 2:
Code: PHP_FUNCTION(snmp2_getnext)
{
php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_2c);
}
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: _tiffReadProc(thandle_t fd, void* buf, tmsize_t size)
{
size_t size_io = (size_t) size;
if ((tmsize_t) size_io != size)
{
errno=EINVAL;
return (tmsize_t) -1;
}
return ((tmsize_t) read((int) fd, buf, size_io));
}
CWE ID: CWE-369
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 LayoutSVGViewportContainer::calculateLocalTransform()
{
if (!m_needsTransformUpdate)
return false;
m_localToParentTransform = AffineTransform::translation(m_viewport.x(), m_viewport.y()) * viewportTransform();
m_needsTransformUpdate = false;
return true;
}
CWE ID:
Target: 1
Example 2:
Code: DeferredTaskPopupListSelectMultiple(WebPagePrivate* webPagePrivate, int size, const bool* selecteds)
: DeferredTaskType(webPagePrivate)
{
webPagePrivate->m_cachedPopupListSelecteds.append(selecteds, size);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t IPCThreadState::requestDeathNotification(int32_t handle, BpBinder* proxy)
{
mOut.writeInt32(BC_REQUEST_DEATH_NOTIFICATION);
mOut.writeInt32((int32_t)handle);
mOut.writePointer((uintptr_t)proxy);
return NO_ERROR;
}
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: isofs_export_encode_fh(struct inode *inode,
__u32 *fh32,
int *max_len,
struct inode *parent)
{
struct iso_inode_info * ei = ISOFS_I(inode);
int len = *max_len;
int type = 1;
__u16 *fh16 = (__u16*)fh32;
/*
* WARNING: max_len is 5 for NFSv2. Because of this
* limitation, we use the lower 16 bits of fh32[1] to hold the
* offset of the inode and the upper 16 bits of fh32[1] to
* hold the offset of the parent.
*/
if (parent && (len < 5)) {
*max_len = 5;
return 255;
} else if (len < 3) {
*max_len = 3;
return 255;
}
len = 3;
fh32[0] = ei->i_iget5_block;
fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */
fh32[2] = inode->i_generation;
if (parent) {
struct iso_inode_info *eparent;
eparent = ISOFS_I(parent);
fh32[3] = eparent->i_iget5_block;
fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */
fh32[4] = parent->i_generation;
len = 5;
type = 2;
}
*max_len = len;
return type;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: TestingPlatformSupport::~TestingPlatformSupport()
{
Platform::initialize(m_oldPlatform);
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static IMFSample* CreateEmptySample() {
base::win::ScopedComPtr<IMFSample> sample;
HRESULT hr = MFCreateSample(sample.Receive());
RETURN_ON_HR_FAILURE(hr, "MFCreateSample failed", NULL);
return sample.Detach();
}
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: BlockEntry::Kind SimpleBlock::GetKind() const
{
return kBlockSimple;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void PrintWebViewHelper::UpdateFrameAndViewFromCssPageLayout(
WebFrame* frame,
const WebNode& node,
PrepareFrameAndViewForPrint* prepare,
const PrintMsg_Print_Params& params,
bool ignore_css_margins) {
if (PrintingNodeOrPdfFrame(frame, node))
return;
bool fit_to_page = ignore_css_margins &&
params.print_scaling_option ==
WebKit::WebPrintScalingOptionFitToPrintableArea;
PrintMsg_Print_Params print_params = CalculatePrintParamsForCss(
frame, 0, params, ignore_css_margins, fit_to_page, NULL);
prepare->UpdatePrintParams(print_params);
}
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 bool decode_openldap_dereference(void *mem_ctx, DATA_BLOB in, void *_out)
{
void **out = (void **)_out;
struct asn1_data *data = asn1_init(mem_ctx);
struct dsdb_openldap_dereference_result_control *control;
struct dsdb_openldap_dereference_result **r = NULL;
int i = 0;
if (!data) return false;
control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control);
if (!control) return false;
if (!asn1_load(data, in)) {
return false;
}
control = talloc(mem_ctx, struct dsdb_openldap_dereference_result_control);
if (!control) {
return false;
}
if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) {
return false;
}
while (asn1_tag_remaining(data) > 0) {
r = talloc_realloc(control, r, struct dsdb_openldap_dereference_result *, i + 2);
if (!r) {
return false;
}
r[i] = talloc_zero(r, struct dsdb_openldap_dereference_result);
if (!r[i]) {
return false;
}
if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) {
return false;
}
asn1_read_OctetString_talloc(r[i], data, &r[i]->source_attribute);
asn1_read_OctetString_talloc(r[i], data, &r[i]->dereferenced_dn);
if (asn1_peek_tag(data, ASN1_CONTEXT(0))) {
if (!asn1_start_tag(data, ASN1_CONTEXT(0))) {
return false;
}
ldap_decode_attribs_bare(r, data, &r[i]->attributes,
&r[i]->num_attributes);
if (!asn1_end_tag(data)) {
return false;
}
}
if (!asn1_end_tag(data)) {
return false;
}
i++;
r[i] = NULL;
}
if (!asn1_end_tag(data)) {
return false;
}
control->attributes = r;
*out = control;
return true;
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int send_write_chunks(struct svcxprt_rdma *xprt,
struct rpcrdma_write_array *wr_ary,
struct rpcrdma_msg *rdma_resp,
struct svc_rqst *rqstp,
struct svc_rdma_req_map *vec)
{
u32 xfer_len = rqstp->rq_res.page_len;
int write_len;
u32 xdr_off;
int chunk_off;
int chunk_no;
int nchunks;
struct rpcrdma_write_array *res_ary;
int ret;
res_ary = (struct rpcrdma_write_array *)
&rdma_resp->rm_body.rm_chunks[1];
/* Write chunks start at the pagelist */
nchunks = be32_to_cpu(wr_ary->wc_nchunks);
for (xdr_off = rqstp->rq_res.head[0].iov_len, chunk_no = 0;
xfer_len && chunk_no < nchunks;
chunk_no++) {
struct rpcrdma_segment *arg_ch;
u64 rs_offset;
arg_ch = &wr_ary->wc_array[chunk_no].wc_target;
write_len = min(xfer_len, be32_to_cpu(arg_ch->rs_length));
/* Prepare the response chunk given the length actually
* written */
xdr_decode_hyper((__be32 *)&arg_ch->rs_offset, &rs_offset);
svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no,
arg_ch->rs_handle,
arg_ch->rs_offset,
write_len);
chunk_off = 0;
while (write_len) {
ret = send_write(xprt, rqstp,
be32_to_cpu(arg_ch->rs_handle),
rs_offset + chunk_off,
xdr_off,
write_len,
vec);
if (ret <= 0)
goto out_err;
chunk_off += ret;
xdr_off += ret;
xfer_len -= ret;
write_len -= ret;
}
}
/* Update the req with the number of chunks actually used */
svc_rdma_xdr_encode_write_list(rdma_resp, chunk_no);
return rqstp->rq_res.page_len;
out_err:
pr_err("svcrdma: failed to send write chunks, rc=%d\n", ret);
return -EIO;
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: static int iccbasecolor(i_ctx_t * i_ctx_p, ref *space, int base, int *stage, int *cont, int *stack_depth)
{
*stage = 0;
*cont = 1;
return 0;
}
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: TEE_Result syscall_asymm_verify(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *data, size_t data_len,
const void *sig, size_t sig_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
struct tee_obj *o;
size_t hash_size;
int salt_len = 0;
TEE_Attribute *params = NULL;
uint32_t hash_algo;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
if (cs->mode != TEE_MODE_VERIFY)
return TEE_ERROR_BAD_PARAMETERS;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)data, data_len);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(utc,
TEE_MEMORY_ACCESS_READ |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t)sig, sig_len);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * num_params);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_BAD_PARAMETERS;
goto out;
}
switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
case TEE_MAIN_ALGO_RSA:
if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) {
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
if (data_len != hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params,
hash_size);
}
res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len,
data, data_len, sig,
sig_len);
break;
case TEE_MAIN_ALGO_DSA:
hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
res = tee_hash_get_digest_size(hash_algo, &hash_size);
if (res != TEE_SUCCESS)
break;
/*
* Depending on the DSA algorithm (NIST), the digital signature
* output size may be truncated to the size of a key pair
* (Q prime size). Q prime size must be less or equal than the
* hash output length of the hash algorithm involved.
*/
if (data_len > hash_size) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
res = crypto_acipher_dsa_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
case TEE_MAIN_ALGO_ECDSA:
res = crypto_acipher_ecc_verify(cs->algo, o->attr, data,
data_len, sig, sig_len);
break;
default:
res = TEE_ERROR_NOT_SUPPORTED;
}
out:
free(params);
return res;
}
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 SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
OMX_U32 frameSize = (mWidth * mHeight * 3) / 2;
if (outHeader->nAllocLen < frameSize) {
android_errorWriteLog(0x534e4554, "27833616");
ALOGE("Insufficient output buffer size");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = frameSize;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void Pack<WebGLImageConversion::kDataFormatR32F,
WebGLImageConversion::kAlphaDoNothing,
float,
float>(const float* source,
float* destination,
unsigned pixels_per_row) {
for (unsigned i = 0; i < pixels_per_row; ++i) {
destination[0] = source[0];
source += 4;
destination += 1;
}
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Verify_StoreExistingGroup() {
EXPECT_TRUE(delegate()->stored_group_success_);
EXPECT_EQ(group_.get(), delegate()->stored_group_.get());
EXPECT_EQ(cache2_.get(), group_->newest_complete_cache());
EXPECT_TRUE(cache2_->is_complete());
AppCacheDatabase::GroupRecord group_record;
AppCacheDatabase::CacheRecord cache_record;
EXPECT_TRUE(database()->FindGroup(1, &group_record));
EXPECT_TRUE(database()->FindCache(2, &cache_record));
EXPECT_FALSE(database()->FindCache(1, &cache_record));
EXPECT_EQ(kDefaultEntrySize + 100, storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(100, mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
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: freeimage(Image *image)
{
freebuffer(image);
png_image_free(&image->image);
if (image->input_file != NULL)
{
fclose(image->input_file);
image->input_file = NULL;
}
if (image->input_memory != NULL)
{
free(image->input_memory);
image->input_memory = NULL;
image->input_memory_size = 0;
}
if (image->tmpfile_name[0] != 0 && (image->opts & KEEP_TMPFILES) == 0)
{
remove(image->tmpfile_name);
image->tmpfile_name[0] = 0;
}
}
CWE ID:
Target: 1
Example 2:
Code: PHP_FUNCTION(openssl_pkey_new)
{
struct php_x509_request req;
zval * args = NULL;
zval *data;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a!", &args) == FAILURE) {
return;
}
RETVAL_FALSE;
if (args && Z_TYPE_P(args) == IS_ARRAY) {
EVP_PKEY *pkey;
if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "rsa", sizeof("rsa")-1)) != NULL &&
Z_TYPE_P(data) == IS_ARRAY) {
pkey = EVP_PKEY_new();
if (pkey) {
RSA *rsa = RSA_new();
if (rsa) {
if (php_openssl_pkey_init_and_assign_rsa(pkey, rsa, data)) {
RETURN_RES(zend_register_resource(pkey, le_key));
}
RSA_free(rsa);
}
EVP_PKEY_free(pkey);
}
RETURN_FALSE;
} else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "dsa", sizeof("dsa") - 1)) != NULL &&
Z_TYPE_P(data) == IS_ARRAY) {
pkey = EVP_PKEY_new();
if (pkey) {
DSA *dsa = DSA_new();
if (dsa) {
if (php_openssl_pkey_init_dsa(dsa, data)) {
if (EVP_PKEY_assign_DSA(pkey, dsa)) {
RETURN_RES(zend_register_resource(pkey, le_key));
}
}
DSA_free(dsa);
}
EVP_PKEY_free(pkey);
}
RETURN_FALSE;
} else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "dh", sizeof("dh") - 1)) != NULL &&
Z_TYPE_P(data) == IS_ARRAY) {
pkey = EVP_PKEY_new();
if (pkey) {
DH *dh = DH_new();
if (dh) {
if (php_openssl_pkey_init_dh(dh, data)) {
if (EVP_PKEY_assign_DH(pkey, dh)) {
ZVAL_COPY_VALUE(return_value, zend_list_insert(pkey, le_key));
return;
}
}
DH_free(dh);
}
EVP_PKEY_free(pkey);
}
RETURN_FALSE;
}
}
PHP_SSL_REQ_INIT(&req);
if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS)
{
if (php_openssl_generate_private_key(&req)) {
/* pass back a key resource */
RETVAL_RES(zend_register_resource(req.priv_key, le_key));
/* make sure the cleanup code doesn't zap it! */
req.priv_key = NULL;
}
}
PHP_SSL_REQ_DISPOSE(&req);
}
CWE ID: CWE-754
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::vector<std::string> GetRecordedDeltaHistogramNames() {
return recorded_delta_histogram_names_;
}
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 r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) {
size_t i, j, k;
RBinDwarfDIE *dies;
RBinDwarfAttrValue *values;
if (!inf || !f) {
return;
}
for (i = 0; i < inf->length; i++) {
fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset);
fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length);
fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version);
fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset);
fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size);
dies = inf->comp_units[i].dies;
for (j = 0; j < inf->comp_units[i].length; j++) {
fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code);
if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type &&
dwarf_tag_name_encodings[dies[j].tag]) {
fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]);
} else {
fprintf (f, "(Unknown abbrev tag)\n");
}
if (!dies[j].abbrev_code) {
continue;
}
values = dies[j].attr_values;
for (k = 0; k < dies[j].length; k++) {
if (!values[k].name)
continue;
if (values[k].name < DW_AT_vtable_elem_location &&
dwarf_attr_encodings[values[k].name]) {
fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]);
} else {
fprintf (f, " TODO\t");
}
r_bin_dwarf_dump_attr_value (&values[k], f);
fprintf (f, "\n");
}
}
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: ar6000_cookie_cleanup(struct ar6_softc *ar)
{
/* It is gone .... */
ar->arCookieList = NULL;
ar->arCookieCount = 0;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {
RFlagsAtOffset *flags = NULL;
RFlagsAtOffset key;
key.off = off;
if (dir >= 0) {
flags = r_skiplist_get_geq (f->by_off, &key);
} else {
flags = r_skiplist_get_leq (f->by_off, &key);
}
if (dir == 0 && flags && flags->off != off) {
return NULL;
}
return flags;
}
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: DataPipeProducerDispatcher::Deserialize(const void* data,
size_t num_bytes,
const ports::PortName* ports,
size_t num_ports,
PlatformHandle* handles,
size_t num_handles) {
if (num_ports != 1 || num_handles != 1 ||
num_bytes != sizeof(SerializedState)) {
return nullptr;
}
const SerializedState* state = static_cast<const SerializedState*>(data);
if (!state->options.capacity_num_bytes || !state->options.element_num_bytes ||
state->options.capacity_num_bytes < state->options.element_num_bytes) {
return nullptr;
}
NodeController* node_controller = Core::Get()->GetNodeController();
ports::PortRef port;
if (node_controller->node()->GetPort(ports[0], &port) != ports::OK)
return nullptr;
auto region_handle = CreateSharedMemoryRegionHandleFromPlatformHandles(
std::move(handles[0]), PlatformHandle());
auto region = base::subtle::PlatformSharedMemoryRegion::Take(
std::move(region_handle),
base::subtle::PlatformSharedMemoryRegion::Mode::kUnsafe,
state->options.capacity_num_bytes,
base::UnguessableToken::Deserialize(state->buffer_guid_high,
state->buffer_guid_low));
auto ring_buffer =
base::UnsafeSharedMemoryRegion::Deserialize(std::move(region));
if (!ring_buffer.IsValid()) {
DLOG(ERROR) << "Failed to deserialize shared buffer handle.";
return nullptr;
}
scoped_refptr<DataPipeProducerDispatcher> dispatcher =
new DataPipeProducerDispatcher(node_controller, port,
std::move(ring_buffer), state->options,
state->pipe_id);
{
base::AutoLock lock(dispatcher->lock_);
dispatcher->write_offset_ = state->write_offset;
dispatcher->available_capacity_ = state->available_capacity;
dispatcher->peer_closed_ = state->flags & kFlagPeerClosed;
if (!dispatcher->InitializeNoLock())
return nullptr;
dispatcher->UpdateSignalsStateNoLock();
}
return dispatcher;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int rtp_new_av_stream(HTTPContext *c,
int stream_index, struct sockaddr_in *dest_addr,
HTTPContext *rtsp_c)
{
AVFormatContext *ctx;
AVStream *st;
char *ipaddr;
URLContext *h = NULL;
uint8_t *dummy_buf;
int max_packet_size;
void *st_internal;
/* now we can open the relevant output stream */
ctx = avformat_alloc_context();
if (!ctx)
return -1;
ctx->oformat = av_guess_format("rtp", NULL, NULL);
st = avformat_new_stream(ctx, NULL);
if (!st)
goto fail;
st_internal = st->internal;
if (!c->stream->feed ||
c->stream->feed == c->stream)
unlayer_stream(st, c->stream->streams[stream_index]);
else
unlayer_stream(st,
c->stream->feed->streams[c->stream->feed_streams[stream_index]]);
av_assert0(st->priv_data == NULL);
av_assert0(st->internal == st_internal);
/* build destination RTP address */
ipaddr = inet_ntoa(dest_addr->sin_addr);
switch(c->rtp_protocol) {
case RTSP_LOWER_TRANSPORT_UDP:
case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
/* RTP/UDP case */
/* XXX: also pass as parameter to function ? */
if (c->stream->is_multicast) {
int ttl;
ttl = c->stream->multicast_ttl;
if (!ttl)
ttl = 16;
snprintf(ctx->filename, sizeof(ctx->filename),
"rtp://%s:%d?multicast=1&ttl=%d",
ipaddr, ntohs(dest_addr->sin_port), ttl);
} else {
snprintf(ctx->filename, sizeof(ctx->filename),
"rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
}
if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
goto fail;
c->rtp_handles[stream_index] = h;
max_packet_size = h->max_packet_size;
break;
case RTSP_LOWER_TRANSPORT_TCP:
/* RTP/TCP case */
c->rtsp_c = rtsp_c;
max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
break;
default:
goto fail;
}
http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
ipaddr, ntohs(dest_addr->sin_port),
c->stream->filename, stream_index, c->protocol);
/* normally, no packets should be output here, but the packet size may
* be checked */
if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
/* XXX: close stream */
goto fail;
if (avformat_write_header(ctx, NULL) < 0) {
fail:
if (h)
ffurl_close(h);
av_free(st);
av_free(ctx);
return -1;
}
avio_close_dyn_buf(ctx->pb, &dummy_buf);
ctx->pb = NULL;
av_free(dummy_buf);
c->rtp_ctx[stream_index] = ctx;
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,
++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls -
rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls -
rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
<< r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
<< r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
pi->pirlvl->prcheightexpn);
pi->prcno = prcvind *
pi->pirlvl->numhprcs +
prchind;
assert(pi->prcno <
pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FileBrowserHandlerCustomBindings::GetEntryURL(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK(args.Length() == 1);
CHECK(args[0]->IsObject());
const blink::WebURL& url =
blink::WebDOMFileSystem::createFileSystemURL(args[0]);
args.GetReturnValue().Set(v8_helpers::ToV8StringUnsafe(
args.GetIsolate(), url.string().utf8().c_str()));
}
CWE ID:
Target: 1
Example 2:
Code: tilde_map_1( httpd_conn* hc )
{
static char* temp;
static size_t maxtemp = 0;
int len;
static char* prefix = TILDE_MAP_1;
len = strlen( hc->expnfilename ) - 1;
httpd_realloc_str( &temp, &maxtemp, len );
(void) strcpy( temp, &hc->expnfilename[1] );
httpd_realloc_str(
&hc->expnfilename, &hc->maxexpnfilename, strlen( prefix ) + 1 + len );
(void) strcpy( hc->expnfilename, prefix );
if ( prefix[0] != '\0' )
(void) strcat( hc->expnfilename, "/" );
(void) strcat( hc->expnfilename, temp );
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: frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(dp->ip6f_offlg);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
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: int blk_rq_map_user_iov(struct request_queue *q, struct request *rq,
struct rq_map_data *map_data,
const struct iov_iter *iter, gfp_t gfp_mask)
{
bool copy = false;
unsigned long align = q->dma_pad_mask | queue_dma_alignment(q);
struct bio *bio = NULL;
struct iov_iter i;
int ret;
if (map_data)
copy = true;
else if (iov_iter_alignment(iter) & align)
copy = true;
else if (queue_virt_boundary(q))
copy = queue_virt_boundary(q) & iov_iter_gap_alignment(iter);
i = *iter;
do {
ret =__blk_rq_map_user_iov(rq, map_data, &i, gfp_mask, copy);
if (ret)
goto unmap_rq;
if (!bio)
bio = rq->bio;
} while (iov_iter_count(&i));
if (!bio_flagged(bio, BIO_USER_MAPPED))
rq->cmd_flags |= REQ_COPY_USER;
return 0;
unmap_rq:
__blk_rq_unmap_user(bio);
rq->bio = NULL;
return -EINVAL;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: int PVGetDecBitrate(VideoDecControls *decCtrl)
{
VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
int idx;
int32 sum = 0;
for (idx = 0; idx < BITRATE_AVERAGE_WINDOW; idx++)
{
sum += video->nBitsPerVop[idx];
}
sum = (sum * video->frameRate) / (10 * BITRATE_AVERAGE_WINDOW);
return (int) sum;
}
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 Performance::NotifyNavigationTimingToObservers() {
if (!navigation_timing_)
navigation_timing_ = CreateNavigationTimingInstance();
if (navigation_timing_)
NotifyObserversOfEntry(*navigation_timing_);
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->fp[i]);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: int do_show(FILE *stream, const char *path_p, const struct stat *st,
acl_t acl, acl_t dacl)
{
struct name_list *acl_names = get_list(st, acl),
*first_acl_name = acl_names;
struct name_list *dacl_names = get_list(st, dacl),
*first_dacl_name = dacl_names;
int acl_names_width = max_name_length(acl_names);
int dacl_names_width = max_name_length(dacl_names);
acl_entry_t acl_ent;
acl_entry_t dacl_ent;
char acl_mask[ACL_PERMS+1], dacl_mask[ACL_PERMS+1];
int ret;
names_width = 8;
if (acl_names_width > names_width)
names_width = acl_names_width;
if (dacl_names_width > names_width)
names_width = dacl_names_width;
acl_mask[0] = '\0';
if (acl) {
acl_mask_perm_str(acl, acl_mask);
ret = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_ent);
if (ret == 0)
acl = NULL;
if (ret < 0)
return ret;
}
dacl_mask[0] = '\0';
if (dacl) {
acl_mask_perm_str(dacl, dacl_mask);
ret = acl_get_entry(dacl, ACL_FIRST_ENTRY, &dacl_ent);
if (ret == 0)
dacl = NULL;
if (ret < 0)
return ret;
}
fprintf(stream, "# file: %s\n", xquote(path_p, "\n\r"));
while (acl_names != NULL || dacl_names != NULL) {
acl_tag_t acl_tag, dacl_tag;
if (acl)
acl_get_tag_type(acl_ent, &acl_tag);
if (dacl)
acl_get_tag_type(dacl_ent, &dacl_tag);
if (acl && (!dacl || acl_tag < dacl_tag)) {
show_line(stream, &acl_names, acl, &acl_ent, acl_mask,
NULL, NULL, NULL, NULL);
continue;
} else if (dacl && (!acl || dacl_tag < acl_tag)) {
show_line(stream, NULL, NULL, NULL, NULL,
&dacl_names, dacl, &dacl_ent, dacl_mask);
continue;
} else {
if (acl_tag == ACL_USER || acl_tag == ACL_GROUP) {
id_t *acl_id_p = NULL, *dacl_id_p = NULL;
if (acl_ent)
acl_id_p = acl_get_qualifier(acl_ent);
if (dacl_ent)
dacl_id_p = acl_get_qualifier(dacl_ent);
if (acl && (!dacl || *acl_id_p < *dacl_id_p)) {
show_line(stream, &acl_names, acl,
&acl_ent, acl_mask,
NULL, NULL, NULL, NULL);
continue;
} else if (dacl &&
(!acl || *dacl_id_p < *acl_id_p)) {
show_line(stream, NULL, NULL, NULL,
NULL, &dacl_names, dacl,
&dacl_ent, dacl_mask);
continue;
}
}
show_line(stream, &acl_names, acl, &acl_ent, acl_mask,
&dacl_names, dacl, &dacl_ent, dacl_mask);
}
}
free_list(first_acl_name);
free_list(first_dacl_name);
return 0;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Platform::IntPoint InRegionScrollableArea::calculateMinimumScrollPosition(const Platform::IntSize& viewportSize, float overscrollLimitFactor) const
{
ASSERT(!allowsOverscroll());
return Platform::IntPoint(-(viewportSize.width() * overscrollLimitFactor),
-(viewportSize.height() * overscrollLimitFactor));
}
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 semctl_main(struct ipc_namespace *ns, int semid, int semnum,
int cmd, void __user *p)
{
struct sem_array *sma;
struct sem* curr;
int err, nsems;
ushort fast_sem_io[SEMMSL_FAST];
ushort* sem_io = fast_sem_io;
struct list_head tasks;
INIT_LIST_HEAD(&tasks);
rcu_read_lock();
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
rcu_read_unlock();
return PTR_ERR(sma);
}
nsems = sma->sem_nsems;
err = -EACCES;
if (ipcperms(ns, &sma->sem_perm,
cmd == SETALL ? S_IWUGO : S_IRUGO)) {
rcu_read_unlock();
goto out_wakeup;
}
err = security_sem_semctl(sma, cmd);
if (err) {
rcu_read_unlock();
goto out_wakeup;
}
err = -EACCES;
switch (cmd) {
case GETALL:
{
ushort __user *array = p;
int i;
if(nsems > SEMMSL_FAST) {
sem_getref(sma);
sem_io = ipc_alloc(sizeof(ushort)*nsems);
if(sem_io == NULL) {
sem_putref(sma);
return -ENOMEM;
}
sem_lock_and_putref(sma);
if (sma->sem_perm.deleted) {
sem_unlock(sma);
err = -EIDRM;
goto out_free;
}
}
spin_lock(&sma->sem_perm.lock);
for (i = 0; i < sma->sem_nsems; i++)
sem_io[i] = sma->sem_base[i].semval;
sem_unlock(sma);
err = 0;
if(copy_to_user(array, sem_io, nsems*sizeof(ushort)))
err = -EFAULT;
goto out_free;
}
case SETALL:
{
int i;
struct sem_undo *un;
ipc_rcu_getref(sma);
rcu_read_unlock();
if(nsems > SEMMSL_FAST) {
sem_io = ipc_alloc(sizeof(ushort)*nsems);
if(sem_io == NULL) {
sem_putref(sma);
return -ENOMEM;
}
}
if (copy_from_user (sem_io, p, nsems*sizeof(ushort))) {
sem_putref(sma);
err = -EFAULT;
goto out_free;
}
for (i = 0; i < nsems; i++) {
if (sem_io[i] > SEMVMX) {
sem_putref(sma);
err = -ERANGE;
goto out_free;
}
}
sem_lock_and_putref(sma);
if (sma->sem_perm.deleted) {
sem_unlock(sma);
err = -EIDRM;
goto out_free;
}
for (i = 0; i < nsems; i++)
sma->sem_base[i].semval = sem_io[i];
assert_spin_locked(&sma->sem_perm.lock);
list_for_each_entry(un, &sma->list_id, list_id) {
for (i = 0; i < nsems; i++)
un->semadj[i] = 0;
}
sma->sem_ctime = get_seconds();
/* maybe some queued-up processes were waiting for this */
do_smart_update(sma, NULL, 0, 0, &tasks);
err = 0;
goto out_unlock;
}
/* GETVAL, GETPID, GETNCTN, GETZCNT: fall-through */
}
err = -EINVAL;
if (semnum < 0 || semnum >= nsems) {
rcu_read_unlock();
goto out_wakeup;
}
spin_lock(&sma->sem_perm.lock);
curr = &sma->sem_base[semnum];
switch (cmd) {
case GETVAL:
err = curr->semval;
goto out_unlock;
case GETPID:
err = curr->sempid;
goto out_unlock;
case GETNCNT:
err = count_semncnt(sma,semnum);
goto out_unlock;
case GETZCNT:
err = count_semzcnt(sma,semnum);
goto out_unlock;
}
out_unlock:
sem_unlock(sma);
out_wakeup:
wake_up_sem_queue_do(&tasks);
out_free:
if(sem_io != fast_sem_io)
ipc_free(sem_io, sizeof(ushort)*nsems);
return err;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: cmsBool CMSEXPORT cmsIT8SetDataRowCol(cmsHANDLE hIT8, int row, int col, const char* Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
_cmsAssert(hIT8 != NULL);
return SetData(it8, row, col, Val);
}
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: char *url_decode_r(char *to, char *url, size_t size) {
char *s = url, // source
*d = to, // destination
*e = &to[size - 1]; // destination end
while(*s && d < e) {
if(unlikely(*s == '%')) {
if(likely(s[1] && s[2])) {
*d++ = from_hex(s[1]) << 4 | from_hex(s[2]);
s += 2;
}
}
else if(unlikely(*s == '+'))
*d++ = ' ';
else
*d++ = *s;
s++;
}
*d = '\0';
return to;
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static unsigned create_oops_dump_dirs(GList *oops_list, unsigned oops_cnt)
{
unsigned countdown = MAX_DUMPED_DD_COUNT; /* do not report hundreds of oopses */
log_notice("Saving %u oopses as problem dirs", oops_cnt >= countdown ? countdown : oops_cnt);
char *cmdline_str = xmalloc_fopen_fgetline_fclose("/proc/cmdline");
char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled");
char *proc_modules = xmalloc_open_read_close("/proc/modules", /*maxsize:*/ NULL);
char *suspend_stats = xmalloc_open_read_close("/sys/kernel/debug/suspend_stats", /*maxsize:*/ NULL);
time_t t = time(NULL);
const char *iso_date = iso_date_string(&t);
/* dump should be readable by all if we're run with -x */
uid_t my_euid = (uid_t)-1L;
mode_t mode = DEFAULT_DUMP_DIR_MODE | S_IROTH;
/* and readable only for the owner otherwise */
if (!world_readable_dump)
{
mode = DEFAULT_DUMP_DIR_MODE;
my_euid = geteuid();
}
pid_t my_pid = getpid();
unsigned idx = 0;
unsigned errors = 0;
while (idx < oops_cnt)
{
char base[sizeof("oops-YYYY-MM-DD-hh:mm:ss-%lu-%lu") + 2 * sizeof(long)*3];
sprintf(base, "oops-%s-%lu-%lu", iso_date, (long)my_pid, (long)idx);
char *path = concat_path_file(debug_dumps_dir, base);
struct dump_dir *dd = dd_create(path, /*uid:*/ my_euid, mode);
if (dd)
{
dd_create_basic_files(dd, /*uid:*/ my_euid, NULL);
save_oops_data_in_dump_dir(dd, (char*)g_list_nth_data(oops_list, idx++), proc_modules);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
dd_save_text(dd, FILENAME_ANALYZER, "Kerneloops");
dd_save_text(dd, FILENAME_TYPE, "Kerneloops");
if (cmdline_str)
dd_save_text(dd, FILENAME_CMDLINE, cmdline_str);
if (proc_modules)
dd_save_text(dd, "proc_modules", proc_modules);
if (fips_enabled && strcmp(fips_enabled, "0") != 0)
dd_save_text(dd, "fips_enabled", fips_enabled);
if (suspend_stats)
dd_save_text(dd, "suspend_stats", suspend_stats);
dd_close(dd);
notify_new_path(path);
}
else
errors++;
free(path);
if (--countdown == 0)
break;
if (dd && throttle_dd_creation)
sleep(1);
}
free(cmdline_str);
free(proc_modules);
free(fips_enabled);
free(suspend_stats);
return errors;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: htmlCreateFileParserCtxt(const char *filename, const char *encoding)
{
htmlParserCtxtPtr ctxt;
htmlParserInputPtr inputStream;
char *canonicFilename;
/* htmlCharEncoding enc; */
xmlChar *content, *content_line = (xmlChar *) "charset=";
if (filename == NULL)
return(NULL);
ctxt = htmlNewParserCtxt();
if (ctxt == NULL) {
return(NULL);
}
canonicFilename = (char *) xmlCanonicPath((const xmlChar *) filename);
if (canonicFilename == NULL) {
#ifdef LIBXML_SAX1_ENABLED
if (xmlDefaultSAXHandler.error != NULL) {
xmlDefaultSAXHandler.error(NULL, "out of memory\n");
}
#endif
xmlFreeParserCtxt(ctxt);
return(NULL);
}
inputStream = xmlLoadExternalEntity(canonicFilename, NULL, ctxt);
xmlFree(canonicFilename);
if (inputStream == NULL) {
xmlFreeParserCtxt(ctxt);
return(NULL);
}
inputPush(ctxt, inputStream);
/* set encoding */
if (encoding) {
size_t l = strlen(encoding);
if (l < 1000) {
content = xmlMallocAtomic (xmlStrlen(content_line) + l + 1);
if (content) {
strcpy ((char *)content, (char *)content_line);
strcat ((char *)content, (char *)encoding);
htmlCheckEncoding (ctxt, content);
xmlFree (content);
}
}
}
return(ctxt);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval)
{
GetByteContext *gb = &s->gb;
RangeCoder *rc = &s->rc;
unsigned totfr = pixel->total_freq;
unsigned value, x = 0, cumfr = 0, cnt_x = 0;
int i, j, ret, c, cnt_c;
if ((ret = s->get_freq(rc, totfr, &value)) < 0)
return ret;
while (x < 16) {
cnt_x = pixel->lookup[x];
if (value >= cumfr + cnt_x)
cumfr += cnt_x;
else
break;
x++;
}
c = x * 16;
cnt_c = 0;
while (c < 256) {
cnt_c = pixel->freq[c];
if (value >= cumfr + cnt_c)
cumfr += cnt_c;
else
break;
c++;
}
if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0)
return ret;
pixel->freq[c] = cnt_c + step;
pixel->lookup[x] = cnt_x + step;
totfr += step;
if (totfr > BOT) {
totfr = 0;
for (i = 0; i < 256; i++) {
unsigned nc = (pixel->freq[i] >> 1) + 1;
pixel->freq[i] = nc;
totfr += nc;
}
for (i = 0; i < 16; i++) {
unsigned sum = 0;
unsigned i16_17 = i << 4;
for (j = 0; j < 16; j++)
sum += pixel->freq[i16_17 + j];
pixel->lookup[i] = sum;
}
}
pixel->total_freq = totfr;
*rval = c & s->cbits;
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: SPL_METHOD(SplFileInfo, getFileInfo)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_class_entry *ce = intern->info_class;
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) {
spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void CheckFails(
const WebURLRequest& request,
WebAssociatedURLLoaderOptions options = WebAssociatedURLLoaderOptions()) {
expected_loader_ = CreateAssociatedURLLoader(options);
EXPECT_TRUE(expected_loader_);
did_fail_ = false;
expected_loader_->LoadAsynchronously(request, this);
EXPECT_FALSE(did_fail_);
RunPendingTasks();
EXPECT_TRUE(did_fail_);
EXPECT_FALSE(did_receive_response_);
}
CWE ID: CWE-93
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: char *flash_strncpy(char *dst, const char *src, size_t c) {
char *d = dst;
uint32_t *s = (uint32_t *)src;
size_t slen = flash_strlen(src);
size_t len = slen > c ? c : slen;
while (len >= 4) {
uint32_t w = *s++;
*d++ = w & 0xff; w >>= 8;
*d++ = w & 0xff; w >>= 8;
*d++ = w & 0xff; w >>= 8;
*d++ = w & 0xff;
len -= 4;
}
if (len > 0) {
uint32_t w = *s++;
while (len-- > 0) {
*d++ = w & 0xff; w >>= 8;
}
}
if (slen < c) *d = 0;
return dst;
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void HTMLAnchorElement::handleClick(Event* event)
{
event->setDefaultHandled();
LocalFrame* frame = document().frame();
if (!frame)
return;
StringBuilder url;
url.append(stripLeadingAndTrailingHTMLSpaces(fastGetAttribute(hrefAttr)));
appendServerMapMousePosition(url, event);
KURL completedURL = document().completeURL(url.toString());
sendPings(completedURL);
ResourceRequest request(completedURL);
request.setUIStartTime(event->platformTimeStamp());
request.setInputPerfMetricReportPolicy(InputToLoadPerfMetricReportPolicy::ReportLink);
ReferrerPolicy policy;
if (hasAttribute(referrerpolicyAttr) && SecurityPolicy::referrerPolicyFromString(fastGetAttribute(referrerpolicyAttr), &policy) && !hasRel(RelationNoReferrer)) {
request.setHTTPReferrer(SecurityPolicy::generateReferrer(policy, completedURL, document().outgoingReferrer()));
}
if (hasAttribute(downloadAttr)) {
request.setRequestContext(WebURLRequest::RequestContextDownload);
bool isSameOrigin = completedURL.protocolIsData() || document().getSecurityOrigin()->canRequest(completedURL);
const AtomicString& suggestedName = (isSameOrigin ? fastGetAttribute(downloadAttr) : nullAtom);
frame->loader().client()->loadURLExternally(request, NavigationPolicyDownload, suggestedName, false);
} else {
request.setRequestContext(WebURLRequest::RequestContextHyperlink);
FrameLoadRequest frameRequest(&document(), request, getAttribute(targetAttr));
frameRequest.setTriggeringEvent(event);
if (hasRel(RelationNoReferrer)) {
frameRequest.setShouldSendReferrer(NeverSendReferrer);
frameRequest.setShouldSetOpener(NeverSetOpener);
}
if (hasRel(RelationNoOpener))
frameRequest.setShouldSetOpener(NeverSetOpener);
frame->loader().load(frameRequest);
}
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void coroutine_fn bdrv_create_co_entry(void *opaque)
{
Error *local_err = NULL;
int ret;
CreateCo *cco = opaque;
assert(cco->drv);
ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
if (local_err) {
error_propagate(&cco->err, local_err);
}
cco->ret = ret;
}
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 WebContentsImpl::DidGetResourceResponseStart(
const ResourceRequestDetails& details) {
controller_.ssl_manager()->DidStartResourceResponse(details);
FOR_EACH_OBSERVER(WebContentsObserver, observers_,
DidGetResourceResponseStart(details));
NotificationService::current()->Notify(
NOTIFICATION_RESOURCE_RESPONSE_STARTED,
Source<WebContents>(this),
Details<const ResourceRequestDetails>(&details));
}
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: base::PlatformFileError ModifyCacheState(
const FilePath& source_path,
const FilePath& dest_path,
GDataCache::FileOperationType file_operation_type,
const FilePath& symlink_path,
bool create_symlink) {
if (source_path != dest_path) {
bool success = false;
if (file_operation_type == GDataCache::FILE_OPERATION_MOVE)
success = file_util::Move(source_path, dest_path);
else if (file_operation_type == GDataCache::FILE_OPERATION_COPY)
success = file_util::CopyFile(source_path, dest_path);
if (!success) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error "
<< (file_operation_type == GDataCache::FILE_OPERATION_MOVE ?
"moving " : "copying ")
<< source_path.value()
<< " to " << dest_path.value();
return error;
} else {
DVLOG(1) << (file_operation_type == GDataCache::FILE_OPERATION_MOVE ?
"Moved " : "Copied ")
<< source_path.value()
<< " to " << dest_path.value();
}
} else {
DVLOG(1) << "No need to move file: source = destination";
}
if (symlink_path.empty())
return base::PLATFORM_FILE_OK;
bool deleted = util::DeleteSymlink(symlink_path);
if (deleted) {
DVLOG(1) << "Deleted symlink " << symlink_path.value();
} else {
if (errno != ENOENT)
PLOG(WARNING) << "Error deleting symlink " << symlink_path.value();
}
if (!create_symlink)
return base::PLATFORM_FILE_OK;
if (!file_util::CreateSymbolicLink(dest_path, symlink_path)) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error creating symlink " << symlink_path.value()
<< " for " << dest_path.value();
return error;
} else {
DVLOG(1) << "Created symlink " << symlink_path.value()
<< " to " << dest_path.value();
}
return base::PLATFORM_FILE_OK;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void update_or_create_fnhe(struct fib_nh *nh, __be32 daddr, __be32 gw,
u32 pmtu, unsigned long expires)
{
struct fnhe_hash_bucket *hash;
struct fib_nh_exception *fnhe;
struct rtable *rt;
u32 genid, hval;
unsigned int i;
int depth;
genid = fnhe_genid(dev_net(nh->nh_dev));
hval = fnhe_hashfun(daddr);
spin_lock_bh(&fnhe_lock);
hash = rcu_dereference(nh->nh_exceptions);
if (!hash) {
hash = kzalloc(FNHE_HASH_SIZE * sizeof(*hash), GFP_ATOMIC);
if (!hash)
goto out_unlock;
rcu_assign_pointer(nh->nh_exceptions, hash);
}
hash += hval;
depth = 0;
for (fnhe = rcu_dereference(hash->chain); fnhe;
fnhe = rcu_dereference(fnhe->fnhe_next)) {
if (fnhe->fnhe_daddr == daddr)
break;
depth++;
}
if (fnhe) {
if (fnhe->fnhe_genid != genid)
fnhe->fnhe_genid = genid;
if (gw)
fnhe->fnhe_gw = gw;
if (pmtu)
fnhe->fnhe_pmtu = pmtu;
fnhe->fnhe_expires = max(1UL, expires);
/* Update all cached dsts too */
rt = rcu_dereference(fnhe->fnhe_rth_input);
if (rt)
fill_route_from_fnhe(rt, fnhe);
rt = rcu_dereference(fnhe->fnhe_rth_output);
if (rt)
fill_route_from_fnhe(rt, fnhe);
} else {
if (depth > FNHE_RECLAIM_DEPTH)
fnhe = fnhe_oldest(hash);
else {
fnhe = kzalloc(sizeof(*fnhe), GFP_ATOMIC);
if (!fnhe)
goto out_unlock;
fnhe->fnhe_next = hash->chain;
rcu_assign_pointer(hash->chain, fnhe);
}
fnhe->fnhe_genid = genid;
fnhe->fnhe_daddr = daddr;
fnhe->fnhe_gw = gw;
fnhe->fnhe_pmtu = pmtu;
fnhe->fnhe_expires = expires;
/* Exception created; mark the cached routes for the nexthop
* stale, so anyone caching it rechecks if this exception
* applies to them.
*/
rt = rcu_dereference(nh->nh_rth_input);
if (rt)
rt->dst.obsolete = DST_OBSOLETE_KILL;
for_each_possible_cpu(i) {
struct rtable __rcu **prt;
prt = per_cpu_ptr(nh->nh_pcpu_rth_output, i);
rt = rcu_dereference(*prt);
if (rt)
rt->dst.obsolete = DST_OBSOLETE_KILL;
}
}
fnhe->fnhe_stamp = jiffies;
out_unlock:
spin_unlock_bh(&fnhe_lock);
}
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 DiscardAndActivateTest(DiscardReason reason) {
LifecycleUnit* background_lifecycle_unit = nullptr;
LifecycleUnit* foreground_lifecycle_unit = nullptr;
CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit,
&foreground_lifecycle_unit);
content::WebContents* initial_web_contents =
tab_strip_model_->GetWebContentsAt(0);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true));
background_lifecycle_unit->Discard(reason);
testing::Mock::VerifyAndClear(&tab_observer_);
TransitionFromPendingDiscardToDiscardedIfNeeded(reason,
background_lifecycle_unit);
EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0));
EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false));
tab_strip_model_->ActivateTabAt(0, true);
testing::Mock::VerifyAndClear(&tab_observer_);
EXPECT_EQ(LifecycleUnitState::ACTIVE,
background_lifecycle_unit->GetState());
EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0)
->GetController()
.GetPendingEntry());
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void UrlData::set_has_opaque_data(bool has_opaque_data) {
if (has_opaque_data_)
return;
has_opaque_data_ = has_opaque_data;
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: void LocalFrameClientImpl::DidRunInsecureContent(const SecurityOrigin* origin,
const KURL& insecure_url) {
if (web_frame_->Client()) {
web_frame_->Client()->DidRunInsecureContent(WebSecurityOrigin(origin),
insecure_url);
}
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int do_recv_XButtonEvent(rpc_message_t *message, XEvent *xevent)
{
int32_t x, y, x_root, y_root, same_screen;
uint32_t root, subwindow, time, state, button;
int error;
if ((error = do_recv_XAnyEvent(message, xevent)) < 0)
return error;
if ((error = rpc_message_recv_uint32(message, &root)) < 0)
return error;
if ((error = rpc_message_recv_uint32(message, &subwindow)) < 0)
return error;
if ((error = rpc_message_recv_uint32(message, &time)) < 0)
return error;
if ((error = rpc_message_recv_int32(message, &x)) < 0)
return error;
if ((error = rpc_message_recv_int32(message, &y)) < 0)
return error;
if ((error = rpc_message_recv_int32(message, &x_root)) < 0)
return error;
if ((error = rpc_message_recv_int32(message, &y_root)) < 0)
return error;
if ((error = rpc_message_recv_uint32(message, &state)) < 0)
return error;
if ((error = rpc_message_recv_uint32(message, &button)) < 0)
return error;
if ((error = rpc_message_recv_int32(message, &same_screen)) < 0)
return error;
xevent->xbutton.root = root;
xevent->xbutton.subwindow = subwindow;
xevent->xbutton.time = time;
xevent->xbutton.x = x;
xevent->xbutton.y = y;
xevent->xbutton.x_root = x_root;
xevent->xbutton.y_root = y_root;
xevent->xbutton.state = state;
xevent->xbutton.button = button;
xevent->xbutton.same_screen = same_screen;
return RPC_ERROR_NO_ERROR;
}
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: validate_event(struct pmu_hw_events *hw_events,
struct perf_event *event)
{
struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
struct hw_perf_event fake_event = event->hw;
struct pmu *leader_pmu = event->group_leader->pmu;
if (is_software_event(event))
return 1;
if (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF)
return 1;
if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)
return 1;
return armpmu->get_event_idx(hw_events, &fake_event) >= 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void HTMLFormControlElement::dispatchChangeEvent() {
dispatchScopedEvent(Event::createBubble(EventTypeNames::change));
}
CWE ID: CWE-1021
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 sctp_getsockopt_assoc_number(struct sock *sk, int len,
char __user *optval, int __user *optlen)
{
struct sctp_sock *sp = sctp_sk(sk);
struct sctp_association *asoc;
u32 val = 0;
if (sctp_style(sk, TCP))
return -EOPNOTSUPP;
if (len < sizeof(u32))
return -EINVAL;
len = sizeof(u32);
list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
val++;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
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: unsigned int SAD(unsigned int max_sad, int block_idx = 0) {
unsigned int ret;
const uint8_t* const reference = GetReference(block_idx);
REGISTER_STATE_CHECK(ret = GET_PARAM(2)(source_data_, source_stride_,
reference, reference_stride_,
max_sad));
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
{
#if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
return inet_ntop(af, src, dst, len);
#else
if (af == AF_INET) {
const struct in_addr *in = src;
const ev_uint32_t a = ntohl(in->s_addr);
int r;
r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
(int)(ev_uint8_t)((a>>24)&0xff),
(int)(ev_uint8_t)((a>>16)&0xff),
(int)(ev_uint8_t)((a>>8 )&0xff),
(int)(ev_uint8_t)((a )&0xff));
if (r<0||(size_t)r>=len)
return NULL;
else
return dst;
#ifdef AF_INET6
} else if (af == AF_INET6) {
const struct in6_addr *addr = src;
char buf[64], *cp;
int longestGapLen = 0, longestGapPos = -1, i,
curGapPos = -1, curGapLen = 0;
ev_uint16_t words[8];
for (i = 0; i < 8; ++i) {
words[i] =
(((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
}
if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
(words[5] == 0xffff))) {
/* This is an IPv4 address. */
if (words[5] == 0) {
evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
addr->s6_addr[12], addr->s6_addr[13],
addr->s6_addr[14], addr->s6_addr[15]);
} else {
evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
addr->s6_addr[12], addr->s6_addr[13],
addr->s6_addr[14], addr->s6_addr[15]);
}
if (strlen(buf) > len)
return NULL;
strlcpy(dst, buf, len);
return dst;
}
i = 0;
while (i < 8) {
if (words[i] == 0) {
curGapPos = i++;
curGapLen = 1;
while (i<8 && words[i] == 0) {
++i; ++curGapLen;
}
if (curGapLen > longestGapLen) {
longestGapPos = curGapPos;
longestGapLen = curGapLen;
}
} else {
++i;
}
}
if (longestGapLen<=1)
longestGapPos = -1;
cp = buf;
for (i = 0; i < 8; ++i) {
if (words[i] == 0 && longestGapPos == i) {
if (i == 0)
*cp++ = ':';
*cp++ = ':';
while (i < 8 && words[i] == 0)
++i;
--i; /* to compensate for loop increment. */
} else {
evutil_snprintf(cp,
sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
cp += strlen(cp);
if (i != 7)
*cp++ = ':';
}
}
*cp = '\0';
if (strlen(buf) > len)
return NULL;
strlcpy(dst, buf, len);
return dst;
#endif
} else {
return NULL;
}
#endif
}
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 dns_deinit(void)
{
struct dns_resolvers *resolvers, *resolversback;
struct dns_nameserver *ns, *nsback;
struct dns_resolution *res, *resback;
struct dns_requester *req, *reqback;
struct dns_srvrq *srvrq, *srvrqback;
list_for_each_entry_safe(resolvers, resolversback, &dns_resolvers, list) {
list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
free(ns->id);
free((char *)ns->conf.file);
if (ns->dgram && ns->dgram->t.sock.fd != -1)
fd_delete(ns->dgram->t.sock.fd);
free(ns->dgram);
LIST_DEL(&ns->list);
free(ns);
}
list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
list_for_each_entry_safe(req, reqback, &res->requesters, list) {
LIST_DEL(&req->list);
free(req);
}
dns_free_resolution(res);
}
list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
list_for_each_entry_safe(req, reqback, &res->requesters, list) {
LIST_DEL(&req->list);
free(req);
}
dns_free_resolution(res);
}
free(resolvers->id);
free((char *)resolvers->conf.file);
task_delete(resolvers->t);
task_free(resolvers->t);
LIST_DEL(&resolvers->list);
free(resolvers);
}
list_for_each_entry_safe(srvrq, srvrqback, &dns_srvrq_list, list) {
free(srvrq->name);
free(srvrq->hostname_dn);
LIST_DEL(&srvrq->list);
free(srvrq);
}
}
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 PromoResourceService::PostNotification(int64 delay_ms) {
if (web_resource_update_scheduled_)
return;
if (delay_ms > 0) {
web_resource_update_scheduled_ = true;
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&PromoResourceService::PromoResourceStateChange,
weak_ptr_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(delay_ms));
} else if (delay_ms == 0) {
PromoResourceStateChange();
}
}
CWE ID:
Target: 1
Example 2:
Code: static unsigned int __ctr_crypt(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
const unsigned int bsize = CAST5_BLOCK_SIZE;
unsigned int nbytes = walk->nbytes;
u64 *src = (u64 *)walk->src.virt.addr;
u64 *dst = (u64 *)walk->dst.virt.addr;
/* Process multi-block batch */
if (nbytes >= bsize * CAST5_PARALLEL_BLOCKS) {
do {
cast5_ctr_16way(ctx, (u8 *)dst, (u8 *)src,
(__be64 *)walk->iv);
src += CAST5_PARALLEL_BLOCKS;
dst += CAST5_PARALLEL_BLOCKS;
nbytes -= bsize * CAST5_PARALLEL_BLOCKS;
} while (nbytes >= bsize * CAST5_PARALLEL_BLOCKS);
if (nbytes < bsize)
goto done;
}
/* Handle leftovers */
do {
u64 ctrblk;
if (dst != src)
*dst = *src;
ctrblk = *(u64 *)walk->iv;
be64_add_cpu((__be64 *)walk->iv, 1);
__cast5_encrypt(ctx, (u8 *)&ctrblk, (u8 *)&ctrblk);
*dst ^= ctrblk;
src += 1;
dst += 1;
nbytes -= bsize;
} while (nbytes >= bsize);
done:
return nbytes;
}
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 AutofillDialogViews::SectionContainer::OnMouseMoved(
const ui::MouseEvent& event) {
SetActive(ShouldForwardEvent(event));
}
CWE ID: CWE-20
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.