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: static bool TokenExitsSVG(const CompactHTMLToken& token) {
return DeprecatedEqualIgnoringCase(token.Data(),
SVGNames::foreignObjectTag.LocalName());
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: WORD32 ih264d_parse_sei_payload(dec_bit_stream_t *ps_bitstrm,
UWORD32 ui4_payload_type,
UWORD32 ui4_payload_size,
dec_struct_t *ps_dec)
{
sei *ps_sei;
WORD32 i4_status = 0;
ps_sei = (sei *)ps_dec->ps_sei;
switch(ui4_payload_type)
{
case SEI_BUF_PERIOD:
i4_status = ih264d_parse_buffering_period(&ps_sei->s_buf_period,
ps_bitstrm, ps_dec);
/*if(i4_status != OK)
return i4_status;*/
break;
case SEI_PIC_TIMING:
if(NULL == ps_dec->ps_cur_sps)
ih264d_flush_bits_h264(ps_bitstrm, (ui4_payload_size << 3));
else
ih264d_parse_pic_timing(ps_bitstrm, ps_dec,
ui4_payload_size);
break;
case SEI_RECOVERY_PT:
ih264d_parse_recovery_point(ps_bitstrm, ps_dec,
ui4_payload_size);
break;
default:
ih264d_flush_bits_h264(ps_bitstrm, (ui4_payload_size << 3));
break;
}
return (i4_status);
}
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: const Cluster* Segment::GetNext(const Cluster* pCurr)
{
assert(pCurr);
assert(pCurr != &m_eos);
assert(m_clusters);
long idx = pCurr->m_index;
if (idx >= 0)
{
assert(m_clusterCount > 0);
assert(idx < m_clusterCount);
assert(pCurr == m_clusters[idx]);
++idx;
if (idx >= m_clusterCount)
return &m_eos; //caller will LoadCluster as desired
Cluster* const pNext = m_clusters[idx];
assert(pNext);
assert(pNext->m_index >= 0);
assert(pNext->m_index == idx);
return pNext;
}
assert(m_clusterPreloadCount > 0);
long long pos = pCurr->m_element_start;
assert(m_size >= 0); //TODO
const long long stop = m_start + m_size; //end of segment
{
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); //TODO
if (result != 0)
return NULL;
const long long id = ReadUInt(m_pReader, pos, len);
assert(id == 0x0F43B675); //Cluster ID
if (id != 0x0F43B675)
return NULL;
pos += len; //consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); //TODO
assert((pos + len) <= stop); //TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size > 0); //TODO
pos += len; //consume length of size of element
assert((pos + size) <= stop); //TODO
pos += size; //consume payload
}
long long off_next = 0;
while (pos < stop)
{
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); //TODO
if (result != 0)
return NULL;
const long long idpos = pos; //pos of next (potential) cluster
const long long id = ReadUInt(m_pReader, idpos, len);
assert(id > 0); //TODO
pos += len; //consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); //TODO
assert((pos + len) <= stop); //TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size >= 0); //TODO
pos += len; //consume length of size of element
assert((pos + size) <= stop); //TODO
if (size == 0) //weird
continue;
if (id == 0x0F43B675) //Cluster ID
{
const long long off_next_ = idpos - m_start;
long long pos_;
long len_;
const long status = Cluster::HasBlockEntries(
this,
off_next_,
pos_,
len_);
assert(status >= 0);
if (status > 0)
{
off_next = off_next_;
break;
}
}
pos += size; //consume payload
}
if (off_next <= 0)
return 0;
Cluster** const ii = m_clusters + m_clusterCount;
Cluster** i = ii;
Cluster** const jj = ii + m_clusterPreloadCount;
Cluster** j = jj;
while (i < j)
{
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pNext = *k;
assert(pNext);
assert(pNext->m_index < 0);
pos = pNext->GetPosition();
if (pos < off_next)
i = k + 1;
else if (pos > off_next)
j = k;
else
return pNext;
}
assert(i == j);
Cluster* const pNext = Cluster::Create(this,
-1,
off_next);
assert(pNext);
const ptrdiff_t idx_next = i - m_clusters; //insertion position
PreloadCluster(pNext, idx_next);
assert(m_clusters);
assert(idx_next < m_clusterSize);
assert(m_clusters[idx_next] == pNext);
return pNext;
}
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: RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host)
: host_(RenderWidgetHostImpl::From(host)),
ALLOW_THIS_IN_INITIALIZER_LIST(window_(new aura::Window(this))),
in_shutdown_(false),
is_fullscreen_(false),
popup_parent_host_view_(NULL),
popup_child_host_view_(NULL),
is_loading_(false),
text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
can_compose_inline_(true),
has_composition_text_(false),
device_scale_factor_(1.0f),
current_surface_(0),
current_surface_is_protected_(true),
current_surface_in_use_by_compositor_(true),
protection_state_id_(0),
surface_route_id_(0),
paint_canvas_(NULL),
synthetic_move_sent_(false),
accelerated_compositing_state_changed_(false),
can_lock_compositor_(YES) {
host_->SetView(this);
window_observer_.reset(new WindowObserver(this));
window_->AddObserver(window_observer_.get());
aura::client::SetTooltipText(window_, &tooltip_);
aura::client::SetActivationDelegate(window_, this);
gfx::Screen::GetScreenFor(window_)->AddObserver(this);
}
CWE ID:
Target: 1
Example 2:
Code: struct crypto_alg *crypto_alg_lookup(const char *name, u32 type, u32 mask)
{
struct crypto_alg *alg;
down_read(&crypto_alg_sem);
alg = __crypto_alg_lookup(name, type, mask);
up_read(&crypto_alg_sem);
return alg;
}
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: MagickExport MagickBooleanType SetQuantumDepth(const Image *image,
QuantumInfo *quantum_info,const size_t depth)
{
size_t
extent,
quantum;
/*
Allocate the quantum pixel buffer.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickSignature);
quantum_info->depth=depth;
if (quantum_info->format == FloatingPointQuantumFormat)
{
if (quantum_info->depth > 32)
quantum_info->depth=64;
else
if (quantum_info->depth > 16)
quantum_info->depth=32;
else
quantum_info->depth=16;
}
if (quantum_info->pixels != (unsigned char **) NULL)
DestroyQuantumPixels(quantum_info);
quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8;
extent=image->columns*quantum;
if (quantum != (extent/image->columns))
return(MagickFalse);
return(AcquireQuantumPixels(quantum_info,extent));
}
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: static bool do_write_pids(pid_t tpid, const char *contrl, const char *cg, const char *file, const char *buf)
{
int sock[2] = {-1, -1};
pid_t qpid, cpid = -1;
FILE *pids_file = NULL;
bool answer = false, fail = false;
pids_file = open_pids_file(contrl, cg);
if (!pids_file)
return false;
/*
* write the pids to a socket, have helper in writer's pidns
* call movepid for us
*/
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sock) < 0) {
perror("socketpair");
goto out;
}
cpid = fork();
if (cpid == -1)
goto out;
if (!cpid) { // child
fclose(pids_file);
pid_from_ns_wrapper(sock[1], tpid);
}
const char *ptr = buf;
while (sscanf(ptr, "%d", &qpid) == 1) {
struct ucred cred;
char v;
if (write(sock[0], &qpid, sizeof(qpid)) != sizeof(qpid)) {
fprintf(stderr, "%s: error writing pid to child: %s\n",
__func__, strerror(errno));
goto out;
}
if (recv_creds(sock[0], &cred, &v)) {
if (v == '0') {
if (fprintf(pids_file, "%d", (int) cred.pid) < 0)
fail = true;
}
}
ptr = strchr(ptr, '\n');
if (!ptr)
break;
ptr++;
}
/* All good, write the value */
qpid = -1;
if (write(sock[0], &qpid ,sizeof(qpid)) != sizeof(qpid))
fprintf(stderr, "Warning: failed to ask child to exit\n");
if (!fail)
answer = true;
out:
if (cpid != -1)
wait_for_pid(cpid);
if (sock[0] != -1) {
close(sock[0]);
close(sock[1]);
}
if (pids_file) {
if (fclose(pids_file) != 0)
answer = false;
}
return answer;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: virtual void TearDown() {
sync_service_.reset();
profile()->ResetRequestContext();
DestroyBrowser();
set_profile(NULL);
MessageLoop::current()->RunAllPending();
io_thread_.Stop();
MessageLoop::current()->RunAllPending();
BrowserWithTestWindowTest::TearDown();
}
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 u32 vmci_transport_get_local_cid(void)
{
return vmci_get_context_id();
}
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: bool PlatformSensorProviderBase::CreateSharedBufferIfNeeded() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
if (shared_buffer_handle_.is_valid())
return true;
shared_buffer_handle_ =
mojo::SharedBufferHandle::Create(kSharedBufferSizeInBytes);
return shared_buffer_handle_.is_valid();
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: void Performance::NotifyObserversOfEntries(PerformanceEntryVector& entries) {
for (const auto& entry : entries) {
NotifyObserversOfEntry(*entry.Get());
}
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void pdf_run_Ts(fz_context *ctx, pdf_processor *proc, float rise)
{
pdf_run_processor *pr = (pdf_run_processor *)proc;
pdf_gstate *gstate = pr->gstate + pr->gtop;
gstate->text.rise = rise;
}
CWE ID: CWE-416
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Maybe<bool> IncludesValueImpl(Isolate* isolate,
Handle<JSObject> receiver,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
bool search_for_hole = value->IsUndefined(isolate);
if (!search_for_hole) {
Maybe<bool> result = Nothing<bool>();
if (DictionaryElementsAccessor::IncludesValueFastPath(
isolate, receiver, value, start_from, length, &result)) {
return result;
}
}
Handle<SeededNumberDictionary> dictionary(
SeededNumberDictionary::cast(receiver->elements()), isolate);
for (uint32_t k = start_from; k < length; ++k) {
int entry = dictionary->FindEntry(isolate, k);
if (entry == SeededNumberDictionary::kNotFound) {
if (search_for_hole) return Just(true);
continue;
}
PropertyDetails details = GetDetailsImpl(*dictionary, entry);
switch (details.kind()) {
case kData: {
Object* element_k = dictionary->ValueAt(entry);
if (value->SameValueZero(element_k)) return Just(true);
break;
}
case kAccessor: {
LookupIterator it(isolate, receiver, k,
LookupIterator::OWN_SKIP_INTERCEPTOR);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
Handle<Object> element_k;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
Nothing<bool>());
if (value->SameValueZero(*element_k)) return Just(true);
if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
if (*dictionary == receiver->elements()) continue;
if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
if (receiver->map()->GetInitialElements() == receiver->elements()) {
return Just(search_for_hole);
}
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
dictionary = handle(
SeededNumberDictionary::cast(receiver->elements()), isolate);
break;
}
}
}
return Just(false);
}
CWE ID: CWE-704
Target: 1
Example 2:
Code: FixedLengthEncoder::~FixedLengthEncoder() {
if (str->isEncoder())
delete str;
}
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: map_engine_persons(void)
{
int i;
if (s_person_list == NULL)
s_person_list = vector_new(sizeof(person_t*));
vector_clear(s_person_list);
for (i = 0; i < s_num_persons; ++i)
vector_push(s_person_list, &s_persons[i]);
return s_person_list;
}
CWE ID: CWE-190
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i+1], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1]));
break;
}
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i+1]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[i+1] && atts[i+1][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
i++;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void sco_conn_defer_accept(struct hci_conn *conn, u16 setting)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("conn %p", conn);
conn->state = BT_CONFIG;
if (!lmp_esco_capable(hdev)) {
struct hci_cp_accept_conn_req cp;
bacpy(&cp.bdaddr, &conn->dst);
cp.role = 0x00; /* Ignored */
hci_send_cmd(hdev, HCI_OP_ACCEPT_CONN_REQ, sizeof(cp), &cp);
} else {
struct hci_cp_accept_sync_conn_req cp;
bacpy(&cp.bdaddr, &conn->dst);
cp.pkt_type = cpu_to_le16(conn->pkt_type);
cp.tx_bandwidth = cpu_to_le32(0x00001f40);
cp.rx_bandwidth = cpu_to_le32(0x00001f40);
cp.content_format = cpu_to_le16(setting);
switch (setting & SCO_AIRMODE_MASK) {
case SCO_AIRMODE_TRANSP:
if (conn->pkt_type & ESCO_2EV3)
cp.max_latency = cpu_to_le16(0x0008);
else
cp.max_latency = cpu_to_le16(0x000D);
cp.retrans_effort = 0x02;
break;
case SCO_AIRMODE_CVSD:
cp.max_latency = cpu_to_le16(0xffff);
cp.retrans_effort = 0xff;
break;
}
hci_send_cmd(hdev, HCI_OP_ACCEPT_SYNC_CONN_REQ,
sizeof(cp), &cp);
}
}
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 RenderFrameImpl::PluginDidStopLoading() {
DidStopLoading();
}
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: virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video) {
frame_flags_ &= ~(VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
if (droppable_nframes_ > 0 &&
(cfg_.g_pass == VPX_RC_LAST_PASS || cfg_.g_pass == VPX_RC_ONE_PASS)) {
for (unsigned int i = 0; i < droppable_nframes_; ++i) {
if (droppable_frames_[i] == video->frame()) {
std::cout << " Encoding droppable frame: "
<< droppable_frames_[i] << "\n";
frame_flags_ |= (VP8_EFLAG_NO_UPD_LAST |
VP8_EFLAG_NO_UPD_GF |
VP8_EFLAG_NO_UPD_ARF);
return;
}
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk)
{
unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12;
return &chunk[total_chunk_length];
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
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: AppCache::AppCache(AppCacheStorage* storage, int64_t cache_id)
: cache_id_(cache_id),
owning_group_(nullptr),
online_whitelist_all_(false),
is_complete_(false),
cache_size_(0),
storage_(storage) {
storage_->working_set()->AddCache(this);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void HTMLSelectElement::typeAheadFind(KeyboardEvent* event)
{
int index = m_typeAhead.handleEvent(event, TypeAhead::MatchPrefix | TypeAhead::CycleFirstChar);
if (index < 0)
return;
selectOption(listToOptionIndex(index), DeselectOtherOptions | DispatchChangeEvent | UserDriven);
if (!usesMenuList())
listBoxOnChange();
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int init_ssl_connection(SSL *con)
{
int i;
const char *str;
X509 *peer;
long verify_error;
MS_STATIC char buf[BUFSIZ];
#ifndef OPENSSL_NO_KRB5
char *client_princ;
#endif
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
const unsigned char *next_proto_neg;
unsigned next_proto_neg_len;
#endif
unsigned char *exportedkeymat;
i = SSL_accept(con);
#ifdef CERT_CB_TEST_RETRY
{
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
&& SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) {
fprintf(stderr,
"LOOKUP from certificate callback during accept\n");
i = SSL_accept(con);
}
}
#endif
#ifndef OPENSSL_NO_SRP
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
srp_callback_parm.user =
SRP_VBASE_get_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
srp_callback_parm.user =
SRP_VBASE_get_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
return (1);
}
BIO_printf(bio_err, "ERROR\n");
verify_error = SSL_get_verify_result(con);
if (verify_error != X509_V_OK) {
BIO_printf(bio_err, "verify error:%s\n",
X509_verify_cert_error_string(verify_error));
}
/* Always print any error messages */
ERR_print_errors(bio_err);
return (0);
}
if (s_brief)
print_ssl_summary(bio_err, con);
PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
peer = SSL_get_peer_certificate(con);
if (peer != NULL) {
BIO_printf(bio_s_out, "Client certificate\n");
PEM_write_bio_X509(bio_s_out, peer);
X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
BIO_printf(bio_s_out, "subject=%s\n", buf);
X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
BIO_printf(bio_s_out, "issuer=%s\n", buf);
X509_free(peer);
}
if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
ssl_print_sigalgs(bio_s_out, con);
#ifndef OPENSSL_NO_EC
ssl_print_point_formats(bio_s_out, con);
ssl_print_curves(bio_s_out, con, 0);
#endif
BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
if (next_proto_neg) {
BIO_printf(bio_s_out, "NEXTPROTO is ");
BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
BIO_printf(bio_s_out, "\n");
}
#endif
#ifndef OPENSSL_NO_SRTP
{
SRTP_PROTECTION_PROFILE *srtp_profile
= SSL_get_selected_srtp_profile(con);
if (srtp_profile)
BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
srtp_profile->name);
}
#endif
if (SSL_cache_hit(con))
BIO_printf(bio_s_out, "Reused session-id\n");
if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) &
TLS1_FLAGS_TLS_PADDING_BUG)
BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n");
#ifndef OPENSSL_NO_KRB5
client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con));
if (client_princ != NULL) {
BIO_printf(bio_s_out, "Kerberos peer principal is %s\n",
client_princ);
}
#endif /* OPENSSL_NO_KRB5 */
BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
if (keymatexportlabel != NULL) {
BIO_printf(bio_s_out, "Keying material exporter:\n");
BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
exportedkeymat = OPENSSL_malloc(keymatexportlen);
if (exportedkeymat != NULL) {
if (!SSL_export_keying_material(con, exportedkeymat,
keymatexportlen,
keymatexportlabel,
strlen(keymatexportlabel),
NULL, 0, 0)) {
BIO_printf(bio_s_out, " Error\n");
} else {
BIO_printf(bio_s_out, " Keying material: ");
for (i = 0; i < keymatexportlen; i++)
BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
BIO_printf(bio_s_out, "\n");
}
OPENSSL_free(exportedkeymat);
}
}
return (1);
}
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 set_banner(struct openconnect_info *vpninfo)
{
char *banner, *q;
const char *p;
if (!vpninfo->banner || !(banner = malloc(strlen(vpninfo->banner)))) {
unsetenv("CISCO_BANNER");
return;
}
p = vpninfo->banner;
q = banner;
while (*p) {
if (*p == '%' && isxdigit((int)(unsigned char)p[1]) &&
isxdigit((int)(unsigned char)p[2])) {
*(q++) = unhex(p + 1);
p += 3;
} else
*(q++) = *(p++);
}
*q = 0;
setenv("CISCO_BANNER", banner, 1);
free(banner);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: uint32_t MPEG4DataSource::flags() {
return mSource->flags();
}
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: Smb4KWorkgroup *Smb4KGlobal::findWorkgroup( const QString &name )
{
Smb4KWorkgroup *workgroup = NULL;
mutex.lock();
for ( int i = 0; i < p->workgroupsList.size(); ++i )
{
if ( QString::compare( p->workgroupsList.at( i )->workgroupName(),
name, Qt::CaseInsensitive ) == 0 )
{
workgroup = p->workgroupsList.at( i );
break;
}
else
{
continue;
}
}
mutex.unlock();
return workgroup;
}
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: activate_desktop_file (ActivateParameters *parameters,
NautilusFile *file)
{
ActivateParametersDesktop *parameters_desktop;
char *primary, *secondary, *display_name;
GtkWidget *dialog;
GdkScreen *screen;
char *uri;
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
if (!nautilus_file_is_trusted_link (file))
{
/* copy the parts of parameters we are interested in as the orignal will be freed */
parameters_desktop = g_new0 (ActivateParametersDesktop, 1);
if (parameters->parent_window)
{
parameters_desktop->parent_window = parameters->parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) ¶meters_desktop->parent_window);
}
parameters_desktop->file = nautilus_file_ref (file);
primary = _("Untrusted application launcher");
display_name = nautilus_file_get_display_name (file);
secondary =
g_strdup_printf (_("The application launcher “%s” has not been marked as trusted. "
"If you do not know the source of this file, launching it may be unsafe."
),
display_name);
dialog = gtk_message_dialog_new (parameters->parent_window,
0,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_NONE,
NULL);
g_object_set (dialog,
"text", primary,
"secondary-text", secondary,
NULL);
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("_Launch Anyway"), RESPONSE_RUN);
if (nautilus_file_can_set_permissions (file))
{
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("Mark as _Trusted"), RESPONSE_MARK_TRUSTED);
}
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL);
g_signal_connect (dialog, "response",
G_CALLBACK (untrusted_launcher_response_callback),
parameters_desktop);
gtk_widget_show (dialog);
g_free (display_name);
g_free (secondary);
return;
}
uri = nautilus_file_get_uri (file);
DEBUG ("Launching trusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void free_duplicate_context(MpegEncContext *s)
{
if (!s)
return;
av_freep(&s->sc.edge_emu_buffer);
av_freep(&s->me.scratchpad);
s->me.temp =
s->sc.rd_scratchpad =
s->sc.b_scratchpad =
s->sc.obmc_scratchpad = NULL;
av_freep(&s->dct_error_sum);
av_freep(&s->me.map);
av_freep(&s->me.score_map);
av_freep(&s->blocks);
av_freep(&s->block32);
av_freep(&s->ac_val_base);
s->block = NULL;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: accept_xsmp_connection (SmsConn sms_conn,
GsmXsmpServer *server,
unsigned long *mask_ret,
SmsCallbacks *callbacks_ret,
char **failure_reason_ret)
{
IceConn ice_conn;
GsmXSMPClient *client;
/* FIXME: what about during shutdown but before gsm_xsmp_shutdown? */
if (server->priv->xsmp_sockets == NULL) {
g_debug ("GsmXsmpServer: In shutdown, rejecting new client");
*failure_reason_ret = strdup (_("Refusing new client connection because the session is currently being shut down\n"));
return FALSE;
}
ice_conn = SmsGetIceConnection (sms_conn);
client = ice_conn->context;
g_return_val_if_fail (client != NULL, TRUE);
gsm_xsmp_client_connect (client, sms_conn, mask_ret, callbacks_ret);
return TRUE;
}
CWE ID: CWE-835
Output:
| 1 |
Here are some example code snippets. Analyze the following 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 MediaElementAudioSourceHandler::Process(size_t number_of_frames) {
AudioBus* output_bus = Output(0).Bus();
MutexTryLocker try_locker(process_lock_);
if (try_locker.Locked()) {
if (!MediaElement() || !source_sample_rate_) {
output_bus->Zero();
return;
}
if (source_number_of_channels_ != output_bus->NumberOfChannels()) {
output_bus->Zero();
return;
}
AudioSourceProvider& provider = MediaElement()->GetAudioSourceProvider();
if (multi_channel_resampler_.get()) {
DCHECK_NE(source_sample_rate_, Context()->sampleRate());
multi_channel_resampler_->Process(&provider, output_bus,
number_of_frames);
} else {
DCHECK_EQ(source_sample_rate_, Context()->sampleRate());
provider.ProvideInput(output_bus, number_of_frames);
}
if (!PassesCORSAccessCheck()) {
if (maybe_print_cors_message_) {
maybe_print_cors_message_ = false;
PostCrossThreadTask(
*task_runner_, FROM_HERE,
CrossThreadBind(&MediaElementAudioSourceHandler::PrintCORSMessage,
WrapRefCounted(this), current_src_string_));
}
output_bus->Zero();
}
} else {
output_bus->Zero();
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: InitConstructResourceBytesCtx(ConstructResourceBytesCtx *ctx,
ClientPtr sendClient,
long numSpecs,
xXResResourceIdSpec *specs)
{
ctx->sendClient = sendClient;
ctx->numSizes = 0;
ctx->resultBytes = 0;
xorg_list_init(&ctx->response);
ctx->status = Success;
ctx->numSpecs = numSpecs;
ctx->specs = specs;
ctx->visitedResources = ht_create(sizeof(XID), 0,
ht_resourceid_hash, ht_resourceid_compare,
NULL);
if (!ctx->visitedResources) {
return FALSE;
} else {
return TRUE;
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
size_t msg_len)
{
struct sock *sk = asoc->base.sk;
int err = 0;
long current_timeo = *timeo_p;
DEFINE_WAIT(wait);
pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc,
*timeo_p, msg_len);
/* Increment the association's refcnt. */
sctp_association_hold(asoc);
/* Wait on the association specific sndbuf space. */
for (;;) {
prepare_to_wait_exclusive(&asoc->wait, &wait,
TASK_INTERRUPTIBLE);
if (!*timeo_p)
goto do_nonblock;
if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
asoc->base.dead)
goto do_error;
if (signal_pending(current))
goto do_interrupted;
if (msg_len <= sctp_wspace(asoc))
break;
/* Let another process have a go. Since we are going
* to sleep anyway.
*/
release_sock(sk);
current_timeo = schedule_timeout(current_timeo);
BUG_ON(sk != asoc->base.sk);
lock_sock(sk);
*timeo_p = current_timeo;
}
out:
finish_wait(&asoc->wait, &wait);
/* Release the association's refcnt. */
sctp_association_put(asoc);
return err;
do_error:
err = -EPIPE;
goto out;
do_interrupted:
err = sock_intr_errno(*timeo_p);
goto out;
do_nonblock:
err = -EAGAIN;
goto out;
}
CWE ID: CWE-362
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline void find_entity_for_char(
unsigned int k,
enum entity_charset charset,
const entity_stage1_row *table,
const unsigned char **entity,
size_t *entity_len,
unsigned char *old,
size_t oldlen,
size_t *cursor)
{
unsigned stage1_idx = ENT_STAGE1_INDEX(k);
const entity_stage3_row *c;
if (stage1_idx > 0x1D) {
*entity = NULL;
*entity_len = 0;
return;
}
c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)];
if (!c->ambiguous) {
*entity = (const unsigned char *)c->data.ent.entity;
*entity_len = c->data.ent.entity_len;
} else {
/* peek at next char */
size_t cursor_before = *cursor;
int status = SUCCESS;
unsigned next_char;
if (!(*cursor < oldlen))
goto no_suitable_2nd;
next_char = get_next_char(charset, old, oldlen, cursor, &status);
if (status == FAILURE)
goto no_suitable_2nd;
{
const entity_multicodepoint_row *s, *e;
s = &c->data.multicodepoint_table[1];
e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size;
/* we could do a binary search but it's not worth it since we have
* at most two entries... */
for ( ; s <= e; s++) {
if (s->normal_entry.second_cp == next_char) {
*entity = s->normal_entry.entity;
*entity_len = s->normal_entry.entity_len;
return;
}
}
}
no_suitable_2nd:
*cursor = cursor_before;
*entity = (const unsigned char *)
c->data.multicodepoint_table[0].leading_entry.default_entity;
*entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len;
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: bool RenderMenuList::itemIsSelected(unsigned listIndex) const
{
const Vector<HTMLElement*>& listItems = toHTMLSelectElement(node())->listItems();
if (listIndex >= listItems.size())
return false;
HTMLElement* element = listItems[listIndex];
return element->hasTagName(optionTag) && toHTMLOptionElement(element)->selected();
}
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: struct inode *isofs_iget(struct super_block *sb,
unsigned long block,
unsigned long offset)
{
unsigned long hashval;
struct inode *inode;
struct isofs_iget5_callback_data data;
long ret;
if (offset >= 1ul << sb->s_blocksize_bits)
return ERR_PTR(-EINVAL);
data.block = block;
data.offset = offset;
hashval = (block << sb->s_blocksize_bits) | offset;
inode = iget5_locked(sb, hashval, &isofs_iget5_test,
&isofs_iget5_set, &data);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
ret = isofs_read_inode(inode);
if (ret < 0) {
iget_failed(inode);
inode = ERR_PTR(ret);
} else {
unlock_new_inode(inode);
}
}
return inode;
}
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 ip_options_get_finish(struct net *net, struct ip_options **optp,
struct ip_options *opt, int optlen)
{
while (optlen & 3)
opt->__data[optlen++] = IPOPT_END;
opt->optlen = optlen;
if (optlen && ip_options_compile(net, opt, NULL)) {
kfree(opt);
return -EINVAL;
}
kfree(*optp);
*optp = opt;
return 0;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static void asymmetric_key_match_free(struct key_match_data *match_data)
{
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AppCacheUpdateJob::DeleteSoon() {
ClearPendingMasterEntries();
manifest_response_writer_.reset();
storage_->CancelDelegateCallbacks(this);
service_->RemoveObserver(this);
service_ = NULL;
if (group_) {
group_->SetUpdateAppCacheStatus(AppCacheGroup::IDLE);
group_ = NULL;
}
base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
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: Response PageHandler::SetDownloadBehavior(const std::string& behavior,
Maybe<std::string> download_path) {
WebContentsImpl* web_contents = GetWebContents();
if (!web_contents)
return Response::InternalError();
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Allow &&
!download_path.isJust())
return Response::Error("downloadPath not provided");
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Default) {
DevToolsDownloadManagerHelper::RemoveFromWebContents(web_contents);
download_manager_delegate_ = nullptr;
return Response::OK();
}
content::BrowserContext* browser_context = web_contents->GetBrowserContext();
DCHECK(browser_context);
content::DownloadManager* download_manager =
content::BrowserContext::GetDownloadManager(browser_context);
download_manager_delegate_ =
DevToolsDownloadManagerDelegate::TakeOver(download_manager);
DevToolsDownloadManagerHelper::CreateForWebContents(web_contents);
DevToolsDownloadManagerHelper* download_helper =
DevToolsDownloadManagerHelper::FromWebContents(web_contents);
download_helper->SetDownloadBehavior(
DevToolsDownloadManagerHelper::DownloadBehavior::DENY);
if (behavior == Page::SetDownloadBehavior::BehaviorEnum::Allow) {
download_helper->SetDownloadBehavior(
DevToolsDownloadManagerHelper::DownloadBehavior::ALLOW);
download_helper->SetDownloadPath(download_path.fromJust());
}
return Response::OK();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static kadm5_ret_t new_server_handle(krb5_ui_4 api_version,
struct svc_req *rqstp,
kadm5_server_handle_t
*out_handle)
{
kadm5_server_handle_t handle;
*out_handle = NULL;
if (! (handle = (kadm5_server_handle_t)
malloc(sizeof(*handle))))
return ENOMEM;
*handle = *(kadm5_server_handle_t)global_server_handle;
handle->api_version = api_version;
if (! gss_to_krb5_name(handle, rqst2name(rqstp),
&handle->current_caller)) {
free(handle);
return KADM5_FAILURE;
}
*out_handle = handle;
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: cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: do_async_error (IncrementData *data)
{
GError *error;
error = g_error_new (MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"%s",
"this method always loses");
dbus_g_method_return_error (data->context, error);
g_free (data);
return FALSE;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct extent_map *em = NULL;
struct extent_state *cached_state = NULL;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
u64 mask = root->sectorsize - 1;
u64 hole_start = (oldsize + mask) & ~mask;
u64 block_end = (size + mask) & ~mask;
u64 last_byte;
u64 cur_offset;
u64 hole_size;
int err = 0;
if (size <= hole_start)
return 0;
while (1) {
struct btrfs_ordered_extent *ordered;
btrfs_wait_ordered_range(inode, hole_start,
block_end - hole_start);
lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
&cached_state);
ordered = btrfs_lookup_ordered_extent(inode, hole_start);
if (!ordered)
break;
unlock_extent_cached(io_tree, hole_start, block_end - 1,
&cached_state, GFP_NOFS);
btrfs_put_ordered_extent(ordered);
}
cur_offset = hole_start;
while (1) {
em = btrfs_get_extent(inode, NULL, 0, cur_offset,
block_end - cur_offset, 0);
if (IS_ERR(em)) {
err = PTR_ERR(em);
break;
}
last_byte = min(extent_map_end(em), block_end);
last_byte = (last_byte + mask) & ~mask;
if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
struct extent_map *hole_em;
hole_size = last_byte - cur_offset;
trans = btrfs_start_transaction(root, 3);
if (IS_ERR(trans)) {
err = PTR_ERR(trans);
break;
}
err = btrfs_drop_extents(trans, root, inode,
cur_offset,
cur_offset + hole_size, 1);
if (err) {
btrfs_abort_transaction(trans, root, err);
btrfs_end_transaction(trans, root);
break;
}
err = btrfs_insert_file_extent(trans, root,
btrfs_ino(inode), cur_offset, 0,
0, hole_size, 0, hole_size,
0, 0, 0);
if (err) {
btrfs_abort_transaction(trans, root, err);
btrfs_end_transaction(trans, root);
break;
}
btrfs_drop_extent_cache(inode, cur_offset,
cur_offset + hole_size - 1, 0);
hole_em = alloc_extent_map();
if (!hole_em) {
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags);
goto next;
}
hole_em->start = cur_offset;
hole_em->len = hole_size;
hole_em->orig_start = cur_offset;
hole_em->block_start = EXTENT_MAP_HOLE;
hole_em->block_len = 0;
hole_em->orig_block_len = 0;
hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
hole_em->compress_type = BTRFS_COMPRESS_NONE;
hole_em->generation = trans->transid;
while (1) {
write_lock(&em_tree->lock);
err = add_extent_mapping(em_tree, hole_em);
if (!err)
list_move(&hole_em->list,
&em_tree->modified_extents);
write_unlock(&em_tree->lock);
if (err != -EEXIST)
break;
btrfs_drop_extent_cache(inode, cur_offset,
cur_offset +
hole_size - 1, 0);
}
free_extent_map(hole_em);
next:
btrfs_update_inode(trans, root, inode);
btrfs_end_transaction(trans, root);
}
free_extent_map(em);
em = NULL;
cur_offset = last_byte;
if (cur_offset >= block_end)
break;
}
free_extent_map(em);
unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
GFP_NOFS);
return err;
}
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: poly_recv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
POLYGON *poly;
int32 npts;
int32 i;
int size;
npts = pq_getmsgint(buf, sizeof(int32));
if (npts <= 0 || npts >= (int32) ((INT_MAX - offsetof(POLYGON, p[0])) / sizeof(Point)))
ereport(ERROR,
(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
errmsg("invalid number of points in external \"polygon\" value")));
size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * npts;
poly = (POLYGON *) palloc0(size); /* zero any holes */
SET_VARSIZE(poly, size);
poly->npts = npts;
for (i = 0; i < npts; i++)
{
poly->p[i].x = pq_getmsgfloat8(buf);
poly->p[i].y = pq_getmsgfloat8(buf);
}
make_bound_box(poly);
PG_RETURN_POLYGON_P(poly);
}
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: int Track::Info::CopyStr(char* Info::*str, Info& dst_) const
{
if (str == static_cast<char* Info::*>(NULL))
return -1;
char*& dst = dst_.*str;
if (dst) //should be NULL already
return -1;
const char* const src = this->*str;
if (src == NULL)
return 0;
const size_t len = strlen(src);
dst = new (std::nothrow) char[len+1];
if (dst == NULL)
return -1;
strcpy(dst, src);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ContainerNode::childrenChanged(const ChildrenChange& change)
{
document().incDOMTreeVersion();
if (!change.byParser && change.type != TextChanged)
document().updateRangesAfterChildrenChanged(this);
invalidateNodeListCachesInAncestors();
if (change.isChildInsertion() && !childNeedsStyleRecalc()) {
setChildNeedsStyleRecalc();
markAncestorsWithChildNeedsStyleRecalc();
}
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void v9fs_fix_path(V9fsPath *dst, V9fsPath *src, int len)
{
V9fsPath str;
v9fs_path_init(&str);
v9fs_path_copy(&str, dst);
v9fs_path_sprintf(dst, "%s%s", src->data, str.data + len);
v9fs_path_free(&str);
}
CWE ID: CWE-362
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void OMX::binderDied(const wp<IBinder> &the_late_who) {
OMXNodeInstance *instance;
{
Mutex::Autolock autoLock(mLock);
ssize_t index = mLiveNodes.indexOfKey(the_late_who);
CHECK(index >= 0);
instance = mLiveNodes.editValueAt(index);
mLiveNodes.removeItemsAt(index);
index = mDispatchers.indexOfKey(instance->nodeID());
CHECK(index >= 0);
mDispatchers.removeItemsAt(index);
invalidateNodeID_l(instance->nodeID());
}
instance->onObserverDied(mMaster);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: bt_status_t btif_set_remote_device_property(bt_bdaddr_t *remote_addr,
const bt_property_t *property)
{
btif_storage_req_t req;
if (!btif_is_enabled())
return BT_STATUS_NOT_READY;
memcpy(&(req.write_req.bd_addr), remote_addr, sizeof(bt_bdaddr_t));
memcpy(&(req.write_req.prop), property, sizeof(bt_property_t));
return btif_transfer_context(execute_storage_remote_request,
BTIF_CORE_STORAGE_REMOTE_WRITE,
(char*)&req,
sizeof(btif_storage_req_t)+property->len,
btif_in_storage_request_copy_cb);
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static uintmax_t parse_mark_ref(const char *p, char **endptr)
{
uintmax_t mark;
assert(*p == ':');
p++;
mark = strtoumax(p, endptr, 10);
if (*endptr == p)
die("No value after ':' in mark: %s", command_buf.buf);
return mark;
}
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 VarianceTest<VarianceFunctionType>::RefTest() {
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < block_size_; j++) {
src_[j] = rnd.Rand8();
ref_[j] = rnd.Rand8();
}
unsigned int sse1, sse2;
unsigned int var1;
REGISTER_STATE_CHECK(var1 = variance_(src_, width_, ref_, width_, &sse1));
const unsigned int var2 = variance_ref(src_, ref_, log2width_,
log2height_, &sse2);
EXPECT_EQ(sse1, sse2);
EXPECT_EQ(var1, var2);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Browser::TabReplacedAt(TabStripModel* tab_strip_model,
TabContentsWrapper* old_contents,
TabContentsWrapper* new_contents,
int index) {
TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
TabInsertedAt(new_contents, index,
(index == tab_handler_->GetTabStripModel()->active_index()));
int entry_count = new_contents->controller().entry_count();
if (entry_count > 0) {
new_contents->controller().NotifyEntryChanged(
new_contents->controller().GetEntryAtIndex(entry_count - 1),
entry_count - 1);
}
SessionService* session_service = profile()->GetSessionService();
if (session_service) {
session_service->TabRestored(
&new_contents->controller(),
tab_handler_->GetTabStripModel()->IsTabPinned(index));
}
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
if (devtools_manager) // NULL in unit tests.
devtools_manager->TabReplaced(old_contents, new_contents);
}
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: get_control(png_const_structrp png_ptr)
{
/* This just returns the (file*). The chunk and idat control structures
* don't always exist.
*/
struct control *control = png_voidcast(struct control*,
png_get_error_ptr(png_ptr));
return &control->file;
}
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 inline RefPtr<DocumentFragment> createFragmentFromSource(const String& sourceString, const String& sourceMIMEType, Document* outputDoc)
{
RefPtr<DocumentFragment> fragment = outputDoc->createDocumentFragment();
if (sourceMIMEType == "text/html") {
RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(outputDoc);
fragment->parseHTML(sourceString, fakeBody.get());
} else if (sourceMIMEType == "text/plain")
fragment->parserAddChild(Text::create(outputDoc, sourceString));
else {
bool successfulParse = fragment->parseXML(sourceString, 0);
if (!successfulParse)
return 0;
}
return fragment;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void Tab::OnMouseReleased(const ui::MouseEvent& event) {
controller_->OnMouseEventInTab(this, event);
if (controller_->EndDrag(END_DRAG_COMPLETE))
return;
if (event.IsMiddleMouseButton()) {
if (HitTestPoint(event.location())) {
controller_->CloseTab(this, CLOSE_TAB_FROM_MOUSE);
} else if (closing_) {
gfx::Point location_in_parent = event.location();
ConvertPointToTarget(this, parent(), &location_in_parent);
Tab* closest_tab = controller_->GetTabAt(location_in_parent);
if (closest_tab)
controller_->CloseTab(closest_tab, CLOSE_TAB_FROM_MOUSE);
}
} else if (event.IsOnlyLeftMouseButton() && !event.IsShiftDown() &&
!IsSelectionModifierDown(event)) {
controller_->SelectTab(this, event);
}
}
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 PopulateURLResponse(
const GURL& url,
const ResourceResponseInfo& info,
WebURLResponse* response) {
response->setURL(url);
response->setResponseTime(info.response_time.ToDoubleT());
response->setMIMEType(WebString::fromUTF8(info.mime_type));
response->setTextEncodingName(WebString::fromUTF8(info.charset));
response->setExpectedContentLength(info.content_length);
response->setSecurityInfo(info.security_info);
response->setAppCacheID(info.appcache_id);
response->setAppCacheManifestURL(info.appcache_manifest_url);
response->setWasCached(!info.load_timing.request_start_time.is_null() &&
info.response_time < info.load_timing.request_start_time);
response->setRemoteIPAddress(
WebString::fromUTF8(info.socket_address.host()));
response->setRemotePort(info.socket_address.port());
response->setConnectionID(info.load_timing.socket_log_id);
response->setConnectionReused(info.load_timing.socket_reused);
response->setDownloadFilePath(
webkit_base::FilePathToWebString(info.download_file_path));
WebURLResponseExtraDataImpl* extra_data =
new WebURLResponseExtraDataImpl(info.npn_negotiated_protocol);
response->setExtraData(extra_data);
extra_data->set_was_fetched_via_spdy(info.was_fetched_via_spdy);
extra_data->set_was_npn_negotiated(info.was_npn_negotiated);
extra_data->set_was_alternate_protocol_available(
info.was_alternate_protocol_available);
extra_data->set_was_fetched_via_proxy(info.was_fetched_via_proxy);
if (!info.load_timing.receive_headers_end.is_null()) {
WebURLLoadTiming timing;
PopulateURLLoadTiming(info.load_timing, &timing);
response->setLoadTiming(timing);
}
if (info.devtools_info) {
WebHTTPLoadInfo load_info;
load_info.setHTTPStatusCode(info.devtools_info->http_status_code);
load_info.setHTTPStatusText(WebString::fromUTF8(
info.devtools_info->http_status_text));
load_info.setEncodedDataLength(info.encoded_data_length);
load_info.setRequestHeadersText(WebString::fromUTF8(
info.devtools_info->request_headers_text));
load_info.setResponseHeadersText(WebString::fromUTF8(
info.devtools_info->response_headers_text));
const HeadersVector& request_headers = info.devtools_info->request_headers;
for (HeadersVector::const_iterator it = request_headers.begin();
it != request_headers.end(); ++it) {
load_info.addRequestHeader(WebString::fromUTF8(it->first),
WebString::fromUTF8(it->second));
}
const HeadersVector& response_headers =
info.devtools_info->response_headers;
for (HeadersVector::const_iterator it = response_headers.begin();
it != response_headers.end(); ++it) {
load_info.addResponseHeader(WebString::fromUTF8(it->first),
WebString::fromUTF8(it->second));
}
response->setHTTPLoadInfo(load_info);
}
const net::HttpResponseHeaders* headers = info.headers;
if (!headers)
return;
WebURLResponse::HTTPVersion version = WebURLResponse::Unknown;
if (headers->GetHttpVersion() == net::HttpVersion(0, 9))
version = WebURLResponse::HTTP_0_9;
else if (headers->GetHttpVersion() == net::HttpVersion(1, 0))
version = WebURLResponse::HTTP_1_0;
else if (headers->GetHttpVersion() == net::HttpVersion(1, 1))
version = WebURLResponse::HTTP_1_1;
response->setHTTPVersion(version);
response->setHTTPStatusCode(headers->response_code());
response->setHTTPStatusText(WebString::fromUTF8(headers->GetStatusText()));
std::string value;
headers->EnumerateHeader(NULL, "content-disposition", &value);
response->setSuggestedFileName(
net::GetSuggestedFilename(url,
value,
std::string(), // referrer_charset
std::string(), // suggested_name
std::string(), // mime_type
std::string())); // default_name
Time time_val;
if (headers->GetLastModifiedValue(&time_val))
response->setLastModifiedDate(time_val.ToDoubleT());
void* iter = NULL;
std::string name;
while (headers->EnumerateHeaderLines(&iter, &name, &value)) {
response->addHTTPHeaderField(WebString::fromUTF8(name),
WebString::fromUTF8(value));
}
}
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: cJSON *cJSON_CreateArray( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_Array;
return item;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool WebMediaPlayerMS::Seeking() const {
DCHECK(thread_checker_.CalledOnValidThread());
return false;
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: explicit MockScreenshotManager(content::NavigationControllerImpl* owner)
: content::NavigationEntryScreenshotManager(owner),
encoding_screenshot_in_progress_(false) {
}
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: get_part_table_device_file (struct udev_device *given_device,
const gchar *given_device_file,
gchar **out_partition_table_syspath,
guint64 *out_offset,
guint64 *out_alignment_offset,
guint *out_partition_number)
{
gchar *ret;
guint64 offset;
guint partition_number;
const gchar *devpath;
gchar *partition_table_syspath;
guint64 alignment_offset;
devpath = NULL;
offset = 0;
ret = NULL;
partition_table_syspath = NULL;
alignment_offset = 0;
devpath = udev_device_get_syspath (given_device);
if (devpath == NULL)
goto out;
partition_number = sysfs_get_int (devpath, "partition");
/* find device file for partition table device */
if (partition_number > 0)
{
struct udev_device *device;
guint n;
/* partition */
partition_table_syspath = g_strdup (devpath);
for (n = strlen (partition_table_syspath) - 1; partition_table_syspath[n] != '/'; n--)
partition_table_syspath[n] = '\0';
partition_table_syspath[n] = '\0';
device = udev_device_new_from_syspath (udev_device_get_udev (given_device), partition_table_syspath);
if (device == NULL)
{
g_printerr ("Error getting udev device for syspath %s: %m\n", partition_table_syspath);
goto out;
}
ret = g_strdup (udev_device_get_devnode (device));
udev_device_unref (device);
if (ret == NULL)
{
/* This Should Not Happen™, but was reported in a distribution upgrade
scenario, so handle it gracefully */
g_printerr ("Error getting devnode from udev device path %s: %m\n", partition_table_syspath);
goto out;
}
offset = sysfs_get_uint64 (devpath, "start") * 512;
alignment_offset = sysfs_get_uint64 (devpath, "alignment_offset");
}
else
{
const char *targets_type;
const char *encoded_targets_params;
targets_type = g_getenv ("UDISKS_DM_TARGETS_TYPE");
if (targets_type == NULL)
targets_type = udev_device_get_property_value (given_device, "UDISKS_DM_TARGETS_TYPE");
encoded_targets_params = g_getenv ("UDISKS_DM_TARGETS_PARAMS");
if (encoded_targets_params == NULL)
encoded_targets_params = udev_device_get_property_value (given_device, "UDISKS_DM_TARGETS_PARAMS");
if (g_strcmp0 (targets_type, "linear") == 0)
{
gint partition_slave_major;
gchar *targets_params;
targets_params = decode_udev_encoded_string (encoded_targets_params);
if (targets_params == NULL || sscanf (targets_params,
"%d:%d\x20%" G_GUINT64_FORMAT,
&partition_slave_major,
&partition_slave_minor,
&offset_sectors) != 3)
{
g_printerr ("Error decoding UDISKS_DM_TARGETS_PARAMS=`%s'\n", targets_params);
}
else
{
struct udev_device *mp_device;
mp_device = udev_device_new_from_devnum (udev_device_get_udev (given_device),
'b', makedev (partition_slave_major,
partition_slave_minor));
if (mp_device != NULL)
{
const char *dm_name;
gint n;
/* now figure out the partition number... we infer this from DM_NAME */
partition_number = 0;
dm_name = g_getenv ("DM_NAME");
if (dm_name == NULL)
dm_name = udev_device_get_property_value (given_device, "DM_NAME");
if (dm_name == NULL || strlen (dm_name) == 0)
{
g_printerr ("DM_NAME not available\n");
goto out;
}
for (n = strlen (dm_name) - 1; n >= 0; n--)
{
if (!isdigit (dm_name[n]))
break;
}
if (n < 0 || dm_name[n] != 'p')
{
g_printerr ("DM_NAME=`%s' is malformed (expected <name>p<number>)\n", dm_name);
goto out;
}
partition_number = atoi (dm_name + n + 1);
if (partition_number < 1)
{
g_printerr ("Error determining partition number from DM_NAME=`%s'\n", dm_name);
goto out;
}
ret = g_strdup (udev_device_get_devnode (mp_device));
offset = offset_sectors * 512;
partition_table_syspath = g_strdup (udev_device_get_syspath (mp_device));
udev_device_unref (mp_device);
g_free (targets_params);
/* TODO: set alignment_offset */
goto out;
}
}
g_free (targets_params);
}
/* not a kernel partition */
partition_table_syspath = g_strdup (devpath);
ret = g_strdup (given_device_file);
partition_number = 0;
}
out:
if (out_offset != NULL)
*out_offset = offset;
if (out_partition_number != NULL)
*out_partition_number = partition_number;
if (out_partition_table_syspath != NULL)
*out_partition_table_syspath = partition_table_syspath;
else
g_free (partition_table_syspath);
if (out_alignment_offset != NULL)
*out_alignment_offset = alignment_offset;
return ret;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url, MixedContentBlockingTreatment treatment) const
{
if (treatment == TreatAsDefaultForType) {
switch (type) {
case Resource::XSLStyleSheet:
ASSERT(RuntimeEnabledFeatures::xsltEnabled());
case Resource::Script:
case Resource::SVGDocument:
case Resource::CSSStyleSheet:
case Resource::ImportResource:
treatment = TreatAsActiveContent;
break;
case Resource::Font:
treatment = TreatAsActiveContent;
break;
case Resource::TextTrack:
case Resource::Raw:
case Resource::Image:
case Resource::Media:
treatment = TreatAsPassiveContent;
break;
case Resource::MainResource:
case Resource::LinkPrefetch:
case Resource::LinkSubresource:
treatment = TreatAsAlwaysAllowedContent;
break;
}
}
if (frame() && !frame()->tree().top()->isLocalFrame())
return false;
if (treatment == TreatAsActiveContent) {
if (LocalFrame* f = frame()) {
if (!f->loader().mixedContentChecker()->canRunInsecureContent(m_document->securityOrigin(), url))
return false;
Frame* top = f->tree().top();
if (top != f && !toLocalFrame(top)->loader().mixedContentChecker()->canRunInsecureContent(toLocalFrame(top)->document()->securityOrigin(), url))
return false;
}
} else if (treatment == TreatAsPassiveContent) {
if (LocalFrame* f = frame()) {
Frame* top = f->tree().top();
if (!toLocalFrame(top)->loader().mixedContentChecker()->canDisplayInsecureContent(toLocalFrame(top)->document()->securityOrigin(), url))
return false;
if (MixedContentChecker::isMixedContent(toLocalFrame(top)->document()->securityOrigin(), url)) {
switch (type) {
case Resource::TextTrack:
UseCounter::count(toLocalFrame(top)->document(), UseCounter::MixedContentTextTrack);
break;
case Resource::Raw:
UseCounter::count(toLocalFrame(top)->document(), UseCounter::MixedContentRaw);
break;
case Resource::Image:
UseCounter::count(toLocalFrame(top)->document(), UseCounter::MixedContentImage);
break;
case Resource::Media:
UseCounter::count(toLocalFrame(top)->document(), UseCounter::MixedContentMedia);
break;
default:
ASSERT_NOT_REACHED();
}
}
}
} else {
ASSERT(treatment == TreatAsAlwaysAllowedContent);
}
return true;
}
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 ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat)
{
struct file *file = kiocb->ki_filp;
ssize_t ret = 0;
switch (kiocb->ki_opcode) {
case IOCB_CMD_PREAD:
ret = -EBADF;
if (unlikely(!(file->f_mode & FMODE_READ)))
break;
ret = -EFAULT;
if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,
kiocb->ki_left)))
break;
ret = security_file_permission(file, MAY_READ);
if (unlikely(ret))
break;
ret = aio_setup_single_vector(kiocb);
if (ret)
break;
ret = -EINVAL;
if (file->f_op->aio_read)
kiocb->ki_retry = aio_rw_vect_retry;
break;
case IOCB_CMD_PWRITE:
ret = -EBADF;
if (unlikely(!(file->f_mode & FMODE_WRITE)))
break;
ret = -EFAULT;
if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,
kiocb->ki_left)))
break;
ret = security_file_permission(file, MAY_WRITE);
if (unlikely(ret))
break;
ret = aio_setup_single_vector(kiocb);
if (ret)
break;
ret = -EINVAL;
if (file->f_op->aio_write)
kiocb->ki_retry = aio_rw_vect_retry;
break;
case IOCB_CMD_PREADV:
ret = -EBADF;
if (unlikely(!(file->f_mode & FMODE_READ)))
break;
ret = security_file_permission(file, MAY_READ);
if (unlikely(ret))
break;
ret = aio_setup_vectored_rw(READ, kiocb, compat);
if (ret)
break;
ret = -EINVAL;
if (file->f_op->aio_read)
kiocb->ki_retry = aio_rw_vect_retry;
break;
case IOCB_CMD_PWRITEV:
ret = -EBADF;
if (unlikely(!(file->f_mode & FMODE_WRITE)))
break;
ret = security_file_permission(file, MAY_WRITE);
if (unlikely(ret))
break;
ret = aio_setup_vectored_rw(WRITE, kiocb, compat);
if (ret)
break;
ret = -EINVAL;
if (file->f_op->aio_write)
kiocb->ki_retry = aio_rw_vect_retry;
break;
case IOCB_CMD_FDSYNC:
ret = -EINVAL;
if (file->f_op->aio_fsync)
kiocb->ki_retry = aio_fdsync;
break;
case IOCB_CMD_FSYNC:
ret = -EINVAL;
if (file->f_op->aio_fsync)
kiocb->ki_retry = aio_fsync;
break;
default:
dprintk("EINVAL: io_submit: no operation provided\n");
ret = -EINVAL;
}
if (!kiocb->ki_retry)
return ret;
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: void VarianceTest<VarianceFunctionType>::ZeroTest() {
for (int i = 0; i <= 255; ++i) {
memset(src_, i, block_size_);
for (int j = 0; j <= 255; ++j) {
memset(ref_, j, block_size_);
unsigned int sse;
unsigned int var;
REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse));
EXPECT_EQ(0u, var) << "src values: " << i << "ref values: " << j;
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void __l2cap_chan_add(struct l2cap_conn *conn, struct sock *sk, struct sock *parent)
{
struct l2cap_chan_list *l = &conn->chan_list;
BT_DBG("conn %p, psm 0x%2.2x, dcid 0x%4.4x", conn,
l2cap_pi(sk)->psm, l2cap_pi(sk)->dcid);
conn->disc_reason = 0x13;
l2cap_pi(sk)->conn = conn;
if (sk->sk_type == SOCK_SEQPACKET) {
/* Alloc CID for connection-oriented socket */
l2cap_pi(sk)->scid = l2cap_alloc_cid(l);
} else if (sk->sk_type == SOCK_DGRAM) {
/* Connectionless socket */
l2cap_pi(sk)->scid = L2CAP_CID_CONN_LESS;
l2cap_pi(sk)->dcid = L2CAP_CID_CONN_LESS;
l2cap_pi(sk)->omtu = L2CAP_DEFAULT_MTU;
} else {
/* Raw socket can send/recv signalling messages only */
l2cap_pi(sk)->scid = L2CAP_CID_SIGNALING;
l2cap_pi(sk)->dcid = L2CAP_CID_SIGNALING;
l2cap_pi(sk)->omtu = L2CAP_DEFAULT_MTU;
}
__l2cap_chan_link(l, sk);
if (parent)
bt_accept_enqueue(parent, sk);
}
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: main(void)
{
fprintf(stderr,
" test ignored: no support to modify unknown chunk handling\n");
/* So the test is skipped: */
return 77;
}
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 gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag;
int wid;
int w, wstart;
int thick = im->thick;
if (color == gdAntiAliased) {
/*
gdAntiAliased passed as color: use the much faster, much cheaper
and equally attractive gdImageAALine implementation. That
clips too, so don't clip twice.
*/
gdImageAALine(im, x1, y1, x2, y2, im->AA_color);
return;
}
/* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn */
if (!clip_1d(&x1,&y1,&x2,&y2,gdImageSX(im)) || !clip_1d(&y1,&x1,&y2,&x2,gdImageSY(im))) {
return;
}
dx = abs (x2 - x1);
dy = abs (y2 - y1);
if (dx == 0) {
gdImageVLine(im, x1, y1, y2, color);
return;
} else if (dy == 0) {
gdImageHLine(im, y1, x1, x2, color);
return;
}
if (dy <= dx) {
/* More-or-less horizontal. use wid for vertical stroke */
/* Doug Claar: watch out for NaN in atan2 (2.0.5) */
if ((dx == 0) && (dy == 0)) {
wid = 1;
} else {
/* 2.0.12: Michael Schwartz: divide rather than multiply;
TBB: but watch out for /0! */
double ac = cos (atan2 (dy, dx));
if (ac != 0) {
wid = thick / ac;
} else {
wid = 1;
}
if (wid == 0) {
wid = 1;
}
}
d = 2 * dy - dx;
incr1 = 2 * dy;
incr2 = 2 * (dy - dx);
if (x1 > x2) {
x = x2;
y = y2;
ydirflag = (-1);
xend = x1;
} else {
x = x1;
y = y1;
ydirflag = 1;
xend = x2;
}
/* Set up line thickness */
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel(im, x, w, color);
}
if (((y2 - y1) * ydirflag) > 0) {
while (x < xend) {
x++;
if (d < 0) {
d += incr1;
} else {
y++;
d += incr2;
}
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, x, w, color);
}
}
} else {
while (x < xend) {
x++;
if (d < 0) {
d += incr1;
} else {
y--;
d += incr2;
}
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, x, w, color);
}
}
}
} else {
/* More-or-less vertical. use wid for horizontal stroke */
/* 2.0.12: Michael Schwartz: divide rather than multiply;
TBB: but watch out for /0! */
double as = sin (atan2 (dy, dx));
if (as != 0) {
wid = thick / as;
} else {
wid = 1;
}
if (wid == 0) {
wid = 1;
}
d = 2 * dx - dy;
incr1 = 2 * dx;
incr2 = 2 * (dx - dy);
if (y1 > y2) {
y = y2;
x = x2;
yend = y1;
xdirflag = (-1);
} else {
y = y1;
x = x1;
yend = y2;
xdirflag = 1;
}
/* Set up line thickness */
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
if (((x2 - x1) * xdirflag) > 0) {
while (y < yend) {
y++;
if (d < 0) {
d += incr1;
} else {
x++;
d += incr2;
}
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
}
} else {
while (y < yend) {
y++;
if (d < 0) {
d += incr1;
} else {
x--;
d += incr2;
}
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel (im, w, y, color);
}
}
}
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: String WebPageSerializerImpl::postActionAfterSerializeEndTag(
const Element* element, SerializeDomParam* param)
{
StringBuilder result;
if (!param->isHTMLDocument)
return result.toString();
if (isHTMLBaseElement(*element)) {
result.appendLiteral("-->");
result.append(WebPageSerializer::generateBaseTagDeclaration(
param->document->baseTarget()));
}
return result.toString();
}
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: tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
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: UriSuite() {
TEST_ADD(UriSuite::testDistinction)
TEST_ADD(UriSuite::testIpFour)
TEST_ADD(UriSuite::testIpSixPass)
TEST_ADD(UriSuite::testIpSixFail)
TEST_ADD(UriSuite::testUri)
TEST_ADD(UriSuite::testUriUserInfoHostPort1)
TEST_ADD(UriSuite::testUriUserInfoHostPort2)
TEST_ADD(UriSuite::testUriUserInfoHostPort22_Bug1948038)
TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_1)
TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_2)
TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_3)
TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_4)
TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_1)
TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_12)
TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_2)
TEST_ADD(UriSuite::testUriUserInfoHostPort3)
TEST_ADD(UriSuite::testUriUserInfoHostPort4)
TEST_ADD(UriSuite::testUriUserInfoHostPort5)
TEST_ADD(UriSuite::testUriUserInfoHostPort6)
TEST_ADD(UriSuite::testUriHostRegname)
TEST_ADD(UriSuite::testUriHostIpFour1)
TEST_ADD(UriSuite::testUriHostIpFour2)
TEST_ADD(UriSuite::testUriHostIpSix1)
TEST_ADD(UriSuite::testUriHostIpSix2)
TEST_ADD(UriSuite::testUriHostIpFuture)
TEST_ADD(UriSuite::testUriHostEmpty)
TEST_ADD(UriSuite::testUriComponents)
TEST_ADD(UriSuite::testUriComponents_Bug20070701)
TEST_ADD(UriSuite::testEscaping)
TEST_ADD(UriSuite::testUnescaping)
TEST_ADD(UriSuite::testTrailingSlash)
TEST_ADD(UriSuite::testAddBase)
TEST_ADD(UriSuite::testToString)
TEST_ADD(UriSuite::testToString_Bug1950126)
TEST_ADD(UriSuite::testToStringCharsRequired)
TEST_ADD(UriSuite::testToStringCharsRequired)
TEST_ADD(UriSuite::testNormalizeSyntaxMaskRequired)
TEST_ADD(UriSuite::testNormalizeSyntax)
TEST_ADD(UriSuite::testNormalizeSyntaxComponents)
TEST_ADD(UriSuite::testNormalizeCrash_Bug20080224)
TEST_ADD(UriSuite::testFilenameUriConversion)
TEST_ADD(UriSuite::testCrash_FreeUriMembers_Bug20080116)
TEST_ADD(UriSuite::testCrash_Report2418192)
TEST_ADD(UriSuite::testPervertedQueryString);
TEST_ADD(UriSuite::testQueryStringEndingInEqualSign_NonBug32);
TEST_ADD(UriSuite::testCrash_MakeOwner_Bug20080207)
TEST_ADD(UriSuite::testQueryList)
TEST_ADD(UriSuite::testQueryListPair)
TEST_ADD(UriSuite::testQueryDissection_Bug3590761)
TEST_ADD(UriSuite::testFreeCrash_Bug20080827)
TEST_ADD(UriSuite::testParseInvalid_Bug16)
TEST_ADD(UriSuite::testRangeComparison)
TEST_ADD(UriSuite::testRangeComparison_RemoveBaseUri_Issue19)
TEST_ADD(UriSuite::testEquals)
TEST_ADD(UriSuite::testHostTextTermination_Issue15)
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: PlatformSensorAndroid::~PlatformSensorAndroid() {
JNIEnv* env = AttachCurrentThread();
Java_PlatformSensor_sensorDestroyed(env, j_object_);
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static enum lru_status dentry_lru_isolate_shrink(struct list_head *item,
struct list_lru_one *lru, spinlock_t *lru_lock, void *arg)
{
struct list_head *freeable = arg;
struct dentry *dentry = container_of(item, struct dentry, d_lru);
/*
* we are inverting the lru lock/dentry->d_lock here,
* so use a trylock. If we fail to get the lock, just skip
* it
*/
if (!spin_trylock(&dentry->d_lock))
return LRU_SKIP;
d_lru_shrink_move(lru, dentry, freeable);
spin_unlock(&dentry->d_lock);
return LRU_REMOVED;
}
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: VP8PictureToVaapiDecodeSurface(const scoped_refptr<VP8Picture>& pic) {
VaapiVP8Picture* vaapi_pic = pic->AsVaapiVP8Picture();
CHECK(vaapi_pic);
return vaapi_pic->dec_surface();
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: int DevToolsWindow::GetHeight(int container_height) {
if (height_ == -1) {
height_ = profile_->GetPrefs()->
GetInteger(prefs::kDevToolsHSplitLocation);
}
if (height_ == -1)
height_ = container_height / 3;
height_ = std::max(GetMinimumHeight(), height_);
height_ = std::min(container_height - kMinContentsSize, height_);
return height_;
}
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 rawv6_err(struct sock *sk, struct sk_buff *skb,
struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
int err;
int harderr;
/* Report error on raw socket, if:
1. User requested recverr.
2. Socket is connected (otherwise the error indication
is useless without recverr and error is hard.
*/
if (!np->recverr && sk->sk_state != TCP_ESTABLISHED)
return;
harderr = icmpv6_err_convert(type, code, &err);
if (type == ICMPV6_PKT_TOOBIG) {
ip6_sk_update_pmtu(skb, sk, info);
harderr = (np->pmtudisc == IPV6_PMTUDISC_DO);
}
if (type == NDISC_REDIRECT) {
ip6_sk_redirect(skb, sk);
return;
}
if (np->recverr) {
u8 *payload = skb->data;
if (!inet->hdrincl)
payload += offset;
ipv6_icmp_error(sk, skb, err, 0, ntohl(info), payload);
}
if (np->recverr || harderr) {
sk->sk_err = err;
sk->sk_error_report(sk);
}
}
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: foreach_nfs_shareopt(const char *shareopts,
nfs_shareopt_callback_t callback, void *cookie)
{
char *shareopts_dup, *opt, *cur, *value;
int was_nul, rc;
if (shareopts == NULL)
return (SA_OK);
shareopts_dup = strdup(shareopts);
if (shareopts_dup == NULL)
return (SA_NO_MEMORY);
opt = shareopts_dup;
was_nul = 0;
while (1) {
cur = opt;
while (*cur != ',' && *cur != '\0')
cur++;
if (*cur == '\0')
was_nul = 1;
*cur = '\0';
if (cur > opt) {
value = strchr(opt, '=');
if (value != NULL) {
*value = '\0';
value++;
}
rc = callback(opt, value, cookie);
if (rc != SA_OK) {
free(shareopts_dup);
return (rc);
}
}
opt = cur + 1;
if (was_nul)
break;
}
free(shareopts_dup);
return (0);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool Document::NeedsLayoutTreeUpdateForNode(const Node& node,
bool ignore_adjacent_style) const {
if (!node.CanParticipateInFlatTree())
return false;
if (!NeedsLayoutTreeUpdate())
return false;
if (!node.isConnected())
return false;
if (NeedsFullLayoutTreeUpdate() || node.NeedsStyleRecalc() ||
node.NeedsStyleInvalidation())
return true;
for (const ContainerNode* ancestor = LayoutTreeBuilderTraversal::Parent(node);
ancestor; ancestor = LayoutTreeBuilderTraversal::Parent(*ancestor)) {
if (ShadowRoot* root = ancestor->GetShadowRoot()) {
if (root->NeedsStyleRecalc() || root->NeedsStyleInvalidation() ||
root->NeedsAdjacentStyleRecalc()) {
return true;
}
}
if (ancestor->NeedsStyleRecalc() || ancestor->NeedsStyleInvalidation() ||
(ancestor->NeedsAdjacentStyleRecalc() && !ignore_adjacent_style)) {
return true;
}
}
return false;
}
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 RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
size_t offset,
const gfx::Range& range) {
Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
selection_text,
offset,
range));
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void virgl_resource_attach_backing(VirtIOGPU *g,
struct virtio_gpu_ctrl_command *cmd)
{
struct virtio_gpu_resource_attach_backing att_rb;
struct iovec *res_iovs;
int ret;
VIRTIO_GPU_FILL_CMD(att_rb);
trace_virtio_gpu_cmd_res_back_attach(att_rb.resource_id);
ret = virtio_gpu_create_mapping_iov(&att_rb, cmd, NULL, &res_iovs);
if (ret != 0) {
cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;
return;
}
virgl_renderer_resource_attach_iov(att_rb.resource_id,
res_iovs, att_rb.nr_entries);
}
CWE ID: CWE-772
Target: 1
Example 2:
Code: void AwContents::SmoothScroll(JNIEnv* env,
jobject obj,
jint target_x,
jint target_y,
jlong duration_ms) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
float scale = browser_view_renderer_.dip_scale() *
browser_view_renderer_.page_scale_factor();
render_view_host_ext_->SmoothScroll(target_x / scale, target_y / scale,
duration_ms);
}
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 bool ExecuteMoveToBeginningOfParagraphAndModifySelection(
LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
frame.Selection().Modify(
SelectionModifyAlteration::kExtend, SelectionModifyDirection::kBackward,
TextGranularity::kParagraphBoundary, SetSelectionBy::kUser);
return true;
}
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::CreateBlockGroup(long long start_offset, long long size,
long long discard_padding) {
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count >= 0);
assert(m_entries_count < m_entries_size);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = start_offset;
const long long stop = start_offset + size;
long long prev = 1; // nonce
long long next = 0; // nonce
long long duration = -1; // really, this is unsigned
long long bpos = -1;
long long bsize = -1;
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume size
if (id == 0x21) { // Block ID
if (bpos < 0) { // Block ID
bpos = pos;
bsize = size;
}
} else if (id == 0x1B) { // Duration ID
assert(size <= 8);
duration = UnserializeUInt(pReader, pos, size);
assert(duration >= 0); // TODO
} else if (id == 0x7B) { // ReferenceBlock
assert(size <= 8);
const long size_ = static_cast<long>(size);
long long time;
long status = UnserializeInt(pReader, pos, size_, time);
assert(status == 0);
if (status != 0)
return -1;
if (time <= 0) // see note above
prev = time;
else // weird
next = time;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
assert(bpos >= 0);
assert(bsize >= 0);
const long idx = m_entries_count;
BlockEntry** const ppEntry = m_entries + idx;
BlockEntry*& pEntry = *ppEntry;
pEntry = new (std::nothrow)
BlockGroup(this, idx, bpos, bsize, prev, next, duration, discard_padding);
if (pEntry == NULL)
return -1; // generic error
BlockGroup* const p = static_cast<BlockGroup*>(pEntry);
const long status = p->Parse();
if (status == 0) { // success
++m_entries_count;
return 0;
}
delete pEntry;
pEntry = 0;
return status;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: npasses_from_interlace_type(png_const_structp pp, int interlace_type)
{
switch (interlace_type)
{
default:
png_error(pp, "invalid interlace type");
case PNG_INTERLACE_NONE:
return 1;
case PNG_INTERLACE_ADAM7:
return PNG_INTERLACE_ADAM7_PASSES;
}
}
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 SendInterstitialCommand(
content::WebContents* tab,
security_interstitials::SecurityInterstitialCommand command) {
if (AreCommittedInterstitialsEnabled()) {
security_interstitials::SecurityInterstitialTabHelper* helper =
security_interstitials::SecurityInterstitialTabHelper::
FromWebContents(tab);
helper->GetBlockingPageForCurrentlyCommittedNavigationForTesting()
->CommandReceived(base::IntToString(command));
return;
}
tab->GetInterstitialPage()->GetDelegateForTesting()->CommandReceived(
base::IntToString(command));
}
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: PHP_FUNCTION(pg_get_notify)
{
zval *pgsql_link;
int id = -1;
long result_type = PGSQL_ASSOC;
PGconn *pgsql;
PGnotify *pgsql_notify;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l",
&pgsql_link, &result_type) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (!(result_type & PGSQL_BOTH)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
RETURN_FALSE;
}
PQconsumeInput(pgsql);
pgsql_notify = PQnotifies(pgsql);
if (!pgsql_notify) {
/* no notify message */
RETURN_FALSE;
}
array_init(return_value);
if (result_type & PGSQL_NUM) {
add_index_string(return_value, 0, pgsql_notify->relname, 1);
add_index_long(return_value, 1, pgsql_notify->be_pid);
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) {
#else
if (atof(PG_VERSION) >= 9.0) {
#endif
#if HAVE_PQPARAMETERSTATUS
add_index_string(return_value, 2, pgsql_notify->extra, 1);
#endif
}
}
if (result_type & PGSQL_ASSOC) {
add_assoc_string(return_value, "message", pgsql_notify->relname, 1);
add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
#if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) {
#else
if (atof(PG_VERSION) >= 9.0) {
#endif
#if HAVE_PQPARAMETERSTATUS
add_assoc_string(return_value, "payload", pgsql_notify->extra, 1);
#endif
}
}
PQfreemem(pgsql_notify);
}
/* }}} */
/* {{{ proto int pg_get_pid([resource connection)
Get backend(server) pid */
PHP_FUNCTION(pg_get_pid)
{
zval *pgsql_link;
int id = -1;
PGconn *pgsql;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
&pgsql_link) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
RETURN_LONG(PQbackendPID(pgsql));
}
/* }}} */
/* {{{ php_pgsql_meta_data
* TODO: Add meta_data cache for better performance
*/
PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, zval *meta TSRMLS_DC)
{
PGresult *pg_result;
char *src, *tmp_name, *tmp_name2 = NULL;
char *escaped;
smart_str querystr = {0};
size_t new_len;
int i, num_rows;
zval *elem;
if (!*table_name) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "The table name must be specified");
return FAILURE;
}
src = estrdup(table_name);
tmp_name = php_strtok_r(src, ".", &tmp_name2);
if (!tmp_name2 || !*tmp_name2) {
/* Default schema */
tmp_name2 = tmp_name;
"SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotnull, a.atthasdef, a.attndims, t.typtype = 'e' "
"FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n "
"WHERE a.attnum > 0 AND a.attrelid = c.oid AND c.relname = '");
escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1);
new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL);
if (new_len) {
smart_str_appendl(&querystr, escaped, new_len);
}
efree(escaped);
smart_str_appends(&querystr, "' AND c.relnamespace = n.oid AND n.nspname = '");
escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1);
new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL);
if (new_len) {
smart_str_appendl(&querystr, escaped, new_len);
}
efree(escaped);
smart_str_appends(&querystr, "' AND a.atttypid = t.oid ORDER BY a.attnum;");
smart_str_0(&querystr);
efree(src);
pg_result = PQexec(pg_link, querystr.c);
if (PQresultStatus(pg_result) != PGRES_TUPLES_OK || (num_rows = PQntuples(pg_result)) == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Table '%s' doesn't exists", table_name);
smart_str_free(&querystr);
PQclear(pg_result);
return FAILURE;
}
smart_str_free(&querystr);
for (i = 0; i < num_rows; i++) {
char *name;
MAKE_STD_ZVAL(elem);
array_init(elem);
add_assoc_long(elem, "num", atoi(PQgetvalue(pg_result,i,1)));
add_assoc_string(elem, "type", PQgetvalue(pg_result,i,2), 1);
add_assoc_long(elem, "len", atoi(PQgetvalue(pg_result,i,3)));
if (!strcmp(PQgetvalue(pg_result,i,4), "t")) {
add_assoc_bool(elem, "not null", 1);
}
else {
add_assoc_bool(elem, "not null", 0);
}
if (!strcmp(PQgetvalue(pg_result,i,5), "t")) {
add_assoc_bool(elem, "has default", 1);
}
else {
add_assoc_bool(elem, "has default", 0);
}
add_assoc_long(elem, "array dims", atoi(PQgetvalue(pg_result,i,6)));
if (!strcmp(PQgetvalue(pg_result,i,7), "t")) {
add_assoc_bool(elem, "is enum", 1);
}
else {
add_assoc_bool(elem, "is enum", 0);
}
name = PQgetvalue(pg_result,i,0);
add_assoc_zval(meta, name, elem);
}
PQclear(pg_result);
return SUCCESS;
}
/* }}} */
CWE ID:
Target: 1
Example 2:
Code: static void decrypt_callback(void *priv, u8 *srcdst, unsigned int nbytes)
{
const unsigned int bsize = TF_BLOCK_SIZE;
struct twofish_ctx *ctx = priv;
int i;
if (nbytes == 3 * bsize) {
twofish_dec_blk_3way(ctx, srcdst, srcdst);
return;
}
for (i = 0; i < nbytes / bsize; i++, srcdst += bsize)
twofish_dec_blk(ctx, srcdst, srcdst);
}
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 V8TestObject::RaisesExceptionVoidMethodTestCallbackInterfaceArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_raisesExceptionVoidMethodTestCallbackInterfaceArg");
test_object_v8_internal::RaisesExceptionVoidMethodTestCallbackInterfaceArgMethod(info);
}
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 Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection,
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
CWE ID:
Target: 1
Example 2:
Code: static int sas_configure_set(struct domain_device *dev, int phy_id,
u8 *sas_addr, int index, int include)
{
int res;
u8 *cri_req;
u8 *cri_resp;
cri_req = alloc_smp_req(CRI_REQ_SIZE);
if (!cri_req)
return -ENOMEM;
cri_resp = alloc_smp_resp(CRI_RESP_SIZE);
if (!cri_resp) {
kfree(cri_req);
return -ENOMEM;
}
cri_req[1] = SMP_CONF_ROUTE_INFO;
*(__be16 *)(cri_req+6) = cpu_to_be16(index);
cri_req[9] = phy_id;
if (SAS_ADDR(sas_addr) == 0 || !include)
cri_req[12] |= 0x80;
memcpy(cri_req+16, sas_addr, SAS_ADDR_SIZE);
res = smp_execute_task(dev, cri_req, CRI_REQ_SIZE, cri_resp,
CRI_RESP_SIZE);
if (res)
goto out;
res = cri_resp[2];
if (res == SMP_RESP_NO_INDEX) {
SAS_DPRINTK("overflow of indexes: dev %016llx phy 0x%x "
"index 0x%x\n",
SAS_ADDR(dev->sas_addr), phy_id, index);
}
out:
kfree(cri_req);
kfree(cri_resp);
return res;
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void red_channel_handle_migrate_data(RedChannelClient *rcc, uint32_t size, void *message)
{
spice_debug("channel type %d id %d rcc %p size %u",
rcc->channel->type, rcc->channel->id, rcc, size);
if (!rcc->channel->channel_cbs.handle_migrate_data) {
return;
}
if (!red_channel_client_waits_for_migrate_data(rcc)) {
spice_channel_client_error(rcc, "unexpected");
return;
}
if (rcc->channel->channel_cbs.handle_migrate_data_get_serial) {
red_channel_client_set_message_serial(rcc,
rcc->channel->channel_cbs.handle_migrate_data_get_serial(rcc, size, message));
}
if (!rcc->channel->channel_cbs.handle_migrate_data(rcc, size, message)) {
spice_channel_client_error(rcc, "handle_migrate_data failed");
return;
}
red_channel_client_seamless_migration_done(rcc);
}
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: DataPipeConsumerDispatcher::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<DataPipeConsumerDispatcher> dispatcher =
new DataPipeConsumerDispatcher(node_controller, port,
std::move(ring_buffer), state->options,
state->pipe_id);
{
base::AutoLock lock(dispatcher->lock_);
dispatcher->read_offset_ = state->read_offset;
dispatcher->bytes_available_ = state->bytes_available;
dispatcher->new_data_available_ = state->bytes_available > 0;
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 void cirrus_cursor_invalidate(VGACommonState *s1)
{
CirrusVGAState *s = container_of(s1, CirrusVGAState, vga);
int size;
if (!(s->vga.sr[0x12] & CIRRUS_CURSOR_SHOW)) {
size = 0;
} else {
if (s->vga.sr[0x12] & CIRRUS_CURSOR_LARGE)
size = 64;
else
size = 32;
}
/* invalidate last cursor and new cursor if any change */
if (s->last_hw_cursor_size != size ||
s->last_hw_cursor_x != s->hw_cursor_x ||
s->last_hw_cursor_y != s->hw_cursor_y) {
invalidate_cursor1(s);
s->last_hw_cursor_size = size;
s->last_hw_cursor_x = s->hw_cursor_x;
s->last_hw_cursor_y = s->hw_cursor_y;
/* compute the real cursor min and max y */
cirrus_cursor_compute_yrange(s);
invalidate_cursor1(s);
}
}
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: QQuickUrlSchemeDelegate* QQuickWebViewExperimental::schemeDelegates_At(QDeclarativeListProperty<QQuickUrlSchemeDelegate>* property, int index)
{
const QObjectList children = property->object->children();
if (index < children.count())
return static_cast<QQuickUrlSchemeDelegate*>(children.at(index));
return 0;
}
CWE ID: CWE-189
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int main(int argc, char *argv[]) {
struct mschm_decompressor *chmd;
struct mschmd_header *chm;
struct mschmd_file *file, **f;
unsigned int numf, i;
setbuf(stdout, NULL);
setbuf(stderr, NULL);
user_umask = umask(0); umask(user_umask);
MSPACK_SYS_SELFTEST(i);
if (i) return 0;
if ((chmd = mspack_create_chm_decompressor(NULL))) {
for (argv++; *argv; argv++) {
printf("%s\n", *argv);
if ((chm = chmd->open(chmd, *argv))) {
/* build an ordered list of files for maximum extraction speed */
for (numf=0, file=chm->files; file; file = file->next) numf++;
if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) {
for (i=0, file=chm->files; file; file = file->next) f[i++] = file;
qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc);
for (i = 0; i < numf; i++) {
char *outname = create_output_name((unsigned char *)f[i]->filename,NULL,0,1,0);
printf("Extracting %s\n", outname);
ensure_filepath(outname);
if (chmd->extract(chmd, f[i], outname)) {
printf("%s: extract error on \"%s\": %s\n",
*argv, f[i]->filename, ERROR(chmd));
}
free(outname);
}
free(f);
}
chmd->close(chmd, chm);
}
else {
printf("%s: can't open -- %s\n", *argv, ERROR(chmd));
}
}
mspack_destroy_chm_decompressor(chmd);
}
return 0;
}
CWE ID: CWE-22
Target: 1
Example 2:
Code: static void usb_mixer_selector_elem_free(struct snd_kcontrol *kctl)
{
int i, num_ins = 0;
if (kctl->private_data) {
struct usb_mixer_elem_info *cval = kctl->private_data;
num_ins = cval->max;
kfree(cval);
kctl->private_data = NULL;
}
if (kctl->private_value) {
char **itemlist = (char **)kctl->private_value;
for (i = 0; i < num_ins; i++)
kfree(itemlist[i]);
kfree(itemlist);
kctl->private_value = 0;
}
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler)
{
this->needsRewrite = false;
XMP_IO* file = handler->parent->ioRef;
file->Seek(12, kXMP_SeekFromStart);
XMP_Int64 size = handler->initialFileSize;
XMP_Uns32 peek = 0;
while (file->Offset() < size) {
peek = XIO::PeekUns32_LE(file);
switch (peek) {
case kChunk_XMP_:
this->addChunk(new XMPChunk(this, handler));
break;
case kChunk_VP8X:
this->addChunk(new VP8XChunk(this, handler));
break;
default:
this->addChunk(new Chunk(this, handler));
break;
}
}
if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) {
XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat);
}
if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) {
this->needsRewrite = true;
this->addChunk(new VP8XChunk(this));
}
if (this->chunks[WEBP_CHUNK_XMP].size() == 0) {
XMPChunk* xmpChunk = new XMPChunk(this);
this->addChunk(xmpChunk);
handler->xmpChunk = xmpChunk;
this->vp8x->xmp(true);
}
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int svc_rdma_bc_sendto(struct svcxprt_rdma *rdma,
struct rpc_rqst *rqst)
{
struct xdr_buf *sndbuf = &rqst->rq_snd_buf;
struct svc_rdma_op_ctxt *ctxt;
struct svc_rdma_req_map *vec;
struct ib_send_wr send_wr;
int ret;
vec = svc_rdma_get_req_map(rdma);
ret = svc_rdma_map_xdr(rdma, sndbuf, vec, false);
if (ret)
goto out_err;
ret = svc_rdma_repost_recv(rdma, GFP_NOIO);
if (ret)
goto out_err;
ctxt = svc_rdma_get_context(rdma);
ctxt->pages[0] = virt_to_page(rqst->rq_buffer);
ctxt->count = 1;
ctxt->direction = DMA_TO_DEVICE;
ctxt->sge[0].lkey = rdma->sc_pd->local_dma_lkey;
ctxt->sge[0].length = sndbuf->len;
ctxt->sge[0].addr =
ib_dma_map_page(rdma->sc_cm_id->device, ctxt->pages[0], 0,
sndbuf->len, DMA_TO_DEVICE);
if (ib_dma_mapping_error(rdma->sc_cm_id->device, ctxt->sge[0].addr)) {
ret = -EIO;
goto out_unmap;
}
svc_rdma_count_mappings(rdma, ctxt);
memset(&send_wr, 0, sizeof(send_wr));
ctxt->cqe.done = svc_rdma_wc_send;
send_wr.wr_cqe = &ctxt->cqe;
send_wr.sg_list = ctxt->sge;
send_wr.num_sge = 1;
send_wr.opcode = IB_WR_SEND;
send_wr.send_flags = IB_SEND_SIGNALED;
ret = svc_rdma_send(rdma, &send_wr);
if (ret) {
ret = -EIO;
goto out_unmap;
}
out_err:
svc_rdma_put_req_map(rdma, vec);
dprintk("svcrdma: %s returns %d\n", __func__, ret);
return ret;
out_unmap:
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 1);
goto out_err;
}
CWE ID: CWE-404
Target: 1
Example 2:
Code: static int snd_timer_user_status(struct file *file,
struct snd_timer_status __user *_status)
{
struct snd_timer_user *tu;
struct snd_timer_status status;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
memset(&status, 0, sizeof(status));
status.tstamp = tu->tstamp;
status.resolution = snd_timer_resolution(tu->timeri);
status.lost = tu->timeri->lost;
status.overrun = tu->overrun;
spin_lock_irq(&tu->qlock);
status.queue = tu->qused;
spin_unlock_irq(&tu->qlock);
if (copy_to_user(_status, &status, sizeof(status)))
return -EFAULT;
return 0;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t BnCrypto::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case INIT_CHECK:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(initCheck());
return OK;
}
case IS_CRYPTO_SUPPORTED:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
reply->writeInt32(isCryptoSchemeSupported(uuid));
return OK;
}
case CREATE_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
size_t opaqueSize = data.readInt32();
void *opaqueData = NULL;
if (opaqueSize > 0) {
opaqueData = malloc(opaqueSize);
data.read(opaqueData, opaqueSize);
}
reply->writeInt32(createPlugin(uuid, opaqueData, opaqueSize));
if (opaqueData != NULL) {
free(opaqueData);
opaqueData = NULL;
}
return OK;
}
case DESTROY_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(destroyPlugin());
return OK;
}
case REQUIRES_SECURE_COMPONENT:
{
CHECK_INTERFACE(ICrypto, data, reply);
const char *mime = data.readCString();
reply->writeInt32(requiresSecureDecoderComponent(mime));
return OK;
}
case DECRYPT:
{
CHECK_INTERFACE(ICrypto, data, reply);
bool secure = data.readInt32() != 0;
CryptoPlugin::Mode mode = (CryptoPlugin::Mode)data.readInt32();
uint8_t key[16];
data.read(key, sizeof(key));
uint8_t iv[16];
data.read(iv, sizeof(iv));
size_t totalSize = data.readInt32();
sp<IMemory> sharedBuffer =
interface_cast<IMemory>(data.readStrongBinder());
int32_t offset = data.readInt32();
int32_t numSubSamples = data.readInt32();
CryptoPlugin::SubSample *subSamples =
new CryptoPlugin::SubSample[numSubSamples];
data.read(
subSamples,
sizeof(CryptoPlugin::SubSample) * numSubSamples);
void *secureBufferId, *dstPtr;
if (secure) {
secureBufferId = reinterpret_cast<void *>(static_cast<uintptr_t>(data.readInt64()));
} else {
dstPtr = calloc(1, totalSize);
}
AString errorDetailMsg;
ssize_t result;
size_t sumSubsampleSizes = 0;
bool overflow = false;
for (int32_t i = 0; i < numSubSamples; ++i) {
CryptoPlugin::SubSample &ss = subSamples[i];
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfEncryptedData) {
sumSubsampleSizes += ss.mNumBytesOfEncryptedData;
} else {
overflow = true;
}
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfClearData) {
sumSubsampleSizes += ss.mNumBytesOfClearData;
} else {
overflow = true;
}
}
if (overflow || sumSubsampleSizes != totalSize) {
result = -EINVAL;
} else if (offset + totalSize > sharedBuffer->size()) {
result = -EINVAL;
} else {
result = decrypt(
secure,
key,
iv,
mode,
sharedBuffer, offset,
subSamples, numSubSamples,
secure ? secureBufferId : dstPtr,
&errorDetailMsg);
}
reply->writeInt32(result);
if (isCryptoError(result)) {
reply->writeCString(errorDetailMsg.c_str());
}
if (!secure) {
if (result >= 0) {
CHECK_LE(result, static_cast<ssize_t>(totalSize));
reply->write(dstPtr, result);
}
free(dstPtr);
dstPtr = NULL;
}
delete[] subSamples;
subSamples = NULL;
return OK;
}
case NOTIFY_RESOLUTION:
{
CHECK_INTERFACE(ICrypto, data, reply);
int32_t width = data.readInt32();
int32_t height = data.readInt32();
notifyResolution(width, height);
return OK;
}
case SET_MEDIADRM_SESSION:
{
CHECK_INTERFACE(IDrm, data, reply);
Vector<uint8_t> sessionId;
readVector(data, sessionId);
reply->writeInt32(setMediaDrmSession(sessionId));
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
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: krb5_gss_inquire_context(minor_status, context_handle, initiator_name,
acceptor_name, lifetime_rec, mech_type, ret_flags,
locally_initiated, opened)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_name_t *initiator_name;
gss_name_t *acceptor_name;
OM_uint32 *lifetime_rec;
gss_OID *mech_type;
OM_uint32 *ret_flags;
int *locally_initiated;
int *opened;
{
krb5_context context;
krb5_error_code code;
krb5_gss_ctx_id_rec *ctx;
krb5_gss_name_t initiator, acceptor;
krb5_timestamp now;
krb5_deltat lifetime;
if (initiator_name)
*initiator_name = (gss_name_t) NULL;
if (acceptor_name)
*acceptor_name = (gss_name_t) NULL;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
initiator = NULL;
acceptor = NULL;
context = ctx->k5_context;
if ((code = krb5_timeofday(context, &now))) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
if ((lifetime = ctx->krb_times.endtime - now) < 0)
lifetime = 0;
if (initiator_name) {
if ((code = kg_duplicate_name(context,
ctx->initiate ? ctx->here : ctx->there,
&initiator))) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
}
if (acceptor_name) {
if ((code = kg_duplicate_name(context,
ctx->initiate ? ctx->there : ctx->here,
&acceptor))) {
if (initiator)
kg_release_name(context, &initiator);
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
}
if (initiator_name)
*initiator_name = (gss_name_t) initiator;
if (acceptor_name)
*acceptor_name = (gss_name_t) acceptor;
if (lifetime_rec)
*lifetime_rec = lifetime;
if (mech_type)
*mech_type = (gss_OID) ctx->mech_used;
if (ret_flags)
*ret_flags = ctx->gss_flags;
if (locally_initiated)
*locally_initiated = ctx->initiate;
if (opened)
*opened = ctx->established;
*minor_status = 0;
return((lifetime == 0)?GSS_S_CONTEXT_EXPIRED:GSS_S_COMPLETE);
}
CWE ID:
Target: 1
Example 2:
Code: IV_API_CALL_STATUS_T impeg2d_api_retrieve_mem_rec(iv_obj_t *ps_dechdl,
void *pv_api_ip,
void *pv_api_op)
{
UWORD32 u4_i;
dec_state_t *ps_dec_state;
dec_state_multi_core_t *ps_dec_state_multi_core;
iv_mem_rec_t *ps_mem_rec;
iv_mem_rec_t *ps_temp_rec;
impeg2d_retrieve_mem_rec_ip_t *ps_retr_mem_rec_ip;
impeg2d_retrieve_mem_rec_op_t *ps_retr_mem_rec_op;
ps_retr_mem_rec_ip = (impeg2d_retrieve_mem_rec_ip_t *)pv_api_ip;
ps_retr_mem_rec_op = (impeg2d_retrieve_mem_rec_op_t *)pv_api_op;
ps_mem_rec = ps_retr_mem_rec_ip->s_ivd_retrieve_mem_rec_ip_t.pv_mem_rec_location;
ps_dec_state_multi_core = (dec_state_multi_core_t *) (ps_dechdl->pv_codec_handle);
ps_dec_state = ps_dec_state_multi_core->ps_dec_state[0];
ps_temp_rec = ps_dec_state->pv_memTab;
for(u4_i = 0; u4_i < (ps_dec_state->u4_num_mem_records);u4_i++)
{
ps_mem_rec[u4_i].u4_mem_size = ps_temp_rec[u4_i].u4_mem_size;
ps_mem_rec[u4_i].u4_mem_alignment = ps_temp_rec[u4_i].u4_mem_alignment;
ps_mem_rec[u4_i].e_mem_type = ps_temp_rec[u4_i].e_mem_type;
ps_mem_rec[u4_i].pv_base = ps_temp_rec[u4_i].pv_base;
}
ps_retr_mem_rec_op->s_ivd_retrieve_mem_rec_op_t.u4_error_code = IV_SUCCESS;
ps_retr_mem_rec_op->s_ivd_retrieve_mem_rec_op_t.u4_num_mem_rec_filled = ps_dec_state->u4_num_mem_records;
impeg2_jobq_deinit(ps_dec_state->pv_jobq);
IMPEG2D_PRINT_STATISTICS();
return(IV_SUCCESS);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void sem_lock_and_putref(struct sem_array *sma)
{
ipc_lock_by_ptr(&sma->sem_perm);
ipc_rcu_putref(sma);
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RemoveInvalidFilesFromPersistentDirectory(
const GDataCacheMetadataMap::ResourceIdToFilePathMap& persistent_file_map,
const GDataCacheMetadataMap::ResourceIdToFilePathMap& outgoing_file_map,
GDataCacheMetadataMap::CacheMap* cache_map) {
for (GDataCacheMetadataMap::ResourceIdToFilePathMap::const_iterator iter =
persistent_file_map.begin();
iter != persistent_file_map.end(); ++iter) {
const std::string& resource_id = iter->first;
const FilePath& file_path = iter->second;
GDataCacheMetadataMap::CacheMap::iterator cache_map_iter =
cache_map->find(resource_id);
if (cache_map_iter != cache_map->end()) {
const GDataCache::CacheEntry& cache_entry = cache_map_iter->second;
if (cache_entry.IsDirty() && outgoing_file_map.count(resource_id) == 0) {
LOG(WARNING) << "Removing dirty-but-not-committed file: "
<< file_path.value();
file_util::Delete(file_path, false);
cache_map->erase(cache_map_iter);
}
if (!cache_entry.IsDirty() && !cache_entry.IsPinned()) {
LOG(WARNING) << "Removing persistent-but-dangling file: "
<< file_path.value();
file_util::Delete(file_path, false);
cache_map->erase(cache_map_iter);
}
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int compat_ipv6_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
int err;
if (level == SOL_IP && sk->sk_type != SOCK_RAW) {
if (udp_prot.compat_getsockopt != NULL)
return udp_prot.compat_getsockopt(sk, level, optname,
optval, optlen);
return udp_prot.getsockopt(sk, level, optname, optval, optlen);
}
if (level != SOL_IPV6)
return -ENOPROTOOPT;
if (optname == MCAST_MSFILTER)
return compat_mc_getsockopt(sk, level, optname, optval, optlen,
ipv6_getsockopt);
err = do_ipv6_getsockopt(sk, level, optname, optval, optlen,
MSG_CMSG_COMPAT);
#ifdef CONFIG_NETFILTER
/* we need to exclude all possible ENOPROTOOPTs except default case */
if (err == -ENOPROTOOPT && optname != IPV6_2292PKTOPTIONS) {
int len;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
err = compat_nf_getsockopt(sk, PF_INET6,
optname, optval, &len);
release_sock(sk);
if (err >= 0)
err = put_user(len, optlen);
}
#endif
return err;
}
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 vmacache_flush_all(struct mm_struct *mm)
{
struct task_struct *g, *p;
count_vm_vmacache_event(VMACACHE_FULL_FLUSHES);
/*
* Single threaded tasks need not iterate the entire
* list of process. We can avoid the flushing as well
* since the mm's seqnum was increased and don't have
* to worry about other threads' seqnum. Current's
* flush will occur upon the next lookup.
*/
if (atomic_read(&mm->mm_users) == 1)
return;
rcu_read_lock();
for_each_process_thread(g, p) {
/*
* Only flush the vmacache pointers as the
* mm seqnum is already set and curr's will
* be set upon invalidation when the next
* lookup is done.
*/
if (mm == p->mm)
vmacache_flush(p);
}
rcu_read_unlock();
}
CWE ID: CWE-416
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int vivid_fb_ioctl(struct fb_info *info, unsigned cmd, unsigned long arg)
{
struct vivid_dev *dev = (struct vivid_dev *)info->par;
switch (cmd) {
case FBIOGET_VBLANK: {
struct fb_vblank vblank;
vblank.flags = FB_VBLANK_HAVE_COUNT | FB_VBLANK_HAVE_VCOUNT |
FB_VBLANK_HAVE_VSYNC;
vblank.count = 0;
vblank.vcount = 0;
vblank.hcount = 0;
if (copy_to_user((void __user *)arg, &vblank, sizeof(vblank)))
return -EFAULT;
return 0;
}
default:
dprintk(dev, 1, "Unknown ioctl %08x\n", cmd);
return -EINVAL;
}
return 0;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
{
RenderLayer* l = layer();
if (l && l->scroll(direction, granularity, multiplier)) {
if (stopNode)
*stopNode = node();
return true;
}
if (stopNode && *stopNode && *stopNode == node())
return true;
RenderBlock* b = containingBlock();
if (b && !b->isRenderView())
return b->scroll(direction, granularity, multiplier, stopNode);
return false;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void tcp_mtup_probe_failed(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
icsk->icsk_mtup.probe_size = 0;
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CrosLibrary::TestApi::SetInputMethodLibrary(
InputMethodLibrary* library, bool own) {
library_->input_method_lib_.SetImpl(library, own);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: GF_Err unkn_Size(GF_Box *s)
{
GF_UnknownBox *ptr = (GF_UnknownBox *)s;
if (ptr->dataSize && ptr->data) {
ptr->size += ptr->dataSize;
}
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: void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (handle != gfx::kNullPluginWindow) {
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
return;
}
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompletedForGPU,
host_id_, params.route_id,
true /* alive */, false /* presented */));
int render_process_id = 0;
int render_widget_id = 0;
if (!GpuSurfaceTracker::Get()->GetRenderWidgetIDForSurface(
params.surface_id, &render_process_id, &render_widget_id)) {
return;
}
RenderWidgetHelper* helper =
RenderWidgetHelper::FromProcessHostID(render_process_id);
if (!helper)
return;
scoped_completion_runner.Release();
helper->DidReceiveBackingStoreMsg(ViewHostMsg_CompositorSurfaceBuffersSwapped(
render_widget_id,
params.surface_id,
params.surface_handle,
params.route_id,
params.size,
host_id_));
}
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 SystemClipboard::WriteImage(Image* image,
const KURL& url,
const String& title) {
DCHECK(image);
PaintImage paint_image = image->PaintImageForCurrentFrame();
SkBitmap bitmap;
if (sk_sp<SkImage> sk_image = paint_image.GetSkImage())
sk_image->asLegacyBitmap(&bitmap);
if (bitmap.isNull())
return;
if (!bitmap.getPixels())
return;
clipboard_->WriteImage(mojom::ClipboardBuffer::kStandard, bitmap);
if (url.IsValid() && !url.IsEmpty()) {
#if !defined(OS_MACOSX)
clipboard_->WriteBookmark(mojom::ClipboardBuffer::kStandard,
url.GetString(), NonNullString(title));
#endif
clipboard_->WriteHtml(mojom::ClipboardBuffer::kStandard,
URLToImageMarkup(url, title), KURL());
}
clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: format_id(const u_char *id)
{
static char buf[25];
snprintf(buf, 25, "%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7]);
buf[24] = '\0';
return buf;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void mpeg4_encode_gop_header(MpegEncContext *s)
{
int hours, minutes, seconds;
int64_t time;
put_bits(&s->pb, 16, 0);
put_bits(&s->pb, 16, GOP_STARTCODE);
time = s->current_picture_ptr->f->pts;
if (s->reordered_input_picture[1])
time = FFMIN(time, s->reordered_input_picture[1]->f->pts);
time = time * s->avctx->time_base.num;
s->last_time_base = FFUDIV(time, s->avctx->time_base.den);
seconds = FFUDIV(time, s->avctx->time_base.den);
minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60);
hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60);
hours = FFUMOD(hours , 24);
put_bits(&s->pb, 5, hours);
put_bits(&s->pb, 6, minutes);
put_bits(&s->pb, 1, 1);
put_bits(&s->pb, 6, seconds);
put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP));
put_bits(&s->pb, 1, 0); // broken link == NO
ff_mpeg4_stuffing(&s->pb);
}
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: usage(const char *prog)
{
fprintf(stderr, "Usage: %s [OPTION...]\n", prog);
fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n");
#if defined _WITH_VRRP_ && defined _WITH_LVS_
fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n");
fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n");
#endif
fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n");
fprintf(stderr, " -l, --log-console Log messages to local console\n");
fprintf(stderr, " -D, --log-detail Detailed log messages\n");
fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n");
fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n");
fprintf(stderr, " --flush-log-file Flush log file on write\n");
fprintf(stderr, " -G, --no-syslog Don't log via syslog\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n");
fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n");
#endif
fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n");
fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n");
fprintf(stderr, " -d, --dump-conf Dump the configuration data\n");
fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n");
#ifdef _WITH_VRRP_
fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n");
#endif
#ifdef _WITH_LVS_
fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n");
fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n");
#endif
#ifdef _WITH_BFD_
fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n");
#endif
#ifdef _WITH_SNMP_
fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n");
fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n");
#endif
#if HAVE_DECL_CLONE_NEWNET
fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n");
#endif
fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n");
fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n");
#ifdef _MEM_CHECK_LOG_
fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n");
#endif
fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n"
" or any lines beginning @^ that do match.\n"
" The config-id defaults to the node name if option not used\n");
fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS"
#ifdef _WITH_JSON_
", JSON"
#endif
"\n");
fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n"
" stderr by default\n");
#ifdef _WITH_PERF_
fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n");
#endif
#ifdef WITH_DEBUG_OPTIONS
fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n");
#ifdef _TIMER_CHECK_
fprintf(stderr, " T - timer debug\n");
#endif
#ifdef _SMTP_ALERT_DEBUG_
fprintf(stderr, " M - email alert debug\n");
#endif
#ifdef _EPOLL_DEBUG_
fprintf(stderr, " E - epoll debug\n");
#endif
#ifdef _EPOLL_THREAD_DUMP_
fprintf(stderr, " D - epoll thread dump debug\n");
#endif
#ifdef _VRRP_FD_DEBUG
fprintf(stderr, " F - vrrp fd dump debug\n");
#endif
#ifdef _REGEX_DEBUG_
fprintf(stderr, " R - regex debug\n");
#endif
#ifdef _WITH_REGEX_TIMERS_
fprintf(stderr, " X - regex timers\n");
#endif
#ifdef _TSM_DEBUG_
fprintf(stderr, " S - TSM debug\n");
#endif
#ifdef _NETLINK_TIMERS_
fprintf(stderr, " N - netlink timer debug\n");
#endif
fprintf(stderr, " Example --debug=TpMEvcp\n");
#endif
fprintf(stderr, " -v, --version Display the version number\n");
fprintf(stderr, " -h, --help Display this help message\n");
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static inline bool cpu_has_vmx_posted_intr(void)
{
return vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
}
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: xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
xmlChar cur;
xmlChar stop;
int count = 0;
xmlParserInputState oldstate = ctxt->instate;
SHRINK;
if (RAW == '"') {
NEXT;
stop = '"';
} else if (RAW == '\'') {
NEXT;
stop = '\'';
} else {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL);
return(NULL);
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
return(NULL);
}
ctxt->instate = XML_PARSER_PUBLIC_LITERAL;
cur = CUR;
while ((IS_PUBIDCHAR_CH(cur)) && (cur != stop)) { /* checked */
if (len + 1 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
return(NULL);
}
buf = tmp;
}
buf[len++] = cur;
count++;
if (count > 50) {
GROW;
count = 0;
}
NEXT;
cur = CUR;
if (cur == 0) {
GROW;
SHRINK;
cur = CUR;
}
}
buf[len] = 0;
if (cur != stop) {
xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL);
} else {
NEXT;
}
ctxt->instate = oldstate;
return(buf);
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long mkvparser::UnserializeInt(
IMkvReader* pReader,
long long pos,
long size,
long long& result)
{
assert(pReader);
assert(pos >= 0);
assert(size > 0);
assert(size <= 8);
{
signed char b;
const long status = pReader->Read(pos, 1, (unsigned char*)&b);
if (status < 0)
return status;
result = b;
++pos;
}
for (long i = 1; i < size; ++i)
{
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return 0; //success
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: GURL OmniboxEditModel::PermanentURL() {
return URLFixerUpper::FixupURL(base::UTF16ToUTF8(permanent_text_),
std::string());
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int fixup_pi_state_owner(u32 __user *uaddr, struct futex_q *q,
struct task_struct *newowner, int fshared)
{
u32 newtid = task_pid_vnr(newowner) | FUTEX_WAITERS;
struct futex_pi_state *pi_state = q->pi_state;
struct task_struct *oldowner = pi_state->owner;
u32 uval, curval, newval;
int ret;
/* Owner died? */
if (!pi_state->owner)
newtid |= FUTEX_OWNER_DIED;
/*
* We are here either because we stole the rtmutex from the
* pending owner or we are the pending owner which failed to
* get the rtmutex. We have to replace the pending owner TID
* in the user space variable. This must be atomic as we have
* to preserve the owner died bit here.
*
* Note: We write the user space value _before_ changing the pi_state
* because we can fault here. Imagine swapped out pages or a fork
* that marked all the anonymous memory readonly for cow.
*
* Modifying pi_state _before_ the user space value would
* leave the pi_state in an inconsistent state when we fault
* here, because we need to drop the hash bucket lock to
* handle the fault. This might be observed in the PID check
* in lookup_pi_state.
*/
retry:
if (get_futex_value_locked(&uval, uaddr))
goto handle_fault;
while (1) {
newval = (uval & FUTEX_OWNER_DIED) | newtid;
curval = cmpxchg_futex_value_locked(uaddr, uval, newval);
if (curval == -EFAULT)
goto handle_fault;
if (curval == uval)
break;
uval = curval;
}
/*
* We fixed up user space. Now we need to fix the pi_state
* itself.
*/
if (pi_state->owner != NULL) {
raw_spin_lock_irq(&pi_state->owner->pi_lock);
WARN_ON(list_empty(&pi_state->list));
list_del_init(&pi_state->list);
raw_spin_unlock_irq(&pi_state->owner->pi_lock);
}
pi_state->owner = newowner;
raw_spin_lock_irq(&newowner->pi_lock);
WARN_ON(!list_empty(&pi_state->list));
list_add(&pi_state->list, &newowner->pi_state_list);
raw_spin_unlock_irq(&newowner->pi_lock);
return 0;
/*
* To handle the page fault we need to drop the hash bucket
* lock here. That gives the other task (either the pending
* owner itself or the task which stole the rtmutex) the
* chance to try the fixup of the pi_state. So once we are
* back from handling the fault we need to check the pi_state
* after reacquiring the hash bucket lock and before trying to
* do another fixup. When the fixup has been done already we
* simply return.
*/
handle_fault:
spin_unlock(q->lock_ptr);
ret = fault_in_user_writeable(uaddr);
spin_lock(q->lock_ptr);
/*
* Check if someone else fixed it for us:
*/
if (pi_state->owner != oldowner)
return 0;
if (ret)
return ret;
goto retry;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ip_forward(struct sk_buff *skb)
{
u32 mtu;
struct iphdr *iph; /* Our header */
struct rtable *rt; /* Route we use */
struct ip_options *opt = &(IPCB(skb)->opt);
/* that should never happen */
if (skb->pkt_type != PACKET_HOST)
goto drop;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb))
goto drop;
if (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb))
return NET_RX_SUCCESS;
skb_forward_csum(skb);
/*
* According to the RFC, we must first decrease the TTL field. If
* that reaches zero, we must reply an ICMP control message telling
* that the packet's lifetime expired.
*/
if (ip_hdr(skb)->ttl <= 1)
goto too_many_hops;
if (!xfrm4_route_forward(skb))
goto drop;
rt = skb_rtable(skb);
if (opt->is_strictroute && rt->rt_uses_gateway)
goto sr_failed;
IPCB(skb)->flags |= IPSKB_FORWARDED;
mtu = ip_dst_mtu_maybe_forward(&rt->dst, true);
if (!ip_may_fragment(skb) && ip_exceeds_mtu(skb, mtu)) {
IP_INC_STATS(dev_net(rt->dst.dev), IPSTATS_MIB_FRAGFAILS);
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
htonl(mtu));
goto drop;
}
/* We are about to mangle packet. Copy it! */
if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+rt->dst.header_len))
goto drop;
iph = ip_hdr(skb);
/* Decrease ttl after skb cow done */
ip_decrease_ttl(iph);
/*
* We now generate an ICMP HOST REDIRECT giving the route
* we calculated.
*/
if (rt->rt_flags&RTCF_DOREDIRECT && !opt->srr && !skb_sec_path(skb))
ip_rt_send_redirect(skb);
skb->priority = rt_tos2priority(iph->tos);
return NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD, skb, skb->dev,
rt->dst.dev, ip_forward_finish);
sr_failed:
/*
* Strict routing permits no gatewaying
*/
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0);
goto drop;
too_many_hops:
/* Tell the sender its packet died... */
IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_INHDRERRORS);
icmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0);
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
CWE ID: CWE-17
Target: 1
Example 2:
Code: TestRenderFrame* frame() {
return static_cast<TestRenderFrame*>(view()->GetMainRenderFrame());
}
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: cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!n){cJSON_Delete(a);return 0;}if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
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 __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu)
{
struct kvm_pit *pit = vcpu->kvm->arch.vpit;
struct hrtimer *timer;
if (!kvm_vcpu_is_bsp(vcpu) || !pit)
return;
timer = &pit->pit_state.timer;
if (hrtimer_cancel(timer))
hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int opfxch(RAsm *a, ut8 *data, const Opcode *op) {
int l = 0;
switch (op->operands_count) {
case 0:
data[l++] = 0xd9;
data[l++] = 0xc9;
break;
case 1:
if (op->operands[0].type & OT_FPUREG & ~OT_REGALL) {
data[l++] = 0xd9;
data[l++] = 0xc8 | op->operands[0].reg;
} else {
return -1;
}
break;
default:
return -1;
}
return l;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int set_side_data(HEVCContext *s)
{
AVFrame *out = s->ref->frame;
if (s->sei.frame_packing.present &&
s->sei.frame_packing.arrangement_type >= 3 &&
s->sei.frame_packing.arrangement_type <= 5 &&
s->sei.frame_packing.content_interpretation_type > 0 &&
s->sei.frame_packing.content_interpretation_type < 3) {
AVStereo3D *stereo = av_stereo3d_create_side_data(out);
if (!stereo)
return AVERROR(ENOMEM);
switch (s->sei.frame_packing.arrangement_type) {
case 3:
if (s->sei.frame_packing.quincunx_subsampling)
stereo->type = AV_STEREO3D_SIDEBYSIDE_QUINCUNX;
else
stereo->type = AV_STEREO3D_SIDEBYSIDE;
break;
case 4:
stereo->type = AV_STEREO3D_TOPBOTTOM;
break;
case 5:
stereo->type = AV_STEREO3D_FRAMESEQUENCE;
break;
}
if (s->sei.frame_packing.content_interpretation_type == 2)
stereo->flags = AV_STEREO3D_FLAG_INVERT;
if (s->sei.frame_packing.arrangement_type == 5) {
if (s->sei.frame_packing.current_frame_is_frame0_flag)
stereo->view = AV_STEREO3D_VIEW_LEFT;
else
stereo->view = AV_STEREO3D_VIEW_RIGHT;
}
}
if (s->sei.display_orientation.present &&
(s->sei.display_orientation.anticlockwise_rotation ||
s->sei.display_orientation.hflip || s->sei.display_orientation.vflip)) {
double angle = s->sei.display_orientation.anticlockwise_rotation * 360 / (double) (1 << 16);
AVFrameSideData *rotation = av_frame_new_side_data(out,
AV_FRAME_DATA_DISPLAYMATRIX,
sizeof(int32_t) * 9);
if (!rotation)
return AVERROR(ENOMEM);
av_display_rotation_set((int32_t *)rotation->data, angle);
av_display_matrix_flip((int32_t *)rotation->data,
s->sei.display_orientation.hflip,
s->sei.display_orientation.vflip);
}
if (s->sei.mastering_display.present > 0 &&
IS_IRAP(s) && s->no_rasl_output_flag) {
s->sei.mastering_display.present--;
}
if (s->sei.mastering_display.present) {
const int mapping[3] = {2, 0, 1};
const int chroma_den = 50000;
const int luma_den = 10000;
int i;
AVMasteringDisplayMetadata *metadata =
av_mastering_display_metadata_create_side_data(out);
if (!metadata)
return AVERROR(ENOMEM);
for (i = 0; i < 3; i++) {
const int j = mapping[i];
metadata->display_primaries[i][0].num = s->sei.mastering_display.display_primaries[j][0];
metadata->display_primaries[i][0].den = chroma_den;
metadata->display_primaries[i][1].num = s->sei.mastering_display.display_primaries[j][1];
metadata->display_primaries[i][1].den = chroma_den;
}
metadata->white_point[0].num = s->sei.mastering_display.white_point[0];
metadata->white_point[0].den = chroma_den;
metadata->white_point[1].num = s->sei.mastering_display.white_point[1];
metadata->white_point[1].den = chroma_den;
metadata->max_luminance.num = s->sei.mastering_display.max_luminance;
metadata->max_luminance.den = luma_den;
metadata->min_luminance.num = s->sei.mastering_display.min_luminance;
metadata->min_luminance.den = luma_den;
metadata->has_luminance = 1;
metadata->has_primaries = 1;
av_log(s->avctx, AV_LOG_DEBUG, "Mastering Display Metadata:\n");
av_log(s->avctx, AV_LOG_DEBUG,
"r(%5.4f,%5.4f) g(%5.4f,%5.4f) b(%5.4f %5.4f) wp(%5.4f, %5.4f)\n",
av_q2d(metadata->display_primaries[0][0]),
av_q2d(metadata->display_primaries[0][1]),
av_q2d(metadata->display_primaries[1][0]),
av_q2d(metadata->display_primaries[1][1]),
av_q2d(metadata->display_primaries[2][0]),
av_q2d(metadata->display_primaries[2][1]),
av_q2d(metadata->white_point[0]), av_q2d(metadata->white_point[1]));
av_log(s->avctx, AV_LOG_DEBUG,
"min_luminance=%f, max_luminance=%f\n",
av_q2d(metadata->min_luminance), av_q2d(metadata->max_luminance));
}
if (s->sei.content_light.present > 0 &&
IS_IRAP(s) && s->no_rasl_output_flag) {
s->sei.content_light.present--;
}
if (s->sei.content_light.present) {
AVContentLightMetadata *metadata =
av_content_light_metadata_create_side_data(out);
if (!metadata)
return AVERROR(ENOMEM);
metadata->MaxCLL = s->sei.content_light.max_content_light_level;
metadata->MaxFALL = s->sei.content_light.max_pic_average_light_level;
av_log(s->avctx, AV_LOG_DEBUG, "Content Light Level Metadata:\n");
av_log(s->avctx, AV_LOG_DEBUG, "MaxCLL=%d, MaxFALL=%d\n",
metadata->MaxCLL, metadata->MaxFALL);
}
if (s->sei.a53_caption.a53_caption) {
AVFrameSideData* sd = av_frame_new_side_data(out,
AV_FRAME_DATA_A53_CC,
s->sei.a53_caption.a53_caption_size);
if (sd)
memcpy(sd->data, s->sei.a53_caption.a53_caption, s->sei.a53_caption.a53_caption_size);
av_freep(&s->sei.a53_caption.a53_caption);
s->sei.a53_caption.a53_caption_size = 0;
s->avctx->properties |= FF_CODEC_PROPERTY_CLOSED_CAPTIONS;
}
if (s->sei.alternative_transfer.present &&
av_color_transfer_name(s->sei.alternative_transfer.preferred_transfer_characteristics) &&
s->sei.alternative_transfer.preferred_transfer_characteristics != AVCOL_TRC_UNSPECIFIED) {
s->avctx->color_trc = out->color_trc = s->sei.alternative_transfer.preferred_transfer_characteristics;
}
return 0;
}
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: find_insert(png_const_charp what, png_charp param)
{
png_uint_32 chunk = 0;
png_charp parameter_list[1024];
int i, nparams;
/* Assemble the chunk name */
for (i=0; i<4; ++i)
{
char ch = what[i];
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
chunk = (chunk << 8) + what[i];
else
break;
}
if (i < 4 || what[4] != 0)
{
fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what);
exit(1);
}
/* Assemble the parameter list. */
nparams = find_parameters(what, param, parameter_list, 1024);
# define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
switch (chunk)
{
case CHUNK(105,67,67,80): /* iCCP */
if (nparams == 2)
return make_insert(what, insert_iCCP, nparams, parameter_list);
break;
case CHUNK(116,69,88,116): /* tEXt */
if (nparams == 2)
return make_insert(what, insert_tEXt, nparams, parameter_list);
break;
case CHUNK(122,84,88,116): /* zTXt */
if (nparams == 2)
return make_insert(what, insert_zTXt, nparams, parameter_list);
break;
case CHUNK(105,84,88,116): /* iTXt */
if (nparams == 4)
return make_insert(what, insert_iTXt, nparams, parameter_list);
break;
case CHUNK(104,73,83,84): /* hIST */
if (nparams <= 256)
return make_insert(what, insert_hIST, nparams, parameter_list);
break;
#if 0
case CHUNK(115,80,76,84): /* sPLT */
return make_insert(what, insert_sPLT, nparams, parameter_list);
#endif
default:
fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n",
what);
exit(1);
}
bad_parameter_count(what, nparams);
return NULL;
}
CWE ID:
Target: 1
Example 2:
Code: void kvm_exit(void)
{
kvm_exit_debug();
misc_deregister(&kvm_dev);
kmem_cache_destroy(kvm_vcpu_cache);
kvm_async_pf_deinit();
unregister_syscore_ops(&kvm_syscore_ops);
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
on_each_cpu(hardware_disable_nolock, NULL, 1);
kvm_arch_hardware_unsetup();
kvm_arch_exit();
free_cpumask_var(cpus_hardware_enabled);
__free_page(hwpoison_page);
__free_page(bad_page);
}
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: LIBOPENMPT_MODPLUG_API unsigned int ModPlug_NumPatterns(ModPlugFile* file)
{
if(!file) return 0;
return openmpt_module_get_num_patterns(file->mod);
}
CWE ID: CWE-120
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 DrawingBuffer::FinishPrepareTextureMailboxGpu(
viz::TextureMailbox* out_mailbox,
std::unique_ptr<cc::SingleReleaseCallback>* out_release_callback) {
DCHECK(state_restorer_);
if (web_gl_version_ > kWebGL1) {
state_restorer_->SetPixelUnpackBufferBindingDirty();
gl_->BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
}
RefPtr<ColorBuffer> color_buffer_for_mailbox;
if (preserve_drawing_buffer_ == kDiscard) {
color_buffer_for_mailbox = back_color_buffer_;
back_color_buffer_ = CreateOrRecycleColorBuffer();
AttachColorBufferToReadFramebuffer();
if (discard_framebuffer_supported_) {
const GLenum kAttachments[3] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT,
GL_STENCIL_ATTACHMENT};
state_restorer_->SetFramebufferBindingDirty();
gl_->BindFramebuffer(GL_FRAMEBUFFER, fbo_);
gl_->DiscardFramebufferEXT(GL_FRAMEBUFFER, 3, kAttachments);
}
} else {
color_buffer_for_mailbox = CreateOrRecycleColorBuffer();
gl_->CopySubTextureCHROMIUM(back_color_buffer_->texture_id, 0,
color_buffer_for_mailbox->parameters.target,
color_buffer_for_mailbox->texture_id, 0, 0, 0,
0, 0, size_.Width(), size_.Height(), GL_FALSE,
GL_FALSE, GL_FALSE);
}
{
gl_->ProduceTextureDirectCHROMIUM(
color_buffer_for_mailbox->texture_id,
color_buffer_for_mailbox->parameters.target,
color_buffer_for_mailbox->mailbox.name);
const GLuint64 fence_sync = gl_->InsertFenceSyncCHROMIUM();
#if defined(OS_MACOSX)
gl_->DescheduleUntilFinishedCHROMIUM();
#endif
gl_->Flush();
gl_->GenSyncTokenCHROMIUM(
fence_sync, color_buffer_for_mailbox->produce_sync_token.GetData());
}
{
bool is_overlay_candidate = color_buffer_for_mailbox->image_id != 0;
bool secure_output_only = false;
*out_mailbox = viz::TextureMailbox(
color_buffer_for_mailbox->mailbox,
color_buffer_for_mailbox->produce_sync_token,
color_buffer_for_mailbox->parameters.target, gfx::Size(size_),
is_overlay_candidate, secure_output_only);
out_mailbox->set_color_space(color_space_);
auto func =
WTF::Bind(&DrawingBuffer::MailboxReleasedGpu,
RefPtr<DrawingBuffer>(this), color_buffer_for_mailbox);
*out_release_callback = cc::SingleReleaseCallback::Create(
ConvertToBaseCallback(std::move(func)));
}
front_color_buffer_ = color_buffer_for_mailbox;
contents_changed_ = false;
SetBufferClearNeeded(true);
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: const views::NativeWidget* BrowserFrameGtk::AsNativeWidget() const {
return this;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Huff_transmit (huff_t *huff, int ch, byte *fout) {
int i;
if (huff->loc[ch] == NULL) {
/* node_t hasn't been transmitted, send a NYT, then the symbol */
Huff_transmit(huff, NYT, fout);
for (i = 7; i >= 0; i--) {
add_bit((char)((ch >> i) & 0x1), fout);
}
} else {
send(huff->loc[ch], NULL, fout);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void TestEnumOrDoubleAttributeAttributeSetter(
v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
ALLOW_UNUSED_LOCAL(isolate);
v8::Local<v8::Object> holder = info.Holder();
ALLOW_UNUSED_LOCAL(holder);
TestObject* impl = V8TestObject::ToImpl(holder);
ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "TestObject", "testEnumOrDoubleAttribute");
TestEnumOrDouble cpp_value;
V8TestEnumOrDouble::ToImpl(info.GetIsolate(), v8_value, cpp_value, UnionTypeConversionMode::kNotNullable, exception_state);
if (exception_state.HadException())
return;
impl->setTestEnumOrDoubleAttribute(cpp_value);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ConfigureEntriesForRestore(
std::vector<linked_ptr<NavigationEntryImpl> >* entries,
NavigationController::RestoreType type) {
for (size_t i = 0; i < entries->size(); ++i) {
(*entries)[i]->SetTransitionType(PAGE_TRANSITION_RELOAD);
(*entries)[i]->set_restore_type(ControllerRestoreTypeToEntryType(type));
SetPageStateIfEmpty((*entries)[i].get());
}
}
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: l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr))); ptr++; /* Result Code */
if (length > 2) { /* Error Code (opt) */
ND_PRINT((ndo, "/%u", EXTRACT_16BITS(ptr))); ptr++;
}
if (length > 4) { /* Error Message (opt) */
ND_PRINT((ndo, " "));
print_string(ndo, (const u_char *)ptr, length - 4);
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BlobStorageContext::RevokePublicBlobURL(const GURL& blob_url) {
std::string uuid;
if (!registry_.DeleteURLMapping(blob_url, &uuid))
return;
DecrementBlobRefCount(uuid);
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void ctrycatch(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catchstm)
{
int L1, L2;
L1 = emitjump(J, F, OP_TRY);
{
/* if we get here, we have caught an exception in the try block */
if (J->strict) {
if (!strcmp(catchvar->string, "arguments"))
jsC_error(J, catchvar, "redefining 'arguments' is not allowed in strict mode");
if (!strcmp(catchvar->string, "eval"))
jsC_error(J, catchvar, "redefining 'eval' is not allowed in strict mode");
}
emitstring(J, F, OP_CATCH, catchvar->string);
cstm(J, F, catchstm);
emit(J, F, OP_ENDCATCH);
L2 = emitjump(J, F, OP_JUMP); /* skip past the try block */
}
label(J, F, L1);
cstm(J, F, trystm);
emit(J, F, OP_ENDTRY);
label(J, F, L2);
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
{
setDeviceOrientationOverride(error, 0, 0, 0);
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AcceleratedStaticBitmapImage::AcceleratedStaticBitmapImage(
sk_sp<SkImage> image,
base::WeakPtr<WebGraphicsContext3DProviderWrapper>&&
context_provider_wrapper)
: paint_image_content_id_(cc::PaintImage::GetNextContentId()) {
CHECK(image && image->isTextureBacked());
texture_holder_ = std::make_unique<SkiaTextureHolder>(
std::move(image), std::move(context_provider_wrapper));
thread_checker_.DetachFromThread();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int mailimf_parse_unwanted_msg_id(const char * message, size_t length,
size_t * indx)
{
size_t cur_token;
int r;
char * word;
int token_parsed;
cur_token = * indx;
token_parsed = TRUE;
while (token_parsed) {
token_parsed = FALSE;
r = mailimf_word_parse(message, length, &cur_token, &word);
if (r == MAILIMF_NO_ERROR) {
mailimf_word_free(word);
token_parsed = TRUE;
}
else if (r == MAILIMF_ERROR_PARSE) {
/* do nothing */
}
else
return r;
r = mailimf_semi_colon_parse(message, length, &cur_token);
if (r == MAILIMF_NO_ERROR)
token_parsed = TRUE;
else if (r == MAILIMF_ERROR_PARSE) {
/* do nothing */
}
else
return r;
r = mailimf_comma_parse(message, length, &cur_token);
if (r == MAILIMF_NO_ERROR)
token_parsed = TRUE;
else if (r == MAILIMF_ERROR_PARSE) {
/* do nothing */
}
else
return r;
r = mailimf_plus_parse(message, length, &cur_token);
if (r == MAILIMF_NO_ERROR)
token_parsed = TRUE;
else if (r == MAILIMF_ERROR_PARSE) {
/* do nothing */
}
else
return r;
r = mailimf_colon_parse(message, length, &cur_token);
if (r == MAILIMF_NO_ERROR)
token_parsed = TRUE;
else if (r == MAILIMF_ERROR_PARSE) {
/* do nothing */
}
else
return r;
r = mailimf_point_parse(message, length, &cur_token);
if (r == MAILIMF_NO_ERROR)
token_parsed = TRUE;
else if (r == MAILIMF_ERROR_PARSE) {
/* do nothing */
}
else
return r;
r = mailimf_at_sign_parse(message, length, &cur_token);
if (r == MAILIMF_NO_ERROR)
token_parsed = TRUE;
else if (r == MAILIMF_ERROR_PARSE) {
/* do nothing */
}
else
return r;
}
* indx = cur_token;
return MAILIMF_NO_ERROR;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: FileReaderLoader::FileReaderLoader(ReadType read_type,
FileReaderLoaderClient* client)
: read_type_(read_type),
client_(client),
handle_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC),
binding_(this) {}
CWE ID: CWE-416
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: RenderView::RenderView(RenderThreadBase* render_thread,
gfx::NativeViewId parent_hwnd,
int32 opener_id,
const RendererPreferences& renderer_prefs,
const WebPreferences& webkit_prefs,
SharedRenderViewCounter* counter,
int32 routing_id,
int64 session_storage_namespace_id,
const string16& frame_name)
: RenderWidget(render_thread, WebKit::WebPopupTypeNone),
webkit_preferences_(webkit_prefs),
send_content_state_immediately_(false),
enabled_bindings_(0),
send_preferred_size_changes_(false),
is_loading_(false),
navigation_gesture_(NavigationGestureUnknown),
opened_by_user_gesture_(true),
opener_suppressed_(false),
page_id_(-1),
last_page_id_sent_to_browser_(-1),
history_list_offset_(-1),
history_list_length_(0),
target_url_status_(TARGET_NONE),
ALLOW_THIS_IN_INITIALIZER_LIST(pepper_delegate_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(accessibility_method_factory_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(cookie_jar_(this)),
geolocation_dispatcher_(NULL),
speech_input_dispatcher_(NULL),
device_orientation_dispatcher_(NULL),
accessibility_ack_pending_(false),
p2p_socket_dispatcher_(NULL),
session_storage_namespace_id_(session_storage_namespace_id) {
routing_id_ = routing_id;
if (opener_id != MSG_ROUTING_NONE)
opener_id_ = opener_id;
webwidget_ = WebView::create(this);
if (counter) {
shared_popup_counter_ = counter;
shared_popup_counter_->data++;
decrement_shared_popup_at_destruction_ = true;
} else {
shared_popup_counter_ = new SharedRenderViewCounter(0);
decrement_shared_popup_at_destruction_ = false;
}
notification_provider_ = new NotificationProvider(this);
render_thread_->AddRoute(routing_id_, this);
AddRef();
if (opener_id == MSG_ROUTING_NONE) {
did_show_ = true;
CompleteInit(parent_hwnd);
}
g_view_map.Get().insert(std::make_pair(webview(), this));
webkit_preferences_.Apply(webview());
webview()->initializeMainFrame(this);
if (!frame_name.empty())
webview()->mainFrame()->setName(frame_name);
webview()->settings()->setMinimumTimerInterval(
is_hidden() ? webkit_glue::kBackgroundTabTimerInterval :
webkit_glue::kForegroundTabTimerInterval);
OnSetRendererPrefs(renderer_prefs);
host_window_ = parent_hwnd;
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableAccessibility))
WebAccessibilityCache::enableAccessibility();
#if defined(ENABLE_P2P_APIS)
p2p_socket_dispatcher_ = new P2PSocketDispatcher(this);
#endif
new MHTMLGenerator(this);
if (command_line.HasSwitch(switches::kEnableMediaStream)) {
media_stream_impl_ = new MediaStreamImpl(
RenderThread::current()->video_capture_impl_manager());
}
content::GetContentClient()->renderer()->RenderViewCreated(this);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void RenderWidgetHostViewAura::SetTextEditCommandForNextKeyEvent(
ui::TextEditCommand command) {}
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 parse_index(git_index *index, const char *buffer, size_t buffer_size)
{
int error = 0;
unsigned int i;
struct index_header header = { 0 };
git_oid checksum_calculated, checksum_expected;
const char *last = NULL;
const char *empty = "";
#define seek_forward(_increase) { \
if (_increase >= buffer_size) { \
error = index_error_invalid("ran out of data while parsing"); \
goto done; } \
buffer += _increase; \
buffer_size -= _increase;\
}
if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE)
return index_error_invalid("insufficient buffer space");
/* Precalculate the SHA1 of the files's contents -- we'll match it to
* the provided SHA1 in the footer */
git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE);
/* Parse header */
if ((error = read_header(&header, buffer)) < 0)
return error;
index->version = header.version;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = empty;
seek_forward(INDEX_HEADER_SIZE);
assert(!index->entries.length);
if (index->ignore_case)
git_idxmap_icase_resize((khash_t(idxicase) *) index->entries_map, header.entry_count);
else
git_idxmap_resize(index->entries_map, header.entry_count);
/* Parse all the entries */
for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) {
git_index_entry *entry = NULL;
size_t entry_size = read_entry(&entry, index, buffer, buffer_size, last);
/* 0 bytes read means an object corruption */
if (entry_size == 0) {
error = index_error_invalid("invalid entry");
goto done;
}
if ((error = git_vector_insert(&index->entries, entry)) < 0) {
index_entry_free(entry);
goto done;
}
INSERT_IN_MAP(index, entry, &error);
if (error < 0) {
index_entry_free(entry);
goto done;
}
error = 0;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = entry->path;
seek_forward(entry_size);
}
if (i != header.entry_count) {
error = index_error_invalid("header entries changed while parsing");
goto done;
}
/* There's still space for some extensions! */
while (buffer_size > INDEX_FOOTER_SIZE) {
size_t extension_size;
extension_size = read_extension(index, buffer, buffer_size);
/* see if we have read any bytes from the extension */
if (extension_size == 0) {
error = index_error_invalid("extension is truncated");
goto done;
}
seek_forward(extension_size);
}
if (buffer_size != INDEX_FOOTER_SIZE) {
error = index_error_invalid(
"buffer size does not match index footer size");
goto done;
}
/* 160-bit SHA-1 over the content of the index file before this checksum. */
git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer);
if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) {
error = index_error_invalid(
"calculated checksum does not match expected");
goto done;
}
git_oid_cpy(&index->checksum, &checksum_calculated);
#undef seek_forward
/* Entries are stored case-sensitively on disk, so re-sort now if
* in-memory index is supposed to be case-insensitive
*/
git_vector_set_sorted(&index->entries, !index->ignore_case);
git_vector_sort(&index->entries);
done:
return error;
}
CWE ID: CWE-415
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void commitCompleteOnCCThread(CCLayerTreeHostImpl*)
{
m_numCommits++;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void kvm_release_page_clean(struct page *page)
{
kvm_release_pfn_clean(page_to_pfn(page));
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
{
jpc_dec_tile_t *tile;
jpc_pi_t *pi;
int ret;
tile = dec->curtile;
pi = tile->pi;
for (;;) {
if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
switch (jpc_dec_lookahead(in)) {
case JPC_MS_EOC:
case JPC_MS_SOT:
return 0;
break;
case JPC_MS_SOP:
case JPC_MS_EPH:
case 0:
break;
default:
return -1;
break;
}
}
if ((ret = jpc_pi_next(pi))) {
return ret;
}
if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
jas_eprintf("warning: stopping decode prematurely as requested\n");
return 0;
}
if (jas_getdbglevel() >= 1) {
jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
"rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
}
if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),
jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
return -1;
}
++dec->numpkts;
}
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: parse_device(dev_t *pdev, struct archive *a, char *val)
{
#define MAX_PACK_ARGS 3
unsigned long numbers[MAX_PACK_ARGS];
char *p, *dev;
int argc;
pack_t *pack;
dev_t result;
const char *error = NULL;
memset(pdev, 0, sizeof(*pdev));
if ((dev = strchr(val, ',')) != NULL) {
/*
* Device's major/minor are given in a specified format.
* Decode and pack it accordingly.
*/
*dev++ = '\0';
if ((pack = pack_find(val)) == NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown format `%s'", val);
return ARCHIVE_WARN;
}
argc = 0;
while ((p = la_strsep(&dev, ",")) != NULL) {
if (*p == '\0') {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Missing number");
return ARCHIVE_WARN;
}
numbers[argc++] = (unsigned long)mtree_atol(&p);
if (argc > MAX_PACK_ARGS) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Too many arguments");
return ARCHIVE_WARN;
}
}
if (argc < 2) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Not enough arguments");
return ARCHIVE_WARN;
}
result = (*pack)(argc, numbers, &error);
if (error != NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"%s", error);
return ARCHIVE_WARN;
}
} else {
/* file system raw value. */
result = (dev_t)mtree_atol(&val);
}
*pdev = result;
return ARCHIVE_OK;
#undef MAX_PACK_ARGS
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: wkbReadInt(wkbObj *w)
{
int i;
memcpy(&i, w->ptr, sizeof(int));
w->ptr += sizeof(int);
return i;
}
CWE ID: CWE-89
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PreresolveJob::PreresolveJob(PreconnectRequest preconnect_request,
PreresolveInfo* info)
: url(std::move(preconnect_request.origin)),
num_sockets(preconnect_request.num_sockets),
allow_credentials(preconnect_request.allow_credentials),
network_isolation_key(
std::move(preconnect_request.network_isolation_key)),
info(info) {
DCHECK_GE(num_sockets, 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: base::SharedMemoryHandle CreateMSKPInSharedMemory() {
SkDynamicMemoryWStream stream;
sk_sp<SkDocument> doc = SkMakeMultiPictureDocument(&stream);
cc::SkiaPaintCanvas canvas(doc->beginPage(800, 600));
SkRect rect = SkRect::MakeXYWH(10, 10, 250, 250);
cc::PaintFlags flags;
flags.setAntiAlias(false);
flags.setColor(SK_ColorRED);
flags.setStyle(cc::PaintFlags::kFill_Style);
canvas.drawRect(rect, flags);
doc->endPage();
doc->close();
size_t len = stream.bytesWritten();
base::SharedMemoryCreateOptions options;
options.size = len;
options.share_read_only = true;
base::SharedMemory shared_memory;
if (shared_memory.Create(options) && shared_memory.Map(len)) {
stream.copyTo(shared_memory.memory());
return base::SharedMemory::DuplicateHandle(shared_memory.handle());
}
return base::SharedMemoryHandle();
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: bool RenderThreadImpl::NeedsToRecordFirstActivePaint(
int ttfap_metric_type) const {
if (ttfap_metric_type == RenderWidget::TTFAP_AFTER_PURGED)
return needs_to_record_first_active_paint_;
if (was_backgrounded_time_.is_min())
return false;
base::TimeDelta passed = base::TimeTicks::Now() - was_backgrounded_time_;
return passed.InMinutes() >= 5;
}
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: _gnutls_ciphertext2compressed (gnutls_session_t session,
opaque * compress_data,
int compress_size,
gnutls_datum_t ciphertext, uint8_t type,
record_parameters_st * params)
{
uint8_t MAC[MAX_HASH_SIZE];
uint16_t c_length;
uint8_t pad;
int length;
uint16_t blocksize;
int ret, i, pad_failed = 0;
opaque preamble[PREAMBLE_SIZE];
int preamble_size;
int ver = gnutls_protocol_get_version (session);
int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm);
blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm);
/* actual decryption (inplace)
*/
switch (_gnutls_cipher_is_block (params->cipher_algorithm))
{
case CIPHER_STREAM:
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state,
ciphertext.data, ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
length = ciphertext.size - hash_size;
break;
case CIPHER_BLOCK:
if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
if ((ret =
_gnutls_cipher_decrypt (¶ms->read.cipher_state,
ciphertext.data, ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
/* ignore the IV in TLS 1.1.
*/
if (_gnutls_version_has_explicit_iv
(session->security_parameters.version))
{
ciphertext.size -= blocksize;
ciphertext.data += blocksize;
if (ciphertext.size == 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
}
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
if ((int) pad > (int) ciphertext.size - hash_size)
if ((int) pad > (int) ciphertext.size - hash_size)
{
gnutls_assert ();
_gnutls_record_log
("REC[%p]: Short record length %d > %d - %d (under attack?)\n",
session, pad, ciphertext.size, hash_size);
/* We do not fail here. We check below for the
* the pad_failed. If zero means success.
*/
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
length = ciphertext.size - hash_size - pad;
/* Check the pading bytes (TLS 1.x)
*/
if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0)
for (i = 2; i < pad; i++)
{
if (ciphertext.data[ciphertext.size - i] !=
ciphertext.data[ciphertext.size - 1])
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
break;
default:
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (length < 0)
length = 0;
c_length = _gnutls_conv_uint16 ((uint16_t) length);
/* Pass the type, version, length and compressed through
* MAC.
*/
if (params->mac_algorithm != GNUTLS_MAC_NULL)
{
digest_hd_st td;
ret = mac_init (&td, params->mac_algorithm,
params->read.mac_secret.data,
params->read.mac_secret.size, ver);
if (ret < 0)
{
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
preamble_size =
make_preamble (UINT64DATA
(params->read.sequence_number), type,
c_length, ver, preamble);
mac_hash (&td, preamble, preamble_size, ver);
if (length > 0)
mac_hash (&td, ciphertext.data, length, ver);
mac_deinit (&td, MAC, ver);
}
/* This one was introduced to avoid a timing attack against the TLS
* 1.0 protocol.
*/
if (pad_failed != 0)
{
gnutls_assert ();
return pad_failed;
}
/* HMAC was not the same.
*/
if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* copy the decrypted stuff to compress_data.
*/
if (compress_size < length)
{
gnutls_assert ();
return GNUTLS_E_DECOMPRESSION_FAILED;
}
memcpy (compress_data, ciphertext.data, length);
return length;
}
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: UWORD16 impeg2d_get_mb_addr_incr(stream_t *ps_stream)
{
UWORD16 u2_mb_addr_incr = 0;
while (impeg2d_bit_stream_nxt(ps_stream,MB_ESCAPE_CODE_LEN) == MB_ESCAPE_CODE)
{
impeg2d_bit_stream_flush(ps_stream,MB_ESCAPE_CODE_LEN);
u2_mb_addr_incr += 33;
}
u2_mb_addr_incr += impeg2d_dec_vld_symbol(ps_stream,gai2_impeg2d_mb_addr_incr,MB_ADDR_INCR_LEN) +
MB_ADDR_INCR_OFFSET;
return(u2_mb_addr_incr);
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: RenderFrameHostManager::GetSiteInstanceForNavigation(
const GURL& dest_url,
SiteInstance* source_instance,
SiteInstance* dest_instance,
SiteInstance* candidate_instance,
ui::PageTransition transition,
bool dest_is_restore,
bool dest_is_view_source_mode,
bool was_server_redirect) {
DCHECK(!source_instance || !dest_instance);
SiteInstance* current_instance = render_frame_host_->GetSiteInstance();
if (current_instance->GetSiteURL().SchemeIs(kGuestScheme))
return current_instance;
BrowserContext* browser_context =
delegate_->GetControllerForRenderManager().GetBrowserContext();
const GURL& current_effective_url =
!render_frame_host_->last_successful_url().is_empty()
? SiteInstanceImpl::GetEffectiveURL(
browser_context, render_frame_host_->last_successful_url())
: render_frame_host_->GetSiteInstance()->GetSiteURL();
const NavigationEntry* current_entry =
delegate_->GetLastCommittedNavigationEntryForRenderManager();
bool current_is_view_source_mode = current_entry ?
current_entry->IsViewSourceMode() : dest_is_view_source_mode;
bool force_swap = ShouldSwapBrowsingInstancesForNavigation(
current_effective_url,
current_is_view_source_mode,
dest_instance,
SiteInstanceImpl::GetEffectiveURL(browser_context, dest_url),
dest_is_view_source_mode);
SiteInstanceDescriptor new_instance_descriptor =
SiteInstanceDescriptor(current_instance);
if (ShouldTransitionCrossSite() || force_swap) {
new_instance_descriptor = DetermineSiteInstanceForURL(
dest_url, source_instance, current_instance, dest_instance, transition,
dest_is_restore, dest_is_view_source_mode, force_swap,
was_server_redirect);
}
scoped_refptr<SiteInstance> new_instance =
ConvertToSiteInstance(new_instance_descriptor, candidate_instance);
if (force_swap)
CHECK_NE(new_instance, current_instance);
if (new_instance == current_instance) {
RenderProcessHostImpl::CleanupSpareRenderProcessHost();
}
DCHECK_EQ(new_instance->GetBrowserContext(), browser_context);
SiteInstanceImpl* new_instance_impl =
static_cast<SiteInstanceImpl*>(new_instance.get());
if (!frame_tree_node_->IsMainFrame() && !new_instance_impl->HasProcess() &&
new_instance_impl->RequiresDedicatedProcess()) {
new_instance_impl->set_process_reuse_policy(
SiteInstanceImpl::ProcessReusePolicy::REUSE_PENDING_OR_COMMITTED_SITE);
}
return new_instance;
}
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: virtual void StartAsync() {
request_->Cancel();
this->NotifyRestartRequired();
}
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: RenderProcessHost* SharedWorkerDevToolsAgentHost::GetProcess() {
return worker_host_ ? RenderProcessHost::FromID(worker_host_->process_id())
: nullptr;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int ioctl_fionbio(struct file *filp, int __user *argp)
{
unsigned int flag;
int on, error;
error = get_user(on, argp);
if (error)
return error;
flag = O_NONBLOCK;
#ifdef __sparc__
/* SunOS compatibility item. */
if (O_NONBLOCK != O_NDELAY)
flag |= O_NDELAY;
#endif
spin_lock(&filp->f_lock);
if (on)
filp->f_flags |= flag;
else
filp->f_flags &= ~flag;
spin_unlock(&filp->f_lock);
return error;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
unsigned char arg[128];
int ret = 0;
unsigned int copylen;
struct net *net = sock_net(sk);
struct netns_ipvs *ipvs = net_ipvs(net);
BUG_ON(!net);
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
return -EINVAL;
if (*len < get_arglen[GET_CMDID(cmd)]) {
pr_err("get_ctl: len %u < %u\n",
*len, get_arglen[GET_CMDID(cmd)]);
return -EINVAL;
}
copylen = get_arglen[GET_CMDID(cmd)];
if (copylen > 128)
return -EINVAL;
if (copy_from_user(arg, user, copylen) != 0)
return -EFAULT;
/*
* Handle daemons first since it has its own locking
*/
if (cmd == IP_VS_SO_GET_DAEMON) {
struct ip_vs_daemon_user d[2];
memset(&d, 0, sizeof(d));
if (mutex_lock_interruptible(&ipvs->sync_mutex))
return -ERESTARTSYS;
if (ipvs->sync_state & IP_VS_STATE_MASTER) {
d[0].state = IP_VS_STATE_MASTER;
strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn,
sizeof(d[0].mcast_ifn));
d[0].syncid = ipvs->master_syncid;
}
if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
d[1].state = IP_VS_STATE_BACKUP;
strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn,
sizeof(d[1].mcast_ifn));
d[1].syncid = ipvs->backup_syncid;
}
if (copy_to_user(user, &d, sizeof(d)) != 0)
ret = -EFAULT;
mutex_unlock(&ipvs->sync_mutex);
return ret;
}
if (mutex_lock_interruptible(&__ip_vs_mutex))
return -ERESTARTSYS;
switch (cmd) {
case IP_VS_SO_GET_VERSION:
{
char buf[64];
sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
ret = -EFAULT;
goto out;
}
*len = strlen(buf)+1;
}
break;
case IP_VS_SO_GET_INFO:
{
struct ip_vs_getinfo info;
info.version = IP_VS_VERSION_CODE;
info.size = ip_vs_conn_tab_size;
info.num_services = ipvs->num_services;
if (copy_to_user(user, &info, sizeof(info)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_SERVICES:
{
struct ip_vs_get_services *get;
int size;
get = (struct ip_vs_get_services *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_service_entry) * get->num_services;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_service_entries(net, get, user);
}
break;
case IP_VS_SO_GET_SERVICE:
{
struct ip_vs_service_entry *entry;
struct ip_vs_service *svc;
union nf_inet_addr addr;
entry = (struct ip_vs_service_entry *)arg;
addr.ip = entry->addr;
if (entry->fwmark)
svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark);
else
svc = __ip_vs_service_find(net, AF_INET,
entry->protocol, &addr,
entry->port);
if (svc) {
ip_vs_copy_service(entry, svc);
if (copy_to_user(user, entry, sizeof(*entry)) != 0)
ret = -EFAULT;
} else
ret = -ESRCH;
}
break;
case IP_VS_SO_GET_DESTS:
{
struct ip_vs_get_dests *get;
int size;
get = (struct ip_vs_get_dests *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_dest_entry) * get->num_dests;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_dest_entries(net, get, user);
}
break;
case IP_VS_SO_GET_TIMEOUT:
{
struct ip_vs_timeout_user t;
__ip_vs_get_timeouts(net, &t);
if (copy_to_user(user, &t, sizeof(t)) != 0)
ret = -EFAULT;
}
break;
default:
ret = -EINVAL;
}
out:
mutex_unlock(&__ip_vs_mutex);
return ret;
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
register const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
register unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void ion_client_destroy(struct ion_client *client)
{
struct ion_device *dev = client->dev;
struct rb_node *n;
pr_debug("%s: %d\n", __func__, __LINE__);
mutex_lock(&debugfs_mutex);
while ((n = rb_first(&client->handles))) {
struct ion_handle *handle = rb_entry(n, struct ion_handle,
node);
ion_handle_destroy(&handle->ref);
}
idr_destroy(&client->idr);
down_write(&dev->lock);
if (client->task)
put_task_struct(client->task);
rb_erase(&client->node, &dev->clients);
debugfs_remove_recursive(client->debug_root);
up_write(&dev->lock);
kfree(client->display_name);
kfree(client->name);
kfree(client);
mutex_unlock(&debugfs_mutex);
}
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: get_arg0_string (Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body;
g_autoptr(GVariant) arg0 = NULL;
char *name = NULL;
if (message != NULL &&
(body = g_dbus_message_get_body (message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
name = g_variant_dup_string (arg0, NULL);
g_object_unref (message);
return name;
}
CWE ID: CWE-436
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: build_principal_va(krb5_context context, krb5_principal princ,
unsigned int rlen, const char *realm, va_list ap)
{
krb5_error_code retval = 0;
char *r = NULL;
krb5_data *data = NULL;
krb5_int32 count = 0;
krb5_int32 size = 2; /* initial guess at needed space */
char *component = NULL;
data = malloc(size * sizeof(krb5_data));
if (!data) { retval = ENOMEM; }
if (!retval) {
r = strdup(realm);
if (!r) { retval = ENOMEM; }
}
while (!retval && (component = va_arg(ap, char *))) {
if (count == size) {
krb5_data *new_data = NULL;
size *= 2;
new_data = realloc(data, size * sizeof(krb5_data));
if (new_data) {
data = new_data;
} else {
retval = ENOMEM;
}
}
if (!retval) {
data[count].length = strlen(component);
data[count].data = strdup(component);
if (!data[count].data) { retval = ENOMEM; }
count++;
}
}
if (!retval) {
princ->type = KRB5_NT_UNKNOWN;
princ->magic = KV5M_PRINCIPAL;
princ->realm = make_data(r, rlen);
princ->data = data;
princ->length = count;
r = NULL; /* take ownership */
data = NULL; /* take ownership */
}
if (data) {
while (--count >= 0) {
free(data[count].data);
}
free(data);
}
free(r);
return retval;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void bar_reset(struct pci_dev *dev, int offset, void *data)
{
struct pci_bar_info *bar = data;
bar->which = 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 void visor_read_int_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
int status = urb->status;
int result;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(&port->dev, "%s - urb shutting down with status: %d\n",
__func__, status);
return;
default:
dev_dbg(&port->dev, "%s - nonzero urb status received: %d\n",
__func__, status);
goto exit;
}
/*
* This information is still unknown what it can be used for.
* If anyone has an idea, please let the author know...
*
* Rumor has it this endpoint is used to notify when data
* is ready to be read from the bulk ones.
*/
usb_serial_debug_data(&port->dev, __func__, urb->actual_length,
urb->transfer_buffer);
exit:
result = usb_submit_urb(urb, GFP_ATOMIC);
if (result)
dev_err(&urb->dev->dev,
"%s - Error %d submitting interrupt urb\n",
__func__, result);
}
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 ChromeContentClient::SandboxPlugin(CommandLine* command_line,
sandbox::TargetPolicy* policy) {
std::wstring plugin_dll = command_line->
GetSwitchValueNative(switches::kPluginPath);
FilePath builtin_flash;
if (!PathService::Get(chrome::FILE_FLASH_PLUGIN, &builtin_flash))
return false;
FilePath plugin_path(plugin_dll);
if (plugin_path.BaseName() != builtin_flash.BaseName())
return false;
if (base::win::GetVersion() <= base::win::VERSION_XP ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableFlashSandbox)) {
return false;
}
if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
L"\\\\.\\pipe\\chrome.*") != sandbox::SBOX_ALL_OK) {
NOTREACHED();
return false;
}
if (LoadFlashBroker(plugin_path, command_line)) {
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_INTERACTIVE);
if (base::win::GetVersion() == base::win::VERSION_VISTA) {
::ChangeWindowMessageFilter(WM_MOUSEWHEEL, MSGFLT_ADD);
::ChangeWindowMessageFilter(WM_APPCOMMAND, MSGFLT_ADD);
}
policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
} else {
DLOG(WARNING) << "Failed to start flash broker";
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(
sandbox::USER_UNPROTECTED, sandbox::USER_UNPROTECTED);
}
return true;
}
CWE ID:
Target: 1
Example 2:
Code: int ptrace_pokeusr(struct task_struct *child, long regno, long val)
{
struct pt_regs *regs;
regs = task_pt_regs(child);
switch (regno) {
case REG_AR_BASE ... REG_AR_BASE + XCHAL_NUM_AREGS - 1:
regs->areg[regno - REG_AR_BASE] = val;
break;
case REG_A_BASE ... REG_A_BASE + 15:
regs->areg[regno - REG_A_BASE] = val;
break;
case REG_PC:
regs->pc = val;
break;
case SYSCALL_NR:
regs->syscall = val;
break;
default:
return -EIO;
}
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void tty_ldisc_kill(struct tty_struct *tty)
{
/*
* Now kill off the ldisc
*/
tty_ldisc_close(tty, tty->ldisc);
tty_ldisc_put(tty->ldisc);
/* Force an oops if we mess this up */
tty->ldisc = NULL;
/* Ensure the next open requests the N_TTY ldisc */
tty_set_termios_ldisc(tty, N_TTY);
}
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 AutofillPopupBaseView::AddExtraInitParams(
views::Widget::InitParams* params) {
params->opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params->shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
void *p;
assert( db!=0 );
p = sqlite3Malloc(n);
if( !p ) sqlite3OomFault(db);
sqlite3MemdebugSetType(p,
(db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
return p;
}
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 DispatchBeforeInputFromComposition(EventTarget* target,
InputEvent::InputType input_type,
const String& data) {
if (!RuntimeEnabledFeatures::InputEventEnabled())
return;
if (!target)
return;
InputEvent* before_input_event = InputEvent::CreateBeforeInput(
input_type, data, InputEvent::kNotCancelable,
InputEvent::EventIsComposing::kIsComposing, nullptr);
target->DispatchEvent(before_input_event);
}
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 CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[512], vpred[2][2], hpred[2];
fseek (ifp, 8, SEEK_CUR);
foveon_huff (huff);
roff[0] = 48;
FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
FORC3 {
fseek (ifp, data_offset+roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
image[row*width+col][c] = hpred[col & 1];
}
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: error::Error GLES2DecoderPassthroughImpl::DoBlendFunc(GLenum sfactor,
GLenum dfactor) {
api()->glBlendFuncFn(sfactor, dfactor);
return error::kNoError;
}
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: ZEND_METHOD(CURLFile, __construct)
{
return_value = getThis();
curlfile_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
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 RTCPeerConnectionHandlerChromium::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription)
{
if (!m_webHandler)
return;
m_webHandler->setRemoteDescription(request, sessionDescription);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: htmlCtxtReadMemory(htmlParserCtxtPtr ctxt, const char *buffer, int size,
const char *URL, const char *encoding, int options)
{
xmlParserInputBufferPtr input;
xmlParserInputPtr stream;
if (ctxt == NULL)
return (NULL);
if (buffer == NULL)
return (NULL);
xmlInitParser();
htmlCtxtReset(ctxt);
input = xmlParserInputBufferCreateMem(buffer, size, XML_CHAR_ENCODING_NONE);
if (input == NULL) {
return(NULL);
}
stream = xmlNewIOInputStream(ctxt, input, XML_CHAR_ENCODING_NONE);
if (stream == NULL) {
xmlFreeParserInputBuffer(input);
return(NULL);
}
inputPush(ctxt, stream);
return (htmlDoRead(ctxt, URL, encoding, options, 1));
}
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: bool WebPagePrivate::hasVirtualViewport() const
{
return !m_virtualViewportSize.isEmpty();
}
CWE ID:
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int getStrrtokenPos(char* str, int savedPos)
{
int result =-1;
int i;
for(i=savedPos-1; i>=0; i--) {
if(isIDSeparator(*(str+i)) ){
/* delimiter found; check for singleton */
if(i>=2 && isIDSeparator(*(str+i-2)) ){
/* a singleton; so send the position of token before the singleton */
result = i-2;
} else {
result = i;
}
break;
}
}
if(result < 1){
/* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */
result =-1;
}
return result;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void SyncBackendHost::GetWorkers(std::vector<ModelSafeWorker*>* out) {
base::AutoLock lock(registrar_lock_);
out->clear();
for (WorkerMap::const_iterator it = registrar_.workers.begin();
it != registrar_.workers.end(); ++it) {
out->push_back((*it).second);
}
}
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 AXTree::CallNodeChangeCallbacks(AXNode* node,
const AXNodeData& old_data,
const AXNodeData& new_data) {
for (AXTreeObserver& observer : observers_)
observer.OnNodeDataWillChange(this, old_data, new_data);
if (old_data.role != new_data.role) {
for (AXTreeObserver& observer : observers_)
observer.OnRoleChanged(this, node, old_data.role, new_data.role);
}
if (old_data.state != new_data.state) {
for (int32_t i = static_cast<int32_t>(ax::mojom::State::kNone) + 1;
i <= static_cast<int32_t>(ax::mojom::State::kMaxValue); ++i) {
ax::mojom::State state = static_cast<ax::mojom::State>(i);
if (old_data.HasState(state) != new_data.HasState(state)) {
for (AXTreeObserver& observer : observers_)
observer.OnStateChanged(this, node, state, new_data.HasState(state));
}
}
}
auto string_callback = [this, node](ax::mojom::StringAttribute attr,
const std::string& old_string,
const std::string& new_string) {
for (AXTreeObserver& observer : observers_) {
observer.OnStringAttributeChanged(this, node, attr, old_string,
new_string);
}
};
CallIfAttributeValuesChanged(old_data.string_attributes,
new_data.string_attributes, std::string(),
string_callback);
auto bool_callback = [this, node](ax::mojom::BoolAttribute attr,
const bool& old_bool,
const bool& new_bool) {
for (AXTreeObserver& observer : observers_)
observer.OnBoolAttributeChanged(this, node, attr, new_bool);
};
CallIfAttributeValuesChanged(old_data.bool_attributes,
new_data.bool_attributes, false, bool_callback);
auto float_callback = [this, node](ax::mojom::FloatAttribute attr,
const float& old_float,
const float& new_float) {
for (AXTreeObserver& observer : observers_)
observer.OnFloatAttributeChanged(this, node, attr, old_float, new_float);
};
CallIfAttributeValuesChanged(old_data.float_attributes,
new_data.float_attributes, 0.0f, float_callback);
auto int_callback = [this, node](ax::mojom::IntAttribute attr,
const int& old_int, const int& new_int) {
for (AXTreeObserver& observer : observers_)
observer.OnIntAttributeChanged(this, node, attr, old_int, new_int);
};
CallIfAttributeValuesChanged(old_data.int_attributes, new_data.int_attributes,
0, int_callback);
auto intlist_callback = [this, node](
ax::mojom::IntListAttribute attr,
const std::vector<int32_t>& old_intlist,
const std::vector<int32_t>& new_intlist) {
for (AXTreeObserver& observer : observers_)
observer.OnIntListAttributeChanged(this, node, attr, old_intlist,
new_intlist);
};
CallIfAttributeValuesChanged(old_data.intlist_attributes,
new_data.intlist_attributes,
std::vector<int32_t>(), intlist_callback);
auto stringlist_callback =
[this, node](ax::mojom::StringListAttribute attr,
const std::vector<std::string>& old_stringlist,
const std::vector<std::string>& new_stringlist) {
for (AXTreeObserver& observer : observers_)
observer.OnStringListAttributeChanged(this, node, attr,
old_stringlist, new_stringlist);
};
CallIfAttributeValuesChanged(old_data.stringlist_attributes,
new_data.stringlist_attributes,
std::vector<std::string>(), stringlist_callback);
}
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 HeapObjectHeader::Finalize(Address object, size_t object_size) {
HeapAllocHooks::FreeHookIfEnabled(object);
const GCInfo* gc_info = ThreadHeap::GcInfo(GcInfoIndex());
if (gc_info->HasFinalizer())
gc_info->finalize_(object);
ASAN_RETIRE_CONTAINER_ANNOTATION(object, object_size);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: bool TestTarget::CanHandleAccelerators() const {
return true;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool PrintPreviewMessageHandler::OnMessageReceived(
const IPC::Message& message,
content::RenderFrameHost* render_frame_host) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(PrintPreviewMessageHandler, message,
render_frame_host)
IPC_MESSAGE_HANDLER(PrintHostMsg_RequestPrintPreview,
OnRequestPrintPreview)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPreviewPageCount,
OnDidGetPreviewPageCount)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidPreviewPage,
OnDidPreviewPage)
IPC_MESSAGE_HANDLER(PrintHostMsg_MetafileReadyForPrinting,
OnMetafileReadyForPrinting)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewFailed,
OnPrintPreviewFailed)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetDefaultPageLayout,
OnDidGetDefaultPageLayout)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewCancelled,
OnPrintPreviewCancelled)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewInvalidPrinterSettings,
OnInvalidPrinterSettings)
IPC_MESSAGE_HANDLER(PrintHostMsg_SetOptionsFromDocument,
OnSetOptionsFromDocument)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
CWE ID: CWE-254
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SubprocessMetricsProviderTest()
: thread_bundle_(content::TestBrowserThreadBundle::DEFAULT) {
base::PersistentHistogramAllocator::GetCreateHistogramResultHistogram();
provider_.MergeHistogramDeltas();
test_recorder_ = base::StatisticsRecorder::CreateTemporaryForTesting();
base::GlobalHistogramAllocator::CreateWithLocalMemory(TEST_MEMORY_SIZE,
0, "");
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void srpt_drain_channel(struct ib_cm_id *cm_id)
{
struct srpt_device *sdev;
struct srpt_rdma_ch *ch;
int ret;
bool do_reset = false;
WARN_ON_ONCE(irqs_disabled());
sdev = cm_id->context;
BUG_ON(!sdev);
spin_lock_irq(&sdev->spinlock);
list_for_each_entry(ch, &sdev->rch_list, list) {
if (ch->cm_id == cm_id) {
do_reset = srpt_test_and_set_ch_state(ch,
CH_CONNECTING, CH_DRAINING) ||
srpt_test_and_set_ch_state(ch,
CH_LIVE, CH_DRAINING) ||
srpt_test_and_set_ch_state(ch,
CH_DISCONNECTING, CH_DRAINING);
break;
}
}
spin_unlock_irq(&sdev->spinlock);
if (do_reset) {
if (ch->sess)
srpt_shutdown_session(ch->sess);
ret = srpt_ch_qp_err(ch);
if (ret < 0)
pr_err("Setting queue pair in error state"
" failed: %d\n", ret);
}
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: g_NPN_GetValue_real(NPP instance, NPNVariable variable, void *value)
{
PluginInstance *plugin = NULL;
if (instance)
plugin = PLUGIN_INSTANCE(instance);
npw_plugin_instance_ref(plugin);
NPError ret = invoke_NPN_GetValue(plugin, variable, value);
npw_plugin_instance_unref(plugin);
return ret;
}
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: PHP_METHOD(Phar, mount)
{
char *fname, *arch = NULL, *entry = NULL, *path, *actual;
int fname_len, arch_len, entry_len;
size_t path_len, actual_len;
phar_archive_data *pphar;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &path, &path_len, &actual, &actual_len) == FAILURE) {
return;
}
fname = (char*)zend_get_executed_filename();
fname_len = strlen(fname);
#ifdef PHP_WIN32
phar_unixify_path_separators(fname, fname_len);
#endif
if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
efree(entry);
entry = NULL;
if (path_len > 7 && !memcmp(path, "phar://", 7)) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path);
efree(arch);
return;
}
carry_on2:
if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) {
if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) {
if (SUCCESS == phar_copy_on_write(&pphar)) {
goto carry_on;
}
}
zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch);
if (arch) {
efree(arch);
}
return;
}
carry_on:
if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) {
zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch);
if (path && path == entry) {
efree(entry);
}
if (arch) {
efree(arch);
}
return;
}
if (entry && path && path == entry) {
efree(entry);
}
if (arch) {
efree(arch);
}
return;
} else if (PHAR_G(phar_fname_map.u.flags) && NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) {
goto carry_on;
} else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) {
if (SUCCESS == phar_copy_on_write(&pphar)) {
goto carry_on;
}
goto carry_on;
} else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) {
path = entry;
path_len = entry_len;
goto carry_on2;
}
zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void UnloadController::CancelWindowClose() {
DCHECK(is_attempting_to_close_browser_);
tabs_needing_before_unload_fired_.clear();
tabs_needing_unload_fired_.clear();
is_attempting_to_close_browser_ = false;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_BROWSER_CLOSE_CANCELLED,
content::Source<Browser>(browser_),
content::NotificationService::NoDetails());
}
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 Cues::PreloadCuePoint(long& cue_points_size, long long pos) const {
assert(m_count == 0);
if (m_preload_count >= cue_points_size) {
const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size;
CuePoint** const qq = new CuePoint* [n];
CuePoint** q = qq; // beginning of target
CuePoint** p = m_cue_points; // beginning of source
CuePoint** const pp = p + m_preload_count; // end of source
while (p != pp)
*q++ = *p++;
delete[] m_cue_points;
m_cue_points = qq;
cue_points_size = n;
}
CuePoint* const pCP = new CuePoint(m_preload_count, pos);
m_cue_points[m_preload_count++] = pCP;
}
CWE ID: CWE-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 CURLcode imap_parse_url_path(struct connectdata *conn)
{
/* the imap struct is already inited in imap_connect() */
struct imap_conn *imapc = &conn->proto.imapc;
struct SessionHandle *data = conn->data;
const char *path = data->state.path;
int len;
if(!*path)
path = "INBOX";
/* url decode the path and use this mailbox */
imapc->mailbox = curl_easy_unescape(data, path, 0, &len);
if(!imapc->mailbox)
return CURLE_OUT_OF_MEMORY;
return CURLE_OK;
}
CWE ID: CWE-89
Target: 1
Example 2:
Code: static AwContents* GetContents(WebContents* web_contents) {
if (!web_contents)
return NULL;
AwContentsUserData* data = static_cast<AwContentsUserData*>(
web_contents->GetUserData(kAwContentsUserDataKey));
return data ? data->contents_ : NULL;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
DCHECK_LT(last_committed_entry_index_, GetEntryCount());
DCHECK(GetEntryCount() || last_committed_entry_index_ == -1);
return last_committed_entry_index_;
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int cmd_mount(void *data, const char *_input) {
ut64 off = 0;
char *input, *oinput, *ptr, *ptr2;
RList *list;
RListIter *iter;
RFSFile *file;
RFSRoot *root;
RFSPlugin *plug;
RFSPartition *part;
RCore *core = (RCore *)data;
if (!strncmp ("kdir", _input, 4)) {
return cmd_mkdir (data, _input);
}
if (!strncmp ("v", _input, 1)) {
return cmd_mv (data, _input);
}
input = oinput = strdup (_input);
switch (*input) {
case ' ':
input++;
if (input[0]==' ')
input++;
ptr = strchr (input, ' ');
if (ptr) {
*ptr = 0;
ptr++;
ptr2 = strchr (ptr, ' ');
if (ptr2) {
*ptr2 = 0;
off = r_num_math (core->num, ptr2+1);
}
if (!r_fs_mount (core->fs, ptr, input, off))
eprintf ("Cannot mount %s\n", input);
} else {
if (!(ptr = r_fs_name (core->fs, core->offset)))
eprintf ("Unknown filesystem type\n");
else if (!r_fs_mount (core->fs, ptr, input, core->offset))
eprintf ("Cannot mount %s\n", input);
free (ptr);
}
break;
case '-':
r_fs_umount (core->fs, input+1);
break;
case '*':
eprintf ("List commands in radare format\n");
r_list_foreach (core->fs->roots, iter, root) {
r_cons_printf ("m %s %s 0x%"PFMT64x"\n",
root-> path, root->p->name, root->delta);
}
break;
case '\0':
r_list_foreach (core->fs->roots, iter, root) {
r_cons_printf ("%s\t0x%"PFMT64x"\t%s\n",
root->p->name, root->delta, root->path);
}
break;
case 'l': // list of plugins
r_list_foreach (core->fs->plugins, iter, plug) {
r_cons_printf ("%10s %s\n", plug->name, plug->desc);
}
break;
case 'd':
input++;
if (input[0]==' ')
input++;
list = r_fs_dir (core->fs, input);
if (list) {
r_list_foreach (list, iter, file) {
r_cons_printf ("%c %s\n", file->type, file->name);
}
r_list_free (list);
} else eprintf ("Cannot open '%s' directory\n", input);
break;
case 'p':
input++;
if (*input == ' ')
input++;
ptr = strchr (input, ' ');
if (ptr) {
*ptr = 0;
off = r_num_math (core->num, ptr+1);
}
list = r_fs_partitions (core->fs, input, off);
if (list) {
r_list_foreach (list, iter, part) {
r_cons_printf ("%d %02x 0x%010"PFMT64x" 0x%010"PFMT64x"\n",
part->number, part->type,
part->start, part->start+part->length);
}
r_list_free (list);
} else eprintf ("Cannot read partition\n");
break;
case 'o':
input++;
if (input[0]==' ')
input++;
file = r_fs_open (core->fs, input);
if (file) {
r_fs_read (core->fs, file, 0, file->size);
r_cons_printf ("f file %d 0x%08"PFMT64x"\n", file->size, file->off);
r_fs_close (core->fs, file);
} else eprintf ("Cannot open file\n");
break;
case 'g':
input++;
if (*input == ' ')
input++;
ptr = strchr (input, ' ');
if (ptr)
*ptr++ = 0;
else
ptr = "./";
file = r_fs_open (core->fs, input);
if (file) {
r_fs_read (core->fs, file, 0, file->size);
write (1, file->data, file->size);
r_fs_close (core->fs, file);
write (1, "\n", 1);
} else if (!r_fs_dir_dump (core->fs, input, ptr))
eprintf ("Cannot open file\n");
break;
case 'f':
input++;
switch (*input) {
case '?':
r_cons_printf (
"Usage: mf[no] [...]\n"
" mfn /foo *.c ; search files by name in /foo path\n"
" mfo /foo 0x5e91 ; search files by offset in /foo path\n"
);
break;
case 'n':
input++;
if (*input == ' ')
input++;
ptr = strchr (input, ' ');
if (ptr) {
*ptr++ = 0;
list = r_fs_find_name (core->fs, input, ptr);
r_list_foreach (list, iter, ptr) {
r_str_chop_path (ptr);
printf ("%s\n", ptr);
}
} else eprintf ("Unknown store path\n");
break;
case 'o':
input++;
if (*input == ' ')
input++;
ptr = strchr (input, ' ');
if (ptr) {
*ptr++ = 0;
ut64 off = r_num_math (core->num, ptr);
list = r_fs_find_off (core->fs, input, off);
r_list_foreach (list, iter, ptr) {
r_str_chop_path (ptr);
printf ("%s\n", ptr);
}
} else eprintf ("Unknown store path\n");
break;
}
break;
case 's':
if (core->http_up) {
free (oinput);
return false;
}
input++;
if (input[0]==' ')
input++;
r_fs_prompt (core->fs, input);
break;
case 'y':
eprintf ("TODO\n");
break;
case '?': {
const char* help_msg[] = {
"Usage:", "m[-?*dgy] [...] ", "Mountpoints management",
"m", "", "List all mountpoints in human readable format",
"m*", "", "Same as above, but in r2 commands",
"ml", "", "List filesystem plugins",
"m", " /mnt", "Mount fs at /mnt with autodetect fs and current offset",
"m", " /mnt ext2 0", "Mount ext2 fs at /mnt with delta 0 on IO",
"m-/", "", "Umount given path (/)",
"my", "", "Yank contents of file into clipboard",
"mo", " /foo", "Get offset and size of given file",
"mg", " /foo", "Get contents of file/dir dumped to disk (XXX?)",
"mf", "[?] [o|n]", "Search files for given filename or for offset",
"md", " /", "List directory contents for path",
"mp", "", "List all supported partition types",
"mp", " msdos 0", "Show partitions in msdos format at offset 0",
"ms", " /mnt", "Open filesystem prompt at /mnt",
NULL};
r_core_cmd_help (core, help_msg);
}
break;
}
free (oinput);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void jas_iccprof_destroy(jas_iccprof_t *prof)
{
if (prof->attrtab)
jas_iccattrtab_destroy(prof->attrtab);
if (prof->tagtab.ents)
jas_free(prof->tagtab.ents);
jas_free(prof);
}
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 Document::EnqueueVisualViewportScrollEvent() {
VisualViewportScrollEvent* event = VisualViewportScrollEvent::Create();
event->SetTarget(domWindow()->visualViewport());
EnsureScriptedAnimationController().EnqueuePerFrameEvent(event);
}
CWE ID: CWE-416
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool isNodeAriaVisible(Node* node) {
if (!node)
return false;
if (!node->isElementNode())
return false;
return equalIgnoringCase(toElement(node)->getAttribute(aria_hiddenAttr),
"false");
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: DevToolsDockSide DevToolsWindow::GetDockSideFromPrefs(Profile* profile) {
std::string dock_side =
profile->GetPrefs()->GetString(prefs::kDevToolsDockSide);
const char kOldPrefBottom[] = "bottom";
const char kOldPrefRight[] = "right";
if ((dock_side == kOldPrefBottom) || (dock_side == kOldPrefRight)) {
if (!profile->GetPrefs()->GetBoolean(prefs::kDevToolsOpenDocked))
return DEVTOOLS_DOCK_SIDE_UNDOCKED;
return (dock_side == kOldPrefBottom) ?
DEVTOOLS_DOCK_SIDE_BOTTOM : DEVTOOLS_DOCK_SIDE_RIGHT;
}
if (dock_side == kPrefUndocked)
return DEVTOOLS_DOCK_SIDE_UNDOCKED;
if (dock_side == kPrefRight)
return DEVTOOLS_DOCK_SIDE_RIGHT;
return DEVTOOLS_DOCK_SIDE_BOTTOM;
}
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 LauncherView::ShowOverflowMenu() {
#if !defined(OS_MACOSX)
if (!delegate_)
return;
std::vector<LauncherItem> items;
GetOverflowItems(&items);
if (items.empty())
return;
MenuDelegateImpl menu_delegate;
ui::SimpleMenuModel menu_model(&menu_delegate);
for (size_t i = 0; i < items.size(); ++i)
menu_model.AddItem(static_cast<int>(i), delegate_->GetTitle(items[i]));
views::MenuModelAdapter menu_adapter(&menu_model);
overflow_menu_runner_.reset(new views::MenuRunner(menu_adapter.CreateMenu()));
gfx::Rect bounds(overflow_button_->size());
gfx::Point origin;
ConvertPointToScreen(overflow_button_, &origin);
if (overflow_menu_runner_->RunMenuAt(GetWidget(), NULL,
gfx::Rect(origin, size()), views::MenuItemView::TOPLEFT, 0) ==
views::MenuRunner::MENU_DELETED)
return;
Shell::GetInstance()->UpdateShelfVisibility();
if (menu_delegate.activated_command_id() == -1)
return;
LauncherID activated_id = items[menu_delegate.activated_command_id()].id;
LauncherItems::const_iterator window_iter = model_->ItemByID(activated_id);
if (window_iter == model_->items().end())
return; // Window was deleted while menu was up.
delegate_->ItemClicked(*window_iter, ui::EF_NONE);
#endif // !defined(OS_MACOSX)
}
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 vis_emul(struct pt_regs *regs, unsigned int insn)
{
unsigned long pc = regs->tpc;
unsigned int opf;
BUG_ON(regs->tstate & TSTATE_PRIV);
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc))
return -EFAULT;
save_and_clear_fpu();
opf = (insn & VIS_OPF_MASK) >> VIS_OPF_SHIFT;
switch (opf) {
default:
return -EINVAL;
/* Pixel Formatting Instructions. */
case FPACK16_OPF:
case FPACK32_OPF:
case FPACKFIX_OPF:
case FEXPAND_OPF:
case FPMERGE_OPF:
pformat(regs, insn, opf);
break;
/* Partitioned Multiply Instructions */
case FMUL8x16_OPF:
case FMUL8x16AU_OPF:
case FMUL8x16AL_OPF:
case FMUL8SUx16_OPF:
case FMUL8ULx16_OPF:
case FMULD8SUx16_OPF:
case FMULD8ULx16_OPF:
pmul(regs, insn, opf);
break;
/* Pixel Compare Instructions */
case FCMPGT16_OPF:
case FCMPGT32_OPF:
case FCMPLE16_OPF:
case FCMPLE32_OPF:
case FCMPNE16_OPF:
case FCMPNE32_OPF:
case FCMPEQ16_OPF:
case FCMPEQ32_OPF:
pcmp(regs, insn, opf);
break;
/* Edge Handling Instructions */
case EDGE8_OPF:
case EDGE8N_OPF:
case EDGE8L_OPF:
case EDGE8LN_OPF:
case EDGE16_OPF:
case EDGE16N_OPF:
case EDGE16L_OPF:
case EDGE16LN_OPF:
case EDGE32_OPF:
case EDGE32N_OPF:
case EDGE32L_OPF:
case EDGE32LN_OPF:
edge(regs, insn, opf);
break;
/* Pixel Component Distance */
case PDIST_OPF:
pdist(regs, insn);
break;
/* Three-Dimensional Array Addressing Instructions */
case ARRAY8_OPF:
case ARRAY16_OPF:
case ARRAY32_OPF:
array(regs, insn, opf);
break;
/* Byte Mask and Shuffle Instructions */
case BMASK_OPF:
bmask(regs, insn);
break;
case BSHUFFLE_OPF:
bshuffle(regs, insn);
break;
}
regs->tpc = regs->tnpc;
regs->tnpc += 4;
return 0;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: PassRefPtr<Node> Element::cloneNode(bool deep)
{
return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nr_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name;
size_t copied;
struct sk_buff *skb;
int er;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
lock_sock(sk);
if (sk->sk_state != TCP_ESTABLISHED) {
release_sock(sk);
return -ENOTCONN;
}
/* Now we can treat all alike */
if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) {
release_sock(sk);
return er;
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (er < 0) {
skb_free_datagram(sk, skb);
release_sock(sk);
return er;
}
if (sax != NULL) {
memset(sax, 0, sizeof(*sax));
sax->sax25_family = AF_NETROM;
skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call,
AX25_ADDR_LEN);
}
msg->msg_namelen = sizeof(*sax);
skb_free_datagram(sk, skb);
release_sock(sk);
return copied;
}
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 PepperRendererConnection::OnMsgDidCreateInProcessInstance(
PP_Instance instance,
const PepperRendererInstanceData& instance_data) {
PepperRendererInstanceData data = instance_data;
data.render_process_id = render_process_id_;
in_process_host_->AddInstance(instance, data);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static struct dentry *udf_nfs_get_inode(struct super_block *sb, u32 block,
u16 partref, __u32 generation)
{
struct inode *inode;
struct kernel_lb_addr loc;
if (block == 0)
return ERR_PTR(-ESTALE);
loc.logicalBlockNum = block;
loc.partitionReferenceNum = partref;
inode = udf_iget(sb, &loc);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return d_obtain_alias(inode);
}
CWE ID: CWE-17
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool DrawingBuffer::Multisample() const {
return anti_aliasing_mode_ != kNone;
}
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 vrend_renderer_context_destroy(uint32_t handle)
{
struct vrend_decode_ctx *ctx;
bool ret;
if (handle >= VREND_MAX_CTX)
return;
ctx = dec_ctx[handle];
if (!ctx)
return;
vrend_hw_switch_context(dec_ctx[0]->grctx, true);
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static inline int next_slot(struct b43_dmaring *ring, int slot)
{
B43_WARN_ON(!(slot >= -1 && slot <= ring->nr_slots - 1));
if (slot == ring->nr_slots - 1)
return 0;
return slot + 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: bool WebGLImageConversion::ExtractTextureData(unsigned width,
unsigned height,
GLenum format,
GLenum type,
unsigned unpack_alignment,
bool flip_y,
bool premultiply_alpha,
const void* pixels,
Vector<uint8_t>& data) {
DataFormat source_data_format = GetDataFormat(format, type);
if (source_data_format == kDataFormatNumFormats)
return false;
unsigned int components_per_pixel, bytes_per_component;
if (!ComputeFormatAndTypeParameters(format, type, &components_per_pixel,
&bytes_per_component))
return false;
unsigned bytes_per_pixel = components_per_pixel * bytes_per_component;
data.resize(width * height * bytes_per_pixel);
if (!PackPixels(static_cast<const uint8_t*>(pixels), source_data_format,
width, height, IntRect(0, 0, width, height), 1,
unpack_alignment, 0, format, type,
(premultiply_alpha ? kAlphaDoPremultiply : kAlphaDoNothing),
data.data(), flip_y))
return false;
return true;
}
CWE ID: CWE-125
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderViewImpl::OnAllowBindings(int enabled_bindings_flags) {
enabled_bindings_ |= enabled_bindings_flags;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
struct bpf_verifier_stack_elem *elem;
elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose("BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
/* pop all elements and return */
while (pop_stack(env, NULL) >= 0);
return NULL;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void send_reject_response (UINT8 rc_handle, UINT8 label, UINT8 pdu, UINT8 status)
{
UINT8 ctype = AVRC_RSP_REJ;
tAVRC_RESPONSE avrc_rsp;
BT_HDR *p_msg = NULL;
memset (&avrc_rsp, 0, sizeof(tAVRC_RESPONSE));
avrc_rsp.rsp.opcode = opcode_from_pdu(pdu);
avrc_rsp.rsp.pdu = pdu;
avrc_rsp.rsp.status = status;
if (AVRC_STS_NO_ERROR == (status = AVRC_BldResponse(rc_handle, &avrc_rsp, &p_msg)) )
{
BTIF_TRACE_DEBUG("%s:Sending error notification to handle:%d. pdu:%s,status:0x%02x",
__FUNCTION__, rc_handle, dump_rc_pdu(pdu), status);
BTA_AvMetaRsp(rc_handle, label, ctype, p_msg);
}
}
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: long Chapters::Atom::ParseDisplay(
IMkvReader* pReader,
long long pos,
long long size)
{
if (!ExpandDisplaysArray())
return -1;
Display& d = m_displays[m_displays_count++];
d.Init();
return d.Parse(pReader, pos, size);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: struct in6_addr *ndp_msg_addrto(struct ndp_msg *msg)
{
return &msg->addrto;
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void OMXNodeInstance::onGetHandleFailed() {
delete this;
}
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 ProcessControlLaunchFailed() {
ADD_FAILURE();
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
}
CWE ID: CWE-94
Target: 1
Example 2:
Code: WebFrameScheduler* WebLocalFrameImpl::Scheduler() const {
return GetFrame()->FrameScheduler();
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int zval_call_destructor(zval *zv) /* {{{ */
{
if (Z_TYPE_P(zv) == IS_INDIRECT) {
zv = Z_INDIRECT_P(zv);
}
if (Z_TYPE_P(zv) == IS_OBJECT && Z_REFCOUNT_P(zv) == 1) {
return ZEND_HASH_APPLY_REMOVE;
} else {
return ZEND_HASH_APPLY_KEEP;
}
}
/* }}} */
CWE ID: CWE-134
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: MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
{
const char
*option;
ExceptionInfo
*exception;
ImageInfo
*clone_info;
/*
Initialize draw attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
(void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));
clone_info=CloneImageInfo(image_info);
GetAffineMatrix(&draw_info->affine);
exception=AcquireExceptionInfo();
(void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke,
exception);
draw_info->stroke_width=1.0;
draw_info->alpha=OpaqueAlpha;
draw_info->fill_rule=EvenOddRule;
draw_info->linecap=ButtCap;
draw_info->linejoin=MiterJoin;
draw_info->miterlimit=10;
draw_info->decorate=NoDecoration;
draw_info->pointsize=12.0;
draw_info->undercolor.alpha=(Quantum) TransparentAlpha;
draw_info->compose=OverCompositeOp;
draw_info->render=MagickTrue;
draw_info->debug=IsEventLogging();
draw_info->stroke_antialias=clone_info->antialias;
if (clone_info->font != (char *) NULL)
draw_info->font=AcquireString(clone_info->font);
if (clone_info->density != (char *) NULL)
draw_info->density=AcquireString(clone_info->density);
draw_info->text_antialias=clone_info->antialias;
if (clone_info->pointsize != 0.0)
draw_info->pointsize=clone_info->pointsize;
draw_info->border_color=clone_info->border_color;
if (clone_info->server_name != (char *) NULL)
draw_info->server_name=AcquireString(clone_info->server_name);
option=GetImageOption(clone_info,"direction");
if (option != (const char *) NULL)
draw_info->direction=(DirectionType) ParseCommandOption(
MagickDirectionOptions,MagickFalse,option);
else
draw_info->direction=UndefinedDirection;
option=GetImageOption(clone_info,"encoding");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->encoding,option);
option=GetImageOption(clone_info,"family");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->family,option);
option=GetImageOption(clone_info,"fill");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,
exception);
option=GetImageOption(clone_info,"gravity");
if (option != (const char *) NULL)
draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"interline-spacing");
if (option != (const char *) NULL)
draw_info->interline_spacing=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"interword-spacing");
if (option != (const char *) NULL)
draw_info->interword_spacing=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"kerning");
if (option != (const char *) NULL)
draw_info->kerning=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"stroke");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,
exception);
option=GetImageOption(clone_info,"strokewidth");
if (option != (const char *) NULL)
draw_info->stroke_width=StringToDouble(option,(char **) NULL);
option=GetImageOption(clone_info,"style");
if (option != (const char *) NULL)
draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"undercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,
exception);
option=GetImageOption(clone_info,"weight");
if (option != (const char *) NULL)
{
ssize_t
weight;
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);
if (weight == -1)
weight=StringToUnsignedLong(option);
draw_info->weight=(size_t) weight;
}
exception=DestroyExceptionInfo(exception);
draw_info->signature=MagickCoreSignature;
clone_info=DestroyImageInfo(clone_info);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static Handle<FixedArray> CreateListFromArrayImpl(Isolate* isolate,
Handle<JSArray> array) {
UNREACHABLE();
return Handle<FixedArray>();
}
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: zsetstrokecolor(i_ctx_t * i_ctx_p)
{
int code;
code = zswapcolors(i_ctx_p);
if (code < 0)
/* Set up for the continuation procedure which will finish by restoring the fill colour space */
/* Make sure the exec stack has enough space */
check_estack(1);
/* Now, the actual continuation routine */
push_op_estack(setstrokecolor_cont);
code = zsetcolor(i_ctx_p);
if (code >= 0)
if (code >= 0)
return o_push_estack;
return code;
}
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: jbig2_decode_gray_scale_image(Jbig2Ctx *ctx, Jbig2Segment *segment,
const byte *data, const size_t size,
bool GSMMR, uint32_t GSW, uint32_t GSH,
uint32_t GSBPP, bool GSUSESKIP, Jbig2Image *GSKIP, int GSTEMPLATE, Jbig2ArithCx *GB_stats)
{
uint8_t **GSVALS = NULL;
size_t consumed_bytes = 0;
int i, j, code, stride;
int x, y;
Jbig2Image **GSPLANES;
Jbig2GenericRegionParams rparams;
Jbig2WordStream *ws = NULL;
Jbig2ArithState *as = NULL;
/* allocate GSPLANES */
GSPLANES = jbig2_new(ctx, Jbig2Image *, GSBPP);
if (GSPLANES == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %d bytes for GSPLANES", GSBPP);
return NULL;
}
for (i = 0; i < GSBPP; ++i) {
GSPLANES[i] = jbig2_image_new(ctx, GSW, GSH);
if (GSPLANES[i] == NULL) {
jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to allocate %dx%d image for GSPLANES", GSW, GSH);
/* free already allocated */
for (j = i - 1; j >= 0; --j) {
jbig2_image_release(ctx, GSPLANES[j]);
}
jbig2_free(ctx->allocator, GSPLANES);
return NULL;
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void change_curseg(struct f2fs_sb_info *sbi, int type, bool reuse)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
struct curseg_info *curseg = CURSEG_I(sbi, type);
unsigned int new_segno = curseg->next_segno;
struct f2fs_summary_block *sum_node;
struct page *sum_page;
write_sum_page(sbi, curseg->sum_blk,
GET_SUM_BLOCK(sbi, curseg->segno));
__set_test_and_inuse(sbi, new_segno);
mutex_lock(&dirty_i->seglist_lock);
__remove_dirty_segment(sbi, new_segno, PRE);
__remove_dirty_segment(sbi, new_segno, DIRTY);
mutex_unlock(&dirty_i->seglist_lock);
reset_curseg(sbi, type, 1);
curseg->alloc_type = SSR;
__next_free_blkoff(sbi, curseg, 0);
if (reuse) {
sum_page = get_sum_page(sbi, new_segno);
sum_node = (struct f2fs_summary_block *)page_address(sum_page);
memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
f2fs_put_page(sum_page, 1);
}
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: LocalFrame::GetRemoteNavigationAssociatedInterfaces() {
DCHECK(Client());
return Client()->GetRemoteNavigationAssociatedInterfaces();
}
CWE ID: CWE-285
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 gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quantization)
{
uint8_t *argb;
int x, y;
uint8_t *p;
uint8_t *out;
size_t out_size;
if (im == NULL) {
return;
}
if (!gdImageTrueColor(im)) {
zend_error(E_ERROR, "Paletter image not supported by webp");
return;
}
if (quantization == -1) {
quantization = 80;
}
argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im));
if (!argb) {
return;
}
p = argb;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
register int c;
register char a;
c = im->tpixels[y][x];
a = gdTrueColorGetAlpha(c);
if (a == 127) {
a = 0;
} else {
a = 255 - ((a << 1) + (a >> 6));
}
*(p++) = gdTrueColorGetRed(c);
*(p++) = gdTrueColorGetGreen(c);
*(p++) = gdTrueColorGetBlue(c);
*(p++) = a;
}
}
out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quantization, &out);
if (out_size == 0) {
zend_error(E_ERROR, "gd-webp encoding failed");
goto freeargb;
}
gdPutBuf(out, out_size, outfile);
free(out);
freeargb:
gdFree(argb);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
{
struct vmcb *vmcb = get_host_vmcb(svm);
vmcb->control.intercept_exceptions |= (1U << bit);
recalc_intercepts(svm);
}
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: next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b, *avail, nl);
if (len >= 0)
len += tested;
}
return (len);
}
CWE ID: CWE-125
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void hugetlb_put_quota(struct address_space *mapping, long delta)
{
struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(mapping->host->i_sb);
if (sbinfo->free_blocks > -1) {
spin_lock(&sbinfo->stat_lock);
sbinfo->free_blocks += delta;
spin_unlock(&sbinfo->stat_lock);
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: dissect_u3v_pending_ack(proto_tree *u3v_telegram_tree, tvbuff_t *tvb, packet_info *pinfo _U_, gint startoffset, gint length, u3v_conv_info_t *u3v_conv_info _U_, gencp_transaction_t *gencp_trans _U_)
{
proto_item *item = NULL;
guint offset = startoffset;
/* Fill in Wireshark GUI Info column */
col_append_fstr(pinfo->cinfo, COL_INFO, " %d ms", tvb_get_letohs(tvb, startoffset+2));
item = proto_tree_add_item(u3v_telegram_tree, hf_u3v_ccd_pending_ack, tvb, startoffset, length, ENC_NA);
u3v_telegram_tree = proto_item_add_subtree(item, ett_u3v_payload_cmd);
/* reserved field */
proto_tree_add_item(u3v_telegram_tree, hf_u3v_reserved, tvb, offset, 2, ENC_NA);
offset += 2;
proto_tree_add_item(u3v_telegram_tree, hf_u3v_time_to_completion, tvb, offset, 2, ENC_LITTLE_ENDIAN);
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: json_t *json_true(void)
{
static json_t the_true = {JSON_TRUE, (size_t)-1};
return &the_true;
}
CWE ID: CWE-310
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Editor::Transpose() {
if (!CanEdit())
//// TODO(yosin): We should move |Transpose()| into |ExecuteTranspose()| in
//// "EditorCommand.cpp"
return;
GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& range = ComputeRangeForTranspose(GetFrame());
if (range.IsNull())
return;
const String& text = PlainText(range);
if (text.length() != 2)
return;
const String& transposed = text.Right(1) + text.Left(1);
if (DispatchBeforeInputInsertText(
EventTargetNodeForDocument(GetFrame().GetDocument()), transposed,
InputEvent::InputType::kInsertTranspose,
new StaticRangeVector(1, StaticRange::Create(range))) !=
DispatchEventResult::kNotCanceled)
return;
if (frame_->GetDocument()->GetFrame() != frame_)
return;
GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& new_range = ComputeRangeForTranspose(GetFrame());
if (new_range.IsNull())
return;
const String& new_text = PlainText(new_range);
if (new_text.length() != 2)
return;
const String& new_transposed = new_text.Right(1) + new_text.Left(1);
const SelectionInDOMTree& new_selection =
SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build();
if (CreateVisibleSelection(new_selection) !=
GetFrame().Selection().ComputeVisibleSelectionInDOMTree())
GetFrame().Selection().SetSelection(new_selection);
ReplaceSelectionWithText(new_transposed, false, false,
InputEvent::InputType::kInsertTranspose);
}
CWE ID:
Target: 1
Example 2:
Code: AudioInputStreamPtr CreateAudioInput() {
AudioInputStreamPtr p;
ExpectDelegateCreation();
impl_ = std::make_unique<MojoAudioInputStream>(
mojo::MakeRequest(&p), std::move(client_ptr_),
base::BindOnce(&MockDelegateFactory::CreateDelegate,
base::Unretained(&mock_delegate_factory_)),
base::BindOnce(&MockClient::Initialized, base::Unretained(&client_)),
base::BindOnce(&MockDeleter::Finished, base::Unretained(&deleter_)));
EXPECT_TRUE(p.is_bound());
return p;
}
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 calc_sq_size(struct mlx5_ib_dev *dev, struct ib_qp_init_attr *attr,
struct mlx5_ib_qp *qp)
{
int wqe_size;
int wq_size;
if (!attr->cap.max_send_wr)
return 0;
wqe_size = calc_send_wqe(attr);
mlx5_ib_dbg(dev, "wqe_size %d\n", wqe_size);
if (wqe_size < 0)
return wqe_size;
if (wqe_size > MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq)) {
mlx5_ib_dbg(dev, "wqe_size(%d) > max_sq_desc_sz(%d)\n",
wqe_size, MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq));
return -EINVAL;
}
qp->max_inline_data = wqe_size - sq_overhead(attr) -
sizeof(struct mlx5_wqe_inline_seg);
attr->cap.max_inline_data = qp->max_inline_data;
if (attr->create_flags & IB_QP_CREATE_SIGNATURE_EN)
qp->signature_en = true;
wq_size = roundup_pow_of_two(attr->cap.max_send_wr * wqe_size);
qp->sq.wqe_cnt = wq_size / MLX5_SEND_WQE_BB;
if (qp->sq.wqe_cnt > (1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz))) {
mlx5_ib_dbg(dev, "send queue size (%d * %d / %d -> %d) exceeds limits(%d)\n",
attr->cap.max_send_wr, wqe_size, MLX5_SEND_WQE_BB,
qp->sq.wqe_cnt,
1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz));
return -ENOMEM;
}
qp->sq.wqe_shift = ilog2(MLX5_SEND_WQE_BB);
qp->sq.max_gs = get_send_sge(attr, wqe_size);
if (qp->sq.max_gs < attr->cap.max_send_sge)
return -ENOMEM;
attr->cap.max_send_sge = qp->sq.max_gs;
qp->sq.max_post = wq_size / wqe_size;
attr->cap.max_send_wr = qp->sq.max_post;
return wq_size;
}
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: sp<ABuffer> decodeBase64(const AString &s) {
size_t n = s.size();
if ((n % 4) != 0) {
return NULL;
}
size_t padding = 0;
if (n >= 1 && s.c_str()[n - 1] == '=') {
padding = 1;
if (n >= 2 && s.c_str()[n - 2] == '=') {
padding = 2;
if (n >= 3 && s.c_str()[n - 3] == '=') {
padding = 3;
}
}
}
size_t outLen = (n / 4) * 3 - padding;
sp<ABuffer> buffer = new ABuffer(outLen);
uint8_t *out = buffer->data();
if (out == NULL || buffer->size() < outLen) {
return NULL;
}
size_t j = 0;
uint32_t accum = 0;
for (size_t i = 0; i < n; ++i) {
char c = s.c_str()[i];
unsigned value;
if (c >= 'A' && c <= 'Z') {
value = c - 'A';
} else if (c >= 'a' && c <= 'z') {
value = 26 + c - 'a';
} else if (c >= '0' && c <= '9') {
value = 52 + c - '0';
} else if (c == '+') {
value = 62;
} else if (c == '/') {
value = 63;
} else if (c != '=') {
return NULL;
} else {
if (i < n - padding) {
return NULL;
}
value = 0;
}
accum = (accum << 6) | value;
if (((i + 1) % 4) == 0) {
out[j++] = (accum >> 16);
if (j < outLen) { out[j++] = (accum >> 8) & 0xff; }
if (j < outLen) { out[j++] = accum & 0xff; }
accum = 0;
}
}
return buffer;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static inline int decode_asi(unsigned int insn, struct pt_regs *regs)
{
if (insn & 0x800000) {
if (insn & 0x2000)
return (unsigned char)(regs->tstate >> 24); /* %asi */
else
return (unsigned char)(insn >> 5); /* imm_asi */
} else
return ASI_P;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __poke_user(struct task_struct *child, addr_t addr, addr_t data)
{
struct user *dummy = NULL;
addr_t offset;
if (addr < (addr_t) &dummy->regs.acrs) {
/*
* psw and gprs are stored on the stack
*/
if (addr == (addr_t) &dummy->regs.psw.mask) {
unsigned long mask = PSW_MASK_USER;
mask |= is_ri_task(child) ? PSW_MASK_RI : 0;
if ((data & ~mask) != PSW_USER_BITS)
return -EINVAL;
if ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA))
return -EINVAL;
}
*(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data;
} else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) {
/*
* access registers are stored in the thread structure
*/
offset = addr - (addr_t) &dummy->regs.acrs;
#ifdef CONFIG_64BIT
/*
* Very special case: old & broken 64 bit gdb writing
* to acrs[15] with a 64 bit value. Ignore the lower
* half of the value and write the upper 32 bit to
* acrs[15]. Sick...
*/
if (addr == (addr_t) &dummy->regs.acrs[15])
child->thread.acrs[15] = (unsigned int) (data >> 32);
else
#endif
*(addr_t *)((addr_t) &child->thread.acrs + offset) = data;
} else if (addr == (addr_t) &dummy->regs.orig_gpr2) {
/*
* orig_gpr2 is stored on the kernel stack
*/
task_pt_regs(child)->orig_gpr2 = data;
} else if (addr < (addr_t) &dummy->regs.fp_regs) {
/*
* prevent writes of padding hole between
* orig_gpr2 and fp_regs on s390.
*/
return 0;
} else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) {
/*
* floating point regs. are stored in the thread structure
*/
if (addr == (addr_t) &dummy->regs.fp_regs.fpc)
if ((unsigned int) data != 0 ||
test_fp_ctl(data >> (BITS_PER_LONG - 32)))
return -EINVAL;
offset = addr - (addr_t) &dummy->regs.fp_regs;
*(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data;
} else if (addr < (addr_t) (&dummy->regs.per_info + 1)) {
/*
* Handle access to the per_info structure.
*/
addr -= (addr_t) &dummy->regs.per_info;
__poke_user_per(child, addr, data);
}
return 0;
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg, *funcname;
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;
funcname = "kadm5_purgekeys";
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) &&
(CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL))) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp);
} else {
ret.code = kadm5_purgekeys((void *)handle, arg->princ,
arg->keepkvno);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void igmp_heard_report(struct in_device *in_dev, __be32 group)
{
struct ip_mc_list *im;
/* Timers are only set for non-local groups */
if (group == IGMP_ALL_HOSTS)
return;
rcu_read_lock();
for_each_pmc_rcu(in_dev, im) {
if (im->multiaddr == group) {
igmp_stop_timer(im);
break;
}
}
rcu_read_unlock();
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: png_get_copyright(png_structp png_ptr)
{
PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */
#ifdef PNG_STRING_COPYRIGHT
return PNG_STRING_COPYRIGHT
#else
#ifdef __STDC__
return ((png_charp) PNG_STRING_NEWLINE \
"libpng version 1.2.52 - November 20, 2014" PNG_STRING_NEWLINE \
"Copyright (c) 1998-2014 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
"Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
"Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
PNG_STRING_NEWLINE);
#else
return ((png_charp) "libpng version 1.2.52 - November 20, 2014\
Copyright (c) 1998-2014 Glenn Randers-Pehrson\
Copyright (c) 1996-1997 Andreas Dilger\
Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.");
#endif
#endif
}
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: init_global_keywords(bool global_active)
{
/* global definitions mapping */
install_keyword_root("linkbeat_use_polling", use_polling_handler, global_active);
#if HAVE_DECL_CLONE_NEWNET
install_keyword_root("net_namespace", &net_namespace_handler, global_active);
install_keyword_root("namespace_with_ipsets", &namespace_ipsets_handler, global_active);
#endif
install_keyword_root("use_pid_dir", &use_pid_dir_handler, global_active);
install_keyword_root("instance", &instance_handler, global_active);
install_keyword_root("child_wait_time", &child_wait_handler, global_active);
install_keyword_root("global_defs", NULL, global_active);
install_keyword("router_id", &routerid_handler);
install_keyword("notification_email_from", &emailfrom_handler);
install_keyword("smtp_server", &smtpserver_handler);
install_keyword("smtp_helo_name", &smtphelo_handler);
install_keyword("smtp_connect_timeout", &smtpto_handler);
install_keyword("notification_email", &email_handler);
install_keyword("smtp_alert", &smtp_alert_handler);
#ifdef _WITH_VRRP_
install_keyword("smtp_alert_vrrp", &smtp_alert_vrrp_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("smtp_alert_checker", &smtp_alert_checker_handler);
#endif
#ifdef _WITH_VRRP_
install_keyword("dynamic_interfaces", &dynamic_interfaces_handler);
install_keyword("no_email_faults", &no_email_faults_handler);
install_keyword("default_interface", &default_interface_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_timeouts", &lvs_timeouts);
install_keyword("lvs_flush", &lvs_flush_handler);
#ifdef _WITH_VRRP_
install_keyword("lvs_sync_daemon", &lvs_syncd_handler);
#endif
#endif
#ifdef _WITH_VRRP_
install_keyword("vrrp_mcast_group4", &vrrp_mcast_group4_handler);
install_keyword("vrrp_mcast_group6", &vrrp_mcast_group6_handler);
install_keyword("vrrp_garp_master_delay", &vrrp_garp_delay_handler);
install_keyword("vrrp_garp_master_repeat", &vrrp_garp_rep_handler);
install_keyword("vrrp_garp_master_refresh", &vrrp_garp_refresh_handler);
install_keyword("vrrp_garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler);
install_keyword("vrrp_garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler);
install_keyword("vrrp_garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler);
install_keyword("vrrp_garp_interval", &vrrp_garp_interval_handler);
install_keyword("vrrp_gna_interval", &vrrp_gna_interval_handler);
install_keyword("vrrp_lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler);
install_keyword("vrrp_higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler);
install_keyword("vrrp_version", &vrrp_version_handler);
install_keyword("vrrp_iptables", &vrrp_iptables_handler);
#ifdef _HAVE_LIBIPSET_
install_keyword("vrrp_ipsets", &vrrp_ipsets_handler);
#endif
install_keyword("vrrp_check_unicast_src", &vrrp_check_unicast_src_handler);
install_keyword("vrrp_skip_check_adv_addr", &vrrp_check_adv_addr_handler);
install_keyword("vrrp_strict", &vrrp_strict_handler);
install_keyword("vrrp_priority", &vrrp_prio_handler);
install_keyword("vrrp_no_swap", &vrrp_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("vrrp_rt_priority", &vrrp_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("vrrp_rlimit_rtime", &vrrp_rt_rlimit_handler);
#endif
#endif
#endif
install_keyword("notify_fifo", &global_notify_fifo);
install_keyword("notify_fifo_script", &global_notify_fifo_script);
#ifdef _WITH_VRRP_
install_keyword("vrrp_notify_fifo", &vrrp_notify_fifo);
install_keyword("vrrp_notify_fifo_script", &vrrp_notify_fifo_script);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_notify_fifo", &lvs_notify_fifo);
install_keyword("lvs_notify_fifo_script", &lvs_notify_fifo_script);
install_keyword("checker_priority", &checker_prio_handler);
install_keyword("checker_no_swap", &checker_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("checker_rt_priority", &checker_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("checker_rlimit_rtime", &checker_rt_rlimit_handler);
#endif
#endif
#endif
#ifdef _WITH_BFD_
install_keyword("bfd_priority", &bfd_prio_handler);
install_keyword("bfd_no_swap", &bfd_no_swap_handler);
#ifdef _HAVE_SCHED_RT_
install_keyword("bfd_rt_priority", &bfd_rt_priority_handler);
#if HAVE_DECL_RLIMIT_RTTIME == 1
install_keyword("bfd_rlimit_rtime", &bfd_rt_rlimit_handler);
#endif
#endif
#endif
#ifdef _WITH_SNMP_
install_keyword("snmp_socket", &snmp_socket_handler);
install_keyword("enable_traps", &trap_handler);
#ifdef _WITH_SNMP_VRRP_
install_keyword("enable_snmp_vrrp", &snmp_vrrp_handler);
install_keyword("enable_snmp_keepalived", &snmp_vrrp_handler); /* Deprecated v2.0.0 */
#endif
#ifdef _WITH_SNMP_RFC_
install_keyword("enable_snmp_rfc", &snmp_rfc_handler);
#endif
#ifdef _WITH_SNMP_RFCV2_
install_keyword("enable_snmp_rfcv2", &snmp_rfcv2_handler);
#endif
#ifdef _WITH_SNMP_RFCV3_
install_keyword("enable_snmp_rfcv3", &snmp_rfcv3_handler);
#endif
#ifdef _WITH_SNMP_CHECKER_
install_keyword("enable_snmp_checker", &snmp_checker_handler);
#endif
#endif
#ifdef _WITH_DBUS_
install_keyword("enable_dbus", &enable_dbus_handler);
install_keyword("dbus_service_name", &dbus_service_name_handler);
#endif
install_keyword("script_user", &script_user_handler);
install_keyword("enable_script_security", &script_security_handler);
#ifdef _WITH_VRRP_
install_keyword("vrrp_netlink_cmd_rcv_bufs", &vrrp_netlink_cmd_rcv_bufs_handler);
install_keyword("vrrp_netlink_cmd_rcv_bufs_force", &vrrp_netlink_cmd_rcv_bufs_force_handler);
install_keyword("vrrp_netlink_monitor_rcv_bufs", &vrrp_netlink_monitor_rcv_bufs_handler);
install_keyword("vrrp_netlink_monitor_rcv_bufs_force", &vrrp_netlink_monitor_rcv_bufs_force_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("lvs_netlink_cmd_rcv_bufs", &lvs_netlink_cmd_rcv_bufs_handler);
install_keyword("lvs_netlink_cmd_rcv_bufs_force", &lvs_netlink_cmd_rcv_bufs_force_handler);
install_keyword("lvs_netlink_monitor_rcv_bufs", &lvs_netlink_monitor_rcv_bufs_handler);
install_keyword("lvs_netlink_monitor_rcv_bufs_force", &lvs_netlink_monitor_rcv_bufs_force_handler);
#endif
#ifdef _WITH_LVS_
install_keyword("rs_init_notifies", &rs_init_notifies_handler);
install_keyword("no_checker_emails", &no_checker_emails_handler);
#endif
#ifdef _WITH_VRRP_
install_keyword("vrrp_rx_bufs_policy", &vrrp_rx_bufs_policy_handler);
install_keyword("vrrp_rx_bufs_multiplier", &vrrp_rx_bufs_multiplier_handler);
#endif
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void xenvif_notify_tx_completion(struct xenvif *vif)
{
if (netif_queue_stopped(vif->dev) && xenvif_rx_schedulable(vif))
netif_wake_queue(vif->dev);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool SectionHasAutofilledField(const FormStructure& form_structure,
const FormData& form,
const std::string& section) {
DCHECK_EQ(form_structure.field_count(), form.fields.size());
for (size_t i = 0; i < form_structure.field_count(); ++i) {
if (form_structure.field(i)->section == section &&
form.fields[i].is_autofilled) {
return true;
}
}
return false;
}
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 jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
AVFrame *picture)
{
int compno, reslevelno, bandno;
int x, y;
uint8_t *line;
Jpeg2000T1Context t1;
/* Loop on tile components */
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
/* Loop on resolution levels */
for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
/* Loop on bands */
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
int nb_precincts, precno;
Jpeg2000Band *band = rlevel->band + bandno;
int cblkno = 0, bandpos;
bandpos = bandno + (reslevelno > 0);
if (band->coord[0][0] == band->coord[0][1] ||
band->coord[1][0] == band->coord[1][1])
continue;
nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
/* Loop on precincts */
for (precno = 0; precno < nb_precincts; precno++) {
Jpeg2000Prec *prec = band->prec + precno;
/* Loop on codeblocks */
for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
int x, y;
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
decode_cblk(s, codsty, &t1, cblk,
cblk->coord[0][1] - cblk->coord[0][0],
cblk->coord[1][1] - cblk->coord[1][0],
bandpos);
x = cblk->coord[0][0];
y = cblk->coord[1][0];
if (codsty->transform == FF_DWT97)
dequantization_float(x, y, cblk, comp, &t1, band);
else
dequantization_int(x, y, cblk, comp, &t1, band);
} /* end cblk */
} /*end prec */
} /* end band */
} /* end reslevel */
/* inverse DWT */
ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
} /*end comp */
/* inverse MCT transformation */
if (tile->codsty[0].mct)
mct_decode(s, tile);
if (s->cdef[0] < 0) {
for (x = 0; x < s->ncomponents; x++)
s->cdef[x] = x + 1;
if ((s->ncomponents & 1) == 0)
s->cdef[s->ncomponents-1] = 0;
}
if (s->precision <= 8) {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
float *datap = comp->f_data;
int32_t *i_datap = comp->i_data;
int cbps = s->cbps[compno];
int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
int planar = !!picture->data[2];
int pixelsize = planar ? 1 : s->ncomponents;
int plane = 0;
if (planar)
plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
y = tile->comp[compno].coord[1][0] - s->image_offset_y;
line = picture->data[plane] + y * picture->linesize[plane];
for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
uint8_t *dst;
x = tile->comp[compno].coord[0][0] - s->image_offset_x;
dst = line + x * pixelsize + compno*!planar;
if (codsty->transform == FF_DWT97) {
for (; x < w; x += s->cdx[compno]) {
int val = lrintf(*datap) + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
*dst = val << (8 - cbps);
datap++;
dst += pixelsize;
}
} else {
for (; x < w; x += s->cdx[compno]) {
int val = *i_datap + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
*dst = val << (8 - cbps);
i_datap++;
dst += pixelsize;
}
}
line += picture->linesize[plane];
}
}
} else {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
float *datap = comp->f_data;
int32_t *i_datap = comp->i_data;
uint16_t *linel;
int cbps = s->cbps[compno];
int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
int planar = !!picture->data[2];
int pixelsize = planar ? 1 : s->ncomponents;
int plane = 0;
if (planar)
plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
y = tile->comp[compno].coord[1][0] - s->image_offset_y;
linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1);
for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
uint16_t *dst;
x = tile->comp[compno].coord[0][0] - s->image_offset_x;
dst = linel + (x * pixelsize + compno*!planar);
if (codsty->transform == FF_DWT97) {
for (; x < w; x += s-> cdx[compno]) {
int val = lrintf(*datap) + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
/* align 12 bit values in little-endian mode */
*dst = val << (16 - cbps);
datap++;
dst += pixelsize;
}
} else {
for (; x < w; x += s-> cdx[compno]) {
int val = *i_datap + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
/* align 12 bit values in little-endian mode */
*dst = val << (16 - cbps);
i_datap++;
dst += pixelsize;
}
}
linel += picture->linesize[plane] >> 1;
}
}
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void SyncBackendHost::LogUnsyncedItems(int level) const {
DCHECK(syncapi_initialized_);
return core_->syncapi()->LogUnsyncedItems(level);
}
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: RenderBlockFlow* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
{
RenderBlockFlow* columnsBlockAncestor = 0;
if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
&& !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
columnsBlockAncestor = containingColumnsBlock(false);
if (columnsBlockAncestor) {
RenderObject* curr = this;
while (curr && curr != columnsBlockAncestor) {
if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
columnsBlockAncestor = 0;
break;
}
curr = curr->parent();
}
}
}
return columnsBlockAncestor;
}
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: vmxnet3_io_bar0_write(void *opaque, hwaddr addr,
uint64_t val, unsigned size)
{
VMXNET3State *s = opaque;
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_TXPROD,
VMXNET3_DEVICE_MAX_TX_QUEUES, VMXNET3_REG_ALIGN)) {
int tx_queue_idx =
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) {
int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR,
VMXNET3_REG_ALIGN);
VMW_CBPRN("Interrupt mask for line %d written: 0x%" PRIx64, l, val);
vmxnet3_on_interrupt_mask_changed(s, l, val);
return;
}
if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN) ||
VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD2,
VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN)) {
return;
}
VMW_WRPRN("BAR0 unknown write [%" PRIx64 "] = %" PRIx64 ", size %d",
(uint64_t) addr, val, size);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void InputDispatcher::InjectionState::release() {
refCount -= 1;
if (refCount == 0) {
delete this;
} else {
ALOG_ASSERT(refCount > 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 void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile(
JNIEnv* env,
const JavaParamRef<jstring>& java_update_request_path,
const JavaParamRef<jstring>& java_start_url,
const JavaParamRef<jstring>& java_scope,
const JavaParamRef<jstring>& java_name,
const JavaParamRef<jstring>& java_short_name,
const JavaParamRef<jstring>& java_primary_icon_url,
const JavaParamRef<jobject>& java_primary_icon_bitmap,
const JavaParamRef<jstring>& java_badge_icon_url,
const JavaParamRef<jobject>& java_badge_icon_bitmap,
const JavaParamRef<jobjectArray>& java_icon_urls,
const JavaParamRef<jobjectArray>& java_icon_hashes,
jint java_display_mode,
jint java_orientation,
jlong java_theme_color,
jlong java_background_color,
const JavaParamRef<jstring>& java_web_manifest_url,
const JavaParamRef<jstring>& java_webapk_package,
jint java_webapk_version,
jboolean java_is_manifest_stale,
jint java_update_reason,
const JavaParamRef<jobject>& java_callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::string update_request_path =
ConvertJavaStringToUTF8(env, java_update_request_path);
ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url)));
info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope));
info.name = ConvertJavaStringToUTF16(env, java_name);
info.short_name = ConvertJavaStringToUTF16(env, java_short_name);
info.user_title = info.short_name;
info.display = static_cast<blink::WebDisplayMode>(java_display_mode);
info.orientation =
static_cast<blink::WebScreenOrientationLockType>(java_orientation);
info.theme_color = (int64_t)java_theme_color;
info.background_color = (int64_t)java_background_color;
info.best_primary_icon_url =
GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url));
info.best_badge_icon_url =
GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url));
info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url));
base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls,
&info.icon_urls);
std::vector<std::string> icon_hashes;
base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes,
&icon_hashes);
std::map<std::string, std::string> icon_url_to_murmur2_hash;
for (size_t i = 0; i < info.icon_urls.size(); ++i)
icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i];
gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap);
SkBitmap primary_icon =
gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock);
primary_icon.setImmutable();
SkBitmap badge_icon;
if (!java_badge_icon_bitmap.is_null()) {
gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap);
gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock);
badge_icon.setImmutable();
}
std::string webapk_package;
ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package);
WebApkUpdateReason update_reason =
static_cast<WebApkUpdateReason>(java_update_reason);
WebApkInstaller::StoreUpdateRequestToFile(
base::FilePath(update_request_path), info, primary_icon, badge_icon,
webapk_package, std::to_string(java_webapk_version),
icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason,
base::BindOnce(&base::android::RunBooleanCallbackAndroid,
ScopedJavaGlobalRef<jobject>(java_callback)));
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __ptrace_may_access(struct task_struct *task, unsigned int mode)
{
const struct cred *cred = current_cred(), *tcred;
/* May we inspect the given task?
* This check is used both for attaching with ptrace
* and for allowing access to sensitive information in /proc.
*
* ptrace_attach denies several cases that /proc allows
* because setting up the necessary parent/child relationship
* or halting the specified task is impossible.
*/
int dumpable = 0;
/* Don't let security modules deny introspection */
if (same_thread_group(task, current))
return 0;
rcu_read_lock();
tcred = __task_cred(task);
if (uid_eq(cred->uid, tcred->euid) &&
uid_eq(cred->uid, tcred->suid) &&
uid_eq(cred->uid, tcred->uid) &&
gid_eq(cred->gid, tcred->egid) &&
gid_eq(cred->gid, tcred->sgid) &&
gid_eq(cred->gid, tcred->gid))
goto ok;
if (ptrace_has_cap(tcred->user_ns, mode))
goto ok;
rcu_read_unlock();
return -EPERM;
ok:
rcu_read_unlock();
smp_rmb();
if (task->mm)
dumpable = get_dumpable(task->mm);
rcu_read_lock();
if (!dumpable && !ptrace_has_cap(__task_cred(task)->user_ns, mode)) {
rcu_read_unlock();
return -EPERM;
}
rcu_read_unlock();
return security_ptrace_access_check(task, mode);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: ExtensionInstallPrompt::GetLocalizedExtensionForDisplay(
const base::DictionaryValue* manifest,
int flags,
const std::string& id,
const std::string& localized_name,
const std::string& localized_description,
std::string* error) {
scoped_ptr<base::DictionaryValue> localized_manifest;
if (!localized_name.empty() || !localized_description.empty()) {
localized_manifest.reset(manifest->DeepCopy());
if (!localized_name.empty()) {
localized_manifest->SetString(extensions::manifest_keys::kName,
localized_name);
}
if (!localized_description.empty()) {
localized_manifest->SetString(extensions::manifest_keys::kDescription,
localized_description);
}
}
return Extension::Create(
base::FilePath(),
Manifest::INTERNAL,
localized_manifest.get() ? *localized_manifest.get() : *manifest,
flags,
id,
error);
}
CWE ID: CWE-17
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GLES2DecoderImpl::DoVertexAttrib4fv(GLuint index, const GLfloat* v) {
VertexAttribManager::VertexAttribInfo* info =
vertex_attrib_manager_->GetVertexAttribInfo(index);
if (!info) {
SetGLError(GL_INVALID_VALUE, "glVertexAttrib4fv", "index out of range");
return;
}
VertexAttribManager::VertexAttribInfo::Vec4 value;
value.v[0] = v[0];
value.v[1] = v[1];
value.v[2] = v[2];
value.v[3] = v[3];
info->set_value(value);
glVertexAttrib4fv(index, v);
}
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: lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
uint8_t i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %d, RES: %d, Sel: %d",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07)));
ND_PRINT((ndo, "Protocol ID: %d", EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
CWE ID: CWE-835
Target: 1
Example 2:
Code: struct sctp_pf *sctp_get_pf_specific(sa_family_t family)
{
switch (family) {
case PF_INET:
return sctp_pf_inet_specific;
case PF_INET6:
return sctp_pf_inet6_specific;
default:
return NULL;
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() {
if (g_idb_dispatcher_tls.Pointer()->Get())
return g_idb_dispatcher_tls.Pointer()->Get();
IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher;
if (WorkerTaskRunner::Instance()->CurrentWorkerId())
webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher);
return dispatcher;
}
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: destroy_one_secret (gpointer data)
{
char *secret = (char *) data;
/* Don't leave the secret lying around in memory */
g_message ("%s: destroying %s", __func__, secret);
memset (secret, 0, strlen (secret));
g_free (secret);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: WebCookieJar* LocalFrameClientImpl::CookieJar() const {
if (!web_frame_->Client())
return nullptr;
return web_frame_->Client()->CookieJar();
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashColorMode srcMode;
SplashImageSource src;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = maskColors;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
break;
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
src = maskColors ? &alphaImageSrc : &imageSrc;
splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse,
width, height, mat);
if (inlineImg) {
while (imgData.y < height) {
imgData.imgStr->getLine();
++imgData.y;
}
}
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
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: method_invocation_get_uid (GDBusMethodInvocation *context)
{
const gchar *sender;
PolkitSubject *busname;
PolkitSubject *process;
uid_t uid;
sender = g_dbus_method_invocation_get_sender (context);
busname = polkit_system_bus_name_new (sender);
process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (busname), NULL, NULL);
uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process));
g_object_unref (busname);
g_object_unref (process);
return uid;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: gs_main_init0(gs_main_instance * minst, FILE * in, FILE * out, FILE * err,
int max_lib_paths)
{
ref *array;
/* Do platform-dependent initialization. */
/* We have to do this as the very first thing, */
/* because it detects attempts to run 80N86 executables (N>0) */
/* on incompatible processors. */
gp_init();
/* Initialize the imager. */
/* Reset debugging flags */
#ifdef PACIFY_VALGRIND
VALGRIND_HG_DISABLE_CHECKING(gs_debug, 128);
#endif
memset(gs_debug, 0, 128);
gs_log_errors = 0; /* gs_debug['#'] = 0 */
gp_get_realtime(minst->base_time);
/* Initialize the file search paths. */
array = (ref *) gs_alloc_byte_array(minst->heap, max_lib_paths, sizeof(ref),
"lib_path array");
if (array == 0) {
gs_lib_finit(1, gs_error_VMerror, minst->heap);
return_error(gs_error_VMerror);
}
make_array(&minst->lib_path.container, avm_foreign, max_lib_paths,
array);
make_array(&minst->lib_path.list, avm_foreign | a_readonly, 0,
minst->lib_path.container.value.refs);
minst->lib_path.env = 0;
minst->lib_path.final = 0;
minst->lib_path.count = 0;
minst->user_errors = 1;
minst->init_done = 0;
return 0;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int encode_msg(struct sip_msg *msg,char *payload,int len)
{
int i,j,k,u,request;
unsigned short int h;
struct hdr_field* hf;
struct msg_start* ms;
struct sip_uri miuri;
char *myerror=NULL;
ptrdiff_t diff;
if(len < MAX_ENCODED_MSG + MAX_MESSAGE_LEN)
return -1;
if(parse_headers(msg,HDR_EOH_F,0)<0){
myerror="in parse_headers";
goto error;
}
memset(payload,0,len);
ms=&msg->first_line;
if(ms->type == SIP_REQUEST)
request=1;
else if(ms->type == SIP_REPLY)
request=0;
else{
myerror="message is neither request nor response";
goto error;
}
if(request) {
for(h=0;h<32;j=(0x01<<h),h++)
if(j & ms->u.request.method_value)
break;
} else {
h=(unsigned short)(ms->u.reply.statuscode);
}
if(h==32){/*statuscode wont be 32...*/
myerror="unknown message type\n";
goto error;
}
h=htons(h);
/*first goes the message code type*/
memcpy(payload,&h,2);
h=htons((unsigned short int)msg->len);
/*then goes the message start idx, but we'll put it later*/
/*then goes the message length (we hope it to be less than 65535 bytes...)*/
memcpy(&payload[MSG_LEN_IDX],&h,2);
/*then goes the content start index (starting from SIP MSG START)*/
if(0>(diff=(get_body(msg)-(msg->buf)))){
myerror="body starts before the message (uh ?)";
goto error;
}else
h=htons((unsigned short int)diff);
memcpy(payload+CONTENT_IDX,&h,2);
payload[METHOD_CODE_IDX]=(unsigned char)(request?
(ms->u.request.method.s-msg->buf):
(ms->u.reply.status.s-msg->buf));
payload[METHOD_CODE_IDX+1]=(unsigned char)(request?
(ms->u.request.method.len):
(ms->u.reply.status.len));
payload[URI_REASON_IDX]=(unsigned char)(request?
(ms->u.request.uri.s-msg->buf):
(ms->u.reply.reason.s-msg->buf));
payload[URI_REASON_IDX+1]=(unsigned char)(request?
(ms->u.request.uri.len):
(ms->u.reply.reason.len));
payload[VERSION_IDX]=(unsigned char)(request?
(ms->u.request.version.s-msg->buf):
(ms->u.reply.version.s-msg->buf));
if(request){
if (parse_uri(ms->u.request.uri.s,ms->u.request.uri.len, &miuri)<0){
LM_ERR("<%.*s>\n",ms->u.request.uri.len,ms->u.request.uri.s);
myerror="while parsing the R-URI";
goto error;
}
if(0>(j=encode_uri2(msg->buf,
ms->u.request.method.s-msg->buf+ms->len,
ms->u.request.uri,&miuri,
(unsigned char*)&payload[REQUEST_URI_IDX+1])))
{
myerror="ENCODE_MSG: ERROR while encoding the R-URI";
goto error;
}
payload[REQUEST_URI_IDX]=(unsigned char)j;
k=REQUEST_URI_IDX+1+j;
}else
k=REQUEST_URI_IDX;
u=k;
k++;
for(i=0,hf=msg->headers;hf;hf=hf->next,i++);
i++;/*we do as if there was an extra header, that marks the end of
the previous header in the headers hashtable(read below)*/
j=k+3*i;
for(i=0,hf=msg->headers;hf;hf=hf->next,k+=3){
payload[k]=(unsigned char)(hf->type & 0xFF);
h=htons(j);
/*now goes a payload-based-ptr to where the header-code starts*/
memcpy(&payload[k+1],&h,2);
/*TODO fix this... fixed with k-=3?*/
if(0>(i=encode_header(msg,hf,(unsigned char*)(payload+j),MAX_ENCODED_MSG+MAX_MESSAGE_LEN-j))){
LM_ERR("encoding header %.*s\n",hf->name.len,hf->name.s);
goto error;
k-=3;
continue;
}
j+=(unsigned short int)i;
}
/*now goes the number of headers that have been found, right after the meta-msg-section*/
payload[u]=(unsigned char)((k-u-1)/3);
j=htons(j);
/*now copy the number of bytes that the headers-meta-section has occupied,right afther
* headers-meta-section(the array with ['v',[2:where],'r',[2:where],'R',[2:where],...]
* this is to know where the LAST header ends, since the length of each header-struct
* is calculated substracting the nextHeaderStart - presentHeaderStart
* the k+1 is because payload[k] is usually the letter*/
memcpy(&payload[k+1],&j,2);
k+=3;
j=ntohs(j);
/*now we copy the headers-meta-section after the msg-headers-meta-section*/
/*memcpy(&payload[k],payload2,j);*/
/*j+=k;*/
/*pkg_free(payload2);*/
/*now we copy the actual message after the headers-meta-section*/
memcpy(&payload[j],msg->buf,msg->len);
LM_DBG("msglen = %d,msg starts at %d\n",msg->len,j);
j=htons(j);
/*now we copy at the beginning, the index to where the actual message starts*/
memcpy(&payload[MSG_START_IDX],&j,2);
return GET_PAY_SIZE( payload );
error:
LM_ERR("%s\n",myerror);
return -1;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::vector<uint8_t> NtlmClient::GenerateAuthenticateMessage(
const base::string16& domain,
const base::string16& username,
const base::string16& password,
const std::string& hostname,
const std::string& channel_bindings,
const std::string& spn,
uint64_t client_time,
base::span<const uint8_t, kChallengeLen> client_challenge,
base::span<const uint8_t> server_challenge_message) const {
if (hostname.length() > kMaxFqdnLen || domain.length() > kMaxFqdnLen ||
username.length() > kMaxUsernameLen ||
password.length() > kMaxPasswordLen) {
return {};
}
NegotiateFlags challenge_flags;
uint8_t server_challenge[kChallengeLen];
uint8_t lm_response[kResponseLenV1];
uint8_t ntlm_response[kResponseLenV1];
std::vector<uint8_t> updated_target_info;
std::vector<uint8_t> v2_proof_input;
uint8_t v2_proof[kNtlmProofLenV2];
uint8_t v2_session_key[kSessionKeyLenV2];
if (IsNtlmV2()) {
std::vector<AvPair> av_pairs;
if (!ParseChallengeMessageV2(server_challenge_message, &challenge_flags,
server_challenge, &av_pairs)) {
return {};
}
uint64_t timestamp;
updated_target_info =
GenerateUpdatedTargetInfo(IsMicEnabled(), IsEpaEnabled(),
channel_bindings, spn, av_pairs, ×tamp);
memset(lm_response, 0, kResponseLenV1);
if (timestamp == UINT64_MAX) {
timestamp = client_time;
}
uint8_t v2_hash[kNtlmHashLen];
GenerateNtlmHashV2(domain, username, password, v2_hash);
v2_proof_input = GenerateProofInputV2(timestamp, client_challenge);
GenerateNtlmProofV2(v2_hash, server_challenge, v2_proof_input,
updated_target_info, v2_proof);
GenerateSessionBaseKeyV2(v2_hash, v2_proof, v2_session_key);
} else {
if (!ParseChallengeMessage(server_challenge_message, &challenge_flags,
server_challenge)) {
return {};
}
GenerateResponsesV1WithSessionSecurity(password, server_challenge,
client_challenge, lm_response,
ntlm_response);
}
NegotiateFlags authenticate_flags = (challenge_flags & negotiate_flags_) |
NegotiateFlags::kExtendedSessionSecurity;
bool is_unicode = (authenticate_flags & NegotiateFlags::kUnicode) ==
NegotiateFlags::kUnicode;
SecurityBuffer lm_info;
SecurityBuffer ntlm_info;
SecurityBuffer domain_info;
SecurityBuffer username_info;
SecurityBuffer hostname_info;
SecurityBuffer session_key_info;
size_t authenticate_message_len;
CalculatePayloadLayout(is_unicode, domain, username, hostname,
updated_target_info.size(), &lm_info, &ntlm_info,
&domain_info, &username_info, &hostname_info,
&session_key_info, &authenticate_message_len);
NtlmBufferWriter authenticate_writer(authenticate_message_len);
bool writer_result = WriteAuthenticateMessage(
&authenticate_writer, lm_info, ntlm_info, domain_info, username_info,
hostname_info, session_key_info, authenticate_flags);
DCHECK(writer_result);
if (IsNtlmV2()) {
writer_result = authenticate_writer.WriteZeros(kVersionFieldLen) &&
authenticate_writer.WriteZeros(kMicLenV2);
DCHECK(writer_result);
}
DCHECK(authenticate_writer.GetCursor() == GetAuthenticateHeaderLength());
DCHECK(GetAuthenticateHeaderLength() == lm_info.offset);
if (IsNtlmV2()) {
writer_result =
WriteResponsePayloadsV2(&authenticate_writer, lm_response, v2_proof,
v2_proof_input, updated_target_info);
} else {
DCHECK_EQ(kResponseLenV1, lm_info.length);
DCHECK_EQ(kResponseLenV1, ntlm_info.length);
writer_result =
WriteResponsePayloads(&authenticate_writer, lm_response, ntlm_response);
}
DCHECK(writer_result);
DCHECK_EQ(authenticate_writer.GetCursor(), domain_info.offset);
writer_result = WriteStringPayloads(&authenticate_writer, is_unicode, domain,
username, hostname);
DCHECK(writer_result);
DCHECK(authenticate_writer.IsEndOfBuffer());
DCHECK_EQ(authenticate_message_len, authenticate_writer.GetLength());
std::vector<uint8_t> auth_msg = authenticate_writer.Pass();
if (IsMicEnabled()) {
DCHECK_LT(kMicOffsetV2 + kMicLenV2, authenticate_message_len);
base::span<uint8_t, kMicLenV2> mic(
const_cast<uint8_t*>(auth_msg.data()) + kMicOffsetV2, kMicLenV2);
GenerateMicV2(v2_session_key, negotiate_message_, server_challenge_message,
auth_msg, mic);
}
return auth_msg;
}
CWE ID: CWE-22
Target: 1
Example 2:
Code: rio_init (void)
{
return pci_register_driver(&rio_driver);
}
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 add_ballooned_pages(int nr_pages)
{
enum bp_state st;
if (xen_hotplug_unpopulated) {
st = reserve_additional_memory();
if (st != BP_ECANCELED) {
mutex_unlock(&balloon_mutex);
wait_event(balloon_wq,
!list_empty(&ballooned_pages));
mutex_lock(&balloon_mutex);
return 0;
}
}
st = decrease_reservation(nr_pages, GFP_USER);
if (st != BP_DONE)
return -ENOMEM;
return 0;
}
CWE ID: CWE-400
Output:
| 1 |
Here are some example code snippets. Analyze the following 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 SpdyWriteQueue::RemovePendingWritesForStreamsAfter(
SpdyStreamId last_good_stream_id) {
CHECK(!removing_writes_);
removing_writes_ = true;
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
std::deque<PendingWrite>* queue = &queue_[i];
std::deque<PendingWrite>::iterator out_it = queue->begin();
for (std::deque<PendingWrite>::const_iterator it = queue->begin();
it != queue->end(); ++it) {
if (it->stream.get() && (it->stream->stream_id() > last_good_stream_id ||
it->stream->stream_id() == 0)) {
delete it->frame_producer;
} else {
*out_it = *it;
++out_it;
}
}
queue->erase(out_it, queue->end());
}
removing_writes_ = false;
}
CWE ID:
Target: 1
Example 2:
Code: LayoutUnit RenderBox::overrideContainingBlockContentLogicalHeight() const
{
ASSERT(hasOverrideContainingBlockLogicalHeight());
return gOverrideContainingBlockLogicalHeightMap->get(this);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
if (!is_hidden_)
return;
TRACE_EVENT0("renderer_host", "RenderWidgetHostImpl::WasShown");
is_hidden_ = false;
if (new_content_rendering_timeout_ &&
new_content_rendering_timeout_->IsRunning()) {
new_content_rendering_timeout_->Stop();
ClearDisplayedGraphics();
}
SendScreenRects();
RestartHangMonitorTimeoutIfNecessary();
bool needs_repainting = true;
needs_repainting_on_restore_ = false;
Send(new ViewMsg_WasShown(routing_id_, needs_repainting, latency_info));
process_->WidgetRestored();
bool is_visible = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED,
Source<RenderWidgetHost>(this),
Details<bool>(&is_visible));
WasResized();
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: char *X509_NAME_oneline(X509_NAME *a, char *buf, int len)
{
X509_NAME_ENTRY *ne;
int i;
int n, lold, l, l1, l2, num, j, type;
const char *s;
char *p;
unsigned char *q;
BUF_MEM *b = NULL;
static const char hex[17] = "0123456789ABCDEF";
int gs_doit[4];
char tmp_buf[80];
#ifdef CHARSET_EBCDIC
char ebcdic_buf[1024];
#endif
if (buf == NULL) {
if ((b = BUF_MEM_new()) == NULL)
goto err;
if (!BUF_MEM_grow(b, 200))
goto err;
b->data[0] = '\0';
len = 200;
} else if (len == 0) {
return NULL;
}
if (a == NULL) {
if (b) {
buf = b->data;
OPENSSL_free(b);
}
strncpy(buf, "NO X509_NAME", len);
buf[len - 1] = '\0';
return buf;
}
len--; /* space for '\0' */
l = 0;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
ne = sk_X509_NAME_ENTRY_value(a->entries, i);
n = OBJ_obj2nid(ne->object);
if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object);
s = tmp_buf;
}
l1 = strlen(s);
type = ne->value->type;
num = ne->value->length;
if (num > NAME_ONELINE_MAX) {
X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
goto end;
}
q = ne->value->data;
#ifdef CHARSET_EBCDIC
if (type == V_ASN1_GENERALSTRING ||
type == V_ASN1_VISIBLESTRING ||
type == V_ASN1_PRINTABLESTRING ||
type == V_ASN1_TELETEXSTRING ||
type == V_ASN1_VISIBLESTRING || type == V_ASN1_IA5STRING) {
ascii2ebcdic(ebcdic_buf, q, (num > sizeof ebcdic_buf)
? sizeof ebcdic_buf : num);
q = ebcdic_buf;
}
#endif
if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) {
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0;
for (j = 0; j < num; j++)
if (q[j] != 0)
gs_doit[j & 3] = 1;
if (gs_doit[0] | gs_doit[1] | gs_doit[2])
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
else {
gs_doit[0] = gs_doit[1] = gs_doit[2] = 0;
gs_doit[3] = 1;
}
} else
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
for (l2 = j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
l2++;
#ifndef CHARSET_EBCDIC
if ((q[j] < ' ') || (q[j] > '~'))
l2 += 3;
#else
if ((os_toascii[q[j]] < os_toascii[' ']) ||
(os_toascii[q[j]] > os_toascii['~']))
l2 += 3;
#endif
}
lold = l;
l += 1 + l1 + 1 + l2;
if (l > NAME_ONELINE_MAX) {
X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
goto end;
}
if (b != NULL) {
if (!BUF_MEM_grow(b, l + 1))
goto err;
p = &(b->data[lold]);
} else if (l > len) {
break;
} else
p = &(buf[lold]);
*(p++) = '/';
memcpy(p, s, (unsigned int)l1);
p += l1;
*(p++) = '=';
#ifndef CHARSET_EBCDIC /* q was assigned above already. */
q = ne->value->data;
#endif
for (j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
#ifndef CHARSET_EBCDIC
n = q[j];
if ((n < ' ') || (n > '~')) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else
*(p++) = n;
#else
n = os_toascii[q[j]];
if ((n < os_toascii[' ']) || (n > os_toascii['~'])) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else
*(p++) = q[j];
#endif
}
*p = '\0';
}
if (b != NULL) {
p = b->data;
OPENSSL_free(b);
} else
p = buf;
if (i == 0)
*p = '\0';
return (p);
err:
X509err(X509_F_X509_NAME_ONELINE, ERR_R_MALLOC_FAILURE);
end:
BUF_MEM_free(b);
return (NULL);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: PHP_MINFO_FUNCTION(openssl)
{
php_info_print_table_start();
php_info_print_table_row(2, "OpenSSL support", "enabled");
php_info_print_table_row(2, "OpenSSL Library Version", SSLeay_version(SSLEAY_VERSION));
php_info_print_table_row(2, "OpenSSL Header Version", OPENSSL_VERSION_TEXT);
php_info_print_table_row(2, "Openssl default config", default_ssl_conf_filename);
php_info_print_table_end();
DISPLAY_INI_ENTRIES();
}
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: static int db_interception(struct vcpu_svm *svm)
{
struct kvm_run *kvm_run = svm->vcpu.run;
if (!(svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
!svm->nmi_singlestep) {
kvm_queue_exception(&svm->vcpu, DB_VECTOR);
return 1;
}
if (svm->nmi_singlestep) {
svm->nmi_singlestep = false;
if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
svm->vmcb->save.rflags &=
~(X86_EFLAGS_TF | X86_EFLAGS_RF);
update_db_bp_intercept(&svm->vcpu);
}
if (svm->vcpu.guest_debug &
(KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
kvm_run->exit_reason = KVM_EXIT_DEBUG;
kvm_run->debug.arch.pc =
svm->vmcb->save.cs.base + svm->vmcb->save.rip;
kvm_run->debug.arch.exception = DB_VECTOR;
return 0;
}
return 1;
}
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: restore_page_device(i_ctx_t *i_ctx_p, const gs_gstate * pgs_old, const gs_gstate * pgs_new)
{
gx_device *dev_old = gs_currentdevice(pgs_old);
gx_device *dev_new;
gx_device *dev_t1;
gx_device *dev_t2;
bool samepagedevice = obj_eq(dev_old->memory, &gs_int_gstate(pgs_old)->pagedevice,
&gs_int_gstate(pgs_new)->pagedevice);
bool LockSafetyParams = dev_old->LockSafetyParams;
if ((dev_t1 = (*dev_proc(dev_old, get_page_device)) (dev_old)) == 0)
return 0;
/* If we are going to putdeviceparams in a callout, we need to */
/* unlock temporarily. The device will be re-locked as needed */
/* by putdeviceparams from the pgs_old->pagedevice dict state. */
if (!samepagedevice)
dev_old->LockSafetyParams = false;
dev_new = gs_currentdevice(pgs_new);
if (dev_old != dev_new) {
if ((dev_t2 = (*dev_proc(dev_new, get_page_device)) (dev_new)) == 0)
samepagedevice = true;
else if (dev_t1 != dev_t2)
samepagedevice = false;
}
if (LockSafetyParams && !samepagedevice) {
const int required_ops = 512;
const int required_es = 32;
/* The %grestorepagedevice must complete: the biggest danger
is operand stack overflow. As we use get/putdeviceparams
that means pushing all the device params onto the stack,
pdfwrite having by far the largest number of parameters
at (currently) 212 key/value pairs - thus needing (currently)
424 entries on the op stack. Allowing for working stack
space, and safety margin.....
*/
if (required_ops + ref_stack_count(&o_stack) >= ref_stack_max_count(&o_stack)) {
gs_currentdevice(pgs_old)->LockSafetyParams = LockSafetyParams;
return_error(gs_error_stackoverflow);
}
/* We also want enough exec stack space - 32 is an overestimate of
what we need to complete the Postscript call out.
*/
if (required_es + ref_stack_count(&e_stack) >= ref_stack_max_count(&e_stack)) {
gs_currentdevice(pgs_old)->LockSafetyParams = LockSafetyParams;
return_error(gs_error_execstackoverflow);
}
}
/*
* The current implementation of setpagedevice just sets new
* parameters in the same device object, so we have to check
* whether the page device dictionaries are the same.
*/
return samepagedevice ? 0 : 1;
}
CWE ID:
Target: 1
Example 2:
Code: Eina_Bool ewk_frame_feed_focus_out(Evas_Object* ewkFrame)
{
ERR("what to do?");
return false;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ResourceDispatcherHostImpl::OnDidChangePriority(
int request_id,
net::RequestPriority new_priority,
int intra_priority_value) {
ResourceLoader* loader = GetLoader(filter_->child_id(), request_id);
if (!loader)
return;
scheduler_->ReprioritizeRequest(loader->request(), new_priority,
intra_priority_value);
}
CWE ID: CWE-362
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct ucma_multicast* ucma_alloc_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc;
mc = kzalloc(sizeof(*mc), GFP_KERNEL);
if (!mc)
return NULL;
mutex_lock(&mut);
mc->id = idr_alloc(&multicast_idr, mc, 0, 0, GFP_KERNEL);
mutex_unlock(&mut);
if (mc->id < 0)
goto error;
mc->ctx = ctx;
list_add_tail(&mc->list, &ctx->mc_list);
return mc;
error:
kfree(mc);
return NULL;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
{
if (to_vmx(vcpu)->nested.nested_run_pending)
return 0;
if (!enable_vnmi &&
to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
return 0;
return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
(GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
| GUEST_INTR_STATE_NMI));
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool GLES2DecoderImpl::SimulateFixedAttribs(
GLuint max_vertex_accessed, bool* simulated) {
DCHECK(simulated);
*simulated = false;
if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2)
return true;
if (!vertex_attrib_manager_.HaveFixedAttribs()) {
return true;
}
int num_vertices = max_vertex_accessed + 1;
int elements_needed = 0;
const VertexAttribManager::VertexAttribInfoList& infos =
vertex_attrib_manager_.GetEnabledVertexAttribInfos();
for (VertexAttribManager::VertexAttribInfoList::const_iterator it =
infos.begin(); it != infos.end(); ++it) {
const VertexAttribManager::VertexAttribInfo* info = *it;
const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info =
current_program_->GetAttribInfoByLocation(info->index());
if (attrib_info &&
info->CanAccess(max_vertex_accessed) &&
info->type() == GL_FIXED) {
int elements_used = 0;
if (!SafeMultiply(
static_cast<int>(num_vertices),
info->size(), &elements_used) ||
!SafeAdd(elements_needed, elements_used, &elements_needed)) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: simulating GL_FIXED attribs");
return false;
}
}
}
const int kSizeOfFloat = sizeof(float); // NOLINT
int size_needed = 0;
if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed)) {
SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: simulating GL_FIXED attribs");
return false;
}
glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_);
if (size_needed > fixed_attrib_buffer_size_) {
glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW);
}
GLintptr offset = 0;
for (VertexAttribManager::VertexAttribInfoList::const_iterator it =
infos.begin(); it != infos.end(); ++it) {
const VertexAttribManager::VertexAttribInfo* info = *it;
const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info =
current_program_->GetAttribInfoByLocation(info->index());
if (attrib_info &&
info->CanAccess(max_vertex_accessed) &&
info->type() == GL_FIXED) {
int num_elements = info->size() * kSizeOfFloat;
int size = num_elements * num_vertices;
scoped_array<float> data(new float[size]);
const int32* src = reinterpret_cast<const int32 *>(
info->buffer()->GetRange(info->offset(), size));
const int32* end = src + num_elements;
float* dst = data.get();
while (src != end) {
*dst++ = static_cast<float>(*src++) / 65536.0f;
}
glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get());
glVertexAttribPointer(
info->index(), info->size(), GL_FLOAT, false, 0,
reinterpret_cast<GLvoid*>(offset));
offset += size;
}
}
*simulated = true;
return true;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
}
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: bool WebMediaPlayerMS::Paused() const {
DCHECK(thread_checker_.CalledOnValidThread());
return paused_;
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct nfs4_state *nfs4_do_open(struct inode *dir, struct dentry *dentry, fmode_t fmode, int flags, struct iattr *sattr, struct rpc_cred *cred)
{
struct nfs4_exception exception = { };
struct nfs4_state *res;
int status;
do {
status = _nfs4_do_open(dir, dentry, fmode, flags, sattr, cred, &res);
if (status == 0)
break;
/* NOTE: BAD_SEQID means the server and client disagree about the
* book-keeping w.r.t. state-changing operations
* (OPEN/CLOSE/LOCK/LOCKU...)
* It is actually a sign of a bug on the client or on the server.
*
* If we receive a BAD_SEQID error in the particular case of
* doing an OPEN, we assume that nfs_increment_open_seqid() will
* have unhashed the old state_owner for us, and that we can
* therefore safely retry using a new one. We should still warn
* the user though...
*/
if (status == -NFS4ERR_BAD_SEQID) {
printk(KERN_WARNING "NFS: v4 server %s "
" returned a bad sequence-id error!\n",
NFS_SERVER(dir)->nfs_client->cl_hostname);
exception.retry = 1;
continue;
}
/*
* BAD_STATEID on OPEN means that the server cancelled our
* state before it received the OPEN_CONFIRM.
* Recover by retrying the request as per the discussion
* on Page 181 of RFC3530.
*/
if (status == -NFS4ERR_BAD_STATEID) {
exception.retry = 1;
continue;
}
if (status == -EAGAIN) {
/* We must have found a delegation */
exception.retry = 1;
continue;
}
res = ERR_PTR(nfs4_handle_exception(NFS_SERVER(dir),
status, &exception));
} while (exception.retry);
return res;
}
CWE ID: CWE-189
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int fill_autodev(const struct lxc_rootfs *rootfs)
{
int ret;
char path[MAXPATHLEN];
int i;
mode_t cmask;
INFO("Creating initial consoles under container /dev");
ret = snprintf(path, MAXPATHLEN, "%s/dev", rootfs->path ? rootfs->mount : "");
if (ret < 0 || ret >= MAXPATHLEN) {
ERROR("Error calculating container /dev location");
return -1;
}
if (!dir_exists(path)) // ignore, just don't try to fill in
return 0;
INFO("Populating container /dev");
cmask = umask(S_IXUSR | S_IXGRP | S_IXOTH);
for (i = 0; i < sizeof(lxc_devs) / sizeof(lxc_devs[0]); i++) {
const struct lxc_devs *d = &lxc_devs[i];
ret = snprintf(path, MAXPATHLEN, "%s/dev/%s", rootfs->path ? rootfs->mount : "", d->name);
if (ret < 0 || ret >= MAXPATHLEN)
return -1;
ret = mknod(path, d->mode, makedev(d->maj, d->min));
if (ret && errno != EEXIST) {
char hostpath[MAXPATHLEN];
FILE *pathfile;
ret = snprintf(hostpath, MAXPATHLEN, "/dev/%s", d->name);
if (ret < 0 || ret >= MAXPATHLEN)
return -1;
pathfile = fopen(path, "wb");
if (!pathfile) {
SYSERROR("Failed to create device mount target '%s'", path);
return -1;
}
fclose(pathfile);
if (mount(hostpath, path, 0, MS_BIND, NULL) != 0) {
SYSERROR("Failed bind mounting device %s from host into container",
d->name);
return -1;
}
}
}
umask(cmask);
INFO("Populated container /dev");
return 0;
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: static void HTML_abort(HTStructured * me, HTError e)
{
char *include = NULL;
if (me->text) {
/*
* If we have emphasis on, or open A, FONT, or FORM containers, turn it
* off or close them now. - FM
*/
if (me->inUnderline) {
HText_appendCharacter(me->text, LY_UNDERLINE_END_CHAR);
me->inUnderline = FALSE;
me->Underline_Level = 0;
}
if (me->inA) {
HTML_end_element(me, HTML_A, &include);
me->inA = FALSE;
}
if (me->inFONT) {
HTML_end_element(me, HTML_FONT, &include);
me->inFONT = FALSE;
}
if (me->inFORM) {
HTML_end_element(me, HTML_FORM, &include);
me->inFORM = FALSE;
}
/*
* Now call the cleanup function. - FM
*/
HText_endAppend(me->text);
}
if (me->option.size > 0) {
/*
* If we still have data in the me->option chunk after forcing a close
* of a still-open form, something must have gone very wrong. - kw
*/
if (TRACE) {
CTRACE((tfp,
"HTML_abort: SELECT or OPTION not ended properly *****\n"));
HTChunkTerminate(&me->option);
CTRACE((tfp, "HTML_abort: ***** leftover option data: %s\n",
me->option.data));
}
HTChunkClear(&me->option);
}
if (me->textarea.size > 0) {
/*
* If we still have data in the me->textarea chunk after forcing a
* close of a still-open form, something must have gone very wrong. -
* kw
*/
if (TRACE) {
CTRACE((tfp, "HTML_abort: TEXTAREA not used properly *****\n"));
HTChunkTerminate(&me->textarea);
CTRACE((tfp, "HTML_abort: ***** leftover textarea data: %s\n",
me->textarea.data));
}
HTChunkClear(&me->textarea);
}
if (me->target) {
(*me->targetClass._abort) (me->target, e);
}
if (me->sp && me->sp->style && GetHTStyleName(me->sp->style)) {
if (me->sp->style->id == ST_DivCenter ||
me->sp->style->id == ST_HeadingCenter ||
me->sp->style->id == ST_Heading1) {
me->sp->style->alignment = HT_CENTER;
} else if (me->sp->style->id == ST_DivRight ||
me->sp->style->id == ST_HeadingRight) {
me->sp->style->alignment = HT_RIGHT;
} else {
me->sp->style->alignment = HT_LEFT;
}
styles[HTML_PRE]->alignment = HT_LEFT;
}
FREE(me->base_href);
FREE(me->map_address);
FREE(me->textarea_name);
FREE(me->textarea_accept_cs);
FREE(me->textarea_id);
FREE(me->LastOptionValue);
FREE(me->xinclude);
clear_objectdata(me);
FREE(me);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_,
long long& val) {
assert(pReader);
assert(pos >= 0);
long long total, available;
const long status = pReader->Length(&total, &available);
assert(status >= 0);
assert((total < 0) || (available <= total));
if (status < 0)
return false;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
if ((unsigned long)id != id_)
return false;
pos += len; // consume id
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert(size <= 8);
assert(len > 0);
assert(len <= 8);
assert((pos + len) <= available);
pos += len; // consume length of size of payload
val = UnserializeUInt(pReader, pos, size);
assert(val >= 0);
pos += size; // consume size of payload
return true;
}
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: long long Chapters::Atom::GetStartTimecode() const
{
return m_start_timecode;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ip_mc_leave_src(struct sock *sk, struct ip_mc_socklist *iml,
struct in_device *in_dev)
{
struct ip_sf_socklist *psf = rtnl_dereference(iml->sflist);
int err;
if (psf == NULL) {
/* any-source empty exclude case */
return ip_mc_del_src(in_dev, &iml->multi.imr_multiaddr.s_addr,
iml->sfmode, 0, NULL, 0);
}
err = ip_mc_del_src(in_dev, &iml->multi.imr_multiaddr.s_addr,
iml->sfmode, psf->sl_count, psf->sl_addr, 0);
RCU_INIT_POINTER(iml->sflist, NULL);
/* decrease mem now to avoid the memleak warning */
atomic_sub(IP_SFLSIZE(psf->sl_max), &sk->sk_omem_alloc);
kfree_rcu(psf, rcu);
return err;
}
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: png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
png_size_t png_struct_size)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* to save current jump buffer */
#endif
int i = 0;
png_structp png_ptr=*ptr_ptr;
if (png_ptr == NULL)
return;
do
{
if (user_png_ver[i] != png_libpng_ver[i])
{
#ifdef PNG_LEGACY_SUPPORTED
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
#else
png_ptr->warning_fn = NULL;
png_warning(png_ptr,
"Application uses deprecated png_read_init() and should be"
" recompiled.");
break;
#endif
}
} while (png_libpng_ver[i++]);
png_debug(1, "in png_read_init_3");
#ifdef PNG_SETJMP_SUPPORTED
/* Save jump buffer and error functions */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
if (png_sizeof(png_struct) > png_struct_size)
{
png_destroy_struct(png_ptr);
*ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
png_ptr = *ptr_ptr;
}
/* Reset all variables to 0 */
png_memset(png_ptr, 0, png_sizeof(png_struct));
#ifdef PNG_SETJMP_SUPPORTED
/* Restore jump buffer */
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
/* Added at libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
png_ptr->user_width_max = PNG_USER_WIDTH_MAX;
png_ptr->user_height_max = PNG_USER_HEIGHT_MAX;
#endif
/* Initialize zbuf - compression buffer */
png_ptr->zbuf_size = PNG_ZBUF_SIZE;
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zstream.zfree = png_zfree;
png_ptr->zstream.opaque = (voidpf)png_ptr;
switch (inflateInit(&png_ptr->zstream))
{
case Z_OK: /* Do nothing */ break;
case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error");
break;
default: png_error(png_ptr, "Unknown zlib error");
}
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::unique_ptr<content::BluetoothChooser> Browser::RunBluetoothChooser(
content::RenderFrameHost* frame,
const content::BluetoothChooser::EventHandler& event_handler) {
std::unique_ptr<BluetoothChooserController> bluetooth_chooser_controller(
new BluetoothChooserController(frame, event_handler));
std::unique_ptr<BluetoothChooserDesktop> bluetooth_chooser_desktop(
new BluetoothChooserDesktop(bluetooth_chooser_controller.get()));
std::unique_ptr<ChooserBubbleDelegate> chooser_bubble_delegate(
new ChooserBubbleDelegate(frame,
std::move(bluetooth_chooser_controller)));
Browser* browser = chrome::FindBrowserWithWebContents(
WebContents::FromRenderFrameHost(frame));
BubbleReference bubble_reference = browser->GetBubbleManager()->ShowBubble(
std::move(chooser_bubble_delegate));
return std::move(bluetooth_chooser_desktop);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: perf_event_alloc(struct perf_event_attr *attr, int cpu,
struct task_struct *task,
struct perf_event *group_leader,
struct perf_event *parent_event,
perf_overflow_handler_t overflow_handler,
void *context)
{
struct pmu *pmu;
struct perf_event *event;
struct hw_perf_event *hwc;
long err;
if ((unsigned)cpu >= nr_cpu_ids) {
if (!task || cpu != -1)
return ERR_PTR(-EINVAL);
}
event = kzalloc(sizeof(*event), GFP_KERNEL);
if (!event)
return ERR_PTR(-ENOMEM);
/*
* Single events are their own group leaders, with an
* empty sibling list:
*/
if (!group_leader)
group_leader = event;
mutex_init(&event->child_mutex);
INIT_LIST_HEAD(&event->child_list);
INIT_LIST_HEAD(&event->group_entry);
INIT_LIST_HEAD(&event->event_entry);
INIT_LIST_HEAD(&event->sibling_list);
INIT_LIST_HEAD(&event->rb_entry);
init_waitqueue_head(&event->waitq);
init_irq_work(&event->pending, perf_pending_event);
mutex_init(&event->mmap_mutex);
atomic_long_set(&event->refcount, 1);
event->cpu = cpu;
event->attr = *attr;
event->group_leader = group_leader;
event->pmu = NULL;
event->oncpu = -1;
event->parent = parent_event;
event->ns = get_pid_ns(task_active_pid_ns(current));
event->id = atomic64_inc_return(&perf_event_id);
event->state = PERF_EVENT_STATE_INACTIVE;
if (task) {
event->attach_state = PERF_ATTACH_TASK;
if (attr->type == PERF_TYPE_TRACEPOINT)
event->hw.tp_target = task;
#ifdef CONFIG_HAVE_HW_BREAKPOINT
/*
* hw_breakpoint is a bit difficult here..
*/
else if (attr->type == PERF_TYPE_BREAKPOINT)
event->hw.bp_target = task;
#endif
}
if (!overflow_handler && parent_event) {
overflow_handler = parent_event->overflow_handler;
context = parent_event->overflow_handler_context;
}
event->overflow_handler = overflow_handler;
event->overflow_handler_context = context;
perf_event__state_init(event);
pmu = NULL;
hwc = &event->hw;
hwc->sample_period = attr->sample_period;
if (attr->freq && attr->sample_freq)
hwc->sample_period = 1;
hwc->last_period = hwc->sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
/*
* we currently do not support PERF_FORMAT_GROUP on inherited events
*/
if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
goto done;
pmu = perf_init_event(event);
done:
err = 0;
if (!pmu)
err = -EINVAL;
else if (IS_ERR(pmu))
err = PTR_ERR(pmu);
if (err) {
if (event->ns)
put_pid_ns(event->ns);
kfree(event);
return ERR_PTR(err);
}
if (!event->parent) {
if (event->attach_state & PERF_ATTACH_TASK)
static_key_slow_inc(&perf_sched_events.key);
if (event->attr.mmap || event->attr.mmap_data)
atomic_inc(&nr_mmap_events);
if (event->attr.comm)
atomic_inc(&nr_comm_events);
if (event->attr.task)
atomic_inc(&nr_task_events);
if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
err = get_callchain_buffers();
if (err) {
free_event(event);
return ERR_PTR(err);
}
}
if (has_branch_stack(event)) {
static_key_slow_inc(&perf_sched_events.key);
if (!(event->attach_state & PERF_ATTACH_TASK))
atomic_inc(&per_cpu(perf_branch_stack_events,
event->cpu));
}
}
return 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: void MediaStreamManager::GenerateStream(
int render_process_id,
int render_frame_id,
int page_request_id,
const StreamControls& controls,
MediaDeviceSaltAndOrigin salt_and_origin,
bool user_gesture,
GenerateStreamCallback generate_stream_cb,
DeviceStoppedCallback device_stopped_cb,
DeviceChangedCallback device_changed_cb) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DVLOG(1) << "GenerateStream()";
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, page_request_id, user_gesture,
MEDIA_GENERATE_STREAM, controls, std::move(salt_and_origin),
std::move(device_stopped_cb));
request->device_changed_cb = std::move(device_changed_cb);
const std::string& label = AddRequest(request);
request->generate_stream_cb = std::move(generate_stream_cb);
if (generate_stream_test_callback_) {
if (std::move(generate_stream_test_callback_).Run(controls)) {
FinalizeGenerateStream(label, request);
} else {
FinalizeRequestFailed(label, request, MEDIA_DEVICE_INVALID_STATE);
}
return;
}
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
}
CWE ID: CWE-189
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int sctp_process_param(struct sctp_association *asoc,
union sctp_params param,
const union sctp_addr *peer_addr,
gfp_t gfp)
{
struct net *net = sock_net(asoc->base.sk);
union sctp_addr addr;
int i;
__u16 sat;
int retval = 1;
sctp_scope_t scope;
time_t stale;
struct sctp_af *af;
union sctp_addr_param *addr_param;
struct sctp_transport *t;
struct sctp_endpoint *ep = asoc->ep;
/* We maintain all INIT parameters in network byte order all the
* time. This allows us to not worry about whether the parameters
* came from a fresh INIT, and INIT ACK, or were stored in a cookie.
*/
switch (param.p->type) {
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 != asoc->base.sk->sk_family)
break;
goto do_addr_param;
case SCTP_PARAM_IPV4_ADDRESS:
/* v4 addresses are not allowed on v6-only socket */
if (ipv6_only_sock(asoc->base.sk))
break;
do_addr_param:
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0);
scope = sctp_scope(peer_addr);
if (sctp_in_scope(net, &addr, scope))
if (!sctp_assoc_add_peer(asoc, &addr, gfp, SCTP_UNCONFIRMED))
return 0;
break;
case SCTP_PARAM_COOKIE_PRESERVATIVE:
if (!net->sctp.cookie_preserve_enable)
break;
stale = ntohl(param.life->lifespan_increment);
/* Suggested Cookie Life span increment's unit is msec,
* (1/1000sec).
*/
asoc->cookie_life = ktime_add_ms(asoc->cookie_life, stale);
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
pr_debug("%s: unimplemented SCTP_HOST_NAME_ADDRESS\n", __func__);
break;
case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
/* Turn off the default values first so we'll know which
* ones are really set by the peer.
*/
asoc->peer.ipv4_address = 0;
asoc->peer.ipv6_address = 0;
/* Assume that peer supports the address family
* by which it sends a packet.
*/
if (peer_addr->sa.sa_family == AF_INET6)
asoc->peer.ipv6_address = 1;
else if (peer_addr->sa.sa_family == AF_INET)
asoc->peer.ipv4_address = 1;
/* Cycle through address types; avoid divide by 0. */
sat = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
if (sat)
sat /= sizeof(__u16);
for (i = 0; i < sat; ++i) {
switch (param.sat->types[i]) {
case SCTP_PARAM_IPV4_ADDRESS:
asoc->peer.ipv4_address = 1;
break;
case SCTP_PARAM_IPV6_ADDRESS:
if (PF_INET6 == asoc->base.sk->sk_family)
asoc->peer.ipv6_address = 1;
break;
case SCTP_PARAM_HOST_NAME_ADDRESS:
asoc->peer.hostname_address = 1;
break;
default: /* Just ignore anything else. */
break;
}
}
break;
case SCTP_PARAM_STATE_COOKIE:
asoc->peer.cookie_len =
ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
asoc->peer.cookie = param.cookie->body;
break;
case SCTP_PARAM_HEARTBEAT_INFO:
/* Would be odd to receive, but it causes no problems. */
break;
case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
/* Rejected during verify stage. */
break;
case SCTP_PARAM_ECN_CAPABLE:
asoc->peer.ecn_capable = 1;
break;
case SCTP_PARAM_ADAPTATION_LAYER_IND:
asoc->peer.adaptation_ind = ntohl(param.aind->adaptation_ind);
break;
case SCTP_PARAM_SET_PRIMARY:
if (!net->sctp.addip_enable)
goto fall_through;
addr_param = param.v + sizeof(sctp_addip_param_t);
af = sctp_get_af_specific(param_type2af(param.p->type));
af->from_addr_param(&addr, addr_param,
htons(asoc->peer.port), 0);
/* if the address is invalid, we can't process it.
* XXX: see spec for what to do.
*/
if (!af->addr_valid(&addr, NULL, NULL))
break;
t = sctp_assoc_lookup_paddr(asoc, &addr);
if (!t)
break;
sctp_assoc_set_primary(asoc, t);
break;
case SCTP_PARAM_SUPPORTED_EXT:
sctp_process_ext_param(asoc, param);
break;
case SCTP_PARAM_FWD_TSN_SUPPORT:
if (net->sctp.prsctp_enable) {
asoc->peer.prsctp_capable = 1;
break;
}
/* Fall Through */
goto fall_through;
case SCTP_PARAM_RANDOM:
if (!ep->auth_enable)
goto fall_through;
/* Save peer's random parameter */
asoc->peer.peer_random = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_random) {
retval = 0;
break;
}
break;
case SCTP_PARAM_HMAC_ALGO:
if (!ep->auth_enable)
goto fall_through;
/* Save peer's HMAC list */
asoc->peer.peer_hmacs = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_hmacs) {
retval = 0;
break;
}
/* Set the default HMAC the peer requested*/
sctp_auth_asoc_set_default_hmac(asoc, param.hmac_algo);
break;
case SCTP_PARAM_CHUNKS:
if (!ep->auth_enable)
goto fall_through;
asoc->peer.peer_chunks = kmemdup(param.p,
ntohs(param.p->length), gfp);
if (!asoc->peer.peer_chunks)
retval = 0;
break;
fall_through:
default:
/* Any unrecognized parameters should have been caught
* and handled by sctp_verify_param() which should be
* called prior to this routine. Simply log the error
* here.
*/
pr_debug("%s: ignoring param:%d for association:%p.\n",
__func__, ntohs(param.p->type), asoc);
break;
}
return retval;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int DecodeIPV6FragTest01 (void)
{
uint8_t raw_frag1[] = {
0x60, 0x0f, 0x1a, 0xcf, 0x05, 0xa8, 0x2c, 0x36, 0x20, 0x01, 0x04, 0x70, 0x00, 0x01, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x20, 0x01, 0x09, 0x80, 0x32, 0xb2, 0x00, 0x01,
0x2e, 0x41, 0x38, 0xff, 0xfe, 0xa7, 0xea, 0xeb, 0x06, 0x00, 0x00, 0x01, 0xdf, 0xf8, 0x11, 0xd7,
0x00, 0x50, 0xa6, 0x5c, 0xcc, 0xd7, 0x28, 0x9f, 0xc3, 0x34, 0xc6, 0x58, 0x80, 0x10, 0x20, 0x13,
0x18, 0x1f, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0xcd, 0xf9, 0x3a, 0x41, 0x00, 0x1a, 0x91, 0x8a,
0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x20, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x0d,
0x0a, 0x44, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x30, 0x32, 0x20, 0x44,
0x65, 0x63, 0x20, 0x32, 0x30, 0x31, 0x31, 0x20, 0x30, 0x38, 0x3a, 0x33, 0x32, 0x3a, 0x35, 0x37,
0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x41, 0x70,
0x61, 0x63, 0x68, 0x65, 0x0d, 0x0a, 0x43, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x43, 0x6f, 0x6e, 0x74,
0x72, 0x6f, 0x6c, 0x3a, 0x20, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x0d, 0x0a, 0x50,
0x72, 0x61, 0x67, 0x6d, 0x61, 0x3a, 0x20, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x0d,
0x0a, 0x45, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x3a, 0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x30,
0x31, 0x20, 0x4a, 0x61, 0x6e, 0x20, 0x31, 0x39, 0x37, 0x31, 0x20, 0x30, 0x30, 0x3a, 0x30, 0x30,
0x3a, 0x30, 0x30, 0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x31, 0x35, 0x39, 0x39, 0x0d, 0x0a, 0x4b,
0x65, 0x65, 0x70, 0x2d, 0x41, 0x6c, 0x69, 0x76, 0x65, 0x3a, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x6f,
0x75, 0x74, 0x3d, 0x35, 0x2c, 0x20, 0x6d, 0x61, 0x78, 0x3d, 0x39, 0x39, 0x0d, 0x0a, 0x43, 0x6f,
0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x4b, 0x65, 0x65, 0x70, 0x2d, 0x41,
0x6c, 0x69, 0x76, 0x65, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79,
0x70, 0x65, 0x3a, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f,
0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3b, 0x63, 0x68, 0x61, 0x72, 0x73,
0x65, 0x74, 0x3d, 0x61, 0x73, 0x63, 0x69, 0x69, 0x0d, 0x0a, 0x0d, 0x0a, 0x5f, 0x6a, 0x71, 0x6a,
0x73, 0x70, 0x28, 0x7b, 0x22, 0x69, 0x70, 0x22, 0x3a, 0x22, 0x32, 0x30, 0x30, 0x31, 0x3a, 0x39,
0x38, 0x30, 0x3a, 0x33, 0x32, 0x62, 0x32, 0x3a, 0x31, 0x3a, 0x32, 0x65, 0x34, 0x31, 0x3a, 0x33,
0x38, 0x66, 0x66, 0x3a, 0x66, 0x65, 0x61, 0x37, 0x3a, 0x65, 0x61, 0x65, 0x62, 0x22, 0x2c, 0x22,
0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x22, 0x69, 0x70, 0x76, 0x36, 0x22, 0x2c, 0x22, 0x73, 0x75,
0x62, 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x22, 0x22, 0x2c, 0x22, 0x76, 0x69, 0x61, 0x22, 0x3a,
0x22, 0x22, 0x2c, 0x22, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x22, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
};
uint8_t raw_frag2[] = {
0x60, 0x0f, 0x1a, 0xcf, 0x00, 0x1c, 0x2c, 0x36, 0x20, 0x01, 0x04, 0x70, 0x00, 0x01, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x20, 0x01, 0x09, 0x80, 0x32, 0xb2, 0x00, 0x01,
0x2e, 0x41, 0x38, 0xff, 0xfe, 0xa7, 0xea, 0xeb, 0x06, 0x00, 0x05, 0xa0, 0xdf, 0xf8, 0x11, 0xd7,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20,
};
Packet *pkt;
Packet *p1 = PacketGetFromAlloc();
if (unlikely(p1 == NULL))
return 0;
Packet *p2 = PacketGetFromAlloc();
if (unlikely(p2 == NULL)) {
SCFree(p1);
return 0;
}
ThreadVars tv;
DecodeThreadVars dtv;
int result = 0;
PacketQueue pq;
FlowInitConfig(FLOW_QUIET);
DefragInit();
memset(&pq, 0, sizeof(PacketQueue));
memset(&tv, 0, sizeof(ThreadVars));
memset(&dtv, 0, sizeof(DecodeThreadVars));
PacketCopyData(p1, raw_frag1, sizeof(raw_frag1));
PacketCopyData(p2, raw_frag2, sizeof(raw_frag2));
DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1), &pq);
if (!(IPV6_EXTHDR_ISSET_FH(p1))) {
printf("ipv6 frag header not detected: ");
goto end;
}
DecodeIPV6(&tv, &dtv, p2, GET_PKT_DATA(p2), GET_PKT_LEN(p2), &pq);
if (!(IPV6_EXTHDR_ISSET_FH(p2))) {
printf("ipv6 frag header not detected: ");
goto end;
}
if (pq.len != 1) {
printf("no reassembled packet: ");
goto end;
}
result = 1;
end:
PACKET_RECYCLE(p1);
PACKET_RECYCLE(p2);
SCFree(p1);
SCFree(p2);
pkt = PacketDequeue(&pq);
while (pkt != NULL) {
PACKET_RECYCLE(pkt);
SCFree(pkt);
pkt = PacketDequeue(&pq);
}
DefragDestroy();
FlowShutdown();
return result;
}
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 M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M_fs_file_mode_t mode, M_fs_progress_cb_t cb, M_fs_progress_flags_t progress_flags, M_fs_progress_t *progress, const M_fs_perms_t *perms)
{
M_fs_file_t *fd_old;
M_fs_file_t *fd_new;
M_fs_info_t *info = NULL;
unsigned char temp[M_FS_BUF_SIZE];
size_t read_len;
size_t wrote_len;
size_t wrote_total = 0;
size_t offset;
M_fs_error_t res;
/* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it
* to new file. */
if (M_fs_perms_can_access(path_new, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) {
/* Try to delete the file since we'll be overwrite it. This is so when we create the file we create it without
* any permissions and to ensure that anything that has the file already open won't be able to read the new
* contents we're writing to the file or be able to change the perms. There is an unavoidable race condition
* between deleting and creating the file where someone could create the file and have access. However,
* depending on the OS they may have access even if the file is created with no perms... */
res = M_fs_delete(path_new, M_FALSE, NULL, M_FS_PROGRESS_NOEXTRA);
if (res != M_FS_ERROR_SUCCESS) {
return res;
}
}
/* Open the old file */
res = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL);
if (res != M_FS_ERROR_SUCCESS) {
return res;
}
if (perms == NULL && mode & M_FS_FILE_MODE_PRESERVE_PERMS) {
res = M_fs_info_file(&info, fd_old, M_FS_PATH_INFO_FLAGS_NONE);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_file_close(fd_old);
return res;
}
perms = M_fs_info_get_perms(info);
}
res = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms);
M_fs_info_destroy(info);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_file_close(fd_old);
return res;
}
/* Copy the contents of old into new. */
while ((res = M_fs_file_read(fd_old, temp, sizeof(temp), &read_len, M_FS_FILE_RW_NORMAL)) == M_FS_ERROR_SUCCESS && read_len != 0) {
offset = 0;
while (offset < read_len) {
res = M_fs_file_write(fd_new, temp+offset, read_len-offset, &wrote_len, M_FS_FILE_RW_NORMAL);
offset += wrote_len;
wrote_total += wrote_len;
if (cb) {
M_fs_progress_set_result(progress, res);
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total_progess(progress, M_fs_progress_get_size_total_progess(progress)+wrote_len);
}
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current_progress(progress, wrote_total);
}
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1);
}
if (!cb(progress)) {
res = M_FS_ERROR_CANCELED;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
M_fs_file_close(fd_old);
M_fs_file_close(fd_new);
if (res != M_FS_ERROR_SUCCESS) {
return res;
}
return M_FS_ERROR_SUCCESS;
}
CWE ID: CWE-732
Output:
| 1 |
Here are some example code snippets. Analyze the following 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 xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx)
{
struct xenvif *vif;
struct pending_tx_info *pending_tx_info;
pending_ring_idx_t index;
/* Already complete? */
if (netbk->mmap_pages[pending_idx] == NULL)
return;
pending_tx_info = &netbk->pending_tx_info[pending_idx];
vif = pending_tx_info->vif;
make_tx_response(vif, &pending_tx_info->req, XEN_NETIF_RSP_OKAY);
index = pending_index(netbk->pending_prod++);
netbk->pending_ring[index] = pending_idx;
xenvif_put(vif);
netbk->mmap_pages[pending_idx]->mapping = 0;
put_page(netbk->mmap_pages[pending_idx]);
netbk->mmap_pages[pending_idx] = NULL;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool got_user_gesture() const {
return got_user_gesture_;
}
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: virtual size_t GetNumActiveInputMethods() {
scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods());
return input_methods->size();
}
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 WriteProfile(j_compress_ptr jpeg_info,Image *image)
{
const char
*name;
const StringInfo
*profile;
MagickBooleanType
iptc;
register ssize_t
i;
size_t
length,
tag_length;
StringInfo
*custom_profile;
/*
Save image profile as a APP marker.
*/
iptc=MagickFalse;
custom_profile=AcquireStringInfo(65535L);
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
register unsigned char
*p;
profile=GetImageProfile(image,name);
p=GetStringInfoDatum(custom_profile);
if (LocaleCompare(name,"EXIF") == 0)
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65533L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65533L);
jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile)+i,
(unsigned int) length);
}
if (LocaleCompare(name,"ICC") == 0)
{
register unsigned char
*p;
tag_length=strlen(ICC_PROFILE);
p=GetStringInfoDatum(custom_profile);
(void) CopyMagickMemory(p,ICC_PROFILE,tag_length);
p[tag_length]='\0';
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65519L);
p[12]=(unsigned char) ((i/65519L)+1);
p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1);
(void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i,
length);
jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum(
custom_profile),(unsigned int) (length+tag_length+3));
}
}
if (((LocaleCompare(name,"IPTC") == 0) ||
(LocaleCompare(name,"8BIM") == 0)) && (iptc == MagickFalse))
{
size_t
roundup;
iptc=MagickTrue;
for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L)
{
length=MagickMin(GetStringInfoLength(profile)-i,65500L);
roundup=(size_t) (length & 0x01);
if (LocaleNCompare((char *) GetStringInfoDatum(profile),"8BIM",4) == 0)
{
(void) memcpy(p,"Photoshop 3.0 ",14);
tag_length=14;
}
else
{
(void) CopyMagickMemory(p,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24);
tag_length=26;
p[24]=(unsigned char) (length >> 8);
p[25]=(unsigned char) (length & 0xff);
}
p[13]=0x00;
(void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length);
if (roundup != 0)
p[length+tag_length]='\0';
jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum(
custom_profile),(unsigned int) (length+tag_length+roundup));
}
}
if (LocaleCompare(name,"XMP") == 0)
{
StringInfo
*xmp_profile;
/*
Add namespace to XMP profile.
*/
xmp_profile=StringToStringInfo("http://ns.adobe.com/xap/1.0/ ");
if (xmp_profile != (StringInfo *) NULL)
{
if (profile != (StringInfo *) NULL)
ConcatenateStringInfo(xmp_profile,profile);
GetStringInfoDatum(xmp_profile)[28]='\0';
for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L)
{
length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L);
jpeg_write_marker(jpeg_info,XML_MARKER,
GetStringInfoDatum(xmp_profile)+i,(unsigned int) length);
}
xmp_profile=DestroyStringInfo(xmp_profile);
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"%s profile: %.20g bytes",name,(double) GetStringInfoLength(profile));
name=GetNextImageProfile(image);
}
custom_profile=DestroyStringInfo(custom_profile);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void HttpProxyClientSocket::SetSubresourceSpeculation() {
if (transport_.get() && transport_->socket()) {
transport_->socket()->SetSubresourceSpeculation();
} else {
NOTREACHED();
}
}
CWE ID: CWE-19
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 PasswordAutofillAgent::WasFormStructureChanged(
const FormStructureInfo& form_info) const {
if (form_info.unique_renderer_id == FormData::kNotSetFormRendererId)
return true;
auto cached_form = forms_structure_cache_.find(form_info.unique_renderer_id);
if (cached_form == forms_structure_cache_.end())
return true;
const FormStructureInfo& cached_form_info = cached_form->second;
if (form_info.fields.size() != cached_form_info.fields.size())
return true;
for (size_t i = 0; i < form_info.fields.size(); ++i) {
const FormFieldInfo& form_field = form_info.fields[i];
const FormFieldInfo& cached_form_field = cached_form_info.fields[i];
if (form_field.unique_renderer_id != cached_form_field.unique_renderer_id)
return true;
if (form_field.form_control_type != cached_form_field.form_control_type)
return true;
if (form_field.autocomplete_attribute !=
cached_form_field.autocomplete_attribute) {
return true;
}
if (form_field.is_focusable != cached_form_field.is_focusable)
return true;
}
return false;
}
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: do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
unsigned char arg[128];
int ret = 0;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (*len < get_arglen[GET_CMDID(cmd)]) {
pr_err("get_ctl: len %u < %u\n",
*len, get_arglen[GET_CMDID(cmd)]);
return -EINVAL;
}
if (copy_from_user(arg, user, get_arglen[GET_CMDID(cmd)]) != 0)
return -EFAULT;
if (mutex_lock_interruptible(&__ip_vs_mutex))
return -ERESTARTSYS;
switch (cmd) {
case IP_VS_SO_GET_VERSION:
{
char buf[64];
sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
NVERSION(IP_VS_VERSION_CODE), IP_VS_CONN_TAB_SIZE);
if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
ret = -EFAULT;
goto out;
}
*len = strlen(buf)+1;
}
break;
case IP_VS_SO_GET_INFO:
{
struct ip_vs_getinfo info;
info.version = IP_VS_VERSION_CODE;
info.size = IP_VS_CONN_TAB_SIZE;
info.num_services = ip_vs_num_services;
if (copy_to_user(user, &info, sizeof(info)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_SERVICES:
{
struct ip_vs_get_services *get;
int size;
get = (struct ip_vs_get_services *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_service_entry) * get->num_services;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_service_entries(get, user);
}
break;
case IP_VS_SO_GET_SERVICE:
{
struct ip_vs_service_entry *entry;
struct ip_vs_service *svc;
union nf_inet_addr addr;
entry = (struct ip_vs_service_entry *)arg;
addr.ip = entry->addr;
if (entry->fwmark)
svc = __ip_vs_svc_fwm_get(AF_INET, entry->fwmark);
else
svc = __ip_vs_service_get(AF_INET, entry->protocol,
&addr, entry->port);
if (svc) {
ip_vs_copy_service(entry, svc);
if (copy_to_user(user, entry, sizeof(*entry)) != 0)
ret = -EFAULT;
ip_vs_service_put(svc);
} else
ret = -ESRCH;
}
break;
case IP_VS_SO_GET_DESTS:
{
struct ip_vs_get_dests *get;
int size;
get = (struct ip_vs_get_dests *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_dest_entry) * get->num_dests;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_dest_entries(get, user);
}
break;
case IP_VS_SO_GET_TIMEOUT:
{
struct ip_vs_timeout_user t;
__ip_vs_get_timeouts(&t);
if (copy_to_user(user, &t, sizeof(t)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_DAEMON:
{
struct ip_vs_daemon_user d[2];
memset(&d, 0, sizeof(d));
if (ip_vs_sync_state & IP_VS_STATE_MASTER) {
d[0].state = IP_VS_STATE_MASTER;
strlcpy(d[0].mcast_ifn, ip_vs_master_mcast_ifn, sizeof(d[0].mcast_ifn));
d[0].syncid = ip_vs_master_syncid;
}
if (ip_vs_sync_state & IP_VS_STATE_BACKUP) {
d[1].state = IP_VS_STATE_BACKUP;
strlcpy(d[1].mcast_ifn, ip_vs_backup_mcast_ifn, sizeof(d[1].mcast_ifn));
d[1].syncid = ip_vs_backup_syncid;
}
if (copy_to_user(user, &d, sizeof(d)) != 0)
ret = -EFAULT;
}
break;
default:
ret = -EINVAL;
}
out:
mutex_unlock(&__ip_vs_mutex);
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: nfs41_free_lock_state(struct nfs_server *server, struct nfs4_lock_state *lsp)
{
struct rpc_task *task;
struct rpc_cred *cred = lsp->ls_state->owner->so_cred;
task = _nfs41_free_stateid(server, &lsp->ls_stateid, cred, false);
nfs4_free_lock_state(server, lsp);
if (IS_ERR(task))
return;
rpc_put_task(task);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void parse_input(h2o_http2_conn_t *conn)
{
size_t http2_max_concurrent_requests_per_connection = conn->super.ctx->globalconf->http2.max_concurrent_requests_per_connection;
int perform_early_exit = 0;
if (conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed != http2_max_concurrent_requests_per_connection)
perform_early_exit = 1;
/* handle the input */
while (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && conn->sock->input->size != 0) {
if (perform_early_exit == 1 &&
conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed == http2_max_concurrent_requests_per_connection)
goto EarlyExit;
/* process a frame */
const char *err_desc = NULL;
ssize_t ret = conn->_read_expect(conn, (uint8_t *)conn->sock->input->bytes, conn->sock->input->size, &err_desc);
if (ret == H2O_HTTP2_ERROR_INCOMPLETE) {
break;
} else if (ret < 0) {
if (ret != H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY) {
enqueue_goaway(conn, (int)ret,
err_desc != NULL ? (h2o_iovec_t){(char *)err_desc, strlen(err_desc)} : (h2o_iovec_t){});
}
close_connection(conn);
return;
}
/* advance to the next frame */
h2o_buffer_consume(&conn->sock->input, ret);
}
if (!h2o_socket_is_reading(conn->sock))
h2o_socket_read_start(conn->sock, on_read);
return;
EarlyExit:
if (h2o_socket_is_reading(conn->sock))
h2o_socket_read_stop(conn->sock);
}
CWE ID:
Output:
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.