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 void save_text_if_changed(const char *name, const char *new_value)
{
/* a text value can't be change if the file is not loaded */
/* returns NULL if the name is not found; otherwise nonzero */
if (!g_hash_table_lookup(g_loaded_texts, name))
return;
const char *old_value = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : "";
if (!old_value)
old_value = "";
if (strcmp(new_value, old_value) != 0)
{
struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name);
if (dd)
dd_save_text(dd, name, new_value);
dd_close(dd);
problem_data_reload_from_dump_dir();
update_gui_state_from_problem_data(/* don't update selected event */ 0);
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool AppCacheBackendImpl::SetSpawningHostId(
int host_id,
int spawning_host_id) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
host->SetSpawningHostId(process_id_, spawning_host_id);
return true;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nlmsg_populate_mdb_fill(struct sk_buff *skb,
struct net_device *dev,
struct br_mdb_entry *entry, u32 pid,
u32 seq, int type, unsigned int flags)
{
struct nlmsghdr *nlh;
struct br_port_msg *bpm;
struct nlattr *nest, *nest2;
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*bpm), NLM_F_MULTI);
if (!nlh)
return -EMSGSIZE;
bpm = nlmsg_data(nlh);
bpm->family = AF_BRIDGE;
bpm->ifindex = dev->ifindex;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
goto cancel;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL)
goto end;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(*entry), entry))
goto end;
nla_nest_end(skb, nest2);
nla_nest_end(skb, nest);
return nlmsg_end(skb, nlh);
end:
nla_nest_end(skb, nest);
cancel:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
CWE ID: CWE-399
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: image_transform_png_set_expand_16_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
/* expand_16 does something unless the bit depth is already 16. */
return bit_depth < 16;
}
CWE ID:
Target: 1
Example 2:
Code: void ThreadHeap::Compact() {
if (!Compaction()->IsCompacting())
return;
Compaction()->StartThreadCompaction();
for (int i = BlinkGC::kHashTableArenaIndex; i >= BlinkGC::kVector1ArenaIndex;
--i)
static_cast<NormalPageArena*>(arenas_[i])->SweepAndCompact();
Compaction()->FinishThreadCompaction();
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void copyIPv6IfDifferent(void * dest, const void * src)
{
if(dest != src) {
memcpy(dest, src, sizeof(struct in6_addr));
}
}
CWE ID: CWE-476
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PageSerializer::addImageToResources(ImageResource* image, RenderObject* imageRenderer, const KURL& url)
{
if (!shouldAddURL(url))
return;
if (!image || !image->hasImage() || image->image() == Image::nullImage())
return;
RefPtr<SharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
if (!data)
data = image->image()->data();
addToResources(image, data, url);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void OmniboxViewViews::DoInsertChar(base::char16 ch) {
if (insert_char_time_.is_null()) {
DCHECK_EQ(latency_histogram_state_, NOT_ACTIVE);
latency_histogram_state_ = CHAR_TYPED;
insert_char_time_ = base::TimeTicks::Now();
}
Textfield::DoInsertChar(ch);
}
CWE ID: CWE-79
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: pvscsi_log2(uint32_t input)
{
int log = 0;
assert(input > 0);
while (input >> ++log) {
}
return log;
}
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 WebGL2RenderingContextBase::texSubImage2D(GLenum target,
GLint level,
GLint xoffset,
GLint yoffset,
GLsizei width,
GLsizei height,
GLenum format,
GLenum type,
GLintptr offset) {
if (isContextLost())
return;
if (!ValidateTexture2DBinding("texSubImage2D", target))
return;
if (!bound_pixel_unpack_buffer_) {
SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage2D",
"no bound PIXEL_UNPACK_BUFFER");
return;
}
if (!ValidateTexFunc("texSubImage2D", kTexSubImage, kSourceUnpackBuffer,
target, level, 0, width, height, 1, 0, format, type,
xoffset, yoffset, 0))
return;
if (!ValidateValueFitNonNegInt32("texSubImage2D", "offset", offset))
return;
ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height,
format, type,
reinterpret_cast<const void*>(offset));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: decrypt_2ndtkt(kdc_realm_t *kdc_active_realm, krb5_kdc_req *req,
krb5_flags flags, krb5_db_entry **server_out,
const char **status)
{
krb5_error_code retval;
krb5_db_entry *server;
krb5_keyblock *key;
krb5_kvno kvno;
krb5_ticket *stkt;
if (!(req->kdc_options & STKT_OPTIONS))
return 0;
stkt = req->second_ticket[0];
retval = kdc_get_server_key(kdc_context, stkt,
flags,
TRUE, /* match_enctype */
&server,
&key,
&kvno);
if (retval != 0) {
*status = "2ND_TKT_SERVER";
goto cleanup;
}
retval = krb5_decrypt_tkt_part(kdc_context, key,
req->second_ticket[0]);
krb5_free_keyblock(kdc_context, key);
if (retval != 0) {
*status = "2ND_TKT_DECRYPT";
goto cleanup;
}
*server_out = server;
cleanup:
return retval;
}
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 ReceiverWasAdded(const RtpTransceiverState& transceiver_state) {
uintptr_t receiver_id = RTCRtpReceiver::getId(
transceiver_state.receiver_state()->webrtc_receiver().get());
for (const auto& receiver : handler_->rtp_receivers_) {
if (receiver->Id() == receiver_id)
return false;
}
return true;
}
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 unsigned int help(struct sk_buff *skb,
enum ip_conntrack_info ctinfo,
unsigned int protoff,
unsigned int matchoff,
unsigned int matchlen,
struct nf_conntrack_expect *exp)
{
char buffer[sizeof("4294967296 65635")];
u_int16_t port;
unsigned int ret;
/* Reply comes from server. */
exp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port;
exp->dir = IP_CT_DIR_REPLY;
exp->expectfn = nf_nat_follow_master;
/* Try to get same port: if not, try to change it. */
for (port = ntohs(exp->saved_proto.tcp.port); port != 0; port++) {
int ret;
exp->tuple.dst.u.tcp.port = htons(port);
ret = nf_ct_expect_related(exp);
if (ret == 0)
break;
else if (ret != -EBUSY) {
port = 0;
break;
}
}
if (port == 0) {
nf_ct_helper_log(skb, exp->master, "all ports in use");
return NF_DROP;
}
ret = nf_nat_mangle_tcp_packet(skb, exp->master, ctinfo,
protoff, matchoff, matchlen, buffer,
strlen(buffer));
if (ret != NF_ACCEPT) {
nf_ct_helper_log(skb, exp->master, "cannot mangle packet");
nf_ct_unexpect_related(exp);
}
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int cpuset_cpu_inactive(unsigned int cpu)
{
unsigned long flags;
struct dl_bw *dl_b;
bool overflow;
int cpus;
if (!cpuhp_tasks_frozen) {
rcu_read_lock_sched();
dl_b = dl_bw_of(cpu);
raw_spin_lock_irqsave(&dl_b->lock, flags);
cpus = dl_bw_cpus(cpu);
overflow = __dl_overflow(dl_b, cpus, 0, 0);
raw_spin_unlock_irqrestore(&dl_b->lock, flags);
rcu_read_unlock_sched();
if (overflow)
return -EBUSY;
cpuset_update_active_cpus(false);
} else {
num_cpus_frozen++;
partition_sched_domains(1, NULL, NULL);
}
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: SampleTable::SampleTable(const sp<DataSource> &source)
: mDataSource(source),
mChunkOffsetOffset(-1),
mChunkOffsetType(0),
mNumChunkOffsets(0),
mSampleToChunkOffset(-1),
mNumSampleToChunkOffsets(0),
mSampleSizeOffset(-1),
mSampleSizeFieldSize(0),
mDefaultSampleSize(0),
mNumSampleSizes(0),
mTimeToSampleCount(0),
mTimeToSample(),
mSampleTimeEntries(NULL),
mCompositionTimeDeltaEntries(NULL),
mNumCompositionTimeDeltaEntries(0),
mCompositionDeltaLookup(new CompositionDeltaLookup),
mSyncSampleOffset(-1),
mNumSyncSamples(0),
mSyncSamples(NULL),
mLastSyncSampleIndex(0),
mSampleToChunkEntries(NULL) {
mSampleIterator = new SampleIterator(this);
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: tt_cmap10_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p = table + 4;
FT_ULong length, count;
if ( table + 20 > valid->limit )
FT_INVALID_TOO_SHORT;
length = TT_NEXT_ULONG( p );
p = table + 16;
count = TT_NEXT_ULONG( p );
if ( table + length > valid->limit || length < 20 + count * 2 )
FT_INVALID_TOO_SHORT;
/* check glyph indices */
{
FT_UInt gindex;
for ( ; count > 0; count-- )
{
gindex = TT_NEXT_USHORT( p );
if ( gindex >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
return SFNT_Err_Ok;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void RenderThreadImpl::Init() {
TRACE_EVENT_BEGIN_ETW("RenderThreadImpl::Init", 0, "");
#if defined(OS_MACOSX) || defined(OS_ANDROID)
WebKit::WebView::setUseExternalPopupMenus(true);
#endif
lazy_tls.Pointer()->Set(this);
#if defined(OS_WIN)
if (RenderProcessImpl::InProcessPlugins())
initialize_com_.reset(new base::win::ScopedCOMInitializer());
#endif
ChildProcess::current()->set_main_thread(this);
suspend_webkit_shared_timer_ = true;
notify_webkit_of_modal_loop_ = true;
plugin_refresh_allowed_ = true;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_ms_ = kInitialIdleHandlerDelayMs;
idle_notifications_to_skip_ = 0;
compositor_initialized_ = false;
appcache_dispatcher_.reset(new AppCacheDispatcher(Get()));
main_thread_indexed_db_dispatcher_.reset(
IndexedDBDispatcher::ThreadSpecificInstance());
media_stream_center_ = NULL;
db_message_filter_ = new DBMessageFilter();
AddFilter(db_message_filter_.get());
vc_manager_ = new VideoCaptureImplManager();
AddFilter(vc_manager_->video_capture_message_filter());
audio_input_message_filter_ = new AudioInputMessageFilter();
AddFilter(audio_input_message_filter_.get());
audio_message_filter_ = new AudioMessageFilter();
AddFilter(audio_message_filter_.get());
devtools_agent_message_filter_ = new DevToolsAgentFilter();
AddFilter(devtools_agent_message_filter_.get());
AddFilter(new IndexedDBMessageFilter);
content::GetContentClient()->renderer()->RenderThreadStarted();
FilePath media_path;
PathService::Get(content::DIR_MEDIA_LIBS, &media_path);
if (!media_path.empty())
media::InitializeMediaLibrary(media_path);
TRACE_EVENT_END_ETW("RenderThreadImpl::Init", 0, "");
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static PHP_FUNCTION(xmlwriter_start_pi)
{
php_xmlwriter_string_arg(INTERNAL_FUNCTION_PARAM_PASSTHRU, xmlTextWriterStartPI, "Invalid PI Target");
}
CWE ID: CWE-254
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool CCLayerTreeHost::initialize()
{
TRACE_EVENT("CCLayerTreeHost::initialize", this, 0);
if (m_settings.enableCompositorThread) {
m_settings.acceleratePainting = false;
m_settings.showFPSCounter = false;
m_settings.showPlatformLayerTree = false;
m_proxy = CCThreadProxy::create(this);
} else
m_proxy = CCSingleThreadProxy::create(this);
m_proxy->start();
if (!m_proxy->initializeLayerRenderer())
return false;
m_compositorIdentifier = m_proxy->compositorIdentifier();
m_settings.acceleratePainting = m_proxy->layerRendererCapabilities().usingAcceleratedPainting;
setNeedsCommitThenRedraw();
m_contentsTextureManager = TextureManager::create(TextureManager::highLimitBytes(), m_proxy->layerRendererCapabilities().maxTextureSize);
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int set_unalign_ctl(struct task_struct *tsk, unsigned int val)
{
tsk->thread.align_ctl = val;
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: network_connect_to (const char *proxy, int sock,
unsigned long address, int port)
{
struct t_proxy *ptr_proxy;
struct sockaddr_in addr;
struct hostent *hostent;
char *ip4;
int ret;
ptr_proxy = NULL;
if (proxy && proxy[0])
{
ptr_proxy = proxy_search (proxy);
if (!ptr_proxy)
return 0;
}
if (ptr_proxy)
{
memset (&addr, 0, sizeof (addr));
addr.sin_addr.s_addr = htonl (address);
ip4 = inet_ntoa(addr.sin_addr);
memset (&addr, 0, sizeof (addr));
addr.sin_port = htons (CONFIG_INTEGER(ptr_proxy->options[PROXY_OPTION_PORT]));
addr.sin_family = AF_INET;
hostent = gethostbyname (CONFIG_STRING(ptr_proxy->options[PROXY_OPTION_ADDRESS]));
if (!hostent)
return 0;
memcpy(&(addr.sin_addr), *(hostent->h_addr_list), sizeof(struct in_addr));
ret = connect (sock, (struct sockaddr *) &addr, sizeof (addr));
if ((ret == -1) && (errno != EINPROGRESS))
return 0;
if (!network_pass_proxy (proxy, sock, ip4, port))
return 0;
}
else
{
memset (&addr, 0, sizeof (addr));
addr.sin_port = htons (port);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl (address);
ret = connect (sock, (struct sockaddr *) &addr, sizeof (addr));
if ((ret == -1) && (errno != EINPROGRESS))
return 0;
}
return 1;
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SoftOpus::onQueueFilled(OMX_U32 portIndex) {
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
if (mOutputPortSettingsChange != NONE) {
return;
}
if (portIndex == 0 && mInputBufferCount < 3) {
BufferInfo *info = *inQueue.begin();
OMX_BUFFERHEADERTYPE *header = info->mHeader;
const uint8_t *data = header->pBuffer + header->nOffset;
size_t size = header->nFilledLen;
if (mInputBufferCount == 0) {
CHECK(mHeader == NULL);
mHeader = new OpusHeader();
memset(mHeader, 0, sizeof(*mHeader));
if (!ParseOpusHeader(data, size, mHeader)) {
ALOGV("Parsing Opus Header failed.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
uint8_t channel_mapping[kMaxChannels] = {0};
if (mHeader->channels <= kMaxChannelsWithDefaultLayout) {
memcpy(&channel_mapping,
kDefaultOpusChannelLayout,
kMaxChannelsWithDefaultLayout);
} else {
memcpy(&channel_mapping,
mHeader->stream_map,
mHeader->channels);
}
int status = OPUS_INVALID_STATE;
mDecoder = opus_multistream_decoder_create(kRate,
mHeader->channels,
mHeader->num_streams,
mHeader->num_coupled,
channel_mapping,
&status);
if (!mDecoder || status != OPUS_OK) {
ALOGV("opus_multistream_decoder_create failed status=%s",
opus_strerror(status));
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
status =
opus_multistream_decoder_ctl(mDecoder,
OPUS_SET_GAIN(mHeader->gain_db));
if (status != OPUS_OK) {
ALOGV("Failed to set OPUS header gain; status=%s",
opus_strerror(status));
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
} else if (mInputBufferCount == 1) {
mCodecDelay = ns_to_samples(
*(reinterpret_cast<int64_t*>(header->pBuffer +
header->nOffset)),
kRate);
mSamplesToDiscard = mCodecDelay;
} else {
mSeekPreRoll = ns_to_samples(
*(reinterpret_cast<int64_t*>(header->pBuffer +
header->nOffset)),
kRate);
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
}
inQueue.erase(inQueue.begin());
info->mOwnedByUs = false;
notifyEmptyBufferDone(header);
++mInputBufferCount;
return;
}
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
return;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nOffset == 0) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nTimeStamp == 0) {
mSamplesToDiscard = mCodecDelay;
}
const uint8_t *data = inHeader->pBuffer + inHeader->nOffset;
const uint32_t size = inHeader->nFilledLen;
int numFrames = opus_multistream_decode(mDecoder,
data,
size,
(int16_t *)outHeader->pBuffer,
kMaxOpusOutputPacketSizeSamples,
0);
if (numFrames < 0) {
ALOGE("opus_multistream_decode returned %d", numFrames);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
return;
}
outHeader->nOffset = 0;
if (mSamplesToDiscard > 0) {
if (mSamplesToDiscard > numFrames) {
mSamplesToDiscard -= numFrames;
numFrames = 0;
} else {
numFrames -= mSamplesToDiscard;
outHeader->nOffset = mSamplesToDiscard * sizeof(int16_t) *
mHeader->channels;
mSamplesToDiscard = 0;
}
}
outHeader->nFilledLen = numFrames * sizeof(int16_t) * mHeader->channels;
outHeader->nFlags = 0;
outHeader->nTimeStamp = mAnchorTimeUs +
(mNumFramesOutput * 1000000ll) /
kRate;
mNumFramesOutput += numFrames;
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mInputBufferCount;
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
enum event_type_t event_type,
struct task_struct *task)
{
struct perf_event_context *ctx = &cpuctx->ctx;
ctx_sched_in(ctx, cpuctx, event_type, task);
}
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: _posix_to_nfsv4_one(struct posix_acl *pacl, struct nfs4_acl *acl,
unsigned int flags)
{
struct posix_acl_entry *pa, *group_owner_entry;
struct nfs4_ace *ace;
struct posix_acl_summary pas;
unsigned short deny;
int eflag = ((flags & NFS4_ACL_TYPE_DEFAULT) ?
NFS4_INHERITANCE_FLAGS | NFS4_ACE_INHERIT_ONLY_ACE : 0);
BUG_ON(pacl->a_count < 3);
summarize_posix_acl(pacl, &pas);
pa = pacl->a_entries;
ace = acl->aces + acl->naces;
/* We could deny everything not granted by the owner: */
deny = ~pas.owner;
/*
* but it is equivalent (and simpler) to deny only what is not
* granted by later entries:
*/
deny &= pas.users | pas.group | pas.groups | pas.other;
if (deny) {
ace->type = NFS4_ACE_ACCESS_DENIED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = deny_mask_from_posix(deny, flags);
ace->whotype = NFS4_ACL_WHO_OWNER;
ace++;
acl->naces++;
}
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = mask_from_posix(pa->e_perm, flags | NFS4_ACL_OWNER);
ace->whotype = NFS4_ACL_WHO_OWNER;
ace++;
acl->naces++;
pa++;
while (pa->e_tag == ACL_USER) {
deny = ~(pa->e_perm & pas.mask);
deny &= pas.groups | pas.group | pas.other;
if (deny) {
ace->type = NFS4_ACE_ACCESS_DENIED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = deny_mask_from_posix(deny, flags);
ace->whotype = NFS4_ACL_WHO_NAMED;
ace->who_uid = pa->e_uid;
ace++;
acl->naces++;
}
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = mask_from_posix(pa->e_perm & pas.mask,
flags);
ace->whotype = NFS4_ACL_WHO_NAMED;
ace->who_uid = pa->e_uid;
ace++;
acl->naces++;
pa++;
}
/* In the case of groups, we apply allow ACEs first, then deny ACEs,
* since a user can be in more than one group. */
/* allow ACEs */
group_owner_entry = pa;
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = mask_from_posix(pas.group, flags);
ace->whotype = NFS4_ACL_WHO_GROUP;
ace++;
acl->naces++;
pa++;
while (pa->e_tag == ACL_GROUP) {
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag | NFS4_ACE_IDENTIFIER_GROUP;
ace->access_mask = mask_from_posix(pa->e_perm & pas.mask,
flags);
ace->whotype = NFS4_ACL_WHO_NAMED;
ace->who_gid = pa->e_gid;
ace++;
acl->naces++;
pa++;
}
/* deny ACEs */
pa = group_owner_entry;
deny = ~pas.group & pas.other;
if (deny) {
ace->type = NFS4_ACE_ACCESS_DENIED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = deny_mask_from_posix(deny, flags);
ace->whotype = NFS4_ACL_WHO_GROUP;
ace++;
acl->naces++;
}
pa++;
while (pa->e_tag == ACL_GROUP) {
deny = ~(pa->e_perm & pas.mask);
deny &= pas.other;
if (deny) {
ace->type = NFS4_ACE_ACCESS_DENIED_ACE_TYPE;
ace->flag = eflag | NFS4_ACE_IDENTIFIER_GROUP;
ace->access_mask = deny_mask_from_posix(deny, flags);
ace->whotype = NFS4_ACL_WHO_NAMED;
ace->who_gid = pa->e_gid;
ace++;
acl->naces++;
}
pa++;
}
if (pa->e_tag == ACL_MASK)
pa++;
ace->type = NFS4_ACE_ACCESS_ALLOWED_ACE_TYPE;
ace->flag = eflag;
ace->access_mask = mask_from_posix(pa->e_perm, flags);
ace->whotype = NFS4_ACL_WHO_EVERYONE;
acl->naces++;
}
CWE ID: CWE-284
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void dtls1_free(SSL *s)
{
DTLS_RECORD_LAYER_free(&s->rlayer);
{
pqueue *buffered_messages;
pqueue *sent_messages;
unsigned int mtu;
unsigned int link_mtu;
DTLS_RECORD_LAYER_clear(&s->rlayer);
if (s->d1) {
buffered_messages = s->d1->buffered_messages;
sent_messages = s->d1->sent_messages;
mtu = s->d1->mtu;
link_mtu = s->d1->link_mtu;
dtls1_clear_queues(s);
memset(s->d1, 0, sizeof(*s->d1));
if (s->server) {
s->d1->cookie_len = sizeof(s->d1->cookie);
}
if (SSL_get_options(s) & SSL_OP_NO_QUERY_MTU) {
s->d1->mtu = mtu;
s->d1->link_mtu = link_mtu;
}
s->d1->buffered_messages = buffered_messages;
s->d1->sent_messages = sent_messages;
}
ssl3_clear(s);
if (s->method->version == DTLS_ANY_VERSION)
s->version = DTLS_MAX_VERSION;
#ifndef OPENSSL_NO_DTLS1_METHOD
else if (s->options & SSL_OP_CISCO_ANYCONNECT)
s->client_version = s->version = DTLS1_BAD_VER;
#endif
else
s->version = s->method->version;
}
long dtls1_ctrl(SSL *s, int cmd, long larg, void *parg)
{
int ret = 0;
switch (cmd) {
case DTLS_CTRL_GET_TIMEOUT:
if (dtls1_get_timeout(s, (struct timeval *)parg) != NULL) {
ret = 1;
}
break;
case DTLS_CTRL_HANDLE_TIMEOUT:
ret = dtls1_handle_timeout(s);
break;
case DTLS_CTRL_SET_LINK_MTU:
if (larg < (long)dtls1_link_min_mtu())
return 0;
s->d1->link_mtu = larg;
return 1;
case DTLS_CTRL_GET_LINK_MIN_MTU:
return (long)dtls1_link_min_mtu();
case SSL_CTRL_SET_MTU:
/*
* We may not have a BIO set yet so can't call dtls1_min_mtu()
* We'll have to make do with dtls1_link_min_mtu() and max overhead
*/
if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
return 0;
s->d1->mtu = larg;
return larg;
default:
ret = ssl3_ctrl(s, cmd, larg, parg);
break;
}
return (ret);
}
void dtls1_start_timer(SSL *s)
{
#ifndef OPENSSL_NO_SCTP
/* Disable timer for SCTP */
if (BIO_dgram_is_sctp(SSL_get_wbio(s))) {
memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
return;
}
#endif
/* If timer is not set, initialize duration with 1 second */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
s->d1->timeout_duration = 1;
}
/* Set timeout to current time */
get_current_time(&(s->d1->next_timeout));
/* Add duration to current time */
s->d1->next_timeout.tv_sec += s->d1->timeout_duration;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
}
struct timeval *dtls1_get_timeout(SSL *s, struct timeval *timeleft)
{
struct timeval timenow;
/* If no timeout is set, just return NULL */
if (s->d1->next_timeout.tv_sec == 0 && s->d1->next_timeout.tv_usec == 0) {
return NULL;
}
/* Get current time */
get_current_time(&timenow);
/* If timer already expired, set remaining time to 0 */
if (s->d1->next_timeout.tv_sec < timenow.tv_sec ||
(s->d1->next_timeout.tv_sec == timenow.tv_sec &&
s->d1->next_timeout.tv_usec <= timenow.tv_usec)) {
memset(timeleft, 0, sizeof(*timeleft));
return timeleft;
}
/* Calculate time left until timer expires */
memcpy(timeleft, &(s->d1->next_timeout), sizeof(struct timeval));
timeleft->tv_sec -= timenow.tv_sec;
timeleft->tv_usec -= timenow.tv_usec;
if (timeleft->tv_usec < 0) {
timeleft->tv_sec--;
timeleft->tv_usec += 1000000;
}
/*
* If remaining time is less than 15 ms, set it to 0 to prevent issues
* because of small divergences with socket timeouts.
*/
if (timeleft->tv_sec == 0 && timeleft->tv_usec < 15000) {
memset(timeleft, 0, sizeof(*timeleft));
}
return timeleft;
}
int dtls1_is_timer_expired(SSL *s)
{
struct timeval timeleft;
/* Get time left until timeout, return false if no timer running */
if (dtls1_get_timeout(s, &timeleft) == NULL) {
return 0;
}
/* Return false if timer is not expired yet */
if (timeleft.tv_sec > 0 || timeleft.tv_usec > 0) {
return 0;
}
/* Timer expired, so return true */
return 1;
}
void dtls1_double_timeout(SSL *s)
{
s->d1->timeout_duration *= 2;
if (s->d1->timeout_duration > 60)
s->d1->timeout_duration = 60;
dtls1_start_timer(s);
}
void dtls1_stop_timer(SSL *s)
{
/* Reset everything */
memset(&s->d1->timeout, 0, sizeof(s->d1->timeout));
memset(&s->d1->next_timeout, 0, sizeof(s->d1->next_timeout));
s->d1->timeout_duration = 1;
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
/* Clear retransmission buffer */
dtls1_clear_record_buffer(s);
}
int dtls1_check_timeout_num(SSL *s)
{
unsigned int mtu;
s->d1->timeout.num_alerts++;
/* Reduce MTU after 2 unsuccessful retransmissions */
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0,
&(s->d1->next_timeout));
/* Clear retransmission buffer */
dtls1_clear_record_buffer(s);
}
int dtls1_check_timeout_num(SSL *s)
if (s->d1->timeout.num_alerts > DTLS1_TMO_ALERT_COUNT) {
/* fail the connection, enough alerts have been sent */
SSLerr(SSL_F_DTLS1_CHECK_TIMEOUT_NUM, SSL_R_READ_TIMEOUT_EXPIRED);
return -1;
}
return 0;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int tg3_ape_lock(struct tg3 *tp, int locknum)
{
int i, off;
int ret = 0;
u32 status, req, gnt, bit;
if (!tg3_flag(tp, ENABLE_APE))
return 0;
switch (locknum) {
case TG3_APE_LOCK_GPIO:
if (tg3_asic_rev(tp) == ASIC_REV_5761)
return 0;
case TG3_APE_LOCK_GRC:
case TG3_APE_LOCK_MEM:
if (!tp->pci_fn)
bit = APE_LOCK_REQ_DRIVER;
else
bit = 1 << tp->pci_fn;
break;
case TG3_APE_LOCK_PHY0:
case TG3_APE_LOCK_PHY1:
case TG3_APE_LOCK_PHY2:
case TG3_APE_LOCK_PHY3:
bit = APE_LOCK_REQ_DRIVER;
break;
default:
return -EINVAL;
}
if (tg3_asic_rev(tp) == ASIC_REV_5761) {
req = TG3_APE_LOCK_REQ;
gnt = TG3_APE_LOCK_GRANT;
} else {
req = TG3_APE_PER_LOCK_REQ;
gnt = TG3_APE_PER_LOCK_GRANT;
}
off = 4 * locknum;
tg3_ape_write32(tp, req + off, bit);
/* Wait for up to 1 millisecond to acquire lock. */
for (i = 0; i < 100; i++) {
status = tg3_ape_read32(tp, gnt + off);
if (status == bit)
break;
udelay(10);
}
if (status != bit) {
/* Revoke the lock request. */
tg3_ape_write32(tp, gnt + off, bit);
ret = -EBUSY;
}
return ret;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GDataFileSystem::GetFileByPath(
const FilePath& file_path,
const GetFileCallback& get_file_callback,
const GetDownloadDataCallback& get_download_data_callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
BrowserThread::CurrentlyOn(BrowserThread::IO));
RunTaskOnUIThread(
base::Bind(&GDataFileSystem::GetFileByPathOnUIThread,
ui_weak_ptr_,
file_path,
CreateRelayCallback(get_file_callback),
CreateRelayCallback(get_download_data_callback)));
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int on_header_cb(nghttp2_session *ngh2, const nghttp2_frame *frame,
const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen,
uint8_t flags,
void *userp)
{
h2_session *session = (h2_session *)userp;
h2_stream * stream;
apr_status_t status;
(void)flags;
stream = get_stream(session, frame->hd.stream_id);
if (!stream) {
ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, session->c,
APLOGNO(02920)
"h2_session: stream(%ld-%d): on_header unknown stream",
session->id, (int)frame->hd.stream_id);
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
status = h2_stream_add_header(stream, (const char *)name, namelen,
(const char *)value, valuelen);
if (status != APR_SUCCESS && !h2_stream_is_ready(stream)) {
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
return 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: views::View* WebsiteSettingsPopupView::CreatePermissionsTab() {
views::View* pane = new views::View();
pane->SetLayoutManager(
new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 1));
cookie_dialog_link_ = new views::Link(
l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_SHOW_SITE_DATA));
cookie_dialog_link_->set_listener(this);
site_data_content_ = new views::View();
views::View* site_data_section =
CreateSection(l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_TITLE_SITE_DATA),
site_data_content_,
cookie_dialog_link_);
pane->AddChildView(site_data_section);
return pane;
}
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: exsltDateCreateDate (exsltDateType type)
{
exsltDateValPtr ret;
ret = (exsltDateValPtr) xmlMalloc(sizeof(exsltDateVal));
if (ret == NULL) {
xsltGenericError(xsltGenericErrorContext,
"exsltDateCreateDate: out of memory\n");
return (NULL);
}
memset (ret, 0, sizeof(exsltDateVal));
if (type != EXSLT_UNKNOWN)
ret->type = type;
return ret;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: CURLcode Curl_close(struct Curl_easy *data)
{
struct Curl_multi *m;
if(!data)
return CURLE_OK;
Curl_expire_clear(data); /* shut off timers */
m = data->multi;
if(m)
/* This handle is still part of a multi handle, take care of this first
and detach this handle from there. */
curl_multi_remove_handle(data->multi, data);
if(data->multi_easy)
/* when curl_easy_perform() is used, it creates its own multi handle to
use and this is the one */
curl_multi_cleanup(data->multi_easy);
/* Destroy the timeout list that is held in the easy handle. It is
/normally/ done by curl_multi_remove_handle() but this is "just in
case" */
Curl_llist_destroy(&data->state.timeoutlist, NULL);
data->magic = 0; /* force a clear AFTER the possibly enforced removal from
the multi handle, since that function uses the magic
field! */
if(data->state.rangestringalloc)
free(data->state.range);
/* freed here just in case DONE wasn't called */
Curl_free_request_state(data);
/* Close down all open SSL info and sessions */
Curl_ssl_close_all(data);
Curl_safefree(data->state.first_host);
Curl_safefree(data->state.scratch);
Curl_ssl_free_certinfo(data);
/* Cleanup possible redirect junk */
free(data->req.newurl);
data->req.newurl = NULL;
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
Curl_up_free(data);
Curl_safefree(data->state.buffer);
Curl_safefree(data->state.headerbuff);
Curl_safefree(data->state.ulbuf);
Curl_flush_cookies(data, 1);
Curl_digest_cleanup(data);
Curl_safefree(data->info.contenttype);
Curl_safefree(data->info.wouldredirect);
/* this destroys the channel and we cannot use it anymore after this */
Curl_resolver_cleanup(data->state.resolver);
Curl_http2_cleanup_dependencies(data);
Curl_convert_close(data);
/* No longer a dirty share, if it exists */
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
data->share->dirty--;
Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
}
/* destruct wildcard structures if it is needed */
Curl_wildcard_dtor(&data->wildcard);
Curl_freeset(data);
free(data);
return CURLE_OK;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
{
unsigned long nr, a0, a1, a2, a3, ret;
int op_64_bit, r = 1;
if (kvm_hv_hypercall_enabled(vcpu->kvm))
return kvm_hv_hypercall(vcpu);
nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
trace_kvm_hypercall(nr, a0, a1, a2, a3);
op_64_bit = is_64_bit_mode(vcpu);
if (!op_64_bit) {
nr &= 0xFFFFFFFF;
a0 &= 0xFFFFFFFF;
a1 &= 0xFFFFFFFF;
a2 &= 0xFFFFFFFF;
a3 &= 0xFFFFFFFF;
}
if (kvm_x86_ops->get_cpl(vcpu) != 0) {
ret = -KVM_EPERM;
goto out;
}
switch (nr) {
case KVM_HC_VAPIC_POLL_IRQ:
ret = 0;
break;
case KVM_HC_KICK_CPU:
kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
ret = 0;
break;
default:
ret = -KVM_ENOSYS;
break;
}
out:
if (!op_64_bit)
ret = (u32)ret;
kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
++vcpu->stat.hypercalls;
return r;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
const void *value, size_t len)
{
struct vendor_attribute *attr;
int res;
if (!h->request_created) {
generr(h, "Please call rad_create_request()");
return -1;
}
if ((attr = malloc(len + 6)) == NULL) {
generr(h, "malloc failure (%d bytes)", len + 6);
return -1;
}
attr->vendor_value = htonl(vendor);
attr->attrib_type = type;
attr->attrib_len = len + 2;
memcpy(attr->attrib_data, value, len);
res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
free(attr);
if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
&& (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
|| type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
h->chap_pass = 1;
}
return (res);
}
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: WORD32 ixheaacd_complex_anal_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer) {
WORD32 idx;
WORD32 anal_size = 2 * ptr_hbe_txposer->synth_size;
WORD32 N = (10 * anal_size);
for (idx = 0; idx < (ptr_hbe_txposer->no_bins >> 1); idx++) {
WORD32 i, j, k, l;
FLOAT32 window_output[640];
FLOAT32 u[128], u_in[256], u_out[256];
FLOAT32 accu_r, accu_i;
const FLOAT32 *inp_signal;
FLOAT32 *anal_buf;
FLOAT32 *analy_cos_sin_tab = ptr_hbe_txposer->analy_cos_sin_tab;
const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->analy_wind_coeff;
FLOAT32 *x = ptr_hbe_txposer->analy_buf;
memset(ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1], 0,
TWICE_QMF_SYNTH_CHANNELS_NUM * sizeof(FLOAT32));
inp_signal = ptr_hbe_txposer->ptr_input_buf +
idx * 2 * ptr_hbe_txposer->synth_size + 1;
anal_buf = &ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1]
[4 * ptr_hbe_txposer->k_start];
for (i = N - 1; i >= anal_size; i--) {
x[i] = x[i - anal_size];
}
for (i = anal_size - 1; i >= 0; i--) {
x[i] = inp_signal[anal_size - 1 - i];
}
for (i = 0; i < N; i++) {
window_output[i] = x[i] * interp_window_coeff[i];
}
for (i = 0; i < 2 * anal_size; i++) {
accu_r = 0.0;
for (j = 0; j < 5; j++) {
accu_r = accu_r + window_output[i + j * 2 * anal_size];
}
u[i] = accu_r;
}
if (anal_size == 40) {
for (i = 1; i < anal_size; i++) {
FLOAT32 temp1 = u[i] + u[2 * anal_size - i];
FLOAT32 temp2 = u[i] - u[2 * anal_size - i];
u[i] = temp1;
u[2 * anal_size - i] = temp2;
}
for (k = 0; k < anal_size; k++) {
accu_r = u[anal_size];
if (k & 1)
accu_i = u[0];
else
accu_i = -u[0];
for (l = 1; l < anal_size; l++) {
accu_r = accu_r + u[0 + l] * analy_cos_sin_tab[2 * l + 0];
accu_i = accu_i + u[2 * anal_size - l] * analy_cos_sin_tab[2 * l + 1];
}
analy_cos_sin_tab += (2 * anal_size);
*anal_buf++ = (FLOAT32)accu_r;
*anal_buf++ = (FLOAT32)accu_i;
}
} else {
FLOAT32 *ptr_u = u_in;
FLOAT32 *ptr_v = u_out;
for (k = 0; k < anal_size * 2; k++) {
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
*ptr_u++ = ((*analy_cos_sin_tab++) * u[k]);
}
if (ixheaacd_cmplx_anal_fft != NULL)
(*ixheaacd_cmplx_anal_fft)(u_in, u_out, anal_size * 2);
else
return -1;
for (k = 0; k < anal_size / 2; k++) {
*(anal_buf + 1) = -*ptr_v++;
*anal_buf = *ptr_v++;
anal_buf += 2;
*(anal_buf + 1) = *ptr_v++;
*anal_buf = -*ptr_v++;
anal_buf += 2;
}
}
}
return 0;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int em_dr_write(struct x86_emulate_ctxt *ctxt)
{
unsigned long val;
if (ctxt->mode == X86EMUL_MODE_PROT64)
val = ctxt->src.val & ~0ULL;
else
val = ctxt->src.val & ~0U;
/* #UD condition is already handled. */
if (ctxt->ops->set_dr(ctxt, ctxt->modrm_reg, val) < 0)
return emulate_gp(ctxt, 0);
/* Disable writeback. */
ctxt->dst.type = OP_NONE;
return X86EMUL_CONTINUE;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC)
{
int err_code = 0;
int found = 0;
php_mb_regex_t *retval = NULL, **rc = NULL;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc);
if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) {
if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str);
retval = NULL;
goto out;
}
zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL);
} else if (found == SUCCESS) {
retval = *rc;
}
out:
return retval;
}
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: void CLASS foveon_load_camf()
{
unsigned type, wide, high, i, j, row, col, diff;
ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
type = get4(); get4(); get4();
wide = get4();
high = get4();
if (type == 2) {
fread (meta_data, 1, meta_length, ifp);
for (i=0; i < meta_length; i++) {
high = (high * 1597 + 51749) % 244944;
wide = high * (INT64) 301593171 >> 24;
meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
}
} else if (type == 4) {
free (meta_data);
meta_data = (char *) malloc (meta_length = wide*high*3/2);
merror (meta_data, "foveon_load_camf()");
foveon_huff (huff);
get4();
getbits(-1);
for (j=row=0; row < high; row++) {
for (col=0; col < wide; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if (col & 1) {
meta_data[j++] = hpred[0] >> 4;
meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
meta_data[j++] = hpred[1];
}
}
}
} else
fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void device_add_disk(struct device *parent, struct gendisk *disk)
{
struct backing_dev_info *bdi;
dev_t devt;
int retval;
/* minors == 0 indicates to use ext devt from part0 and should
* be accompanied with EXT_DEVT flag. Make sure all
* parameters make sense.
*/
WARN_ON(disk->minors && !(disk->major || disk->first_minor));
WARN_ON(!disk->minors && !(disk->flags & GENHD_FL_EXT_DEVT));
disk->flags |= GENHD_FL_UP;
retval = blk_alloc_devt(&disk->part0, &devt);
if (retval) {
WARN_ON(1);
return;
}
disk_to_dev(disk)->devt = devt;
/* ->major and ->first_minor aren't supposed to be
* dereferenced from here on, but set them just in case.
*/
disk->major = MAJOR(devt);
disk->first_minor = MINOR(devt);
disk_alloc_events(disk);
/* Register BDI before referencing it from bdev */
bdi = &disk->queue->backing_dev_info;
bdi_register_dev(bdi, disk_devt(disk));
blk_register_region(disk_devt(disk), disk->minors, NULL,
exact_match, exact_lock, disk);
register_disk(parent, disk);
blk_register_queue(disk);
/*
* Take an extra ref on queue which will be put on disk_release()
* so that it sticks around as long as @disk is there.
*/
WARN_ON_ONCE(!blk_get_queue(disk->queue));
retval = sysfs_create_link(&disk_to_dev(disk)->kobj, &bdi->dev->kobj,
"bdi");
WARN_ON(retval);
disk_add_events(disk);
blk_integrity_add(disk);
}
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: _dbus_close_socket (int fd,
DBusError *error)
{
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
again:
if (closesocket (fd) == SOCKET_ERROR)
{
DBUS_SOCKET_SET_ERRNO ();
if (errno == EINTR)
goto again;
dbus_set_error (error, _dbus_error_from_errno (errno),
"Could not close socket: socket=%d, , %s",
fd, _dbus_strerror_from_errno ());
return FALSE;
}
_dbus_verbose ("_dbus_close_socket: socket=%d, \n", fd);
return TRUE;
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void RemoveResolutionFromResourceBlock(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 == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12)))
{
(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-125
Target: 1
Example 2:
Code: static PHP_FUNCTION(preg_quote)
{
int in_str_len;
char *in_str; /* Input string argument */
char *in_str_end; /* End of the input string */
int delim_len = 0;
char *delim = NULL; /* Additional delimiter argument */
char *out_str, /* Output string with quoted characters */
*p, /* Iterator for input string */
*q, /* Iterator for output string */
delim_char=0, /* Delimiter character to be quoted */
c; /* Current character */
zend_bool quote_delim = 0; /* Whether to quote additional delim char */
/* Get the arguments and check for errors */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &in_str, &in_str_len,
&delim, &delim_len) == FAILURE) {
return;
}
in_str_end = in_str + in_str_len;
/* Nothing to do if we got an empty string */
if (in_str == in_str_end) {
RETURN_EMPTY_STRING();
}
if (delim && *delim) {
delim_char = delim[0];
quote_delim = 1;
}
/* Allocate enough memory so that even if each character
is quoted, we won't run out of room */
out_str = safe_emalloc(4, in_str_len, 1);
/* Go through the string and quote necessary characters */
for(p = in_str, q = out_str; p != in_str_end; p++) {
c = *p;
switch(c) {
case '.':
case '\\':
case '+':
case '*':
case '?':
case '[':
case '^':
case ']':
case '$':
case '(':
case ')':
case '{':
case '}':
case '=':
case '!':
case '>':
case '<':
case '|':
case ':':
case '-':
*q++ = '\\';
*q++ = c;
break;
case '\0':
*q++ = '\\';
*q++ = '0';
*q++ = '0';
*q++ = '0';
break;
default:
if (quote_delim && c == delim_char)
*q++ = '\\';
*q++ = c;
break;
}
}
*q = '\0';
/* Reallocate string and return it */
RETVAL_STRINGL(erealloc(out_str, q - out_str + 1), q - out_str, 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: mcs_recv_connect_response(STREAM mcs_data)
{
UNUSED(mcs_data);
uint8 result;
int length;
STREAM s;
RD_BOOL is_fastpath;
uint8 fastpath_hdr;
logger(Protocol, Debug, "%s()", __func__);
s = iso_recv(&is_fastpath, &fastpath_hdr);
if (s == NULL)
return False;
ber_parse_header(s, MCS_CONNECT_RESPONSE, &length);
ber_parse_header(s, BER_TAG_RESULT, &length);
in_uint8(s, result);
if (result != 0)
{
logger(Protocol, Error, "mcs_recv_connect_response(), result=%d", result);
return False;
}
ber_parse_header(s, BER_TAG_INTEGER, &length);
in_uint8s(s, length); /* connect id */
mcs_parse_domain_params(s);
ber_parse_header(s, BER_TAG_OCTET_STRING, &length);
sec_process_mcs_data(s);
/*
if (length > mcs_data->size)
{
logger(Protocol, Error, "mcs_recv_connect_response(), expected length=%d, got %d",length, mcs_data->size);
length = mcs_data->size;
}
in_uint8a(s, mcs_data->data, length);
mcs_data->p = mcs_data->data;
mcs_data->end = mcs_data->data + length;
*/
return s_check_end(s);
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: psf_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...)
{ va_list argptr ;
int maxlen ;
char *start ;
maxlen = strlen ((char*) psf->header) ;
start = ((char*) psf->header) + maxlen ;
maxlen = sizeof (psf->header) - maxlen ;
va_start (argptr, format) ;
vsnprintf (start, maxlen, format, argptr) ;
va_end (argptr) ;
/* Make sure the string is properly terminated. */
start [maxlen - 1] = 0 ;
psf->headindex = strlen ((char*) psf->header) ;
return ;
} /* psf_asciiheader_printf */
CWE ID: CWE-119
Target: 1
Example 2:
Code: void SupervisedUserService::ChangeExtensionStateIfNecessary(
const std::string& extension_id) {
ExtensionRegistry* registry = ExtensionRegistry::Get(profile_);
const Extension* extension = registry->GetInstalledExtension(extension_id);
if (!extension)
return;
ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile_);
extensions::ExtensionService* service =
ExtensionSystem::Get(profile_)->extension_service();
ExtensionState state = GetExtensionState(*extension);
switch (state) {
case ExtensionState::BLOCKED:
case ExtensionState::FORCED:
break;
case ExtensionState::REQUIRE_APPROVAL:
service->DisableExtension(
extension_id,
extensions::disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED);
break;
case ExtensionState::ALLOWED:
extension_prefs->RemoveDisableReason(
extension_id,
extensions::disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED);
extension_prefs->RemoveDisableReason(
extension_id,
extensions::disable_reason::DISABLE_PERMISSIONS_INCREASE);
if (extension_prefs->GetDisableReasons(extension_id) ==
extensions::disable_reason::DISABLE_NONE) {
service->EnableExtension(extension_id);
}
break;
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
vstart += verdef->vd_aux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
CWE ID: CWE-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: I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
base::Unretained(this)));
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: sched_feat_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char buf[64];
char *cmp;
int neg = 0;
int i;
if (cnt > 63)
cnt = 63;
if (copy_from_user(&buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
cmp = strstrip(buf);
if (strncmp(cmp, "NO_", 3) == 0) {
neg = 1;
cmp += 3;
}
for (i = 0; sched_feat_names[i]; i++) {
if (strcmp(cmp, sched_feat_names[i]) == 0) {
if (neg)
sysctl_sched_features &= ~(1UL << i);
else
sysctl_sched_features |= (1UL << i);
break;
}
}
if (!sched_feat_names[i])
return -EINVAL;
*ppos += cnt;
return cnt;
}
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 SVGDocumentExtensions::pauseAnimations()
{
WillBeHeapHashSet<RawPtrWillBeMember<SVGSVGElement> >::iterator end = m_timeContainers.end();
for (WillBeHeapHashSet<RawPtrWillBeMember<SVGSVGElement> >::iterator itr = m_timeContainers.begin(); itr != end; ++itr)
(*itr)->pauseAnimations();
}
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: store_pool_delete(png_store *ps, store_pool *pool)
{
if (pool->list != NULL)
{
fprintf(stderr, "%s: %s %s: memory lost (list follows):\n", ps->test,
pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
++ps->nerrors;
do
{
store_memory *next = pool->list;
pool->list = next->next;
next->next = NULL;
fprintf(stderr, "\t%lu bytes @ %p\n",
(unsigned long)next->size, (PNG_CONST void*)(next+1));
/* The NULL means this will always return, even if the memory is
* corrupted.
*/
store_memory_free(NULL, pool, next);
}
while (pool->list != NULL);
}
/* And reset the other fields too for the next time. */
if (pool->max > pool->max_max) pool->max_max = pool->max;
pool->max = 0;
if (pool->current != 0) /* unexpected internal error */
fprintf(stderr, "%s: %s %s: memory counter mismatch (internal error)\n",
ps->test, pool == &ps->read_memory_pool ? "read" : "write",
pool == &ps->read_memory_pool ? (ps->current != NULL ?
ps->current->name : "unknown file") : ps->wname);
pool->current = 0;
if (pool->limit > pool->max_limit)
pool->max_limit = pool->limit;
pool->limit = 0;
if (pool->total > pool->max_total)
pool->max_total = pool->total;
pool->total = 0;
/* Get a new mark too. */
store_pool_mark(pool->mark);
}
CWE ID:
Target: 1
Example 2:
Code: HistoryNavigationBeforeCommitInjector(WebContentsImpl* web_contents,
const GURL& url)
: DidCommitProvisionalLoadInterceptor(web_contents),
did_trigger_history_navigation_(false),
url_(url) {}
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: RenderFlexibleBox::RenderFlexibleBox(Element* element)
: RenderBlock(element)
, m_orderIterator(this)
, m_numberOfInFlowChildrenOnFirstLine(-1)
{
setChildrenInline(false); // All of our children must be block-level.
}
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 AppCache::AddEntry(const GURL& url, const AppCacheEntry& entry) {
DCHECK(entries_.find(url) == entries_.end());
entries_.insert(EntryMap::value_type(url, entry));
cache_size_ += entry.response_size();
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void HTMLMediaElement::playbackProgressTimerFired(TimerBase*) {
if (!std::isnan(m_fragmentEndTime) && currentTime() >= m_fragmentEndTime &&
getDirectionOfPlayback() == Forward) {
m_fragmentEndTime = std::numeric_limits<double>::quiet_NaN();
if (!m_paused) {
UseCounter::count(document(),
UseCounter::HTMLMediaElementPauseAtFragmentEnd);
pauseInternal();
}
}
if (!m_seeking)
scheduleTimeupdateEvent(true);
if (!playbackRate())
return;
cueTimeline().updateActiveCues(currentTime());
}
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 BlobURLRequestJob::CountSize() {
error_ = false;
pending_get_file_info_count_ = 0;
total_size_ = 0;
item_length_list_.resize(blob_data_->items().size());
for (size_t i = 0; i < blob_data_->items().size(); ++i) {
const BlobData::Item& item = blob_data_->items().at(i);
if (IsFileType(item.type())) {
++pending_get_file_info_count_;
GetFileStreamReader(i)->GetLength(
base::Bind(&BlobURLRequestJob::DidGetFileItemLength,
weak_factory_.GetWeakPtr(), i));
continue;
}
int64 item_length = static_cast<int64>(item.length());
item_length_list_[i] = item_length;
total_size_ += item_length;
}
if (pending_get_file_info_count_ == 0)
DidCountSize(net::OK);
}
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 em_jcxz(struct x86_emulate_ctxt *ctxt)
{
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
jmp_rel(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void doubleArrayAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
TestObject* imp = V8TestObject::toNative(info.Holder());
v8SetReturnValue(info, v8Array(imp->doubleArray(), info.GetIsolate()));
}
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 AppCacheUpdateJob::FetchUrls() {
DCHECK(internal_state_ == DOWNLOADING);
while (pending_url_fetches_.size() < kMaxConcurrentUrlFetches &&
!urls_to_fetch_.empty()) {
UrlToFetch url_to_fetch = urls_to_fetch_.front();
urls_to_fetch_.pop_front();
AppCache::EntryMap::iterator it = url_file_list_.find(url_to_fetch.url);
DCHECK(it != url_file_list_.end());
AppCacheEntry& entry = it->second;
if (ShouldSkipUrlFetch(entry)) {
NotifyAllProgress(url_to_fetch.url);
++url_fetches_completed_;
} else if (AlreadyFetchedEntry(url_to_fetch.url, entry.types())) {
NotifyAllProgress(url_to_fetch.url);
++url_fetches_completed_; // saved a URL request
} else if (!url_to_fetch.storage_checked &&
MaybeLoadFromNewestCache(url_to_fetch.url, entry)) {
} else {
URLFetcher* fetcher = new URLFetcher(
url_to_fetch.url, URLFetcher::URL_FETCH, this);
if (url_to_fetch.existing_response_info.get()) {
DCHECK(group_->newest_complete_cache());
AppCacheEntry* existing_entry =
group_->newest_complete_cache()->GetEntry(url_to_fetch.url);
DCHECK(existing_entry);
DCHECK(existing_entry->response_id() ==
url_to_fetch.existing_response_info->response_id());
fetcher->set_existing_response_headers(
url_to_fetch.existing_response_info->http_response_info()->headers
.get());
fetcher->set_existing_entry(*existing_entry);
}
fetcher->Start();
pending_url_fetches_.insert(
PendingUrlFetches::value_type(url_to_fetch.url, fetcher));
}
}
}
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 check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
/* high 32 bits are known zero. */
regs[insn->dst_reg].var_off = tnum_cast(
regs[insn->dst_reg].var_off, 4);
__update_reg_bounds(®s[insn->dst_reg]);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: GF_Err dlay_dump(GF_Box *a, FILE * trace)
{
GF_TextScrollDelayBox*p = (GF_TextScrollDelayBox*)a;
gf_isom_box_dump_start(a, "TextScrollDelayBox", trace);
fprintf(trace, "scroll_delay=\"%d\">\n", p->scroll_delay);
gf_isom_box_dump_done("TextScrollDelayBox", a, trace);
return GF_OK;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ACodec::FlushingState::onOMXEvent(
OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
ALOGV("[%s] FlushingState onOMXEvent(%u,%d)",
mCodec->mComponentName.c_str(), event, (OMX_S32)data1);
switch (event) {
case OMX_EventCmdComplete:
{
if (data1 != (OMX_U32)OMX_CommandFlush) {
ALOGE("unexpected EventCmdComplete %s(%d) data2:%d in FlushingState",
asString((OMX_COMMANDTYPE)data1), data1, data2);
mCodec->signalError(OMX_ErrorUndefined, FAILED_TRANSACTION);
return true;
}
if (data2 == kPortIndexInput || data2 == kPortIndexOutput) {
if (mFlushComplete[data2]) {
ALOGW("Flush already completed for %s port",
data2 == kPortIndexInput ? "input" : "output");
return true;
}
mFlushComplete[data2] = true;
if (mFlushComplete[kPortIndexInput] && mFlushComplete[kPortIndexOutput]) {
changeStateIfWeOwnAllBuffers();
}
} else if (data2 == OMX_ALL) {
if (!mFlushComplete[kPortIndexInput] || !mFlushComplete[kPortIndexOutput]) {
ALOGW("received flush complete event for OMX_ALL before ports have been"
"flushed (%d/%d)",
mFlushComplete[kPortIndexInput], mFlushComplete[kPortIndexOutput]);
return false;
}
changeStateIfWeOwnAllBuffers();
} else {
ALOGW("data2 not OMX_ALL but %u in EventCmdComplete CommandFlush", data2);
}
return true;
}
case OMX_EventPortSettingsChanged:
{
sp<AMessage> msg = new AMessage(kWhatOMXMessage, mCodec);
msg->setInt32("type", omx_message::EVENT);
msg->setInt32("node", mCodec->mNode);
msg->setInt32("event", event);
msg->setInt32("data1", data1);
msg->setInt32("data2", data2);
ALOGV("[%s] Deferring OMX_EventPortSettingsChanged",
mCodec->mComponentName.c_str());
mCodec->deferMessage(msg);
return true;
}
default:
return BaseState::onOMXEvent(event, data1, data2);
}
return true;
}
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 btsnoop_net_write(const void *data, size_t length) {
#if (!defined(BT_NET_DEBUG) || (BT_NET_DEBUG != TRUE))
return; // Disable using network sockets for security reasons
#endif
pthread_mutex_lock(&client_socket_lock_);
if (client_socket_ != -1) {
if (send(client_socket_, data, length, 0) == -1 && errno == ECONNRESET) {
safe_close_(&client_socket_);
}
}
pthread_mutex_unlock(&client_socket_lock_);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static int udf_mknod(struct inode *dir, struct dentry *dentry, umode_t mode,
dev_t rdev)
{
struct inode *inode;
if (!old_valid_dev(rdev))
return -EINVAL;
inode = udf_new_inode(dir, mode);
if (IS_ERR(inode))
return PTR_ERR(inode);
init_special_inode(inode, mode, rdev);
return udf_add_nondir(dentry, 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: void RenderProcessHostImpl::EnableAecDumpForId(const base::FilePath& file,
int id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::FILE, FROM_HERE,
base::Bind(&CreateFileForProcess, file.AddExtension(IntToStringType(id))),
base::Bind(&RenderProcessHostImpl::SendAecDumpFileToRenderer,
weak_factory_.GetWeakPtr(), id));
}
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 CrosMock::SetSpeechSynthesisLibraryExpectations() {
InSequence s;
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.Times(AnyNumber())
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false))
.RetiresOnSaturation();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void FileReaderLoader::OnReceivedData(const char* data, unsigned data_length) {
DCHECK(data);
if (error_code_ != FileErrorCode::kOK)
return;
if (read_type_ == kReadByClient) {
bytes_loaded_ += data_length;
if (client_)
client_->DidReceiveDataForClient(data, data_length);
return;
}
unsigned bytes_appended = raw_data_->Append(data, data_length);
if (!bytes_appended) {
raw_data_.reset();
bytes_loaded_ = 0;
Failed(FileErrorCode::kNotReadableErr,
FailureType::kArrayBufferBuilderAppend);
return;
}
bytes_loaded_ += bytes_appended;
is_raw_data_converted_ = false;
AdjustReportedMemoryUsageToV8(bytes_appended);
if (client_)
client_->DidReceiveData();
}
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 PreProcessingFx_ProcessReverse(effect_handle_t self,
audio_buffer_t *inBuffer,
audio_buffer_t *outBuffer)
{
preproc_effect_t * effect = (preproc_effect_t *)self;
int status = 0;
if (effect == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR effect == NULL");
return -EINVAL;
}
preproc_session_t * session = (preproc_session_t *)effect->session;
if (inBuffer == NULL || inBuffer->raw == NULL){
ALOGW("PreProcessingFx_ProcessReverse() ERROR bad pointer");
return -EINVAL;
}
session->revProcessedMsk |= (1<<effect->procId);
if ((session->revProcessedMsk & session->revEnabledMsk) == session->revEnabledMsk) {
effect->session->revProcessedMsk = 0;
if (session->revResampler != NULL) {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
if (session->revBufSize < session->framesRev + fr) {
session->revBufSize = session->framesRev + fr;
session->revBuf = (int16_t *)realloc(session->revBuf,
session->revBufSize * session->inChannelCount * sizeof(int16_t));
}
memcpy(session->revBuf + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
spx_uint32_t frIn = session->framesRev;
spx_uint32_t frOut = session->apmFrameCount;
if (session->inChannelCount == 1) {
speex_resampler_process_int(session->revResampler,
0,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
} else {
speex_resampler_process_interleaved_int(session->revResampler,
session->revBuf,
&frIn,
session->revFrame->_payloadData,
&frOut);
}
memcpy(session->revBuf,
session->revBuf + frIn * session->inChannelCount,
(session->framesRev - frIn) * session->inChannelCount * sizeof(int16_t));
session->framesRev -= frIn;
} else {
size_t fr = session->frameCount - session->framesRev;
if (inBuffer->frameCount < fr) {
fr = inBuffer->frameCount;
}
memcpy(session->revFrame->_payloadData + session->framesRev * session->inChannelCount,
inBuffer->s16,
fr * session->inChannelCount * sizeof(int16_t));
session->framesRev += fr;
inBuffer->frameCount = fr;
if (session->framesRev < session->frameCount) {
return 0;
}
session->framesRev = 0;
}
session->revFrame->_payloadDataLengthInSamples =
session->apmFrameCount * session->inChannelCount;
effect->session->apm->AnalyzeReverseStream(session->revFrame);
return 0;
} else {
return -ENODATA;
}
}
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 inet6_sk_rebuild_header(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct dst_entry *dst;
dst = __sk_dst_check(sk, np->dst_cookie);
if (!dst) {
struct inet_sock *inet = inet_sk(sk);
struct in6_addr *final_p, final;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = sk->sk_protocol;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = np->saddr;
fl6.flowlabel = np->flow_label;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = inet->inet_dport;
fl6.fl6_sport = inet->inet_sport;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
final_p = fl6_update_dst(&fl6, np->opt, &final);
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
sk->sk_route_caps = 0;
sk->sk_err_soft = -PTR_ERR(dst);
return PTR_ERR(dst);
}
__ip6_dst_store(sk, dst, NULL, NULL);
}
return 0;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: BaseShadow::emailUser( const char *subjectline )
{
dprintf(D_FULLDEBUG, "BaseShadow::emailUser() called.\n");
if( !jobAd ) {
return NULL;
}
return email_user_open( jobAd, subjectline );
}
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool RenderLayerCompositor::parentFrameContentLayers(RenderPart* renderer)
{
RenderLayerCompositor* innerCompositor = frameContentsCompositor(renderer);
if (!innerCompositor || !innerCompositor->inCompositingMode() || innerCompositor->rootLayerAttachment() != RootLayerAttachedViaEnclosingFrame)
return false;
RenderLayer* layer = renderer->layer();
if (!layer->hasCompositedLayerMapping())
return false;
CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
GraphicsLayer* hostingLayer = compositedLayerMapping->parentForSublayers();
GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
hostingLayer->removeAllChildren();
hostingLayer->addChild(rootLayer);
}
return true;
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c);
switch (type) {
case EVP_CTRL_INIT:
gctx->key_set = 0;
gctx->iv_set = 0;
gctx->ivlen = EVP_CIPHER_CTX_iv_length(c);
gctx->iv = EVP_CIPHER_CTX_iv_noconst(c);
gctx->taglen = -1;
gctx->iv_gen = 0;
gctx->tls_aad_len = -1;
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
if (arg <= 0)
return 0;
/* Allocate memory for IV if needed */
if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) {
if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c))
OPENSSL_free(gctx->iv);
gctx->iv = OPENSSL_malloc(arg);
if (gctx->iv == NULL)
return 0;
}
gctx->ivlen = arg;
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c))
return 0;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
gctx->taglen = arg;
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c)
|| gctx->taglen < 0)
return 0;
memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg);
return 1;
case EVP_CTRL_GCM_SET_IV_FIXED:
/* Special case: -1 length restores whole IV */
if (arg == -1) {
memcpy(gctx->iv, ptr, gctx->ivlen);
gctx->iv_gen = 1;
return 1;
}
/*
* Fixed field must be at least 4 bytes and invocation field at least
* 8.
*/
if ((arg < 4) || (gctx->ivlen - arg) < 8)
return 0;
if (arg)
memcpy(gctx->iv, ptr, arg);
if (EVP_CIPHER_CTX_encrypting(c)
&& RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0)
return 0;
gctx->iv_gen = 1;
return 1;
case EVP_CTRL_GCM_IV_GEN:
if (gctx->iv_gen == 0 || gctx->key_set == 0)
return 0;
CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
if (arg <= 0 || arg > gctx->ivlen)
arg = gctx->ivlen;
memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg);
/*
* Invocation field will be at least 8 bytes in size and so no need
* to check wrap around or increment more than last 8 bytes.
*/
ctr64_inc(gctx->iv + gctx->ivlen - 8);
gctx->iv_set = 1;
return 1;
case EVP_CTRL_GCM_SET_IV_INV:
if (gctx->iv_gen == 0 || gctx->key_set == 0
|| EVP_CIPHER_CTX_encrypting(c))
return 0;
memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);
CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);
gctx->iv_set = 1;
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
/* Save the AAD for later use */
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
gctx->tls_aad_len = arg;
{
unsigned int len =
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8
| EVP_CIPHER_CTX_buf_noconst(c)[arg - 1];
/* Correct length for explicit IV */
len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
/* If decrypting correct for tag too */
if (!EVP_CIPHER_CTX_encrypting(c))
len -= EVP_GCM_TLS_TAG_LEN;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff;
}
/* Extra padding: tag appended to record */
return EVP_GCM_TLS_TAG_LEN;
case EVP_CTRL_COPY:
{
EVP_CIPHER_CTX *out = ptr;
EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out);
if (gctx->gcm.key) {
if (gctx->gcm.key != &gctx->ks)
return 0;
gctx_out->gcm.key = &gctx_out->ks;
}
if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c))
gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out);
else {
gctx_out->iv = OPENSSL_malloc(gctx->ivlen);
if (gctx_out->iv == NULL)
return 0;
memcpy(gctx_out->iv, gctx->iv, gctx->ivlen);
}
return 1;
}
default:
return -1;
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static struct sock *__iucv_get_sock_by_name(char *nm)
{
struct sock *sk;
sk_for_each(sk, &iucv_sk_list.head)
if (!memcmp(&iucv_sk(sk)->src_name, nm, 8))
return sk;
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: IW_IMPL(int) iw_process_image(struct iw_context *ctx)
{
int ret;
int retval = 0;
if(ctx->use_count>0) {
iw_set_error(ctx,"Internal: Incorrect attempt to reprocess image");
goto done;
}
ctx->use_count++;
ret = iw_prepare_processing(ctx,ctx->canvas_width,ctx->canvas_height);
if(!ret) goto done;
ret = iw_process_internal(ctx);
if(!ret) goto done;
iwpvt_optimize_image(ctx);
retval = 1;
done:
return retval;
}
CWE ID: CWE-787
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int rndis_query_response(USBNetState *s,
rndis_query_msg_type *buf, unsigned int length)
{
rndis_query_cmplt_type *resp;
/* oid_supported_list is the largest data reply */
uint8_t infobuf[sizeof(oid_supported_list)];
uint32_t bufoffs, buflen;
int infobuflen;
unsigned int resplen;
bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
buflen = le32_to_cpu(buf->InformationBufferLength);
if (bufoffs + buflen > length)
return USB_RET_STALL;
infobuflen = ndis_query(s, le32_to_cpu(buf->OID),
bufoffs + (uint8_t *) buf, buflen, infobuf,
resplen = sizeof(rndis_query_cmplt_type) +
((infobuflen < 0) ? 0 : infobuflen);
resp = rndis_queue_response(s, resplen);
if (!resp)
return USB_RET_STALL;
resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);
resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
resp->MessageLength = cpu_to_le32(resplen);
if (infobuflen < 0) {
/* OID not supported */
resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
resp->InformationBufferLength = cpu_to_le32(0);
resp->InformationBufferOffset = cpu_to_le32(0);
return 0;
}
resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
resp->InformationBufferOffset =
cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);
resp->InformationBufferLength = cpu_to_le32(infobuflen);
memcpy(resp + 1, infobuf, infobuflen);
return 0;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void HTMLMediaElement::AudioSourceProviderImpl::ProvideInput(
AudioBus* bus,
size_t frames_to_process) {
DCHECK(bus);
MutexTryLocker try_locker(provide_input_lock);
if (!try_locker.Locked() || !web_audio_source_provider_ || !client_.Get()) {
bus->Zero();
return;
}
unsigned n = bus->NumberOfChannels();
WebVector<float*> web_audio_data(n);
for (unsigned i = 0; i < n; ++i)
web_audio_data[i] = bus->Channel(i)->MutableData();
web_audio_source_provider_->ProvideInput(web_audio_data, frames_to_process);
}
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: IntSize SVGImage::containerSize() const
{
if (!m_page)
return IntSize();
LocalFrame* frame = m_page->mainFrame();
SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
if (!rootElement)
return IntSize();
RenderSVGRoot* renderer = toRenderSVGRoot(rootElement->renderer());
if (!renderer)
return IntSize();
IntSize containerSize = renderer->containerSize();
if (!containerSize.isEmpty())
return containerSize;
ASSERT(renderer->style()->effectiveZoom() == 1);
FloatSize currentSize;
if (rootElement->intrinsicWidth().isFixed() && rootElement->intrinsicHeight().isFixed())
currentSize = rootElement->currentViewportSize();
else
currentSize = rootElement->currentViewBoxRect().size();
if (!currentSize.isEmpty())
return IntSize(static_cast<int>(ceilf(currentSize.width())), static_cast<int>(ceilf(currentSize.height())));
return IntSize(300, 150);
}
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 usage_exit() {
fprintf(stderr, "Usage: %s <infile> <outfile>\n", exec_name);
exit(EXIT_FAILURE);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: AVCodec *avcodec_find_decoder_by_name(const char *name)
{
AVCodec *p;
if (!name)
return NULL;
p = first_avcodec;
while (p) {
if (av_codec_is_decoder(p) && strcmp(name, p->name) == 0)
return p;
p = p->next;
}
return NULL;
}
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: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b = NULL;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey = NULL;
size_t keylen, ivlen, maclen;
int r;
if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
(r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
(r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
(r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
(r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
goto out;
if ((r = mac_setup(mac, mac->name)) != 0)
goto out;
if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
(r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
goto out;
if (maclen > mac->key_len) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
mac->key_len = maclen;
}
if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
(r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
(r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
goto out;
if (enc->name == NULL ||
cipher_by_name(enc->name) != enc->cipher) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (sshbuf_len(b) != 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
enc->key_len = keylen;
enc->iv_len = ivlen;
ssh->kex->newkeys[mode] = newkey;
newkey = NULL;
r = 0;
out:
if (newkey != NULL)
free(newkey);
if (b != NULL)
sshbuf_free(b);
return r;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int get_siz(Jpeg2000DecoderContext *s)
{
int i;
int ncomponents;
uint32_t log2_chroma_wh = 0;
const enum AVPixelFormat *possible_fmts = NULL;
int possible_fmts_nb = 0;
if (bytestream2_get_bytes_left(&s->g) < 36)
return AVERROR_INVALIDDATA;
s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
s->width = bytestream2_get_be32u(&s->g); // Width
s->height = bytestream2_get_be32u(&s->g); // Height
s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
ncomponents = bytestream2_get_be16u(&s->g); // CSiz
if (ncomponents <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
s->ncomponents);
return AVERROR_INVALIDDATA;
}
if (ncomponents > 4) {
avpriv_request_sample(s->avctx, "Support for %d components",
s->ncomponents);
return AVERROR_PATCHWELCOME;
}
s->ncomponents = ncomponents;
if (s->tile_width <= 0 || s->tile_height <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
s->tile_width, s->tile_height);
return AVERROR_INVALIDDATA;
}
if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
return AVERROR_INVALIDDATA;
for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
uint8_t x = bytestream2_get_byteu(&s->g);
s->cbps[i] = (x & 0x7f) + 1;
s->precision = FFMAX(s->cbps[i], s->precision);
s->sgnd[i] = !!(x & 0x80);
s->cdx[i] = bytestream2_get_byteu(&s->g);
s->cdy[i] = bytestream2_get_byteu(&s->g);
if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
|| !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
return AVERROR_INVALIDDATA;
}
log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
}
s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(EINVAL);
}
s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
if (!s->tile) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
Jpeg2000Tile *tile = s->tile + i;
tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
if (!tile->comp)
return AVERROR(ENOMEM);
}
/* compute image size with reduction factor */
s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
s->reduction_factor);
s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
s->reduction_factor);
if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
possible_fmts = xyz_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
} else {
switch (s->colour_space) {
case 16:
possible_fmts = rgb_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
break;
case 17:
possible_fmts = gray_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
break;
case 18:
possible_fmts = yuv_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
break;
default:
possible_fmts = all_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
break;
}
}
for (i = 0; i < possible_fmts_nb; ++i) {
if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
s->avctx->pix_fmt = possible_fmts[i];
break;
}
}
if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
av_log(s->avctx, AV_LOG_ERROR,
"Unknown pix_fmt, profile: %d, colour_space: %d, "
"components: %d, precision: %d, "
"cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n",
s->avctx->profile, s->colour_space, ncomponents, s->precision,
ncomponents > 2 ? s->cdx[1] : 0,
ncomponents > 2 ? s->cdy[1] : 0,
ncomponents > 2 ? s->cdx[2] : 0,
ncomponents > 2 ? s->cdy[2] : 0);
}
s->avctx->bits_per_raw_sample = s->precision;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderWidgetHostViewAndroid::SetContentViewCore(
ContentViewCoreImpl* content_view_core) {
if (content_view_core_ && is_layer_attached_)
content_view_core_->RemoveLayer(layer_);
content_view_core_ = content_view_core;
if (content_view_core_ && is_layer_attached_)
content_view_core_->AttachLayer(layer_);
}
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: std::string ContentBrowserClient::GetStoragePartitionIdForSite(
BrowserContext* browser_context,
const GURL& site) {
return std::string();
}
CWE ID: CWE-264
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int FindStartOffsetOfFileInZipFile(const char* zip_file, const char* filename) {
FileDescriptor fd;
if (!fd.OpenReadOnly(zip_file)) {
LOG_ERRNO("%s: open failed trying to open zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
struct stat stat_buf;
if (stat(zip_file, &stat_buf) == -1) {
LOG_ERRNO("%s: stat failed trying to stat zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
if (stat_buf.st_size > kMaxZipFileLength) {
LOG("%s: The size %ld of %s is too large to map\n",
__FUNCTION__, stat_buf.st_size, zip_file);
return CRAZY_OFFSET_FAILED;
}
void* mem = fd.Map(NULL, stat_buf.st_size, PROT_READ, MAP_PRIVATE, 0);
if (mem == MAP_FAILED) {
LOG_ERRNO("%s: mmap failed trying to mmap zip file %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
ScopedMMap scoped_mmap(mem, stat_buf.st_size);
uint8_t* mem_bytes = static_cast<uint8_t*>(mem);
int off;
for (off = stat_buf.st_size - sizeof(kEndOfCentralDirectoryMarker);
off >= 0; --off) {
if (ReadUInt32(mem_bytes, off) == kEndOfCentralDirectoryMarker) {
break;
}
}
if (off == -1) {
LOG("%s: Failed to find end of central directory in %s\n",
__FUNCTION__, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t length_of_central_dir = ReadUInt32(
mem_bytes, off + kOffsetOfCentralDirLengthInEndOfCentralDirectory);
uint32_t start_of_central_dir = ReadUInt32(
mem_bytes, off + kOffsetOfStartOfCentralDirInEndOfCentralDirectory);
if (start_of_central_dir > off) {
LOG("%s: Found out of range offset %u for start of directory in %s\n",
__FUNCTION__, start_of_central_dir, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t end_of_central_dir = start_of_central_dir + length_of_central_dir;
if (end_of_central_dir > off) {
LOG("%s: Found out of range offset %u for end of directory in %s\n",
__FUNCTION__, end_of_central_dir, zip_file);
return CRAZY_OFFSET_FAILED;
}
uint32_t num_entries = ReadUInt16(
mem_bytes, off + kOffsetNumOfEntriesInEndOfCentralDirectory);
off = start_of_central_dir;
const int target_len = strlen(filename);
int n = 0;
for (; n < num_entries && off < end_of_central_dir; ++n) {
uint32_t marker = ReadUInt32(mem_bytes, off);
if (marker != kCentralDirHeaderMarker) {
LOG("%s: Failed to find central directory header marker in %s. "
"Found 0x%x but expected 0x%x\n", __FUNCTION__,
zip_file, marker, kCentralDirHeaderMarker);
return CRAZY_OFFSET_FAILED;
}
uint32_t file_name_length =
ReadUInt16(mem_bytes, off + kOffsetFilenameLengthInCentralDirectory);
uint32_t extra_field_length =
ReadUInt16(mem_bytes, off + kOffsetExtraFieldLengthInCentralDirectory);
uint32_t comment_field_length =
ReadUInt16(mem_bytes, off + kOffsetCommentLengthInCentralDirectory);
uint32_t header_length = kOffsetFilenameInCentralDirectory +
file_name_length + extra_field_length + comment_field_length;
uint32_t local_header_offset =
ReadUInt32(mem_bytes, off + kOffsetLocalHeaderOffsetInCentralDirectory);
uint8_t* filename_bytes =
mem_bytes + off + kOffsetFilenameInCentralDirectory;
if (file_name_length == target_len &&
memcmp(filename_bytes, filename, target_len) == 0) {
uint32_t marker = ReadUInt32(mem_bytes, local_header_offset);
if (marker != kLocalHeaderMarker) {
LOG("%s: Failed to find local file header marker in %s. "
"Found 0x%x but expected 0x%x\n", __FUNCTION__,
zip_file, marker, kLocalHeaderMarker);
return CRAZY_OFFSET_FAILED;
}
uint32_t compression_method =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetCompressionMethodInLocalHeader);
if (compression_method != kCompressionMethodStored) {
LOG("%s: %s is compressed within %s. "
"Found compression method %u but expected %u\n", __FUNCTION__,
filename, zip_file, compression_method, kCompressionMethodStored);
return CRAZY_OFFSET_FAILED;
}
uint32_t file_name_length =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetFilenameLengthInLocalHeader);
uint32_t extra_field_length =
ReadUInt16(
mem_bytes,
local_header_offset + kOffsetExtraFieldLengthInLocalHeader);
uint32_t header_length =
kOffsetFilenameInLocalHeader + file_name_length + extra_field_length;
return local_header_offset + header_length;
}
off += header_length;
}
if (n < num_entries) {
LOG("%s: Did not find all the expected entries in the central directory. "
"Found %d but expected %d\n", __FUNCTION__, n, num_entries);
}
if (off < end_of_central_dir) {
LOG("%s: There are %d extra bytes at the end of the central directory.\n",
__FUNCTION__, end_of_central_dir - off);
}
LOG("%s: Did not find %s in %s\n", __FUNCTION__, filename, zip_file);
return CRAZY_OFFSET_FAILED;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void TopSitesCache::GenerateCanonicalURLs() {
canonical_urls_.clear();
for (size_t i = 0; i < top_sites_.size(); i++)
StoreRedirectChain(top_sites_[i].redirects, i);
}
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: gdImagePtr gdImageCreateFromWebpPtr (int size, void *data)
{
gdImagePtr im;
gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0);
if (!in)
return 0;
im = gdImageCreateFromWebpCtx(in);
in->gd_free(in);
return im;
}
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: l2tp_q931_cc_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
print_16bits_val(ndo, (const uint16_t *)dat);
ND_PRINT((ndo, ", %02x", dat[2]));
if (length > 3) {
ND_PRINT((ndo, " "));
print_string(ndo, dat+3, length-3);
}
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void GLES2DecoderImpl::DoFlushMappedBufferRange(
GLenum target, GLintptr offset, GLsizeiptr size) {
const char* func_name = "glFlushMappedBufferRange";
if (offset < 0) {
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, "offset < 0");
return;
}
Buffer* buffer = buffer_manager()->GetBufferInfoForTarget(&state_, target);
if (!buffer) {
LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, func_name, "no buffer bound");
return;
}
const Buffer::MappedRange* mapped_range = buffer->GetMappedRange();
if (!mapped_range) {
LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, func_name, "buffer is unmapped");
return;
}
if (!AllBitsSet(mapped_range->access, GL_MAP_FLUSH_EXPLICIT_BIT)) {
LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, func_name,
"buffer is mapped without MAP_FLUSH_EXPLICIT_BIT flag");
return;
}
base::CheckedNumeric<int32_t> range_size = size;
range_size += offset;
if (!range_size.IsValid() ||
range_size.ValueOrDefault(0) > mapped_range->size) {
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name,
"offset + size out of bounds");
return;
}
char* client_data = reinterpret_cast<char*>(mapped_range->GetShmPointer());
DCHECK(client_data);
char* gpu_data = reinterpret_cast<char*>(mapped_range->pointer);
DCHECK(gpu_data);
memcpy(gpu_data + offset, client_data + offset, size);
if (buffer->shadowed()) {
buffer->SetRange(mapped_range->offset + offset, size, client_data + offset);
}
api()->glFlushMappedBufferRangeFn(target, offset, size);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int virtio_net_has_buffers(VirtIONetQueue *q, int bufsize)
{
VirtIONet *n = q->n;
if (virtio_queue_empty(q->rx_vq) ||
(n->mergeable_rx_bufs &&
!virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
virtio_queue_set_notification(q->rx_vq, 1);
/* To avoid a race condition where the guest has made some buffers
* available after the above check but before notification was
* enabled, check for available buffers again.
*/
if (virtio_queue_empty(q->rx_vq) ||
(n->mergeable_rx_bufs &&
!virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
return 0;
}
}
virtio_queue_set_notification(q->rx_vq, 0);
return 1;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void IGDstartelt(void * d, const char * name, int l)
{
struct IGDdatas * datas = (struct IGDdatas *)d;
memcpy( datas->cureltname, name, l);
datas->cureltname[l] = '\0';
datas->level++;
if( (l==7) && !memcmp(name, "service", l) ) {
datas->tmp.controlurl[0] = '\0';
datas->tmp.eventsuburl[0] = '\0';
datas->tmp.scpdurl[0] = '\0';
datas->tmp.servicetype[0] = '\0';
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int php_openssl_make_REQ(struct php_x509_request * req, X509_REQ * csr, zval * dn, zval * attribs TSRMLS_DC)
{
STACK_OF(CONF_VALUE) * dn_sk, *attr_sk = NULL;
char * str, *dn_sect, *attr_sect;
dn_sect = CONF_get_string(req->req_config, req->section_name, "distinguished_name");
if (dn_sect == NULL) {
return FAILURE;
}
dn_sk = CONF_get_section(req->req_config, dn_sect);
if (dn_sk == NULL) {
return FAILURE;
}
attr_sect = CONF_get_string(req->req_config, req->section_name, "attributes");
if (attr_sect == NULL) {
attr_sk = NULL;
} else {
attr_sk = CONF_get_section(req->req_config, attr_sect);
if (attr_sk == NULL) {
return FAILURE;
}
}
/* setup the version number: version 1 */
if (X509_REQ_set_version(csr, 0L)) {
int i, nid;
char * type;
CONF_VALUE * v;
X509_NAME * subj;
HashPosition hpos;
zval ** item;
subj = X509_REQ_get_subject_name(csr);
/* apply values from the dn hash */
zend_hash_internal_pointer_reset_ex(HASH_OF(dn), &hpos);
while(zend_hash_get_current_data_ex(HASH_OF(dn), (void**)&item, &hpos) == SUCCESS) {
char * strindex = NULL;
uint strindexlen = 0;
ulong intindex;
zend_hash_get_current_key_ex(HASH_OF(dn), &strindex, &strindexlen, &intindex, 0, &hpos);
convert_to_string_ex(item);
if (strindex) {
int nid;
nid = OBJ_txt2nid(strindex);
if (nid != NID_undef) {
if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_UTF8,
(unsigned char*)Z_STRVAL_PP(item), -1, -1, 0))
{
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"dn: add_entry_by_NID %d -> %s (failed; check error"
" queue and value of string_mask OpenSSL option "
"if illegal characters are reported)",
nid, Z_STRVAL_PP(item));
return FAILURE;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "dn: %s is not a recognized name", strindex);
}
}
zend_hash_move_forward_ex(HASH_OF(dn), &hpos);
}
/* Finally apply defaults from config file */
for(i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
int len;
char buffer[200 + 1]; /*200 + \0 !*/
v = sk_CONF_VALUE_value(dn_sk, i);
type = v->name;
len = strlen(type);
if (len < sizeof("_default")) {
continue;
}
len -= sizeof("_default") - 1;
if (strcmp("_default", type + len) != 0) {
continue;
}
if (len > 200) {
len = 200;
}
memcpy(buffer, type, len);
buffer[len] = '\0';
type = buffer;
/* Skip past any leading X. X: X, etc to allow for multiple
* instances */
for (str = type; *str; str++) {
if (*str == ':' || *str == ',' || *str == '.') {
str++;
if (*str) {
type = str;
}
break;
}
}
/* if it is already set, skip this */
nid = OBJ_txt2nid(type);
if (X509_NAME_get_index_by_NID(subj, nid, -1) >= 0) {
continue;
}
if (!X509_NAME_add_entry_by_txt(subj, type, MBSTRING_UTF8, (unsigned char*)v->value, -1, -1, 0)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "add_entry_by_txt %s -> %s (failed)", type, v->value);
return FAILURE;
}
if (!X509_NAME_entry_count(subj)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "no objects specified in config file");
return FAILURE;
}
}
if (attribs) {
zend_hash_internal_pointer_reset_ex(HASH_OF(attribs), &hpos);
while(zend_hash_get_current_data_ex(HASH_OF(attribs), (void**)&item, &hpos) == SUCCESS) {
char *strindex = NULL;
uint strindexlen;
ulong intindex;
zend_hash_get_current_key_ex(HASH_OF(attribs), &strindex, &strindexlen, &intindex, 0, &hpos);
convert_to_string_ex(item);
if (strindex) {
int nid;
nid = OBJ_txt2nid(strindex);
if (nid != NID_undef) {
if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_UTF8, (unsigned char*)Z_STRVAL_PP(item), -1, -1, 0)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "attribs: add_entry_by_NID %d -> %s (failed)", nid, Z_STRVAL_PP(item));
return FAILURE;
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "dn: %s is not a recognized name", strindex);
}
}
zend_hash_move_forward_ex(HASH_OF(attribs), &hpos);
}
for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
v = sk_CONF_VALUE_value(attr_sk, i);
/* if it is already set, skip this */
nid = OBJ_txt2nid(v->name);
if (X509_REQ_get_attr_by_NID(csr, nid, -1) >= 0) {
continue;
}
if (!X509_REQ_add1_attr_by_txt(csr, v->name, MBSTRING_UTF8, (unsigned char*)v->value, -1)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"add1_attr_by_txt %s -> %s (failed; check error queue "
"and value of string_mask OpenSSL option if illegal "
"characters are reported)",
v->name, v->value);
return FAILURE;
}
}
}
}
X509_REQ_set_pubkey(csr, req->priv_key);
return SUCCESS;
}
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: ExtensionsGuestViewMessageFilter::FrameNavigationHelper::GetGuestView() const {
return MimeHandlerViewGuest::From(
parent_site_instance_->GetProcess()->GetID(), guest_instance_id_)
->As<MimeHandlerViewGuest>();
}
CWE ID: CWE-362
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr,
char *buf, int *len_ptr)
{
int len, iflags = 0;
struct file_list *flist;
uchar fnamecmp_type = FNAMECMP_FNAME;
int ndx;
read_loop:
while (1) {
ndx = read_ndx(f_in);
if (ndx >= 0)
break;
if (ndx == NDX_DONE)
return ndx;
if (ndx == NDX_DEL_STATS) {
read_del_stats(f_in);
if (am_sender && am_server)
write_del_stats(f_out);
continue;
}
if (!inc_recurse || am_sender) {
int last;
if (first_flist)
last = first_flist->prev->ndx_start + first_flist->prev->used - 1;
else
last = -1;
rprintf(FERROR,
"Invalid file index: %d (%d - %d) [%s]\n",
ndx, NDX_DONE, last, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (ndx == NDX_FLIST_EOF) {
flist_eof = 1;
if (DEBUG_GTE(FLIST, 3))
rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
write_int(f_out, NDX_FLIST_EOF);
continue;
}
ndx = NDX_FLIST_OFFSET - ndx;
if (ndx < 0 || ndx >= dir_flist->used) {
ndx = NDX_FLIST_OFFSET - ndx;
rprintf(FERROR,
"Invalid dir index: %d (%d - %d) [%s]\n",
ndx, NDX_FLIST_OFFSET,
NDX_FLIST_OFFSET - dir_flist->used + 1,
who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
if (DEBUG_GTE(FLIST, 2)) {
rprintf(FINFO, "[%s] receiving flist for dir %d\n",
who_am_i(), ndx);
}
/* Send all the data we read for this flist to the generator. */
start_flist_forward(ndx);
flist = recv_file_list(f_in, ndx);
flist->parent_ndx = ndx;
stop_flist_forward();
}
iflags = protocol_version >= 29 ? read_shortint(f_in)
: ITEM_TRANSFER | ITEM_MISSING_DATA;
/* Support the protocol-29 keep-alive style. */
if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) {
if (am_sender)
maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
goto read_loop;
}
flist = flist_for_ndx(ndx, "read_ndx_and_attrs");
if (flist != cur_flist) {
cur_flist = flist;
if (am_sender) {
file_old_total = cur_flist->used;
for (flist = first_flist; flist != cur_flist; flist = flist->next)
file_old_total += flist->used;
}
}
if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
fnamecmp_type = read_byte(f_in);
*type_ptr = fnamecmp_type;
if (iflags & ITEM_XNAME_FOLLOWS) {
if (iflags & ITEM_XNAME_FOLLOWS) {
if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0)
exit_cleanup(RERR_PROTOCOL);
} else {
*buf = '\0';
len = -1;
rprintf(FERROR,
"received request to transfer non-regular file: %d [%s]\n",
ndx, who_am_i());
exit_cleanup(RERR_PROTOCOL);
}
}
*iflag_ptr = iflags;
return ndx;
}
CWE ID:
Target: 1
Example 2:
Code: static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct perf_event *event = file->private_data;
void (*func)(struct perf_event *);
u32 flags = arg;
switch (cmd) {
case PERF_EVENT_IOC_ENABLE:
func = perf_event_enable;
break;
case PERF_EVENT_IOC_DISABLE:
func = perf_event_disable;
break;
case PERF_EVENT_IOC_RESET:
func = perf_event_reset;
break;
case PERF_EVENT_IOC_REFRESH:
return perf_event_refresh(event, arg);
case PERF_EVENT_IOC_PERIOD:
return perf_event_period(event, (u64 __user *)arg);
case PERF_EVENT_IOC_SET_OUTPUT:
{
int ret;
if (arg != -1) {
struct perf_event *output_event;
struct fd output;
ret = perf_fget_light(arg, &output);
if (ret)
return ret;
output_event = output.file->private_data;
ret = perf_event_set_output(event, output_event);
fdput(output);
} else {
ret = perf_event_set_output(event, NULL);
}
return ret;
}
case PERF_EVENT_IOC_SET_FILTER:
return perf_event_set_filter(event, (void __user *)arg);
default:
return -ENOTTY;
}
if (flags & PERF_IOC_FLAG_GROUP)
perf_event_for_each(event, func);
else
perf_event_for_each_child(event, func);
return 0;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: rcpt_code(thread_t * thread, int status)
{
smtp_t *smtp = THREAD_ARG(thread);
char *fetched_email;
if (status == 250) {
smtp->email_it++;
fetched_email = fetch_next_email(smtp);
if (!fetched_email)
smtp->stage++;
} else {
log_message(LOG_INFO, "Error processing RCPT cmd on SMTP server %s."
" SMTP status code = %d"
, FMT_SMTP_HOST()
, status);
smtp->stage = ERROR;
}
return 0;
}
CWE ID: CWE-59
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)
{
jpc_streamlist_t *streams;
uchar *dataptr;
uint_fast32_t datacnt;
uint_fast32_t tpcnt;
jpc_ppxstabent_t *ent;
int entno;
jas_stream_t *stream;
int n;
if (!(streams = jpc_streamlist_create())) {
goto error;
}
if (!tab->numents) {
return streams;
}
entno = 0;
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
for (;;) {
/* Get the length of the packet header data for the current
tile-part. */
if (datacnt < 4) {
goto error;
}
if (!(stream = jas_stream_memopen(0, 0))) {
goto error;
}
if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),
stream)) {
goto error;
}
tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8)
| dataptr[3];
datacnt -= 4;
dataptr += 4;
/* Get the packet header data for the current tile-part. */
while (tpcnt) {
if (!datacnt) {
if (++entno >= tab->numents) {
goto error;
}
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
}
n = JAS_MIN(tpcnt, datacnt);
if (jas_stream_write(stream, dataptr, n) != n) {
goto error;
}
tpcnt -= n;
dataptr += n;
datacnt -= n;
}
jas_stream_rewind(stream);
if (!datacnt) {
if (++entno >= tab->numents) {
break;
}
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
}
}
return streams;
error:
if (streams) {
jpc_streamlist_destroy(streams);
}
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static unsigned kvm_page_table_hashfn(gfn_t gfn)
{
return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
}
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 BluetoothDeviceChromeOS::RequestAuthorization(
const dbus::ObjectPath& device_path,
const ConfirmationCallback& callback) {
callback.Run(CANCELLED);
}
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: SplashPath *Splash::makeDashedPath(SplashPath *path) {
SplashPath *dPath;
SplashCoord lineDashTotal;
SplashCoord lineDashStartPhase, lineDashDist, segLen;
SplashCoord x0, y0, x1, y1, xa, ya;
GBool lineDashStartOn, lineDashOn, newPath;
int lineDashStartIdx, lineDashIdx;
int i, j, k;
lineDashTotal = 0;
for (i = 0; i < state->lineDashLength; ++i) {
lineDashTotal += state->lineDash[i];
}
if (lineDashTotal == 0) {
return new SplashPath();
}
lineDashStartPhase = state->lineDashPhase;
i = splashFloor(lineDashStartPhase / lineDashTotal);
lineDashStartPhase -= (SplashCoord)i * lineDashTotal;
lineDashStartOn = gTrue;
lineDashStartIdx = 0;
if (lineDashStartPhase > 0) {
while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) {
lineDashStartOn = !lineDashStartOn;
lineDashStartPhase -= state->lineDash[lineDashStartIdx];
++lineDashStartIdx;
}
}
dPath = new SplashPath();
while (i < path->length) {
for (j = i;
j < path->length - 1 && !(path->flags[j] & splashPathLast);
++j) ;
lineDashOn = lineDashStartOn;
lineDashIdx = lineDashStartIdx;
lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase;
newPath = gTrue;
for (k = i; k < j; ++k) {
x0 = path->pts[k].x;
y0 = path->pts[k].y;
x1 = path->pts[k+1].x;
y1 = path->pts[k+1].y;
segLen = splashDist(x0, y0, x1, y1);
while (segLen > 0) {
if (lineDashDist >= segLen) {
if (lineDashOn) {
if (newPath) {
dPath->moveTo(x0, y0);
newPath = gFalse;
}
dPath->lineTo(x1, y1);
}
lineDashDist -= segLen;
segLen = 0;
} else {
xa = x0 + (lineDashDist / segLen) * (x1 - x0);
ya = y0 + (lineDashDist / segLen) * (y1 - y0);
if (lineDashOn) {
if (newPath) {
dPath->moveTo(x0, y0);
newPath = gFalse;
}
dPath->lineTo(xa, ya);
}
x0 = xa;
y0 = ya;
segLen -= lineDashDist;
lineDashDist = 0;
}
if (lineDashDist <= 0) {
lineDashOn = !lineDashOn;
if (++lineDashIdx == state->lineDashLength) {
lineDashIdx = 0;
}
lineDashDist = state->lineDash[lineDashIdx];
newPath = gTrue;
}
}
}
i = j + 1;
}
if (dPath->length == 0) {
GBool allSame = gTrue;
for (int i = 0; allSame && i < path->length - 1; ++i) {
allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y;
}
if (allSame) {
x0 = path->pts[0].x;
y0 = path->pts[0].y;
dPath->moveTo(x0, y0);
dPath->lineTo(x0, y0);
}
}
return dPath;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ChromeDownloadManagerDelegate::DisableSafeBrowsing(DownloadItem* item) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
#if defined(FULL_SAFE_BROWSING)
SafeBrowsingState* state = static_cast<SafeBrowsingState*>(
item->GetUserData(&kSafeBrowsingUserDataKey));
if (!state) {
state = new SafeBrowsingState();
item->SetUserData(&kSafeBrowsingUserDataKey, base::WrapUnique(state));
}
state->CompleteDownload();
#endif
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long Segment::Load() {
assert(m_clusters == NULL);
assert(m_clusterSize == 0);
assert(m_clusterCount == 0);
const long long header_status = ParseHeaders();
if (header_status < 0) // error
return static_cast<long>(header_status);
if (header_status > 0) // underflow
return E_BUFFER_NOT_FULL;
assert(m_pInfo);
assert(m_pTracks);
for (;;) {
const int status = LoadCluster();
if (status < 0) // error
return status;
if (status >= 1) // no more clusters
return 0;
}
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
{
if (origin && BlobURL::getOrigin(url) == "null")
originMap()->add(url.string(), origin);
if (isMainThread())
blobRegistry().registerBlobURL(url, srcURL);
else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
callOnMainThread(®isterBlobURLFromTask, context.leakPtr());
}
}
CWE ID:
Target: 1
Example 2:
Code: WebviewHandler::WebviewHandler() {
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void usage_free(struct snd_seq_usage *res, int num)
{
res->cur -= num;
}
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: BackendImpl::BackendImpl(
const base::FilePath& path,
scoped_refptr<BackendCleanupTracker> cleanup_tracker,
const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread,
net::NetLog* net_log)
: cleanup_tracker_(std::move(cleanup_tracker)),
background_queue_(this, FallbackToInternalIfNull(cache_thread)),
path_(path),
block_files_(path),
mask_(0),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(0),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
net_log_(net_log),
done_(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED),
ptr_factory_(this) {}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static inline key_ref_t __key_update(key_ref_t key_ref,
struct key_preparsed_payload *prep)
{
struct key *key = key_ref_to_ptr(key_ref);
int ret;
/* need write permission on the key to update it */
ret = key_permission(key_ref, KEY_NEED_WRITE);
if (ret < 0)
goto error;
ret = -EEXIST;
if (!key->type->update)
goto error;
down_write(&key->sem);
ret = key->type->update(key, prep);
if (ret == 0)
/* updating a negative key instantiates it */
clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
up_write(&key->sem);
if (ret < 0)
goto error;
out:
return key_ref;
error:
key_put(key);
key_ref = ERR_PTR(ret);
goto out;
}
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 GfxLabColorSpace::getDefaultRanges(double *decodeLow, double *decodeRange,
int maxImgPixel) {
decodeLow[0] = 0;
decodeRange[0] = 100;
decodeLow[1] = aMin;
decodeRange[1] = aMax - aMin;
decodeLow[2] = bMin;
decodeRange[2] = bMax - bMin;
}
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 sfgets(void)
{
struct pollfd pfd;
int pollret;
ssize_t readnb;
signed char seen_r = 0;
static size_t scanned;
static size_t readnbd;
if (scanned > (size_t) 0U) { /* support pipelining */
readnbd -= scanned;
memmove(cmd, cmd + scanned, readnbd); /* safe */
scanned = (size_t) 0U;
}
pfd.fd = clientfd;
#ifdef __APPLE_CC__
pfd.events = POLLIN | POLLERR | POLLHUP;
#else
pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP;
#endif
while (scanned < cmdsize) {
if (scanned >= readnbd) { /* nothing left in the buffer */
pfd.revents = 0;
while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 &&
errno == EINTR);
if (pollret == 0) {
return -1;
}
if (pollret <= 0 ||
(pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
return -2;
}
if ((pfd.revents & (POLLIN | POLLPRI)) == 0) {
continue;
}
if (readnbd >= cmdsize) {
break;
}
#ifdef WITH_TLS
if (tls_cnx != NULL) {
while ((readnb = SSL_read
(tls_cnx, cmd + readnbd, cmdsize - readnbd))
< (ssize_t) 0 && errno == EINTR);
} else
#endif
{
while ((readnb = read(clientfd, cmd + readnbd,
cmdsize - readnbd)) < (ssize_t) 0 &&
errno == EINTR);
}
if (readnb <= (ssize_t) 0) {
return -2;
}
readnbd += readnb;
if (readnbd > cmdsize) {
return -2;
}
}
#ifdef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
if (cmd[scanned] == '\n') {
#ifndef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
cmd[scanned - 1U] = 0;
#ifndef RFC_CONFORMANT_LINES
} else {
cmd[scanned] = 0;
}
#endif
if (++scanned >= readnbd) { /* non-pipelined command */
scanned = readnbd = (size_t) 0U;
}
return 0;
}
seen_r = 0;
#ifdef RFC_CONFORMANT_LINES
}
#endif
if (ISCTRLCODE(cmd[scanned])) {
if (cmd[scanned] == '\r') {
seen_r = 1;
}
#ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */
else if (cmd[scanned] == 0) {
cmd[scanned] = '\n';
}
#else
/* replace control chars with _ */
cmd[scanned] = '_';
#endif
}
scanned++;
}
die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */
return 0; /* to please GCC */
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: explicit MemIterator(base::WeakPtr<MemBackendImpl> backend)
: backend_(backend) {}
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 RenderViewHost::FilterURL(const RenderProcessHost* process,
bool empty_allowed,
GURL* url) {
RenderViewHostImpl::FilterURL(ChildProcessSecurityPolicyImpl::GetInstance(),
process, empty_allowed, url);
}
CWE ID:
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BluetoothDeviceChromeOS::Cancel() {
DCHECK(agent_.get());
VLOG(1) << object_path_.value() << ": Cancel";
DCHECK(pairing_delegate_);
pairing_delegate_->DismissDisplayOrConfirm();
}
CWE ID:
Target: 1
Example 2:
Code: static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
struct shared_msr_entry *msr;
int ret = 0;
u32 msr_index = msr_info->index;
u64 data = msr_info->data;
switch (msr_index) {
case MSR_EFER:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
#ifdef CONFIG_X86_64
case MSR_FS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_FS_BASE, data);
break;
case MSR_GS_BASE:
vmx_segment_cache_clear(vmx);
vmcs_writel(GUEST_GS_BASE, data);
break;
case MSR_KERNEL_GS_BASE:
vmx_load_host_state(vmx);
vmx->msr_guest_kernel_gs_base = data;
break;
#endif
case MSR_IA32_SYSENTER_CS:
vmcs_write32(GUEST_SYSENTER_CS, data);
break;
case MSR_IA32_SYSENTER_EIP:
vmcs_writel(GUEST_SYSENTER_EIP, data);
break;
case MSR_IA32_SYSENTER_ESP:
vmcs_writel(GUEST_SYSENTER_ESP, data);
break;
case MSR_IA32_BNDCFGS:
if (!kvm_mpx_supported() ||
(!msr_info->host_initiated &&
!guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
return 1;
if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
(data & MSR_IA32_BNDCFGS_RSVD))
return 1;
vmcs_write64(GUEST_BNDCFGS, data);
break;
case MSR_IA32_TSC:
kvm_write_tsc(vcpu, msr_info);
break;
case MSR_IA32_CR_PAT:
if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
return 1;
vmcs_write64(GUEST_IA32_PAT, data);
vcpu->arch.pat = data;
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_TSC_ADJUST:
ret = kvm_set_msr_common(vcpu, msr_info);
break;
case MSR_IA32_MCG_EXT_CTL:
if ((!msr_info->host_initiated &&
!(to_vmx(vcpu)->msr_ia32_feature_control &
FEATURE_CONTROL_LMCE)) ||
(data & ~MCG_EXT_CTL_LMCE_EN))
return 1;
vcpu->arch.mcg_ext_ctl = data;
break;
case MSR_IA32_FEATURE_CONTROL:
if (!vmx_feature_control_msr_valid(vcpu, data) ||
(to_vmx(vcpu)->msr_ia32_feature_control &
FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
return 1;
vmx->msr_ia32_feature_control = data;
if (msr_info->host_initiated && data == 0)
vmx_leave_nested(vcpu);
break;
case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
if (!msr_info->host_initiated)
return 1; /* they are read-only */
if (!nested_vmx_allowed(vcpu))
return 1;
return vmx_set_vmx_msr(vcpu, msr_index, data);
case MSR_IA32_XSS:
if (!vmx_xsaves_supported())
return 1;
/*
* The only supported bit as of Skylake is bit 8, but
* it is not supported on KVM.
*/
if (data != 0)
return 1;
vcpu->arch.ia32_xss = data;
if (vcpu->arch.ia32_xss != host_xss)
add_atomic_switch_msr(vmx, MSR_IA32_XSS,
vcpu->arch.ia32_xss, host_xss);
else
clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
break;
case MSR_TSC_AUX:
if (!msr_info->host_initiated &&
!guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
return 1;
/* Check reserved bit, higher 32 bits should be zero */
if ((data >> 32) != 0)
return 1;
/* Otherwise falls through */
default:
msr = find_msr_entry(vmx, msr_index);
if (msr) {
u64 old_msr_data = msr->data;
msr->data = data;
if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
preempt_disable();
ret = kvm_set_shared_msr(msr->index, msr->data,
msr->mask);
preempt_enable();
if (ret)
msr->data = old_msr_data;
}
break;
}
ret = kvm_set_msr_common(vcpu, msr_info);
}
return ret;
}
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: GF_Err sgpd_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupDescriptionBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) fprintf(trace, " default_length=\"%d\"", ptr->default_length);
if ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, " default_group_index=\"%d\"", ptr->default_description_index);
fprintf(trace, ">\n");
for (i=0; i<gf_list_count(ptr->group_descriptions); i++) {
void *entry = gf_list_get(ptr->group_descriptions, i);
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"%d\"/>\n", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable);
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"%s\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known ? "yes" : "no");
if (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known)
fprintf(trace, " num_leading_samples=\"%d\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples);
fprintf(trace, "/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"%d\"/>\n", ((GF_SYNCEntry*)entry)->NALU_type);
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"%d\" IV_size=\"%d\" KID=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16);
if ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) {
fprintf(trace, "\" constant_IV_size=\"%d\" constant_IV=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
}
fprintf(trace, "\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"%d\" SAP_type=\"%d\" />\n", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type);
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"%d\" data=\"", ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
dump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
fprintf(trace, "\"/>\n");
}
}
if (!ptr->size) {
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"yes|no\" num_leading_samples=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"\" IV_size=\"\" KID=\"\" constant_IV_size=\"\" constant_IV=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"\" SAP_type=\"\" />\n");
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"\" data=\"\"/>\n");
}
}
gf_isom_box_dump_done("SampleGroupDescriptionBox", a, trace);
return GF_OK;
}
CWE ID: CWE-125
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian,
const unsigned char *buffer)
{
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
return((unsigned int) (value & 0xffffffff));
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
return((unsigned int) (value & 0xffffffff));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: gfx::Rect TestRenderWidgetHostView::GetViewBounds() const {
return gfx::Rect();
}
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 Browser::TabReplacedAt(TabStripModel* tab_strip_model,
TabContents* old_contents,
TabContents* new_contents,
int index) {
TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE);
SessionService* session_service =
SessionServiceFactory::GetForProfile(profile_);
if (session_service)
session_service->TabClosing(old_contents->web_contents());
TabInsertedAt(new_contents->web_contents(), index, (index == active_index()));
int entry_count =
new_contents->web_contents()->GetController().GetEntryCount();
if (entry_count > 0) {
new_contents->web_contents()->GetController().NotifyEntryChanged(
new_contents->web_contents()->GetController().GetEntryAtIndex(
entry_count - 1),
entry_count - 1);
}
if (session_service) {
session_service->TabRestored(new_contents,
tab_strip_model_->IsTabPinned(index));
}
content::DevToolsManager::GetInstance()->ContentsReplaced(
old_contents->web_contents(), new_contents->web_contents());
}
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: my_object_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
MyObject *mobject;
mobject = MY_OBJECT (object);
switch (prop_id)
{
case PROP_THIS_IS_A_STRING:
g_free (mobject->this_is_a_string);
mobject->this_is_a_string = g_value_dup_string (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: PHP_FUNCTION(imagegammacorrect)
{
zval *IM;
gdImagePtr im;
int i;
double input, output;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rdd", &IM, &input, &output) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (gdImageTrueColor(im)) {
int x, y, c;
for (y = 0; y < gdImageSY(im); y++) {
for (x = 0; x < gdImageSX(im); x++) {
c = gdImageGetPixel(im, x, y);
gdImageSetPixel(im, x, y,
gdTrueColor(
(int) ((pow((pow((gdTrueColorGetRed(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetGreen(c) / 255.0), input)), 1.0 / output) * 255) + .5),
(int) ((pow((pow((gdTrueColorGetBlue(c) / 255.0), input)), 1.0 / output) * 255) + .5)
)
);
}
}
RETURN_TRUE;
}
for (i = 0; i < gdImageColorsTotal(im); i++) {
im->red[i] = (int)((pow((pow((im->red[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->green[i] = (int)((pow((pow((im->green[i] / 255.0), input)), 1.0 / output) * 255) + .5);
im->blue[i] = (int)((pow((pow((im->blue[i] / 255.0), input)), 1.0 / output) * 255) + .5);
}
RETURN_TRUE;
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MockWebRTCPeerConnectionHandler::setLocalDescription(const WebRTCVoidRequest& request, const WebRTCSessionDescriptionDescriptor& localDescription)
{
if (!localDescription.isNull() && localDescription.type() == "offer") {
m_localDescription = localDescription;
postTask(new RTCVoidRequestTask(this, request, true));
} else
postTask(new RTCVoidRequestTask(this, request, false));
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void update_logging() {
bool should_log = module_started &&
(logging_enabled_via_api || stack_config->get_btsnoop_turned_on());
if (should_log == is_logging)
return;
is_logging = should_log;
if (should_log) {
btsnoop_net_open();
const char *log_path = stack_config->get_btsnoop_log_path();
if (stack_config->get_btsnoop_should_save_last()) {
char last_log_path[PATH_MAX];
snprintf(last_log_path, PATH_MAX, "%s.%llu", log_path, btsnoop_timestamp());
if (!rename(log_path, last_log_path) && errno != ENOENT)
LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno));
}
logfile_fd = open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
if (logfile_fd == INVALID_FD) {
LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno));
is_logging = false;
return;
}
write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16);
} else {
if (logfile_fd != INVALID_FD)
close(logfile_fd);
logfile_fd = INVALID_FD;
btsnoop_net_close();
}
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: HTStream *HTMLParsedPresent(HTPresentation *pres,
HTParentAnchor *anchor,
HTStream *sink)
{
HTStream *intermediate = sink;
if (!intermediate) {
/*
* Trick to prevent HTPlainPresent from translating again. Temporarily
* change UCT_STAGE_PARSER setting in anchor while the HTPlain stream
* is initialized, so that HTPlain sees its input and output charsets
* as the same. - kw
*/
int old_parser_cset = HTAnchor_getUCLYhndl(anchor, UCT_STAGE_PARSER);
int structured_cset = HTAnchor_getUCLYhndl(anchor, UCT_STAGE_STRUCTURED);
if (structured_cset < 0)
structured_cset = HTAnchor_getUCLYhndl(anchor, UCT_STAGE_HTEXT);
if (structured_cset < 0)
structured_cset = current_char_set;
HTAnchor_setUCInfoStage(anchor, structured_cset,
UCT_STAGE_PARSER, UCT_SETBY_MIME);
if (pres->rep_out == WWW_SOURCE) {
/* same effect as
intermediate = HTPlainPresent(pres, anchor, NULL);
just written in a more general way:
*/
intermediate = HTStreamStack(WWW_PLAINTEXT, WWW_PRESENT,
NULL, anchor);
} else {
/* this too should amount to calling HTPlainPresent: */
intermediate = HTStreamStack(WWW_PLAINTEXT, pres->rep_out,
NULL, anchor);
}
if (old_parser_cset != structured_cset) {
HTAnchor_resetUCInfoStage(anchor, old_parser_cset,
UCT_STAGE_PARSER, UCT_SETBY_NONE);
if (old_parser_cset >= 0) {
HTAnchor_setUCInfoStage(anchor, old_parser_cset,
UCT_STAGE_PARSER,
UCT_SETBY_DEFAULT + 1);
}
}
}
if (!intermediate)
return NULL;
CTRACE((tfp, "HTMLParsedPresent calling CacheThru_new\n"));
return CacheThru_new(anchor,
SGML_new(&HTML_dtd, anchor,
HTMLGenerator(intermediate)));
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ccid3_hc_rx_getsockopt(struct sock *sk, const int optname, int len,
u32 __user *optval, int __user *optlen)
{
const struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
struct tfrc_rx_info rx_info;
const void *val;
switch (optname) {
case DCCP_SOCKOPT_CCID_RX_INFO:
if (len < sizeof(rx_info))
return -EINVAL;
rx_info.tfrcrx_x_recv = hc->rx_x_recv;
rx_info.tfrcrx_rtt = hc->rx_rtt;
rx_info.tfrcrx_p = tfrc_invert_loss_event_rate(hc->rx_pinv);
len = sizeof(rx_info);
val = &rx_info;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen) || copy_to_user(optval, val, len))
return -EFAULT;
return 0;
}
CWE ID: CWE-200
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
{
int ret;
unsigned char arg[MAX_ARG_LEN];
struct ip_vs_service_user *usvc_compat;
struct ip_vs_service_user_kern usvc;
struct ip_vs_service *svc;
struct ip_vs_dest_user *udest_compat;
struct ip_vs_dest_user_kern udest;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (len != set_arglen[SET_CMDID(cmd)]) {
pr_err("set_ctl: len %u != %u\n",
len, set_arglen[SET_CMDID(cmd)]);
return -EINVAL;
}
if (copy_from_user(arg, user, len) != 0)
return -EFAULT;
/* increase the module use count */
ip_vs_use_count_inc();
if (mutex_lock_interruptible(&__ip_vs_mutex)) {
ret = -ERESTARTSYS;
goto out_dec;
}
if (cmd == IP_VS_SO_SET_FLUSH) {
/* Flush the virtual service */
ret = ip_vs_flush();
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_TIMEOUT) {
/* Set timeout values for (tcp tcpfin udp) */
ret = ip_vs_set_timeout((struct ip_vs_timeout_user *)arg);
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_STARTDAEMON) {
struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
ret = start_sync_thread(dm->state, dm->mcast_ifn, dm->syncid);
goto out_unlock;
} else if (cmd == IP_VS_SO_SET_STOPDAEMON) {
struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
ret = stop_sync_thread(dm->state);
goto out_unlock;
}
usvc_compat = (struct ip_vs_service_user *)arg;
udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
/* We only use the new structs internally, so copy userspace compat
* structs to extended internal versions */
ip_vs_copy_usvc_compat(&usvc, usvc_compat);
ip_vs_copy_udest_compat(&udest, udest_compat);
if (cmd == IP_VS_SO_SET_ZERO) {
/* if no service address is set, zero counters in all */
if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
ret = ip_vs_zero_all();
goto out_unlock;
}
}
/* Check for valid protocol: TCP or UDP, even for fwmark!=0 */
if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP) {
pr_err("set_ctl: invalid protocol: %d %pI4:%d %s\n",
usvc.protocol, &usvc.addr.ip,
ntohs(usvc.port), usvc.sched_name);
ret = -EFAULT;
goto out_unlock;
}
/* Lookup the exact service by <protocol, addr, port> or fwmark */
if (usvc.fwmark == 0)
svc = __ip_vs_service_get(usvc.af, usvc.protocol,
&usvc.addr, usvc.port);
else
svc = __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark);
if (cmd != IP_VS_SO_SET_ADD
&& (svc == NULL || svc->protocol != usvc.protocol)) {
ret = -ESRCH;
goto out_unlock;
}
switch (cmd) {
case IP_VS_SO_SET_ADD:
if (svc != NULL)
ret = -EEXIST;
else
ret = ip_vs_add_service(&usvc, &svc);
break;
case IP_VS_SO_SET_EDIT:
ret = ip_vs_edit_service(svc, &usvc);
break;
case IP_VS_SO_SET_DEL:
ret = ip_vs_del_service(svc);
if (!ret)
goto out_unlock;
break;
case IP_VS_SO_SET_ZERO:
ret = ip_vs_zero_service(svc);
break;
case IP_VS_SO_SET_ADDDEST:
ret = ip_vs_add_dest(svc, &udest);
break;
case IP_VS_SO_SET_EDITDEST:
ret = ip_vs_edit_dest(svc, &udest);
break;
case IP_VS_SO_SET_DELDEST:
ret = ip_vs_del_dest(svc, &udest);
break;
default:
ret = -EINVAL;
}
if (svc)
ip_vs_service_put(svc);
out_unlock:
mutex_unlock(&__ip_vs_mutex);
out_dec:
/* decrease the module use count */
ip_vs_use_count_dec();
return ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ChromePluginServiceFilter::UnrestrictPlugin(
const FilePath& plugin_path) {
base::AutoLock auto_lock(lock_);
restricted_plugins_.erase(plugin_path);
}
CWE ID: CWE-287
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
{
return p->se.cfs_rq;
}
CWE ID: CWE-400
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)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
int debug;
size_t max_mem;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
debug = 0;
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
max_mem = JAS_DEFAULT_MAX_MEM_USAGE;
#endif
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_DEBUG:
debug = atoi(jas_optarg);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_MAXMEM:
max_mem = strtoull(jas_optarg, 0, 10);
break;
case OPT_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
jas_set_max_mem_usage(max_mem);
#endif
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, 0))) {
jas_stream_close(instream);
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
if (!(numcmpts = jas_image_numcmpts(image))) {
fprintf(stderr, "warning: image has no components\n");
}
if (numcmpts) {
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
} else {
width = 0;
height = 0;
depth = 0;
}
if (!(fmtname = jas_image_fmttostr(fmtid))) {
abort();
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void RaiseInfobarForBlocked3DContentOnUIThread(
int render_process_id,
int render_view_id,
const GURL& url,
content::ThreeDAPIType requester) {
RenderViewHost* rvh = RenderViewHost::FromID(
render_process_id, render_view_id);
if (!rvh)
return;
WebContentsImpl* web_contents = static_cast<WebContentsImpl*>(
WebContents::FromRenderViewHost(rvh));
if (!web_contents)
return;
web_contents->DidBlock3DAPIs(url, requester);
}
CWE ID: CWE-287
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual InputMethodDescriptors* GetSupportedInputMethods() {
return GetInputMethodDescriptorsForTesting();
}
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: selReadStream(FILE *fp)
{
char *selname;
char linebuf[L_BUF_SIZE];
l_int32 sy, sx, cy, cx, i, j, version, ignore;
SEL *sel;
PROCNAME("selReadStream");
if (!fp)
return (SEL *)ERROR_PTR("stream not defined", procName, NULL);
if (fscanf(fp, " Sel Version %d\n", &version) != 1)
return (SEL *)ERROR_PTR("not a sel file", procName, NULL);
if (version != SEL_VERSION_NUMBER)
return (SEL *)ERROR_PTR("invalid sel version", procName, NULL);
if (fgets(linebuf, L_BUF_SIZE, fp) == NULL)
return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL);
selname = stringNew(linebuf);
sscanf(linebuf, " ------ %s ------", selname);
if (fscanf(fp, " sy = %d, sx = %d, cy = %d, cx = %d\n",
&sy, &sx, &cy, &cx) != 4) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("dimensions not read", procName, NULL);
}
if ((sel = selCreate(sy, sx, selname)) == NULL) {
LEPT_FREE(selname);
return (SEL *)ERROR_PTR("sel not made", procName, NULL);
}
selSetOrigin(sel, cy, cx);
for (i = 0; i < sy; i++) {
ignore = fscanf(fp, " ");
for (j = 0; j < sx; j++)
ignore = fscanf(fp, "%1d", &sel->data[i][j]);
ignore = fscanf(fp, "\n");
}
ignore = fscanf(fp, "\n");
LEPT_FREE(selname);
return sel;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int inet6_netconf_fill_devconf(struct sk_buff *skb, int ifindex,
struct ipv6_devconf *devconf, u32 portid,
u32 seq, int event, unsigned int flags,
int type)
{
struct nlmsghdr *nlh;
struct netconfmsg *ncm;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct netconfmsg),
flags);
if (nlh == NULL)
return -EMSGSIZE;
ncm = nlmsg_data(nlh);
ncm->ncm_family = AF_INET6;
if (nla_put_s32(skb, NETCONFA_IFINDEX, ifindex) < 0)
goto nla_put_failure;
/* type -1 is used for ALL */
if ((type == -1 || type == NETCONFA_FORWARDING) &&
nla_put_s32(skb, NETCONFA_FORWARDING, devconf->forwarding) < 0)
goto nla_put_failure;
#ifdef CONFIG_IPV6_MROUTE
if ((type == -1 || type == NETCONFA_MC_FORWARDING) &&
nla_put_s32(skb, NETCONFA_MC_FORWARDING,
devconf->mc_forwarding) < 0)
goto nla_put_failure;
#endif
if ((type == -1 || type == NETCONFA_PROXY_NEIGH) &&
nla_put_s32(skb, NETCONFA_PROXY_NEIGH, devconf->proxy_ndp) < 0)
goto nla_put_failure;
nlmsg_end(skb, nlh);
return 0;
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
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 PrintRenderFrameHelper::PrintPagesNative(blink::WebLocalFrame* frame,
int page_count) {
const PrintMsg_PrintPages_Params& params = *print_pages_params_;
const PrintMsg_Print_Params& print_params = params.params;
std::vector<int> printed_pages = GetPrintedPages(params, page_count);
if (printed_pages.empty())
return false;
PdfMetafileSkia metafile(print_params.printed_doc_type);
CHECK(metafile.Init());
for (int page_number : printed_pages) {
PrintPageInternal(print_params, page_number, page_count, frame, &metafile,
nullptr, nullptr);
}
FinishFramePrinting();
metafile.FinishDocument();
#if defined(OS_ANDROID)
int sequence_number = -1;
base::FileDescriptor fd;
Send(new PrintHostMsg_AllocateTempFileForPrinting(routing_id(), &fd,
&sequence_number));
if (!SaveToFD(metafile, fd))
return false;
Send(new PrintHostMsg_TempFileForPrintingWritten(
routing_id(), sequence_number, printed_pages.size()));
return true;
#else
PrintHostMsg_DidPrintDocument_Params page_params;
if (!CopyMetafileDataToSharedMem(metafile,
&page_params.metafile_data_handle)) {
return false;
}
page_params.data_size = metafile.GetDataSize();
page_params.document_cookie = print_params.document_cookie;
Send(new PrintHostMsg_DidPrintDocument(routing_id(), page_params));
return true;
#endif // defined(OS_ANDROID)
}
CWE ID: CWE-787
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ContextualSearchFieldTrial::IsNowOnTapBarIntegrationEnabled() {
return GetBooleanParam(
switches::kEnableContextualSearchNowOnTapBarIntegration,
&is_now_on_tap_bar_integration_enabled_cached_,
&is_now_on_tap_bar_integration_enabled_);
}
CWE ID:
Target: 1
Example 2:
Code: static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
{
if (isRootLineBox)
return toRenderBlock(obj)->createAndAppendRootInlineBox();
if (obj->isText()) {
InlineTextBox* textBox = toRenderText(obj)->createInlineTextBox();
if (obj->isBR())
textBox->setIsText(isOnlyRun || obj->document().inNoQuirksMode());
return textBox;
}
if (obj->isBox())
return toRenderBox(obj)->createInlineBox();
return toRenderInline(obj)->createAndAppendInlineFlowBox();
}
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 RTCPeerConnectionHandler::CloseClientPeerConnection() {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
if (!is_closed_)
client_->ClosePeerConnection();
}
CWE ID: CWE-416
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const Cluster* Segment::FindCluster(long long time_ns) const
{
if ((m_clusters == NULL) || (m_clusterCount <= 0))
return &m_eos;
{
Cluster* const pCluster = m_clusters[0];
assert(pCluster);
assert(pCluster->m_index == 0);
if (time_ns <= pCluster->GetTime())
return pCluster;
}
long i = 0;
long j = m_clusterCount;
while (i < j)
{
const long k = i + (j - i) / 2;
assert(k < m_clusterCount);
Cluster* const pCluster = m_clusters[k];
assert(pCluster);
assert(pCluster->m_index == k);
const long long t = pCluster->GetTime();
if (t <= time_ns)
i = k + 1;
else
j = k;
assert(i <= j);
}
assert(i == j);
assert(i > 0);
assert(i <= m_clusterCount);
const long k = i - 1;
Cluster* const pCluster = m_clusters[k];
assert(pCluster);
assert(pCluster->m_index == k);
assert(pCluster->GetTime() <= time_ns);
return pCluster;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void nci_add_new_target(struct nci_dev *ndev,
struct nci_rf_discover_ntf *ntf)
{
struct nfc_target *target;
int i, rc;
for (i = 0; i < ndev->n_targets; i++) {
target = &ndev->targets[i];
if (target->logical_idx == ntf->rf_discovery_id) {
/* This target already exists, add the new protocol */
nci_add_new_protocol(ndev, target, ntf->rf_protocol,
ntf->rf_tech_and_mode,
&ntf->rf_tech_specific_params);
return;
}
}
/* This is a new target, check if we've enough room */
if (ndev->n_targets == NCI_MAX_DISCOVERED_TARGETS) {
pr_debug("not enough room, ignoring new target...\n");
return;
}
target = &ndev->targets[ndev->n_targets];
rc = nci_add_new_protocol(ndev, target, ntf->rf_protocol,
ntf->rf_tech_and_mode,
&ntf->rf_tech_specific_params);
if (!rc) {
target->logical_idx = ntf->rf_discovery_id;
ndev->n_targets++;
pr_debug("logical idx %d, n_targets %d\n", target->logical_idx,
ndev->n_targets);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int writepng_init(mainprog_info *mainprog_ptr)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
int color_type, interlace_type;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
writepng_error_handler, NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
return 4; /* out of memory */
}
/* setjmp() must be called in every function that calls a PNG-writing
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or some other method to return control to
* application code, so here we go: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 2;
}
/* make sure outfile is (re)opened in BINARY mode */
png_init_io(png_ptr, mainprog_ptr->outfile);
/* set the compression levels--in general, always want to leave filtering
* turned on (except for palette images) and allow all of the filters,
* which is the default; want 32K zlib window, unless entire image buffer
* is 16K or smaller (unknown here)--also the default; usually want max
* compression (NOT the default); and remaining compression flags should
* be left alone */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/*
>> this is default for no filtering; Z_FILTERED is default otherwise:
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
>> these are all defaults:
png_set_compression_mem_level(png_ptr, 8);
png_set_compression_window_bits(png_ptr, 15);
png_set_compression_method(png_ptr, 8);
*/
/* set the image parameters appropriately */
if (mainprog_ptr->pnmtype == 5)
color_type = PNG_COLOR_TYPE_GRAY;
else if (mainprog_ptr->pnmtype == 6)
color_type = PNG_COLOR_TYPE_RGB;
else if (mainprog_ptr->pnmtype == 8)
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
else {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 11;
}
interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 :
PNG_INTERLACE_NONE;
png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
mainprog_ptr->sample_depth, color_type, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (mainprog_ptr->gamma > 0.0)
png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma);
if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */
png_color_16 background;
background.red = mainprog_ptr->bg_red;
background.green = mainprog_ptr->bg_green;
background.blue = mainprog_ptr->bg_blue;
png_set_bKGD(png_ptr, info_ptr, &background);
}
if (mainprog_ptr->have_time) {
png_time modtime;
png_convert_from_time_t(&modtime, mainprog_ptr->modtime);
png_set_tIME(png_ptr, info_ptr, &modtime);
}
if (mainprog_ptr->have_text) {
png_text text[6];
int num_text = 0;
if (mainprog_ptr->have_text & TEXT_TITLE) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Title";
text[num_text].text = mainprog_ptr->title;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_AUTHOR) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Author";
text[num_text].text = mainprog_ptr->author;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_DESC) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Description";
text[num_text].text = mainprog_ptr->desc;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_COPY) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Copyright";
text[num_text].text = mainprog_ptr->copyright;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_EMAIL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "E-mail";
text[num_text].text = mainprog_ptr->email;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_URL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "URL";
text[num_text].text = mainprog_ptr->url;
++num_text;
}
png_set_text(png_ptr, info_ptr, text, num_text);
}
/* write all chunks up to (but not including) first IDAT */
png_write_info(png_ptr, info_ptr);
/* if we wanted to write any more text info *after* the image data, we
* would set up text struct(s) here and call png_set_text() again, with
* just the new data; png_set_tIME() could also go here, but it would
* have no effect since we already called it above (only one tIME chunk
* allowed) */
/* set up the transformations: for now, just pack low-bit-depth pixels
* into bytes (one, two or four pixels per byte) */
png_set_packing(png_ptr);
/* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */
/* make sure we save our pointers for use in writepng_encode_image() */
mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
/* OK, that's all we need to do for now; return happy */
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: WebString WebPageSerializer::generateMetaCharsetDeclaration(const WebString& charset)
{
String charsetString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + static_cast<const String&>(charset) + "\">";
return charsetString;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void TabSpecificContentSettings::RemoveSiteDataObserver(
SiteDataObserver* observer) {
observer_list_.RemoveObserver(observer);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int fscrypt_get_encryption_info(struct inode *inode)
{
struct fscrypt_info *ci = inode->i_crypt_info;
if (!ci ||
(ci->ci_keyring_key &&
(ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) |
(1 << KEY_FLAG_REVOKED) |
(1 << KEY_FLAG_DEAD)))))
return fscrypt_get_crypt_info(inode);
return 0;
}
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: SchedulerObject::setAttribute(std::string key,
std::string name,
std::string value,
std::string &text)
{
PROC_ID id = getProcByString(key.c_str());
if (id.cluster < 0 || id.proc < 0) {
dprintf(D_FULLDEBUG, "SetAttribute: Failed to parse id: %s\n", key.c_str());
text = "Invalid Id";
return false;
}
if (isSubmissionChange(name.c_str())) {
text = "Changes to submission name not allowed";
return false;
}
if (isKeyword(name.c_str())) {
text = "Attribute name is reserved: " + name;
return false;
}
if (!isValidAttributeName(name,text)) {
return false;
}
if (::SetAttribute(id.cluster,
id.proc,
name.c_str(),
value.c_str())) {
text = "Failed to set attribute " + name + " to " + value;
return false;
}
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void CheckFrameDepth(unsigned int expected_depth, FrameTreeNode* node) {
EXPECT_EQ(expected_depth, node->depth());
RenderProcessHost::Priority priority =
node->current_frame_host()->GetRenderWidgetHost()->GetPriority();
EXPECT_EQ(expected_depth, priority.frame_depth);
EXPECT_EQ(expected_depth,
node->current_frame_host()->GetProcess()->GetFrameDepth());
}
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: bool venc_dev::venc_set_vpe_rotation(OMX_S32 rotation_angle)
{
DEBUG_PRINT_LOW("venc_set_vpe_rotation: rotation angle = %d", (int)rotation_angle);
struct v4l2_control control;
int rc;
struct v4l2_format fmt;
struct v4l2_requestbuffers bufreq;
control.id = V4L2_CID_MPEG_VIDC_VIDEO_ROTATION;
if (rotation_angle == 0)
control.value = V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_NONE;
else if (rotation_angle == 90)
control.value = V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_90;
else if (rotation_angle == 180)
control.value = V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_180;
else if (rotation_angle == 270)
control.value = V4L2_CID_MPEG_VIDC_VIDEO_ROTATION_270;
else {
DEBUG_PRINT_ERROR("Failed to find valid rotation angle");
return false;
}
DEBUG_PRINT_LOW("Calling IOCTL set control for id=%x, val=%d", control.id, control.value);
rc = ioctl(m_nDriver_fd, VIDIOC_S_CTRL, &control);
if (rc) {
DEBUG_PRINT_HIGH("Failed to set VPE Rotation control");
return false;
}
DEBUG_PRINT_LOW("Success IOCTL set control for id=%x, value=%d", control.id, control.value);
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
fmt.fmt.pix_mp.height = m_sVenc_cfg.dvs_height;
fmt.fmt.pix_mp.width = m_sVenc_cfg.dvs_width;
fmt.fmt.pix_mp.pixelformat = m_sVenc_cfg.codectype;
if (ioctl(m_nDriver_fd, VIDIOC_S_FMT, &fmt)) {
DEBUG_PRINT_ERROR("Failed to set format on capture port");
return false;
}
m_sOutput_buff_property.datasize = fmt.fmt.pix_mp.plane_fmt[0].sizeimage;
bufreq.memory = V4L2_MEMORY_USERPTR;
bufreq.count = m_sOutput_buff_property.actualcount;
bufreq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
if (ioctl(m_nDriver_fd,VIDIOC_REQBUFS, &bufreq)) {
DEBUG_PRINT_ERROR("ERROR: Request for o/p buffer count failed for rotation");
return false;
}
if (bufreq.count >= m_sOutput_buff_property.mincount)
m_sOutput_buff_property.actualcount = m_sOutput_buff_property.mincount = bufreq.count;
return true;
}
CWE ID: CWE-200
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int hci_uart_set_proto(struct hci_uart *hu, int id)
{
const struct hci_uart_proto *p;
int err;
p = hci_uart_get_proto(id);
if (!p)
return -EPROTONOSUPPORT;
hu->proto = p;
set_bit(HCI_UART_PROTO_READY, &hu->flags);
err = hci_uart_register_dev(hu);
if (err) {
clear_bit(HCI_UART_PROTO_READY, &hu->flags);
return err;
}
return 0;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: static void qeth_switch_to_packing_if_needed(struct qeth_qdio_out_q *queue)
{
if (!queue->do_pack) {
if (atomic_read(&queue->used_buffers)
>= QETH_HIGH_WATERMARK_PACK){
/* switch non-PACKING -> PACKING */
QETH_CARD_TEXT(queue->card, 6, "np->pack");
if (queue->card->options.performance_stats)
queue->card->perf_stats.sc_dp_p++;
queue->do_pack = 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: init_open_stateid(struct nfs4_file *fp, struct nfsd4_open *open)
{
struct nfs4_openowner *oo = open->op_openowner;
struct nfs4_ol_stateid *retstp = NULL;
struct nfs4_ol_stateid *stp;
stp = open->op_stp;
/* We are moving these outside of the spinlocks to avoid the warnings */
mutex_init(&stp->st_mutex);
mutex_lock(&stp->st_mutex);
spin_lock(&oo->oo_owner.so_client->cl_lock);
spin_lock(&fp->fi_lock);
retstp = nfsd4_find_existing_open(fp, open);
if (retstp)
goto out_unlock;
open->op_stp = NULL;
atomic_inc(&stp->st_stid.sc_count);
stp->st_stid.sc_type = NFS4_OPEN_STID;
INIT_LIST_HEAD(&stp->st_locks);
stp->st_stateowner = nfs4_get_stateowner(&oo->oo_owner);
get_nfs4_file(fp);
stp->st_stid.sc_file = fp;
stp->st_access_bmap = 0;
stp->st_deny_bmap = 0;
stp->st_openstp = NULL;
list_add(&stp->st_perstateowner, &oo->oo_owner.so_stateids);
list_add(&stp->st_perfile, &fp->fi_stateids);
out_unlock:
spin_unlock(&fp->fi_lock);
spin_unlock(&oo->oo_owner.so_client->cl_lock);
if (retstp) {
mutex_lock(&retstp->st_mutex);
/* To keep mutex tracking happy */
mutex_unlock(&stp->st_mutex);
stp = retstp;
}
return stp;
}
CWE ID: CWE-404
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ShellWindowFrameView::OnPaint(gfx::Canvas* canvas) {
SkPaint paint;
paint.setAntiAlias(false);
paint.setStyle(SkPaint::kFill_Style);
paint.setColor(SK_ColorWHITE);
gfx::Path path;
const int radius = 1;
path.moveTo(0, radius);
path.lineTo(radius, 0);
path.lineTo(width() - radius - 1, 0);
path.lineTo(width(), radius + 1);
path.lineTo(width(), kCaptionHeight);
path.lineTo(0, kCaptionHeight);
path.close();
canvas->DrawPath(path, paint);
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: int JBIG2MMRDecoder::getWhiteCode() {
const CCITTCode *p;
Guint code;
if (bufLen == 0) {
buf = str->getChar() & 0xff;
bufLen = 8;
++nBytesRead;
}
while (1) {
if (bufLen >= 11 && ((buf >> (bufLen - 7)) & 0x7f) == 0) {
if (bufLen <= 12) {
code = buf << (12 - bufLen);
} else {
code = buf >> (bufLen - 12);
}
p = &whiteTab1[code & 0x1f];
} else {
if (bufLen <= 9) {
code = buf << (9 - bufLen);
} else {
code = buf >> (bufLen - 9);
}
p = &whiteTab2[code & 0x1ff];
}
if (p->bits > 0 && p->bits <= (int)bufLen) {
bufLen -= p->bits;
return p->n;
}
if (bufLen >= 12) {
break;
}
buf = (buf << 8) | (str->getChar() & 0xff);
bufLen += 8;
++nBytesRead;
}
error(str->getPos(), "Bad white code in JBIG2 MMR stream");
--bufLen;
return 1;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void set_data_queue(fixed_queue_t *queue) {
upwards_data_queue = queue;
}
CWE ID: CWE-284
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void wdm_in_callback(struct urb *urb)
{
struct wdm_device *desc = urb->context;
int status = urb->status;
spin_lock(&desc->iuspin);
clear_bit(WDM_RESPONDING, &desc->flags);
if (status) {
switch (status) {
case -ENOENT:
dev_dbg(&desc->intf->dev,
"nonzero urb status received: -ENOENT");
goto skip_error;
case -ECONNRESET:
dev_dbg(&desc->intf->dev,
"nonzero urb status received: -ECONNRESET");
goto skip_error;
case -ESHUTDOWN:
dev_dbg(&desc->intf->dev,
"nonzero urb status received: -ESHUTDOWN");
goto skip_error;
case -EPIPE:
dev_err(&desc->intf->dev,
"nonzero urb status received: -EPIPE\n");
break;
default:
dev_err(&desc->intf->dev,
"Unexpected error %d\n", status);
break;
}
}
desc->rerr = status;
desc->reslength = urb->actual_length;
memmove(desc->ubuf + desc->length, desc->inbuf, desc->reslength);
desc->length += desc->reslength;
skip_error:
wake_up(&desc->wait);
set_bit(WDM_READ, &desc->flags);
spin_unlock(&desc->iuspin);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: phar_entry_info *phar_get_link_source(phar_entry_info *entry TSRMLS_DC) /* {{{ */
{
phar_entry_info *link_entry;
char *link;
if (!entry->link) {
return entry;
}
link = phar_get_link_location(entry TSRMLS_CC);
if (SUCCESS == zend_hash_find(&(entry->phar->manifest), entry->link, strlen(entry->link), (void **)&link_entry) ||
SUCCESS == zend_hash_find(&(entry->phar->manifest), link, strlen(link), (void **)&link_entry)) {
if (link != entry->link) {
efree(link);
}
return phar_get_link_source(link_entry TSRMLS_CC);
} else {
if (link != entry->link) {
efree(link);
}
return NULL;
}
}
/* }}} */
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Node* DOMPatchSupport::patchNode(Node* node, const String& markup, ExceptionCode& ec)
{
if (node->isDocumentNode() || (node->parentNode() && node->parentNode()->isDocumentNode())) {
patchDocument(markup);
return 0;
}
Node* previousSibling = node->previousSibling();
RefPtr<DocumentFragment> fragment = DocumentFragment::create(m_document);
fragment->parseHTML(markup, node->parentElement() ? node->parentElement() : m_document->documentElement());
ContainerNode* parentNode = node->parentNode();
Vector<OwnPtr<Digest> > oldList;
for (Node* child = parentNode->firstChild(); child; child = child->nextSibling())
oldList.append(createDigest(child, 0));
String markupCopy = markup;
markupCopy.makeLower();
Vector<OwnPtr<Digest> > newList;
for (Node* child = parentNode->firstChild(); child != node; child = child->nextSibling())
newList.append(createDigest(child, 0));
for (Node* child = fragment->firstChild(); child; child = child->nextSibling()) {
if (child->hasTagName(headTag) && !child->firstChild() && markupCopy.find("</head>") == notFound)
continue; // HTML5 parser inserts empty <head> tag whenever it parses <body>
if (child->hasTagName(bodyTag) && !child->firstChild() && markupCopy.find("</body>") == notFound)
continue; // HTML5 parser inserts empty <body> tag whenever it parses </head>
newList.append(createDigest(child, &m_unusedNodesMap));
}
for (Node* child = node->nextSibling(); child; child = child->nextSibling())
newList.append(createDigest(child, 0));
if (!innerPatchChildren(parentNode, oldList, newList, ec)) {
ec = 0;
if (!m_domEditor->replaceChild(parentNode, fragment.release(), node, ec))
return 0;
}
return previousSibling ? previousSibling->nextSibling() : parentNode->firstChild();
}
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: void MediaStreamDispatcherHost::DoOpenDevice(
int32_t page_request_id,
const std::string& device_id,
blink::MediaStreamType type,
OpenDeviceCallback callback,
MediaDeviceSaltAndOrigin salt_and_origin) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!MediaStreamManager::IsOriginAllowed(render_process_id_,
salt_and_origin.origin)) {
std::move(callback).Run(false /* success */, std::string(),
blink::MediaStreamDevice());
return;
}
media_stream_manager_->OpenDevice(
render_process_id_, render_frame_id_, page_request_id, requester_id_,
device_id, type, std::move(salt_and_origin), std::move(callback),
base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped,
weak_factory_.GetWeakPtr()));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ChromeContentBrowserClient::ClearInspectorSettings(RenderViewHost* rvh) {
RenderViewHostDelegateHelper::ClearInspectorSettings(
rvh->process()->profile());
}
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 tls1_alpn_handle_client_hello(SSL *s, const unsigned char *data,
unsigned data_len, int *al)
{
unsigned i;
unsigned proto_len;
const unsigned char *selected;
unsigned char selected_len;
int r;
if (s->ctx->alpn_select_cb == NULL)
return 0;
if (data_len < 2)
goto parse_error;
/* data should contain a uint16 length followed by a series of 8-bit,
* length-prefixed strings. */
i = ((unsigned) data[0]) << 8 |
((unsigned) data[1]);
data_len -= 2;
data += 2;
if (data_len != i)
goto parse_error;
if (data_len < 2)
goto parse_error;
for (i = 0; i < data_len;)
{
proto_len = data[i];
i++;
if (proto_len == 0)
goto parse_error;
if (i + proto_len < i || i + proto_len > data_len)
goto parse_error;
i += proto_len;
}
r = s->ctx->alpn_select_cb(s, &selected, &selected_len, data, data_len,
s->ctx->alpn_select_cb_arg);
if (r == SSL_TLSEXT_ERR_OK) {
if (s->s3->alpn_selected)
OPENSSL_free(s->s3->alpn_selected);
s->s3->alpn_selected = OPENSSL_malloc(selected_len);
if (!s->s3->alpn_selected)
{
*al = SSL_AD_INTERNAL_ERROR;
return -1;
}
memcpy(s->s3->alpn_selected, selected, selected_len);
s->s3->alpn_selected_len = selected_len;
}
return 0;
parse_error:
*al = SSL_AD_DECODE_ERROR;
return -1;
}
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 WebGLRenderingContextBase::ValidateHTMLImageElement(
const SecurityOrigin* security_origin,
const char* function_name,
HTMLImageElement* image,
ExceptionState& exception_state) {
if (!image || !image->CachedImage()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "no image");
return false;
}
const KURL& url = image->CachedImage()->GetResponse().Url();
if (url.IsNull() || url.IsEmpty() || !url.IsValid()) {
SynthesizeGLError(GL_INVALID_VALUE, function_name, "invalid image");
return false;
}
if (WouldTaintOrigin(image, security_origin)) {
exception_state.ThrowSecurityError("The cross-origin image at " +
url.ElidedString() +
" may not be loaded.");
return false;
}
return true;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: ChromeNetworkDelegate::ChromeNetworkDelegate(
extensions::EventRouterForwarder* event_router,
BooleanPrefMember* enable_referrers)
: event_router_(event_router),
profile_(NULL),
enable_referrers_(enable_referrers),
enable_do_not_track_(NULL),
force_google_safe_search_(NULL),
url_blacklist_manager_(NULL),
load_time_stats_(NULL),
received_content_length_(0),
original_content_length_(0) {
DCHECK(event_router);
DCHECK(enable_referrers);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool IsManualFallbackForFillingEnabled() {
return base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksFilling) &&
!IsPreLollipopAndroid();
}
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: void *atomic_thread_inc_dec(void *context) {
struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context;
for (int i = 0; i < at->max_val; i++) {
usleep(1);
atomic_inc_prefix_s32(&at->data[i]);
usleep(1);
atomic_dec_prefix_s32(&at->data[i]);
}
return NULL;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: gboolean BrowserWindowGtk::OnMainWindowDeleteEvent(GtkWidget* widget,
GdkEvent* event) {
Close();
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: Blob::Blob()
: m_size(0)
{
ScriptWrappable::init(this);
OwnPtr<BlobData> blobData = BlobData::create();
m_internalURL = BlobURL::createInternalURL();
ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData.release());
}
CWE ID:
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int SoundPool::load(const char* path, int priority __unused)
{
ALOGV("load: path=%s, priority=%d", path, priority);
Mutex::Autolock lock(&mLock);
sp<Sample> sample = new Sample(++mNextSampleID, path);
mSamples.add(sample->sampleID(), sample);
doLoad(sample);
return sample->sampleID();
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: nvmet_fc_xmt_fcp_rsp(struct nvmet_fc_tgtport *tgtport,
struct nvmet_fc_fcp_iod *fod)
{
int ret;
fod->fcpreq->op = NVMET_FCOP_RSP;
fod->fcpreq->timeout = 0;
nvmet_fc_prep_fcp_rsp(tgtport, fod);
ret = tgtport->ops->fcp_op(&tgtport->fc_target_port, fod->fcpreq);
if (ret)
nvmet_fc_abort_op(tgtport, fod);
}
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: long long SegmentInfo::GetTimeCodeScale() const
{
return m_timecodeScale;
}
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 git_pkt_parse_line(
git_pkt **head, const char *line, const char **out, size_t bufflen)
{
int ret;
int32_t len;
/* Not even enough for the length */
if (bufflen > 0 && bufflen < PKT_LEN_SIZE)
return GIT_EBUFS;
len = parse_len(line);
if (len < 0) {
/*
* If we fail to parse the length, it might be because the
* server is trying to send us the packfile already.
*/
if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) {
giterr_clear();
*out = line;
return pack_pkt(head);
}
return (int)len;
}
/*
* If we were given a buffer length, then make sure there is
* enough in the buffer to satisfy this line
*/
if (bufflen > 0 && bufflen < (size_t)len)
return GIT_EBUFS;
/*
* The length has to be exactly 0 in case of a flush
* packet or greater than PKT_LEN_SIZE, as the decoded
* length includes its own encoded length of four bytes.
*/
if (len != 0 && len < PKT_LEN_SIZE)
return GIT_ERROR;
line += PKT_LEN_SIZE;
/*
* TODO: How do we deal with empty lines? Try again? with the next
* line?
*/
if (len == PKT_LEN_SIZE) {
*head = NULL;
*out = line;
return 0;
}
if (len == 0) { /* Flush pkt */
*out = line;
return flush_pkt(head);
}
len -= PKT_LEN_SIZE; /* the encoded length includes its own size */
if (*line == GIT_SIDE_BAND_DATA)
ret = data_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_PROGRESS)
ret = sideband_progress_pkt(head, line, len);
else if (*line == GIT_SIDE_BAND_ERROR)
ret = sideband_error_pkt(head, line, len);
else if (!git__prefixcmp(line, "ACK"))
ret = ack_pkt(head, line, len);
else if (!git__prefixcmp(line, "NAK"))
ret = nak_pkt(head);
else if (!git__prefixcmp(line, "ERR "))
ret = err_pkt(head, line, len);
else if (*line == '#')
ret = comment_pkt(head, line, len);
else if (!git__prefixcmp(line, "ok"))
ret = ok_pkt(head, line, len);
else if (!git__prefixcmp(line, "ng"))
ret = ng_pkt(head, line, len);
else if (!git__prefixcmp(line, "unpack"))
ret = unpack_pkt(head, line, len);
else
ret = ref_pkt(head, line, len);
*out = line + len;
return ret;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void fsl_emb_pmu_stop(struct perf_event *event, int ef_flags)
{
unsigned long flags;
if (event->hw.idx < 0 || !event->hw.sample_period)
return;
if (event->hw.state & PERF_HES_STOPPED)
return;
local_irq_save(flags);
perf_pmu_disable(event->pmu);
fsl_emb_pmu_read(event);
event->hw.state |= PERF_HES_STOPPED | PERF_HES_UPTODATE;
write_pmc(event->hw.idx, 0);
perf_event_update_userpage(event);
perf_pmu_enable(event->pmu);
local_irq_restore(flags);
}
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: JsVar *jslGetTokenValueAsVar() {
if (lex->tokenValue) {
return jsvLockAgain(lex->tokenValue);
} else {
assert(lex->tokenl < JSLEX_MAX_TOKEN_LENGTH);
lex->token[lex->tokenl] = 0; // add final null
return jsvNewFromString(lex->token);
}
}
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 CLASS ljpeg_start (struct jhead *jh, int info_only)
{
int c, tag, len;
uchar data[0x10000];
const uchar *dp;
memset (jh, 0, sizeof *jh);
jh->restart = INT_MAX;
fread (data, 2, 1, ifp);
if (data[1] != 0xd8) return 0;
do {
fread (data, 2, 2, ifp);
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00) return 0;
fread (data, 1, len, ifp);
switch (tag) {
case 0xffc3:
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc0:
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version) getc(ifp);
break;
case 0xffc4:
if (info_only) break;
for (dp = data; dp < data+len && (c = *dp++) < 4; )
jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
break;
case 0xffda:
jh->psv = data[1+data[0]*2];
jh->bits -= data[3+data[0]*2] & 15;
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (info_only) return 1;
FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
if (jh->sraw) {
FORC(4) jh->huff[2+c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
}
jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);
merror (jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void memrevifle(void *ptr, size_t len) {
unsigned char *p = (unsigned char *)ptr,
*e = (unsigned char *)p+len-1,
aux;
int test = 1;
unsigned char *testp = (unsigned char*) &test;
if (testp[0] == 0) return; /* Big endian, nothing to do. */
len /= 2;
while(len--) {
aux = *p;
*p = *e;
*e = aux;
p++;
e--;
}
}
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 Verify_StoreExistingGroupExistingCache(base::Time expected_update_time) {
EXPECT_TRUE(delegate()->stored_group_success_);
EXPECT_EQ(cache_.get(), group_->newest_complete_cache());
AppCacheDatabase::CacheRecord cache_record;
EXPECT_TRUE(database()->FindCache(1, &cache_record));
EXPECT_EQ(1, cache_record.cache_id);
EXPECT_EQ(1, cache_record.group_id);
EXPECT_FALSE(cache_record.online_wildcard);
EXPECT_TRUE(expected_update_time == cache_record.update_time);
EXPECT_EQ(100 + kDefaultEntrySize, cache_record.cache_size);
std::vector<AppCacheDatabase::EntryRecord> entry_records;
EXPECT_TRUE(database()->FindEntriesForCache(1, &entry_records));
EXPECT_EQ(2U, entry_records.size());
if (entry_records[0].url == kDefaultEntryUrl)
entry_records.erase(entry_records.begin());
EXPECT_EQ(1, entry_records[0].cache_id);
EXPECT_EQ(kEntryUrl, entry_records[0].url);
EXPECT_EQ(AppCacheEntry::MASTER, entry_records[0].flags);
EXPECT_EQ(1, entry_records[0].response_id);
EXPECT_EQ(100, entry_records[0].response_size);
EXPECT_EQ(100 + kDefaultEntrySize, storage()->usage_map_[kOrigin]);
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(100, mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied, err;
struct sockaddr_ll *sll;
int vnet_hdr_len = 0;
err = -EINVAL;
if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
goto out;
#if 0
/* What error should we return now? EUNATTACH? */
if (pkt_sk(sk)->ifindex < 0)
return -ENODEV;
#endif
if (flags & MSG_ERRQUEUE) {
err = packet_recv_error(sk, msg, len);
goto out;
}
/*
* Call the generic datagram receiver. This handles all sorts
* of horrible races and re-entrancy so we can forget about it
* in the protocol layers.
*
* Now it will return ENETDOWN, if device have just gone down,
* but then it will block.
*/
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
/*
* An error occurred so return it. Because skb_recv_datagram()
* handles the blocking we don't see and worry about blocking
* retries.
*/
if (skb == NULL)
goto out;
if (pkt_sk(sk)->has_vnet_hdr) {
struct virtio_net_hdr vnet_hdr = { 0 };
err = -EINVAL;
vnet_hdr_len = sizeof(vnet_hdr);
if (len < vnet_hdr_len)
goto out_free;
len -= vnet_hdr_len;
if (skb_is_gso(skb)) {
struct skb_shared_info *sinfo = skb_shinfo(skb);
/* This is a hint as to how much should be linear. */
vnet_hdr.hdr_len = skb_headlen(skb);
vnet_hdr.gso_size = sinfo->gso_size;
if (sinfo->gso_type & SKB_GSO_TCPV4)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
else if (sinfo->gso_type & SKB_GSO_TCPV6)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
else if (sinfo->gso_type & SKB_GSO_UDP)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
else if (sinfo->gso_type & SKB_GSO_FCOE)
goto out_free;
else
BUG();
if (sinfo->gso_type & SKB_GSO_TCP_ECN)
vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
} else
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
if (skb->ip_summed == CHECKSUM_PARTIAL) {
vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
vnet_hdr.csum_start = skb_checksum_start_offset(skb);
vnet_hdr.csum_offset = skb->csum_offset;
} /* else everything is zero */
err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,
vnet_hdr_len);
if (err < 0)
goto out_free;
}
/*
* If the address length field is there to be filled in, we fill
* it in now.
*/
sll = &PACKET_SKB_CB(skb)->sa.ll;
if (sock->type == SOCK_PACKET)
msg->msg_namelen = sizeof(struct sockaddr_pkt);
else
msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr);
/*
* You lose any data beyond the buffer you gave. If it worries a
* user program they can ask the device for its MTU anyway.
*/
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto out_free;
sock_recv_ts_and_drops(msg, sk, skb);
if (msg->msg_name)
memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
msg->msg_namelen);
if (pkt_sk(sk)->auxdata) {
struct tpacket_auxdata aux;
aux.tp_status = TP_STATUS_USER;
if (skb->ip_summed == CHECKSUM_PARTIAL)
aux.tp_status |= TP_STATUS_CSUMNOTREADY;
aux.tp_len = PACKET_SKB_CB(skb)->origlen;
aux.tp_snaplen = skb->len;
aux.tp_mac = 0;
aux.tp_net = skb_network_offset(skb);
if (vlan_tx_tag_present(skb)) {
aux.tp_vlan_tci = vlan_tx_tag_get(skb);
aux.tp_status |= TP_STATUS_VLAN_VALID;
} else {
aux.tp_vlan_tci = 0;
}
put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
}
/*
* Free or return the buffer as appropriate. Again this
* hides all the races and re-entrancy issues from us.
*/
err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
out_free:
skb_free_datagram(sk, skb);
out:
return err;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void HTMLFormControlElement::Reset() {
SetAutofillState(WebAutofillState::kNotFilled);
ResetImpl();
}
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: void InitializePrinting(content::WebContents* web_contents) {
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
printing::PrintViewManager::CreateForWebContents(web_contents);
printing::PrintPreviewMessageHandler::CreateForWebContents(web_contents);
#else
printing::PrintViewManagerBasic::CreateForWebContents(web_contents);
#endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
}
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: void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color)
{
int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2;
int thick = im->thick;
int t;
if (x1 == x2 && y1 == y2 && thick == 1) {
gdImageSetPixel(im, x1, y1, color);
return;
}
if (y2 < y1) {
t=y1;
y1 = y2;
y2 = t;
t = x1;
x1 = x2;
x2 = t;
}
x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2;
if (thick > 1) {
int cx, cy, x1ul, y1ul, x2lr, y2lr;
int half = thick >> 1;
x1ul = x1 - half;
y1ul = y1 - half;
x2lr = x2 + half;
y2lr = y2 + half;
cy = y1ul + thick;
while (cy-- > y1ul) {
cx = x1ul - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y2lr - thick;
while (cy++ < y2lr) {
cx = x1ul - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y1ul + thick - 1;
while (cy++ < y2lr -thick) {
cx = x1ul - 1;
while (cx++ < x1ul + thick) {
gdImageSetPixel(im, cx, cy, color);
}
}
cy = y1ul + thick - 1;
while (cy++ < y2lr -thick) {
cx = x2lr - thick - 1;
while (cx++ < x2lr) {
gdImageSetPixel(im, cx, cy, color);
}
}
return;
} else {
y1v = y1h + 1;
y2v = y2h - 1;
gdImageLine(im, x1h, y1h, x2h, y1h, color);
gdImageLine(im, x1h, y2h, x2h, y2h, color);
gdImageLine(im, x1v, y1v, x1v, y2v, color);
gdImageLine(im, x2v, y1v, x2v, y2v, color);
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int ec_device_remove(struct platform_device *pdev)
{
struct cros_ec_dev *ec = dev_get_drvdata(&pdev->dev);
cdev_del(&ec->cdev);
device_unregister(&ec->class_dev);
return 0;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int jas_stream_gobble(jas_stream_t *stream, int n)
{
int m;
m = n;
for (m = n; m > 0; --m) {
if (jas_stream_getc(stream) == EOF) {
return n - m;
}
}
return n;
}
CWE ID: CWE-190
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ScaleYUVToRGB32(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int source_width,
int source_height,
int width,
int height,
int y_pitch,
int uv_pitch,
int rgb_pitch,
YUVType yuv_type,
Rotate view_rotate,
ScaleFilter filter) {
const int kFilterBufferSize = 4096;
if (source_width > kFilterBufferSize || view_rotate)
filter = FILTER_NONE;
unsigned int y_shift = yuv_type;
if ((view_rotate == ROTATE_180) ||
(view_rotate == ROTATE_270) ||
(view_rotate == MIRROR_ROTATE_0) ||
(view_rotate == MIRROR_ROTATE_90)) {
y_buf += source_width - 1;
u_buf += source_width / 2 - 1;
v_buf += source_width / 2 - 1;
source_width = -source_width;
}
if ((view_rotate == ROTATE_90) ||
(view_rotate == ROTATE_180) ||
(view_rotate == MIRROR_ROTATE_90) ||
(view_rotate == MIRROR_ROTATE_180)) {
y_buf += (source_height - 1) * y_pitch;
u_buf += ((source_height >> y_shift) - 1) * uv_pitch;
v_buf += ((source_height >> y_shift) - 1) * uv_pitch;
source_height = -source_height;
}
if (width == 0 || height == 0)
return;
int source_dx = source_width * kFractionMax / width;
int source_dy = source_height * kFractionMax / height;
#if USE_MMX && defined(_MSC_VER)
int source_dx_uv = source_dx;
#endif
if ((view_rotate == ROTATE_90) ||
(view_rotate == ROTATE_270)) {
int tmp = height;
height = width;
width = tmp;
tmp = source_height;
source_height = source_width;
source_width = tmp;
int original_dx = source_dx;
int original_dy = source_dy;
source_dx = ((original_dy >> kFractionBits) * y_pitch) << kFractionBits;
#if USE_MMX && defined(_MSC_VER)
source_dx_uv = ((original_dy >> kFractionBits) * uv_pitch) << kFractionBits;
#endif
source_dy = original_dx;
if (view_rotate == ROTATE_90) {
y_pitch = -1;
uv_pitch = -1;
source_height = -source_height;
} else {
y_pitch = 1;
uv_pitch = 1;
}
}
uint8 yuvbuf[16 + kFilterBufferSize * 3 + 16];
uint8* ybuf =
reinterpret_cast<uint8*>(reinterpret_cast<uintptr_t>(yuvbuf + 15) & ~15);
uint8* ubuf = ybuf + kFilterBufferSize;
uint8* vbuf = ubuf + kFilterBufferSize;
int yscale_fixed = (source_height << kFractionBits) / height;
for (int y = 0; y < height; ++y) {
uint8* dest_pixel = rgb_buf + y * rgb_pitch;
int source_y_subpixel = (y * yscale_fixed);
if (yscale_fixed >= (kFractionMax * 2)) {
source_y_subpixel += kFractionMax / 2; // For 1/2 or less, center filter.
}
int source_y = source_y_subpixel >> kFractionBits;
const uint8* y0_ptr = y_buf + source_y * y_pitch;
const uint8* y1_ptr = y0_ptr + y_pitch;
const uint8* u0_ptr = u_buf + (source_y >> y_shift) * uv_pitch;
const uint8* u1_ptr = u0_ptr + uv_pitch;
const uint8* v0_ptr = v_buf + (source_y >> y_shift) * uv_pitch;
const uint8* v1_ptr = v0_ptr + uv_pitch;
int source_y_fraction = (source_y_subpixel & kFractionMask) >> 8;
int source_uv_fraction =
((source_y_subpixel >> y_shift) & kFractionMask) >> 8;
const uint8* y_ptr = y0_ptr;
const uint8* u_ptr = u0_ptr;
const uint8* v_ptr = v0_ptr;
if (filter & media::FILTER_BILINEAR_V) {
if (yscale_fixed != kFractionMax &&
source_y_fraction && ((source_y + 1) < source_height)) {
FilterRows(ybuf, y0_ptr, y1_ptr, source_width, source_y_fraction);
} else {
memcpy(ybuf, y0_ptr, source_width);
}
y_ptr = ybuf;
ybuf[source_width] = ybuf[source_width-1];
int uv_source_width = (source_width + 1) / 2;
if (yscale_fixed != kFractionMax &&
source_uv_fraction &&
(((source_y >> y_shift) + 1) < (source_height >> y_shift))) {
FilterRows(ubuf, u0_ptr, u1_ptr, uv_source_width, source_uv_fraction);
FilterRows(vbuf, v0_ptr, v1_ptr, uv_source_width, source_uv_fraction);
} else {
memcpy(ubuf, u0_ptr, uv_source_width);
memcpy(vbuf, v0_ptr, uv_source_width);
}
u_ptr = ubuf;
v_ptr = vbuf;
ubuf[uv_source_width] = ubuf[uv_source_width - 1];
vbuf[uv_source_width] = vbuf[uv_source_width - 1];
}
if (source_dx == kFractionMax) { // Not scaled
FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, width);
} else {
if (filter & FILTER_BILINEAR_H) {
LinearScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, width, source_dx);
} else {
#if USE_MMX && defined(_MSC_VER)
if (width == (source_width * 2)) {
DoubleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, width);
} else if ((source_dx & kFractionMask) == 0) {
ConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, width,
source_dx >> kFractionBits);
} else if (source_dx_uv == source_dx) { // Not rotated.
ScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, width, source_dx);
} else {
RotateConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, width,
source_dx >> kFractionBits,
source_dx_uv >> kFractionBits);
}
#else
ScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, width, source_dx);
#endif
}
}
}
EMMS();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void mntns_put(struct ns_common *ns)
{
put_mnt_ns(to_mnt_ns(ns));
}
CWE ID: CWE-400
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags)
{
/*
* Protect the call to nfs4_state_set_mode_locked and
* serialise the stateid update
*/
write_seqlock(&state->seqlock);
if (deleg_stateid != NULL) {
memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data));
set_bit(NFS_DELEGATED_STATE, &state->flags);
}
if (open_stateid != NULL)
nfs_set_open_stateid_locked(state, open_stateid, open_flags);
write_sequnlock(&state->seqlock);
spin_lock(&state->owner->so_lock);
update_open_stateflags(state, open_flags);
spin_unlock(&state->owner->so_lock);
}
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: long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const
{
return GetTime(pChapters, m_stop_timecode);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int udf_CS0toUTF8(struct ustr *utf_o, const struct ustr *ocu_i)
{
const uint8_t *ocu;
uint8_t cmp_id, ocu_len;
int i;
ocu_len = ocu_i->u_len;
if (ocu_len == 0) {
memset(utf_o, 0, sizeof(struct ustr));
return 0;
}
cmp_id = ocu_i->u_cmpID;
if (cmp_id != 8 && cmp_id != 16) {
memset(utf_o, 0, sizeof(struct ustr));
pr_err("unknown compression code (%d) stri=%s\n",
cmp_id, ocu_i->u_name);
return 0;
}
ocu = ocu_i->u_name;
utf_o->u_len = 0;
for (i = 0; (i < ocu_len) && (utf_o->u_len <= (UDF_NAME_LEN - 3));) {
/* Expand OSTA compressed Unicode to Unicode */
uint32_t c = ocu[i++];
if (cmp_id == 16)
c = (c << 8) | ocu[i++];
/* Compress Unicode to UTF-8 */
if (c < 0x80U)
utf_o->u_name[utf_o->u_len++] = (uint8_t)c;
else if (c < 0x800U) {
utf_o->u_name[utf_o->u_len++] =
(uint8_t)(0xc0 | (c >> 6));
utf_o->u_name[utf_o->u_len++] =
(uint8_t)(0x80 | (c & 0x3f));
} else {
utf_o->u_name[utf_o->u_len++] =
(uint8_t)(0xe0 | (c >> 12));
utf_o->u_name[utf_o->u_len++] =
(uint8_t)(0x80 |
((c >> 6) & 0x3f));
utf_o->u_name[utf_o->u_len++] =
(uint8_t)(0x80 | (c & 0x3f));
}
}
utf_o->u_cmpID = 8;
return utf_o->u_len;
}
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: size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address)
{
/* VPD - all zeros */
return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00,
"s256");
}
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: do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
uint32_t guest_irq, bool set)
{
struct kvm_kernel_irq_routing_entry *e;
struct kvm_irq_routing_table *irq_rt;
struct kvm_lapic_irq irq;
struct kvm_vcpu *vcpu;
struct vcpu_data vcpu_info;
int idx, ret = -EINVAL;
if (!kvm_arch_has_assigned_device(kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(kvm->vcpus[0]))
return 0;
idx = srcu_read_lock(&kvm->irq_srcu);
irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
BUG_ON(guest_irq >= irq_rt->nr_rt_entries);
hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
if (e->type != KVM_IRQ_ROUTING_MSI)
continue;
/*
* VT-d PI cannot support posting multicast/broadcast
* interrupts to a vCPU, we still use interrupt remapping
* for these kind of interrupts.
*
* For lowest-priority interrupts, we only support
* those with single CPU as the destination, e.g. user
* configures the interrupts via /proc/irq or uses
* irqbalance to make the interrupts single-CPU.
*
* We will support full lowest-priority interrupt later.
*/
kvm_set_msi_irq(kvm, e, &irq);
if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
/*
* Make sure the IRTE is in remapped mode if
* we don't handle it in posted mode.
*/
ret = irq_set_vcpu_affinity(host_irq, NULL);
if (ret < 0) {
printk(KERN_INFO
"failed to back to remapped mode, irq: %u\n",
host_irq);
goto out;
}
continue;
}
vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
vcpu_info.vector = irq.vector;
trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
vcpu_info.vector, vcpu_info.pi_desc_addr, set);
if (set)
ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
else {
/* suppress notification event before unposting */
pi_set_sn(vcpu_to_pi_desc(vcpu));
ret = irq_set_vcpu_affinity(host_irq, NULL);
pi_clear_sn(vcpu_to_pi_desc(vcpu));
}
if (ret < 0) {
printk(KERN_INFO "%s: failed to update PI IRTE\n",
__func__);
goto out;
}
}
ret = 0;
out:
srcu_read_unlock(&kvm->irq_srcu, idx);
return ret;
}
CWE ID: CWE-388
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const gfx::ImageSkia PageInfoUI::GetCertificateIcon(
const SkColor related_text_color) {
return gfx::CreateVectorIcon(
kCertificateIcon, kVectorIconSize,
color_utils::DeriveDefaultIconColor(related_text_color));
}
CWE ID: CWE-311
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int handle_wrmsr(struct kvm_vcpu *vcpu)
{
struct msr_data msr;
u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
| ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
msr.data = data;
msr.index = ecx;
msr.host_initiated = false;
if (vmx_set_msr(vcpu, &msr) != 0) {
trace_kvm_msr_write_ex(ecx, data);
kvm_inject_gp(vcpu, 0);
return 1;
}
trace_kvm_msr_write(ecx, data);
skip_emulated_instruction(vcpu);
return 1;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int handle_external_interrupt(struct kvm_vcpu *vcpu,
struct kvm_run *kvm_run)
{
return 1;
}
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 sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc)
{
struct scsi_device *SDev;
struct scsi_sense_hdr sshdr;
int result, err = 0, retries = 0;
SDev = cd->device;
retry:
if (!scsi_block_when_processing_errors(SDev)) {
err = -ENODEV;
goto out;
}
result = scsi_execute(SDev, cgc->cmd, cgc->data_direction,
cgc->buffer, cgc->buflen,
(unsigned char *)cgc->sense, &sshdr,
cgc->timeout, IOCTL_RETRIES, 0, 0, NULL);
/* Minimal error checking. Ignore cases we know about, and report the rest. */
if (driver_byte(result) != 0) {
switch (sshdr.sense_key) {
case UNIT_ATTENTION:
SDev->changed = 1;
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"disc change detected.\n");
if (retries++ < 10)
goto retry;
err = -ENOMEDIUM;
break;
case NOT_READY: /* This happens if there is no disc in drive */
if (sshdr.asc == 0x04 &&
sshdr.ascq == 0x01) {
/* sense: Logical unit is in process of becoming ready */
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"CDROM not ready yet.\n");
if (retries++ < 10) {
/* sleep 2 sec and try again */
ssleep(2);
goto retry;
} else {
/* 20 secs are enough? */
err = -ENOMEDIUM;
break;
}
}
if (!cgc->quiet)
sr_printk(KERN_INFO, cd,
"CDROM not ready. Make sure there "
"is a disc in the drive.\n");
err = -ENOMEDIUM;
break;
case ILLEGAL_REQUEST:
err = -EIO;
if (sshdr.asc == 0x20 &&
sshdr.ascq == 0x00)
/* sense: Invalid command operation code */
err = -EDRIVE_CANT_DO_THIS;
break;
default:
err = -EIO;
}
}
/* Wake up a process waiting for device */
out:
cgc->stat = err;
return err;
}
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 inline void WriteResourceLong(unsigned char *p,
const unsigned int quantum)
{
CWE ID: CWE-125
Target: 1
Example 2:
Code: megasas_read_fw_status_reg_gen2(struct megasas_instance *instance)
{
return readl(&instance->reg_set->outbound_scratch_pad_0);
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void cgtimer_time(cgtimer_t *ts_start)
{
clock_gettime(CLOCK_MONOTONIC, ts_start);
}
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: sctp_chunk_length_valid(struct sctp_chunk *chunk,
__u16 required_length)
{
__u16 chunk_length = ntohs(chunk->chunk_hdr->length);
if (unlikely(chunk_length < required_length))
return 0;
return 1;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void WebsiteSettingsPopupAndroid::SetPermissionInfo(
const PermissionInfoList& permission_info_list) {
JNIEnv* env = base::android::AttachCurrentThread();
std::vector<ContentSettingsType> permissions_to_display;
permissions_to_display.push_back(CONTENT_SETTINGS_TYPE_GEOLOCATION);
permissions_to_display.push_back(CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA);
permissions_to_display.push_back(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC);
permissions_to_display.push_back(CONTENT_SETTINGS_TYPE_NOTIFICATIONS);
permissions_to_display.push_back(CONTENT_SETTINGS_TYPE_IMAGES);
permissions_to_display.push_back(CONTENT_SETTINGS_TYPE_JAVASCRIPT);
permissions_to_display.push_back(CONTENT_SETTINGS_TYPE_POPUPS);
std::map<ContentSettingsType, ContentSetting>
user_specified_settings_to_display;
for (const auto& permission : permission_info_list) {
if (std::find(permissions_to_display.begin(),
permissions_to_display.end(),
permission.type) != permissions_to_display.end() &&
permission.setting != CONTENT_SETTING_DEFAULT) {
user_specified_settings_to_display[permission.type] = permission.setting;
}
}
for (const auto& permission : permissions_to_display) {
if (ContainsKey(user_specified_settings_to_display, permission)) {
base::string16 setting_title =
WebsiteSettingsUI::PermissionTypeToUIString(permission);
Java_WebsiteSettingsPopup_addPermissionSection(
env,
popup_jobject_.obj(),
ConvertUTF16ToJavaString(env, setting_title).obj(),
static_cast<jint>(permission),
static_cast<jint>(user_specified_settings_to_display[permission]));
}
}
Java_WebsiteSettingsPopup_updatePermissionDisplay(env, popup_jobject_.obj());
}
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 AppCacheDatabase::EnsureDatabaseVersion() {
if (!sql::MetaTable::DoesTableExist(db_.get()))
return CreateSchema();
if (!meta_table_->Init(db_.get(), kCurrentVersion, kCompatibleVersion))
return false;
if (meta_table_->GetCompatibleVersionNumber() > kCurrentVersion) {
LOG(WARNING) << "AppCache database is too new.";
return false;
}
std::string stored_flags;
meta_table_->GetValue(kExperimentFlagsKey, &stored_flags);
if (stored_flags != GetActiveExperimentFlags())
return false;
if (meta_table_->GetVersionNumber() < kCurrentVersion)
return UpgradeSchema();
#ifndef NDEBUG
DCHECK(sql::MetaTable::DoesTableExist(db_.get()));
for (int i = 0; i < kTableCount; ++i) {
DCHECK(db_->DoesTableExist(kTables[i].table_name));
}
for (int i = 0; i < kIndexCount; ++i) {
DCHECK(db_->DoesIndexExist(kIndexes[i].index_name));
}
#endif
return true;
}
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 WallpaperManagerBase::GetCustomWallpaperInternal(
const AccountId& account_id,
const WallpaperInfo& info,
const base::FilePath& wallpaper_path,
bool update_wallpaper,
const scoped_refptr<base::SingleThreadTaskRunner>& reply_task_runner,
MovableOnDestroyCallbackHolder on_finish,
base::WeakPtr<WallpaperManagerBase> weak_ptr) {
base::FilePath valid_path = wallpaper_path;
if (!base::PathExists(wallpaper_path)) {
valid_path = GetCustomWallpaperDir(kOriginalWallpaperSubDir);
valid_path = valid_path.Append(info.location);
}
if (!base::PathExists(valid_path)) {
LOG(ERROR) << "Failed to load custom wallpaper from its original fallback "
"file path: " << valid_path.value();
const std::string& old_path = account_id.GetUserEmail(); // Migrated
valid_path = GetCustomWallpaperPath(kOriginalWallpaperSubDir,
WallpaperFilesId::FromString(old_path),
info.location);
}
if (!base::PathExists(valid_path)) {
LOG(ERROR) << "Failed to load previously selected custom wallpaper. "
<< "Fallback to default wallpaper. Expected wallpaper path: "
<< wallpaper_path.value();
reply_task_runner->PostTask(
FROM_HERE,
base::Bind(&WallpaperManagerBase::DoSetDefaultWallpaper, weak_ptr,
account_id, base::Passed(std::move(on_finish))));
} else {
reply_task_runner->PostTask(
FROM_HERE, base::Bind(&WallpaperManagerBase::StartLoad, weak_ptr,
account_id, info, update_wallpaper, valid_path,
base::Passed(std::move(on_finish))));
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
{
struct qstr this;
unsigned int c;
int err;
WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
this.name = name;
this.len = len;
this.hash = full_name_hash(name, len);
if (!len)
return ERR_PTR(-EACCES);
if (unlikely(name[0] == '.')) {
if (len < 2 || (len == 2 && name[1] == '.'))
return ERR_PTR(-EACCES);
}
while (len--) {
c = *(const unsigned char *)name++;
if (c == '/' || c == '\0')
return ERR_PTR(-EACCES);
}
/*
* See if the low-level filesystem might want
* to use its own hash..
*/
if (base->d_flags & DCACHE_OP_HASH) {
int err = base->d_op->d_hash(base, &this);
if (err < 0)
return ERR_PTR(err);
}
err = inode_permission(base->d_inode, MAY_EXEC);
if (err)
return ERR_PTR(err);
return __lookup_hash(&this, base, 0);
}
CWE ID: CWE-59
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void sysbus_esp_hard_reset(DeviceState *dev)
{
SysBusESPState *sysbus = ESP(dev);
esp_hard_reset(&sysbus->esp);
}
CWE ID: CWE-787
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool IsSensitiveURL(const GURL& url,
bool is_request_from_browser_or_webui_renderer) {
bool sensitive_chrome_url = false;
const char kGoogleCom[] = "google.com";
const char kClient[] = "clients";
url::Origin origin = url::Origin::Create(url);
if (origin.DomainIs(kGoogleCom)) {
base::StringPiece host = url.host_piece();
while (host.ends_with("."))
host.remove_suffix(1u);
if (is_request_from_browser_or_webui_renderer) {
base::StringPiece::size_type pos = host.rfind(kClient);
if (pos != base::StringPiece::npos) {
bool match = true;
if (pos > 0 && host[pos - 1] != '.') {
match = false;
} else {
for (base::StringPiece::const_iterator
i = host.begin() + pos + strlen(kClient),
end = host.end() - (strlen(kGoogleCom) + 1);
i != end; ++i) {
if (!isdigit(*i)) {
match = false;
break;
}
}
}
sensitive_chrome_url = sensitive_chrome_url || match;
}
}
sensitive_chrome_url = sensitive_chrome_url ||
(url.DomainIs("chrome.google.com") &&
base::StartsWith(url.path_piece(), "/webstore",
base::CompareCase::SENSITIVE));
}
return sensitive_chrome_url || extension_urls::IsWebstoreUpdateUrl(url) ||
extension_urls::IsBlacklistUpdateUrl(url) ||
extension_urls::IsSafeBrowsingUrl(origin, url.path_piece());
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void bio_free(struct bio *bio)
{
struct bio_set *bs = bio->bi_pool;
void *p;
bio_uninit(bio);
if (bs) {
bvec_free(bs->bvec_pool, bio->bi_io_vec, BVEC_POOL_IDX(bio));
/*
* If we have front padding, adjust the bio pointer before freeing
*/
p = bio;
p -= bs->front_pad;
mempool_free(p, bs->bio_pool);
} else {
/* Bio was allocated by bio_kmalloc() */
kfree(bio);
}
}
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: WORD32 ih264d_parse_islice_data_cavlc(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD8 uc_more_data_flag;
UWORD8 u1_num_mbs, u1_mb_idx;
dec_mb_info_t *ps_cur_mb_info;
deblk_mb_t *ps_cur_deblk_mb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
WORD16 i2_cur_mb_addr;
UWORD8 u1_mbaff;
UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb;
WORD32 ret = OK;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
/* initializations */
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
uc_more_data_flag = 1;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
do
{
UWORD8 u1_mb_type;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_mb_info->u1_end_of_slice = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0);
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type | D_INTRA_MB;
/**************************************************************/
/* Macroblock Layer Begins, Decode the u1_mb_type */
/**************************************************************/
{
UWORD32 u4_bitstream_offset = *pu4_bitstrm_ofst;
UWORD32 u4_word, u4_ldz, u4_temp;
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
NEXTBITS_32(u4_word, u4_bitstream_offset, pu4_bitstrm_buf);
u4_ldz = CLZ(u4_word);
/* Flush the ps_bitstrm */
u4_bitstream_offset += (u4_ldz + 1);
/* Read the suffix from the ps_bitstrm */
u4_word = 0;
if(u4_ldz)
GETBITS(u4_word, u4_bitstream_offset, pu4_bitstrm_buf,
u4_ldz);
*pu4_bitstrm_ofst = u4_bitstream_offset;
u4_temp = ((1 << u4_ldz) + u4_word - 1);
if(u4_temp > 25)
return ERROR_MB_TYPE;
u1_mb_type = u4_temp;
}
ps_cur_mb_info->u1_mb_type = u1_mb_type;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
/**************************************************************/
/* Parse Macroblock data */
/**************************************************************/
if(25 == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
ret = ih264d_parse_imb_cavlc(ps_dec, ps_cur_mb_info, u1_num_mbs, u1_mb_type);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/**************************************************************/
/* Get next Macroblock address */
/**************************************************************/
i2_cur_mb_addr++;
uc_more_data_flag = MORE_RBSP_DATA(ps_bitstrm);
/* Store the colocated information */
{
mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4);
mv_pred_t s_mvPred =
{
{ 0, 0, 0, 0 },
{ -1, -1 }, 0, 0};
ih264d_rep_mv_colz(ps_dec, &s_mvPred, ps_mv_nmb_start, 0,
(UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1), 4,
4);
}
/*if num _cores is set to 3,compute bs will be done in another thread*/
if(ps_dec->u4_num_cores < 3)
{
if(ps_dec->u4_app_disable_deblk_frm == 0)
ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info,
(UWORD16)(u1_num_mbs >> u1_mbaff));
}
u1_num_mbs++;
ps_dec->u2_total_mbs_coded++;
/****************************************************************/
/* Check for End Of Row */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| (!uc_more_data_flag);
ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag);
/*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d",
ps_slice->i4_poc >> ps_slice->u1_field_pic_flag,
ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb));
H264_DEC_DEBUG_PRINT("u1_tfr_n_mb || (!uc_more_data_flag): %d", u1_tfr_n_mb || (!uc_more_data_flag));*/
if(u1_tfr_n_mb || (!uc_more_data_flag))
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
while(uc_more_data_flag);
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: toomany(struct magic_set *ms, const char *name, uint16_t num)
{
if (file_printf(ms, ", too many %s header sections (%u)", name, num
) == -1)
return -1;
return 0;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void inet6_prefix_notify(int event, struct inet6_dev *idev,
struct prefix_info *pinfo)
{
struct sk_buff *skb;
struct net *net = dev_net(idev->dev);
int err = -ENOBUFS;
skb = nlmsg_new(inet6_prefix_nlmsg_size(), GFP_ATOMIC);
if (skb == NULL)
goto errout;
err = inet6_fill_prefix(skb, idev, pinfo, 0, 0, event, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in inet6_prefix_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_IPV6_PREFIX, NULL, GFP_ATOMIC);
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_PREFIX, err);
}
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 svc_rdma_xdr_encode_write_list(struct rpcrdma_msg *rmsgp, int chunks)
{
struct rpcrdma_write_array *ary;
/* no read-list */
rmsgp->rm_body.rm_chunks[0] = xdr_zero;
/* write-array discrim */
ary = (struct rpcrdma_write_array *)
&rmsgp->rm_body.rm_chunks[1];
ary->wc_discrim = xdr_one;
ary->wc_nchunks = cpu_to_be32(chunks);
/* write-list terminator */
ary->wc_array[chunks].wc_target.rs_handle = xdr_zero;
/* reply-array discriminator */
ary->wc_array[chunks].wc_target.rs_length = xdr_zero;
}
CWE ID: CWE-404
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadPNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
ssize_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadPNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
ThrowReaderException(FileOpenError,"UnableToOpenFile");
/*
Verify PNG signature.
*/
count=ReadBlob(image,8,(unsigned char *) magic_number);
if (count < 8 || memcmp(magic_number,"\211PNG\r\n\032\n",8) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Allocate a MngInfo structure.
*/
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize members of the MngInfo structure.
*/
(void) ResetMagickMemory(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOnePNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if ((image->columns == 0) || (image->rows == 0))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadPNGImage() with error.");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if ((IssRGBColorspace(image->colorspace) != MagickFalse) &&
((image->gamma < .45) || (image->gamma > .46)) &&
!(image->chromaticity.red_primary.x>0.6399f &&
image->chromaticity.red_primary.x<0.6401f &&
image->chromaticity.red_primary.y>0.3299f &&
image->chromaticity.red_primary.y<0.3301f &&
image->chromaticity.green_primary.x>0.2999f &&
image->chromaticity.green_primary.x<0.3001f &&
image->chromaticity.green_primary.y>0.5999f &&
image->chromaticity.green_primary.y<0.6001f &&
image->chromaticity.blue_primary.x>0.1499f &&
image->chromaticity.blue_primary.x<0.1501f &&
image->chromaticity.blue_primary.y>0.0599f &&
image->chromaticity.blue_primary.y<0.0601f &&
image->chromaticity.white_point.x>0.3126f &&
image->chromaticity.white_point.x<0.3128f &&
image->chromaticity.white_point.y>0.3289f &&
image->chromaticity.white_point.y<0.3291f))
SetImageColorspace(image,RGBColorspace);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" page.w: %.20g, page.h: %.20g,page.x: %.20g, page.y: %.20g.",
(double) image->page.width,(double) image->page.height,
(double) image->page.x,(double) image->page.y);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadPNGImage()");
return(image);
}
CWE ID: CWE-754
Target: 1
Example 2:
Code: static void xhci_mfwrap_timer(void *opaque)
{
XHCIState *xhci = opaque;
XHCIEvent wrap = { ER_MFINDEX_WRAP, CC_SUCCESS };
xhci_event(xhci, &wrap, 0);
xhci_mfwrap_update(xhci);
}
CWE ID: CWE-835
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
unsigned long data_len, int noblock,
int *errcode)
{
struct sk_buff *skb;
gfp_t gfp_mask;
long timeo;
int err;
gfp_mask = sk->sk_allocation;
if (gfp_mask & __GFP_WAIT)
gfp_mask |= __GFP_REPEAT;
timeo = sock_sndtimeo(sk, noblock);
while (1) {
err = sock_error(sk);
if (err != 0)
goto failure;
err = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto failure;
if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
skb = alloc_skb(header_len, gfp_mask);
if (skb) {
int npages;
int i;
/* No pages, we're done... */
if (!data_len)
break;
npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
skb->truesize += data_len;
skb_shinfo(skb)->nr_frags = npages;
for (i = 0; i < npages; i++) {
struct page *page;
page = alloc_pages(sk->sk_allocation, 0);
if (!page) {
err = -ENOBUFS;
skb_shinfo(skb)->nr_frags = i;
kfree_skb(skb);
goto failure;
}
__skb_fill_page_desc(skb, i,
page, 0,
(data_len >= PAGE_SIZE ?
PAGE_SIZE :
data_len));
data_len -= PAGE_SIZE;
}
/* Full success... */
break;
}
err = -ENOBUFS;
goto failure;
}
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
err = -EAGAIN;
if (!timeo)
goto failure;
if (signal_pending(current))
goto interrupted;
timeo = sock_wait_for_wmem(sk, timeo);
}
skb_set_owner_w(skb, sk);
return skb;
interrupted:
err = sock_intr_errno(timeo);
failure:
*errcode = err;
return NULL;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4|)"
R"([ijl\u0131]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int nfs4_xattr_get_nfs4_acl(struct dentry *dentry, const char *key,
void *buf, size_t buflen, int type)
{
if (strcmp(key, "") != 0)
return -EINVAL;
return nfs4_proc_get_acl(dentry->d_inode, buf, buflen);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
{
netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
}
CWE ID: CWE-476
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int xpm_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
XPMDecContext *x = avctx->priv_data;
AVFrame *p=data;
const uint8_t *end, *ptr = avpkt->data;
int ncolors, cpp, ret, i, j;
int64_t size;
uint32_t *dst;
avctx->pix_fmt = AV_PIX_FMT_BGRA;
end = avpkt->data + avpkt->size;
while (memcmp(ptr, "/* XPM */", 9) && ptr < end - 9)
ptr++;
if (ptr >= end) {
av_log(avctx, AV_LOG_ERROR, "missing signature\n");
return AVERROR_INVALIDDATA;
}
ptr += mod_strcspn(ptr, "\"");
if (sscanf(ptr, "\"%u %u %u %u\",",
&avctx->width, &avctx->height, &ncolors, &cpp) != 4) {
av_log(avctx, AV_LOG_ERROR, "missing image parameters\n");
return AVERROR_INVALIDDATA;
}
if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0)
return ret;
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
if (cpp <= 0 || cpp >= 5) {
av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of chars per pixel: %d\n", cpp);
return AVERROR_INVALIDDATA;
}
size = 1;
for (i = 0; i < cpp; i++)
size *= 94;
if (ncolors <= 0 || ncolors > size) {
av_log(avctx, AV_LOG_ERROR, "invalid number of colors: %d\n", ncolors);
return AVERROR_INVALIDDATA;
}
size *= 4;
av_fast_padded_malloc(&x->pixels, &x->pixels_size, size);
if (!x->pixels)
return AVERROR(ENOMEM);
ptr += mod_strcspn(ptr, ",") + 1;
for (i = 0; i < ncolors; i++) {
const uint8_t *index;
int len;
ptr += mod_strcspn(ptr, "\"") + 1;
if (ptr + cpp > end)
return AVERROR_INVALIDDATA;
index = ptr;
ptr += cpp;
ptr = strstr(ptr, "c ");
if (ptr) {
ptr += 2;
} else {
return AVERROR_INVALIDDATA;
}
len = strcspn(ptr, "\" ");
if ((ret = ascii2index(index, cpp)) < 0)
return ret;
x->pixels[ret] = color_string_to_rgba(ptr, len);
ptr += mod_strcspn(ptr, ",") + 1;
}
for (i = 0; i < avctx->height; i++) {
dst = (uint32_t *)(p->data[0] + i * p->linesize[0]);
ptr += mod_strcspn(ptr, "\"") + 1;
for (j = 0; j < avctx->width; j++) {
if (ptr + cpp > end)
return AVERROR_INVALIDDATA;
if ((ret = ascii2index(ptr, cpp)) < 0)
return ret;
*dst++ = x->pixels[ret];
ptr += cpp;
}
ptr += mod_strcspn(ptr, ",") + 1;
}
p->key_frame = 1;
p->pict_type = AV_PICTURE_TYPE_I;
*got_frame = 1;
return avpkt->size;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int coalesce_t2(struct smb_hdr *psecond, struct smb_hdr *pTargetSMB)
{
struct smb_t2_rsp *pSMB2 = (struct smb_t2_rsp *)psecond;
struct smb_t2_rsp *pSMBt = (struct smb_t2_rsp *)pTargetSMB;
char *data_area_of_target;
char *data_area_of_buf2;
int remaining;
__u16 byte_count, total_data_size, total_in_buf, total_in_buf2;
total_data_size = get_unaligned_le16(&pSMBt->t2_rsp.TotalDataCount);
if (total_data_size !=
get_unaligned_le16(&pSMB2->t2_rsp.TotalDataCount))
cFYI(1, "total data size of primary and secondary t2 differ");
total_in_buf = get_unaligned_le16(&pSMBt->t2_rsp.DataCount);
remaining = total_data_size - total_in_buf;
if (remaining < 0)
return -EINVAL;
if (remaining == 0) /* nothing to do, ignore */
return 0;
total_in_buf2 = get_unaligned_le16(&pSMB2->t2_rsp.DataCount);
if (remaining < total_in_buf2) {
cFYI(1, "transact2 2nd response contains too much data");
}
/* find end of first SMB data area */
data_area_of_target = (char *)&pSMBt->hdr.Protocol +
get_unaligned_le16(&pSMBt->t2_rsp.DataOffset);
/* validate target area */
data_area_of_buf2 = (char *)&pSMB2->hdr.Protocol +
get_unaligned_le16(&pSMB2->t2_rsp.DataOffset);
data_area_of_target += total_in_buf;
/* copy second buffer into end of first buffer */
memcpy(data_area_of_target, data_area_of_buf2, total_in_buf2);
total_in_buf += total_in_buf2;
put_unaligned_le16(total_in_buf, &pSMBt->t2_rsp.DataCount);
byte_count = get_bcc_le(pTargetSMB);
byte_count += total_in_buf2;
put_bcc_le(byte_count, pTargetSMB);
byte_count = pTargetSMB->smb_buf_length;
byte_count += total_in_buf2;
/* BB also add check that we are not beyond maximum buffer size */
pTargetSMB->smb_buf_length = byte_count;
if (remaining == total_in_buf2) {
cFYI(1, "found the last secondary response");
return 0; /* we are done */
} else /* more responses to go */
return 1;
}
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 GetFlagsExperimentsData(FlagsStorage* flags_storage,
FlagAccess access,
base::ListValue* supported_experiments,
base::ListValue* unsupported_experiments) {
std::set<std::string> enabled_experiments;
GetSanitizedEnabledFlags(flags_storage, &enabled_experiments);
int current_platform = GetCurrentPlatform();
for (size_t i = 0; i < num_experiments; ++i) {
const Experiment& experiment = experiments[i];
if (SkipConditionalExperiment(experiment, flags_storage))
continue;
base::DictionaryValue* data = new base::DictionaryValue();
data->SetString("internal_name", experiment.internal_name);
data->SetString("name",
l10n_util::GetStringUTF16(experiment.visible_name_id));
data->SetString("description",
l10n_util::GetStringUTF16(
experiment.visible_description_id));
base::ListValue* supported_platforms = new base::ListValue();
AddOsStrings(experiment.supported_platforms, supported_platforms);
data->Set("supported_platforms", supported_platforms);
switch (experiment.type) {
case Experiment::SINGLE_VALUE:
data->SetBoolean(
"enabled",
enabled_experiments.count(experiment.internal_name) > 0);
break;
case Experiment::MULTI_VALUE:
case Experiment::ENABLE_DISABLE_VALUE:
data->Set("choices", CreateChoiceData(experiment, enabled_experiments));
break;
default:
NOTREACHED();
}
bool supported = (experiment.supported_platforms & current_platform) != 0;
#if defined(OS_CHROMEOS)
if (access == kOwnerAccessToFlags &&
(experiment.supported_platforms & kOsCrOSOwnerOnly) != 0) {
supported = true;
}
#endif
if (supported)
supported_experiments->Append(data);
else
unsupported_experiments->Append(data);
}
}
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 vapic_exit(struct kvm_vcpu *vcpu)
{
struct kvm_lapic *apic = vcpu->arch.apic;
int idx;
if (!apic || !apic->vapic_addr)
return;
idx = srcu_read_lock(&vcpu->kvm->srcu);
kvm_release_page_dirty(apic->vapic_page);
mark_page_dirty(vcpu->kvm, apic->vapic_addr >> PAGE_SHIFT);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
{
struct signal_struct *sig;
if (clone_flags & CLONE_THREAD)
return 0;
sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
tsk->signal = sig;
if (!sig)
return -ENOMEM;
sig->nr_threads = 1;
atomic_set(&sig->live, 1);
atomic_set(&sig->sigcnt, 1);
init_waitqueue_head(&sig->wait_chldexit);
if (clone_flags & CLONE_NEWPID)
sig->flags |= SIGNAL_UNKILLABLE;
sig->curr_target = tsk;
init_sigpending(&sig->shared_pending);
INIT_LIST_HEAD(&sig->posix_timers);
hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
sig->real_timer.function = it_real_fn;
task_lock(current->group_leader);
memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
task_unlock(current->group_leader);
posix_cpu_timers_init_group(sig);
tty_audit_fork(sig);
sig->oom_adj = current->signal->oom_adj;
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree()
{
ASSERT(element()->shadow());
Document* document = element()->document();
ContainerNode* container = element()->userAgentShadowRoot();
RefPtr<DateTimeEditElement> dateTimeEditElement(DateTimeEditElement::create(document, *this));
m_dateTimeEditElement = dateTimeEditElement.get();
container->appendChild(m_dateTimeEditElement);
updateInnerTextValue();
RefPtr<ClearButtonElement> clearButton = ClearButtonElement::create(document, *this);
m_clearButton = clearButton.get();
container->appendChild(clearButton);
RefPtr<SpinButtonElement> spinButton = SpinButtonElement::create(document, *this);
m_spinButtonElement = spinButton.get();
container->appendChild(spinButton);
bool shouldAddPickerIndicator = false;
if (InputType::themeSupportsDataListUI(this))
shouldAddPickerIndicator = true;
RefPtr<RenderTheme> theme = document->page() ? document->page()->theme() : RenderTheme::defaultTheme();
if (theme->supportsCalendarPicker(formControlType())) {
shouldAddPickerIndicator = true;
m_pickerIndicatorIsAlwaysVisible = true;
}
if (shouldAddPickerIndicator) {
RefPtr<PickerIndicatorElement> pickerElement = PickerIndicatorElement::create(document, *this);
m_pickerIndicatorElement = pickerElement.get();
container->appendChild(m_pickerIndicatorElement);
m_pickerIndicatorIsVisible = true;
updatePickerIndicatorVisibility();
}
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static inline const unsigned char *PushDoublePixel(QuantumInfo *quantum_info,
const unsigned char *magick_restrict pixels,double *pixel)
{
double
*p;
unsigned char
quantum[8];
if (quantum_info->endian == LSBEndian)
{
quantum[0]=(*pixels++);
quantum[1]=(*pixels++);
quantum[2]=(*pixels++);
quantum[3]=(*pixels++);
quantum[4]=(*pixels++);
quantum[5]=(*pixels++);
quantum[6]=(*pixels++);
quantum[7]=(*pixels++);
p=(double *) quantum;
*pixel=(*p);
*pixel-=quantum_info->minimum;
*pixel*=quantum_info->scale;
return(pixels);
}
quantum[7]=(*pixels++);
quantum[6]=(*pixels++);
quantum[5]=(*pixels++);
quantum[4]=(*pixels++);
quantum[3]=(*pixels++);
quantum[2]=(*pixels++);
quantum[1]=(*pixels++);
quantum[0]=(*pixels++);
p=(double *) quantum;
*pixel=(*p);
*pixel-=quantum_info->minimum;
*pixel*=quantum_info->scale;
return(pixels);
}
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 WebGLRenderingContextBase::LoseContextImpl(
WebGLRenderingContextBase::LostContextMode mode,
AutoRecoveryMethod auto_recovery_method) {
if (isContextLost())
return;
context_lost_mode_ = mode;
DCHECK_NE(context_lost_mode_, kNotLostContext);
auto_recovery_method_ = auto_recovery_method;
for (size_t i = 0; i < extensions_.size(); ++i) {
ExtensionTracker* tracker = extensions_[i];
tracker->LoseExtension(false);
}
for (size_t i = 0; i < kWebGLExtensionNameCount; ++i)
extension_enabled_[i] = false;
RemoveAllCompressedTextureFormats();
if (mode != kRealLostContext)
DestroyContext();
ConsoleDisplayPreference display =
(mode == kRealLostContext) ? kDisplayInConsole : kDontDisplayInConsole;
SynthesizeGLError(GC3D_CONTEXT_LOST_WEBGL, "loseContext", "context lost",
display);
restore_allowed_ = false;
DeactivateContext(this);
if (auto_recovery_method_ == kWhenAvailable)
AddToEvictedList(this);
dispatch_context_lost_event_timer_.StartOneShot(0, BLINK_FROM_HERE);
}
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: bool XmlReader::Load(const std::string& input) {
const int kParseOptions = XML_PARSE_RECOVER | // recover on errors
XML_PARSE_NONET | // forbid network access
XML_PARSE_NOXXE; // no external entities
reader_ = xmlReaderForMemory(input.data(), static_cast<int>(input.size()),
NULL, NULL, kParseOptions);
return reader_ != NULL;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: PresentationConnection::PresentationConnection(LocalFrame* frame,
const String& id,
const KURL& url)
: ContextClient(frame),
m_id(id),
m_url(url),
m_state(WebPresentationConnectionState::Connecting),
m_binaryType(BinaryTypeBlob),
m_proxy(nullptr) {}
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 struct sock *sctp_v6_create_accept_sk(struct sock *sk,
struct sctp_association *asoc,
bool kern)
{
struct sock *newsk;
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct sctp6_sock *newsctp6sk;
struct ipv6_txoptions *opt;
newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot, kern);
if (!newsk)
goto out;
sock_init_data(NULL, newsk);
sctp_copy_sock(newsk, sk, asoc);
sock_reset_flag(sk, SOCK_ZAPPED);
newsctp6sk = (struct sctp6_sock *)newsk;
inet_sk(newsk)->pinet6 = &newsctp6sk->inet6;
sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
rcu_read_lock();
opt = rcu_dereference(np->opt);
if (opt)
opt = ipv6_dup_options(newsk, opt);
RCU_INIT_POINTER(newnp->opt, opt);
rcu_read_unlock();
/* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname()
* and getpeername().
*/
sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk);
newsk->sk_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
sk_refcnt_debug_inc(newsk);
if (newsk->sk_prot->init(newsk)) {
sk_common_release(newsk);
newsk = NULL;
}
out:
return newsk;
}
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: standard_row_validate(standard_display *dp, png_const_structp pp,
int iImage, int iDisplay, png_uint_32 y)
{
int where;
png_byte std[STANDARD_ROWMAX];
/* The row must be pre-initialized to the magic number here for the size
* tests to pass:
*/
memset(std, 178, sizeof std);
standard_row(pp, std, dp->id, y);
/* At the end both the 'row' and 'display' arrays should end up identical.
* In earlier passes 'row' will be partially filled in, with only the pixels
* that have been read so far, but 'display' will have those pixels
* replicated to fill the unread pixels while reading an interlaced image.
#if PNG_LIBPNG_VER < 10506
* The side effect inside the libpng sequential reader is that the 'row'
* array retains the correct values for unwritten pixels within the row
* bytes, while the 'display' array gets bits off the end of the image (in
* the last byte) trashed. Unfortunately in the progressive reader the
* row bytes are always trashed, so we always do a pixel_cmp here even though
* a memcmp of all cbRow bytes will succeed for the sequential reader.
#endif
*/
if (iImage >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "PNG image row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iImage, y)[where-1]);
png_error(pp, msg);
}
#if PNG_LIBPNG_VER < 10506
/* In this case use pixel_cmp because we need to compare a partial
* byte at the end of the row if the row is not an exact multiple
* of 8 bits wide. (This is fixed in libpng-1.5.6 and pixel_cmp is
* changed to match!)
*/
#endif
if (iDisplay >= 0 &&
(where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y),
dp->bit_width)) != 0)
{
char msg[64];
sprintf(msg, "display row[%lu][%d] changed from %.2x to %.2x",
(unsigned long)y, where-1, std[where-1],
store_image_row(dp->ps, pp, iDisplay, y)[where-1]);
png_error(pp, msg);
}
}
CWE ID:
Target: 1
Example 2:
Code: noinline struct pt_regs * __cpuinit __attribute__((weak)) idle_regs(struct pt_regs *regs)
{
memset(regs, 0, sizeof(struct pt_regs));
return regs;
}
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 InterstitialPageImpl::InterstitialPageRVHDelegateView::GotFocus() {
WebContents* web_contents = interstitial_page_->web_contents();
if (web_contents)
static_cast<WebContentsImpl*>(web_contents)->NotifyWebContentsFocused();
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ScreenPositionController::ConvertHostPointToRelativeToRootWindow(
aura::Window* root_window,
const aura::Window::Windows& root_windows,
gfx::Point* point,
aura::Window** target_root) {
DCHECK(!root_window->parent());
gfx::Point point_in_root(*point);
root_window->GetHost()->ConvertPointFromHost(&point_in_root);
*target_root = root_window;
*point = point_in_root;
#if defined(USE_X11) || defined(USE_OZONE)
if (!root_window->GetHost()->GetBounds().Contains(*point)) {
gfx::Point location_in_native(point_in_root);
root_window->GetHost()->ConvertPointToNativeScreen(&location_in_native);
for (size_t i = 0; i < root_windows.size(); ++i) {
aura::WindowTreeHost* host = root_windows[i]->GetHost();
const gfx::Rect native_bounds = host->GetBounds();
if (native_bounds.Contains(location_in_native)) {
*target_root = root_windows[i];
*point = location_in_native;
host->ConvertPointFromNativeScreen(point);
break;
}
}
}
#else
NOTIMPLEMENTED();
#endif
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: ExtensionFunction::ResponseAction BluetoothSocketCreateFunction::Run() {
DCHECK_CURRENTLY_ON(work_thread_id());
auto params = bluetooth_socket::Create::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params.get());
BluetoothApiSocket* socket = new BluetoothApiSocket(extension_id());
bluetooth_socket::SocketProperties* properties = params->properties.get();
if (properties)
SetSocketProperties(socket, properties);
bluetooth_socket::CreateInfo create_info;
create_info.socket_id = AddSocket(socket);
return RespondNow(
ArgumentList(bluetooth_socket::Create::Results::Create(create_info)));
}
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: l2tp_proto_ver_print(netdissect_options *ndo, const uint16_t *dat)
{
ND_PRINT((ndo, "%u.%u", (EXTRACT_16BITS(dat) >> 8),
(EXTRACT_16BITS(dat) & 0xff)));
}
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: read_file(gchar* filepath)
{
FILE * f;
size_t length;
gchar *ret = NULL;
f = fopen(filepath, "rb");
if (f) {
fseek(f, 0, SEEK_END);
length = (size_t)ftell(f);
fseek(f, 0, SEEK_SET);
/* We can't use MALLOC since it isn't thread safe */
ret = MALLOC(length + 1);
if (ret) {
if (fread(ret, length, 1, f) != 1) {
log_message(LOG_INFO, "Failed to read all of %s", filepath);
}
ret[length] = '\0';
}
else
log_message(LOG_INFO, "Unable to read Dbus file %s", filepath);
fclose(f);
}
return ret;
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: ZEND_API int zend_copy_parameters_array(int param_count, zval *argument_array TSRMLS_DC) /* {{{ */
{
void **p;
int arg_count;
p = zend_vm_stack_top(TSRMLS_C) - 1;
arg_count = (int)(zend_uintptr_t) *p;
if (param_count>arg_count) {
return FAILURE;
}
while (param_count-->0) {
zval **param = (zval **) p-(arg_count--);
zval_add_ref(param);
add_next_index_zval(argument_array, *param);
}
return SUCCESS;
}
/* }}} */
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 webkit_web_view_use_primary_for_paste(WebKitWebView* webView)
{
return webView->priv->usePrimaryForPaste;
}
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: PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */
{
const char *p, *q;
char *name;
const char *endptr = val + vallen;
zval *current;
int namelen;
int has_value;
php_unserialize_data_t var_hash;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
p = val;
while (p < endptr) {
zval **tmp;
q = p;
while (*q != PS_DELIMITER) {
if (++q >= endptr) goto break_outer_loop;
}
if (p[0] == PS_UNDEF_MARKER) {
p++;
has_value = 0;
} else {
has_value = 1;
}
namelen = q - p;
name = estrndup(p, namelen);
q++;
if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) {
if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) {
goto skip;
}
}
if (has_value) {
ALLOC_INIT_ZVAL(current);
if (php_var_unserialize(¤t, (const unsigned char **) &q, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) {
php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC);
} else {
var_push_dtor_no_addref(&var_hash, ¤t);
efree(name);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return FAILURE;
}
var_push_dtor_no_addref(&var_hash, ¤t);
}
PS_ADD_VARL(name, namelen);
skip:
efree(name);
p = q;
}
break_outer_loop:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return SUCCESS;
}
/* }}} */
CWE ID: CWE-74
Target: 1
Example 2:
Code: bool is_skb_forwardable(struct net_device *dev, struct sk_buff *skb)
{
unsigned int len;
if (!(dev->flags & IFF_UP))
return false;
len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
if (skb->len <= len)
return true;
/* if TSO is enabled, we don't care about the length as the packet
* could be forwarded without being segmented before
*/
if (skb_is_gso(skb))
return true;
return false;
}
CWE ID: CWE-400
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: set_text_distance(gs_point *pdist, double dx, double dy, const gs_matrix *pmat)
{
int code = gs_distance_transform_inverse(dx, dy, pmat, pdist);
double rounded;
if (code == gs_error_undefinedresult) {
/* The CTM is degenerate.
Can't know the distance in user space.
} else if (code < 0)
return code;
/* If the distance is very close to integers, round it. */
if (fabs(pdist->x - (rounded = floor(pdist->x + 0.5))) < 0.0005)
pdist->x = rounded;
if (fabs(pdist->y - (rounded = floor(pdist->y + 0.5))) < 0.0005)
pdist->y = rounded;
return 0;
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: zsetcolor(i_ctx_t * i_ctx_p)
{
os_ptr op = osp;
es_ptr ep;
const gs_color_space * pcs = gs_currentcolorspace(igs);
gs_client_color cc;
int n_comps, n_numeric_comps, num_offset = 0, code, depth;
PS_colour_space_t *space;
/* initialize the client color pattern pointer for GC */
cc.pattern = 0;
/* check for a pattern color space */
if ((n_comps = cs_num_components(pcs)) < 0) {
n_comps = -n_comps;
if (r_has_type(op, t_dictionary)) {
ref *pImpl, pPatInst;
code = dict_find_string(op, "Implementation", &pImpl);
if (code != 0) {
code = array_get(imemory, pImpl, 0, &pPatInst);
if (code < 0)
return code;
n_numeric_comps = ( pattern_instance_uses_base_space(cc.pattern)
? n_comps - 1
: 0 );
} else
n_numeric_comps = 0;
} else
n_numeric_comps = 0;
num_offset = 1;
} else
n_numeric_comps = n_comps;
/* gather the numeric operands */
code = float_params(op - num_offset, n_numeric_comps, cc.paint.values);
if (code < 0)
return code;
/* The values are copied to graphic state and compared with */
/* other colors by memcmp() in gx_hld_saved_color_equal() */
/* This is the easiest way to avoid indeterminism */
memset(cc.paint.values + n_numeric_comps, 0,
sizeof(cc.paint.values) - sizeof(*cc.paint.values)*n_numeric_comps);
code = get_space_object(i_ctx_p, &istate->colorspace[0].array, &space);
if (code < 0)
return code;
if (space->validatecomponents) {
code = space->validatecomponents(i_ctx_p,
&istate->colorspace[0].array,
cc.paint.values, n_numeric_comps);
if (code < 0)
return code;
}
/* pass the color to the graphic library */
if ((code = gs_setcolor(igs, &cc)) >= 0) {
if (n_comps > n_numeric_comps) {
istate->pattern[0] = *op; /* save pattern dict or null */
}
}
/* Check the color spaces, to see if we need to run any tint transform
* procedures. Some Adobe applications *eg Photoshop) expect that the
* tint transform will be run and use this to set up duotone DeviceN
* spaces.
*/
code = validate_spaces(i_ctx_p, &istate->colorspace[0].array, &depth);
if (code < 0)
return code;
/* Set up for the continuation procedure which will do the work */
/* Make sure the exec stack has enough space */
check_estack(5);
/* A place holder for data potentially used by transform functions */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'depth' of the space returned during checking above */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'stage' of processing (initially 0) */
ep = esp += 1;
make_int(ep, 0);
/* Store a pointer to the color space stored on the operand stack
* as the stack may grow unpredictably making further access
* to the space difficult
*/
ep = esp += 1;
*ep = istate->colorspace[0].array;
/* Finally, the actual continuation routine */
push_op_estack(setcolor_cont);
return o_push_estack;
}
CWE ID: CWE-704
Target: 1
Example 2:
Code: menu_add_separator_edit(WebKitWebView *page, GArray *argv, GString *result) {
(void) page;
(void) result;
add_separator_to_menu(argv, WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE);
}
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: xmlParseElementChildrenContentDecl(xmlParserCtxtPtr ctxt, int inputchk) {
/* stub left for API/ABI compat */
return(xmlParseElementChildrenContentDeclPriv(ctxt, inputchk, 1));
}
CWE ID: CWE-611
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int decode_zbuf(AVBPrint *bp, const uint8_t *data,
const uint8_t *data_end)
{
z_stream zstream;
unsigned char *buf;
unsigned buf_size;
int ret;
zstream.zalloc = ff_png_zalloc;
zstream.zfree = ff_png_zfree;
zstream.opaque = NULL;
if (inflateInit(&zstream) != Z_OK)
return AVERROR_EXTERNAL;
zstream.next_in = (unsigned char *)data;
zstream.avail_in = data_end - data;
av_bprint_init(bp, 0, -1);
while (zstream.avail_in > 0) {
av_bprint_get_buffer(bp, 1, &buf, &buf_size);
if (!buf_size) {
ret = AVERROR(ENOMEM);
goto fail;
}
zstream.next_out = buf;
zstream.avail_out = buf_size;
ret = inflate(&zstream, Z_PARTIAL_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) {
ret = AVERROR_EXTERNAL;
goto fail;
}
bp->len += zstream.next_out - buf;
if (ret == Z_STREAM_END)
break;
}
inflateEnd(&zstream);
bp->str[bp->len] = 0;
return 0;
fail:
inflateEnd(&zstream);
av_bprint_finalize(bp, NULL);
return ret;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void PlatformSensorProviderLinux::Shutdown() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
const bool did_post_task = file_task_runner_->DeleteSoon(
FROM_HERE, sensor_device_manager_.release());
DCHECK(did_post_task);
sensor_nodes_enumerated_ = false;
sensor_nodes_enumeration_started_ = false;
sensor_devices_by_type_.clear();
}
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: int Reverb_getDescriptor(effect_handle_t self,
effect_descriptor_t *pDescriptor)
{
android::ReverbContext * pContext = (android::ReverbContext *)self;
const effect_descriptor_t *desc;
if (pContext == NULL || pDescriptor == NULL) {
ALOGV("Reverb_getDescriptor() invalid param");
return -EINVAL;
}
if (pContext->auxiliary) {
if (pContext->preset) {
desc = &android::gAuxPresetReverbDescriptor;
} else {
desc = &android::gAuxEnvReverbDescriptor;
}
} else {
if (pContext->preset) {
desc = &android::gInsertPresetReverbDescriptor;
} else {
desc = &android::gInsertEnvReverbDescriptor;
}
}
*pDescriptor = *desc;
return 0;
} /* end Reverb_getDescriptor */
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void nsc_encode_argb_to_aycocg(NSC_CONTEXT* context, const BYTE* data,
UINT32 scanline)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE ccl;
const BYTE* src;
BYTE* yplane = NULL;
BYTE* coplane = NULL;
BYTE* cgplane = NULL;
BYTE* aplane = NULL;
INT16 r_val;
INT16 g_val;
INT16 b_val;
BYTE a_val;
UINT32 tempWidth;
tempWidth = ROUND_UP_TO(context->width, 8);
rw = (context->ChromaSubsamplingLevel ? tempWidth : context->width);
ccl = context->ColorLossLevel;
for (y = 0; y < context->height; y++)
{
src = data + (context->height - 1 - y) * scanline;
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
aplane = context->priv->PlaneBuffers[3] + y * context->width;
for (x = 0; x < context->width; x++)
{
switch (context->format)
{
case PIXEL_FORMAT_BGRX32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGRA32:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_RGBX32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGBA32:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = *src++;
break;
case PIXEL_FORMAT_BGR24:
b_val = *src++;
g_val = *src++;
r_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB24:
r_val = *src++;
g_val = *src++;
b_val = *src++;
a_val = 0xFF;
break;
case PIXEL_FORMAT_BGR16:
b_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
r_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_RGB16:
r_val = (INT16)(((*(src + 1)) & 0xF8) | ((*(src + 1)) >> 5));
g_val = (INT16)((((*(src + 1)) & 0x07) << 5) | (((*src) & 0xE0) >> 3));
b_val = (INT16)((((*src) & 0x1F) << 3) | (((*src) >> 2) & 0x07));
a_val = 0xFF;
src += 2;
break;
case PIXEL_FORMAT_A4:
{
int shift;
BYTE idx;
shift = (7 - (x % 8));
idx = ((*src) >> shift) & 1;
idx |= (((*(src + 1)) >> shift) & 1) << 1;
idx |= (((*(src + 2)) >> shift) & 1) << 2;
idx |= (((*(src + 3)) >> shift) & 1) << 3;
idx *= 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
if (shift == 0)
src += 4;
}
a_val = 0xFF;
break;
case PIXEL_FORMAT_RGB8:
{
int idx = (*src) * 3;
r_val = (INT16) context->palette[idx];
g_val = (INT16) context->palette[idx + 1];
b_val = (INT16) context->palette[idx + 2];
src++;
}
a_val = 0xFF;
break;
default:
r_val = g_val = b_val = a_val = 0;
break;
}
*yplane++ = (BYTE)((r_val >> 2) + (g_val >> 1) + (b_val >> 2));
/* Perform color loss reduction here */
*coplane++ = (BYTE)((r_val - b_val) >> ccl);
*cgplane++ = (BYTE)((-(r_val >> 1) + g_val - (b_val >> 1)) >> ccl);
*aplane++ = a_val;
}
if (context->ChromaSubsamplingLevel && (x % 2) == 1)
{
*yplane = *(yplane - 1);
*coplane = *(coplane - 1);
*cgplane = *(cgplane - 1);
}
}
if (context->ChromaSubsamplingLevel && (y % 2) == 1)
{
yplane = context->priv->PlaneBuffers[0] + y * rw;
coplane = context->priv->PlaneBuffers[1] + y * rw;
cgplane = context->priv->PlaneBuffers[2] + y * rw;
CopyMemory(yplane, yplane - rw, rw);
CopyMemory(coplane, coplane - rw, rw);
CopyMemory(cgplane, cgplane - rw, rw);
}
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static String storageDirectory(DWORD pathIdentifier)
{
Vector<UChar> buffer(MAX_PATH);
if (FAILED(SHGetFolderPathW(0, pathIdentifier | CSIDL_FLAG_CREATE, 0, 0, buffer.data())))
return String();
buffer.resize(wcslen(buffer.data()));
String directory = String::adopt(buffer);
DEFINE_STATIC_LOCAL(String, companyNameDirectory, (ASCIILiteral("Apple Computer\\")));
directory = pathByAppendingComponent(directory, companyNameDirectory + bundleName());
if (!makeAllDirectories(directory))
return String();
return directory;
}
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: mux_client_forward(int fd, int cancel_flag, u_int ftype, struct Forward *fwd)
{
Buffer m;
char *e, *fwd_desc;
u_int type, rid;
fwd_desc = format_forward(ftype, fwd);
debug("Requesting %s %s",
cancel_flag ? "cancellation of" : "forwarding of", fwd_desc);
free(fwd_desc);
buffer_init(&m);
buffer_put_int(&m, cancel_flag ? MUX_C_CLOSE_FWD : MUX_C_OPEN_FWD);
buffer_put_int(&m, muxclient_request_id);
buffer_put_int(&m, ftype);
if (fwd->listen_path != NULL) {
buffer_put_cstring(&m, fwd->listen_path);
} else {
buffer_put_cstring(&m,
fwd->listen_host == NULL ? "" :
(*fwd->listen_host == '\0' ? "*" : fwd->listen_host));
}
buffer_put_int(&m, fwd->listen_port);
if (fwd->connect_path != NULL) {
buffer_put_cstring(&m, fwd->connect_path);
} else {
buffer_put_cstring(&m,
fwd->connect_host == NULL ? "" : fwd->connect_host);
}
buffer_put_int(&m, fwd->connect_port);
if (mux_client_write_packet(fd, &m) != 0)
fatal("%s: write packet: %s", __func__, strerror(errno));
buffer_clear(&m);
/* Read their reply */
if (mux_client_read_packet(fd, &m) != 0) {
buffer_free(&m);
return -1;
}
type = buffer_get_int(&m);
if ((rid = buffer_get_int(&m)) != muxclient_request_id)
fatal("%s: out of sequence reply: my id %u theirs %u",
__func__, muxclient_request_id, rid);
switch (type) {
case MUX_S_OK:
break;
case MUX_S_REMOTE_PORT:
if (cancel_flag)
fatal("%s: got MUX_S_REMOTE_PORT for cancel", __func__);
fwd->allocated_port = buffer_get_int(&m);
verbose("Allocated port %u for remote forward to %s:%d",
fwd->allocated_port,
fwd->connect_host ? fwd->connect_host : "",
fwd->connect_port);
if (muxclient_command == SSHMUX_COMMAND_FORWARD)
fprintf(stdout, "%i\n", fwd->allocated_port);
break;
case MUX_S_PERMISSION_DENIED:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("Master refused forwarding request: %s", e);
return -1;
case MUX_S_FAILURE:
e = buffer_get_string(&m, NULL);
buffer_free(&m);
error("%s: forwarding request failed: %s", __func__, e);
return -1;
default:
fatal("%s: unexpected response from master 0x%08x",
__func__, type);
}
buffer_free(&m);
muxclient_request_id++;
return 0;
}
CWE ID: CWE-254
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static v8::Handle<v8::Value> convert3Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.convert3");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(c*, , V8c::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8c::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->convert3();
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: cluster_hash_alloc (void *p)
{
struct cluster_list * val = (struct cluster_list *) p;
struct cluster_list *cluster;
cluster = XMALLOC (MTYPE_CLUSTER, sizeof (struct cluster_list));
cluster->length = val->length;
if (cluster->length)
{
cluster->list = XMALLOC (MTYPE_CLUSTER_VAL, val->length);
memcpy (cluster->list, val->list, val->length);
}
else
cluster->list = NULL;
cluster->refcnt = 0;
return cluster;
}
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 cmd_setmetadata(const char *tag, char *mboxpat)
{
int c, r = 0;
struct entryattlist *entryatts = NULL;
annotate_state_t *astate = NULL;
c = parse_metadata_store_data(tag, &entryatts);
if (c == EOF) {
eatline(imapd_in, c);
goto freeargs;
}
/* check for CRLF */
if (c == '\r') c = prot_getc(imapd_in);
if (c != '\n') {
prot_printf(imapd_out,
"%s BAD Unexpected extra arguments to Setmetadata\r\n",
tag);
eatline(imapd_in, c);
goto freeargs;
}
astate = annotate_state_new();
annotate_state_set_auth(astate, imapd_userisadmin,
imapd_userid, imapd_authstate);
if (!r) {
if (!*mboxpat) {
r = annotate_state_set_server(astate);
if (!r)
r = annotate_state_store(astate, entryatts);
}
else {
struct annot_store_rock arock;
arock.entryatts = entryatts;
r = apply_mailbox_pattern(astate, mboxpat, annot_store_cb, &arock);
}
}
if (!r)
r = annotate_state_commit(&astate);
else
annotate_state_abort(&astate);
imapd_check(NULL, 0);
if (r) {
prot_printf(imapd_out, "%s NO %s\r\n", tag, error_message(r));
} else {
prot_printf(imapd_out, "%s OK %s\r\n", tag,
error_message(IMAP_OK_COMPLETED));
}
freeargs:
if (entryatts) freeentryatts(entryatts);
return;
}
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 void __net_random_once_deferred(struct work_struct *w)
{
struct __net_random_once_work *work =
container_of(w, struct __net_random_once_work, work);
if (!static_key_enabled(work->key))
static_key_slow_inc(work->key);
kfree(work);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
{
unsigned long old_rflags = vmx_get_rflags(vcpu);
__set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
to_vmx(vcpu)->rflags = rflags;
if (to_vmx(vcpu)->rmode.vm86_active) {
to_vmx(vcpu)->rmode.save_rflags = rflags;
rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
}
vmcs_writel(GUEST_RFLAGS, rflags);
if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
}
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: ExecuteBrowserCommandObserver::~ExecuteBrowserCommandObserver() {
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
//// the first parameter specifies a policy to use as the document csp meaning
//// the document will take ownership of the policy
//// the second parameter specifies a policy to inherit meaning the document
//// will attempt to copy over the policy
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
ContentSecurityPolicy* policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
if (IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
}
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: bool ContainerChunk::removeValue( XMP_Uns32 id )
{
valueMap* cm = &this->childmap;
valueMapIter iter = cm->find( id );
if( iter == cm->end() )
return false; //not found
ValueChunk* propChunk = iter->second;
chunkVect* cv = &this->children;
chunkVectIter cvIter;
for (cvIter = cv->begin(); cvIter != cv->end(); ++cvIter )
{
if ( (*cvIter)->id == id )
break; // found!
}
XMP_Validate( cvIter != cv->end(), "property not found in children vector", kXMPErr_InternalFailure );
cv->erase( cvIter );
cm->erase( iter );
delete propChunk;
return true; // found and removed
}
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: bool file_exist (const char *filename)
{
struct stat sbuffer;
return (stat(filename, &sbuffer) == 0);
}
CWE ID: CWE-93
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int p4_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct perf_event *event;
struct hw_perf_event *hwc;
int idx, handled = 0;
u64 val;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
int overflow;
if (!test_bit(idx, cpuc->active_mask)) {
/* catch in-flight IRQs */
if (__test_and_clear_bit(idx, cpuc->running))
handled++;
continue;
}
event = cpuc->events[idx];
hwc = &event->hw;
WARN_ON_ONCE(hwc->idx != idx);
/* it might be unflagged overflow */
overflow = p4_pmu_clear_cccr_ovf(hwc);
val = x86_perf_event_update(event);
if (!overflow && (val & (1ULL << (x86_pmu.cntval_bits - 1))))
continue;
handled += overflow;
/* event overflow for sure */
data.period = event->hw.last_period;
if (!x86_perf_event_set_period(event))
continue;
if (perf_event_overflow(event, 1, &data, regs))
x86_pmu_stop(event, 0);
}
if (handled)
inc_irq_stat(apic_perf_irqs);
/*
* When dealing with the unmasking of the LVTPC on P4 perf hw, it has
* been observed that the OVF bit flag has to be cleared first _before_
* the LVTPC can be unmasked.
*
* The reason is the NMI line will continue to be asserted while the OVF
* bit is set. This causes a second NMI to generate if the LVTPC is
* unmasked before the OVF bit is cleared, leading to unknown NMI
* messages.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
return handled;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int dcbnl_setapp(struct net_device *netdev, struct nlmsghdr *nlh,
u32 seq, struct nlattr **tb, struct sk_buff *skb)
{
int ret;
u16 id;
u8 up, idtype;
struct nlattr *app_tb[DCB_APP_ATTR_MAX + 1];
if (!tb[DCB_ATTR_APP])
return -EINVAL;
ret = nla_parse_nested(app_tb, DCB_APP_ATTR_MAX, tb[DCB_ATTR_APP],
dcbnl_app_nest);
if (ret)
return ret;
/* all must be non-null */
if ((!app_tb[DCB_APP_ATTR_IDTYPE]) ||
(!app_tb[DCB_APP_ATTR_ID]) ||
(!app_tb[DCB_APP_ATTR_PRIORITY]))
return -EINVAL;
/* either by eth type or by socket number */
idtype = nla_get_u8(app_tb[DCB_APP_ATTR_IDTYPE]);
if ((idtype != DCB_APP_IDTYPE_ETHTYPE) &&
(idtype != DCB_APP_IDTYPE_PORTNUM))
return -EINVAL;
id = nla_get_u16(app_tb[DCB_APP_ATTR_ID]);
up = nla_get_u8(app_tb[DCB_APP_ATTR_PRIORITY]);
if (netdev->dcbnl_ops->setapp) {
ret = netdev->dcbnl_ops->setapp(netdev, idtype, id, up);
} else {
struct dcb_app app;
app.selector = idtype;
app.protocol = id;
app.priority = up;
ret = dcb_setapp(netdev, &app);
}
ret = nla_put_u8(skb, DCB_ATTR_APP, ret);
dcbnl_cee_notify(netdev, RTM_SETDCB, DCB_CMD_SAPP, seq, 0);
return ret;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void misaligned_kernel_word_store(__u64 address, __u64 value)
{
unsigned short x;
unsigned char *p, *q;
p = (unsigned char *) (int) address;
q = (unsigned char *) &x;
x = (__u16) value;
p[0] = q[0];
p[1] = q[1];
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid)
{
struct sem_array *sma;
struct sem_undo_list *ulp;
struct sem_undo *un, *new;
int nsems;
int error;
error = get_undo_list(&ulp);
if (error)
return ERR_PTR(error);
rcu_read_lock();
spin_lock(&ulp->lock);
un = lookup_undo(ulp, semid);
spin_unlock(&ulp->lock);
if (likely(un!=NULL))
goto out;
/* no undo structure around - allocate one. */
/* step 1: figure out the size of the semaphore array */
sma = sem_obtain_object_check(ns, semid);
if (IS_ERR(sma)) {
rcu_read_unlock();
return ERR_CAST(sma);
}
nsems = sma->sem_nsems;
ipc_rcu_getref(sma);
rcu_read_unlock();
/* step 2: allocate new undo structure */
new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
if (!new) {
sem_putref(sma);
return ERR_PTR(-ENOMEM);
}
/* step 3: Acquire the lock on semaphore array */
sem_lock_and_putref(sma);
if (sma->sem_perm.deleted) {
sem_unlock(sma);
kfree(new);
un = ERR_PTR(-EIDRM);
goto out;
}
spin_lock(&ulp->lock);
/*
* step 4: check for races: did someone else allocate the undo struct?
*/
un = lookup_undo(ulp, semid);
if (un) {
kfree(new);
goto success;
}
/* step 5: initialize & link new undo structure */
new->semadj = (short *) &new[1];
new->ulp = ulp;
new->semid = semid;
assert_spin_locked(&ulp->lock);
list_add_rcu(&new->list_proc, &ulp->list_proc);
assert_spin_locked(&sma->sem_perm.lock);
list_add(&new->list_id, &sma->list_id);
un = new;
success:
spin_unlock(&ulp->lock);
rcu_read_lock();
sem_unlock(sma);
out:
return un;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: gpgsm_assuan_simple_command (assuan_context_t ctx, char *cmd,
engine_status_handler_t status_fnc,
void *status_fnc_value)
{
gpg_error_t err;
char *line;
size_t linelen;
err = assuan_write_line (ctx, cmd);
if (err)
return err;
do
{
err = assuan_read_line (ctx, &line, &linelen);
if (err)
return err;
if (*line == '#' || !linelen)
continue;
if (linelen >= 2
&& line[0] == 'O' && line[1] == 'K'
&& (line[2] == '\0' || line[2] == ' '))
return 0;
else if (linelen >= 4
&& line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
&& line[3] == ' ')
err = atoi (&line[4]);
else if (linelen >= 2
&& line[0] == 'S' && line[1] == ' ')
{
char *rest;
gpgme_status_code_t r;
rest = strchr (line + 2, ' ');
if (!rest)
rest = line + linelen; /* set to an empty string */
else
*(rest++) = 0;
r = _gpgme_parse_status (line + 2);
if (r >= 0 && status_fnc)
err = status_fnc (status_fnc_value, r, rest);
else
err = gpg_error (GPG_ERR_GENERAL);
}
else
err = gpg_error (GPG_ERR_GENERAL);
}
while (!err);
return err;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry,
char *args, int lsm_rule, int audit_type)
{
int result;
if (entry->lsm[lsm_rule].rule)
return -EINVAL;
entry->lsm[lsm_rule].type = audit_type;
result = security_filter_rule_init(entry->lsm[lsm_rule].type,
Audit_equal, args,
&entry->lsm[lsm_rule].rule);
return result;
}
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: get_caller_uid (GDBusMethodInvocation *context, gint *uid)
{
PolkitSubject *subject;
PolkitSubject *process;
subject = polkit_system_bus_name_new (g_dbus_method_invocation_get_sender (context));
process = polkit_system_bus_name_get_process_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, NULL);
if (!process) {
g_object_unref (subject);
return FALSE;
}
*uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (process));
g_object_unref (subject);
g_object_unref (process);
return TRUE;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static inline void write_reg(struct pcd_unit *cd, int reg, int val)
{
pi_write_regr(cd->pi, 0, reg, val);
}
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: encode_CT_CLEAR(const struct ofpact_null *null OVS_UNUSED,
enum ofp_version ofp_version OVS_UNUSED,
struct ofpbuf *out)
{
put_NXAST_CT_CLEAR(out);
}
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: RenderFrameHostManager::RenderFrameHostManager(
FrameTreeNode* frame_tree_node,
RenderFrameHostDelegate* render_frame_delegate,
RenderWidgetHostDelegate* render_widget_delegate,
Delegate* delegate)
: frame_tree_node_(frame_tree_node),
delegate_(delegate),
render_frame_delegate_(render_frame_delegate),
render_widget_delegate_(render_widget_delegate),
interstitial_page_(nullptr),
weak_factory_(this) {
DCHECK(frame_tree_node_);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void webkit_web_view_real_window_object_cleared(WebKitWebView*, WebKitWebFrame*, JSGlobalContextRef context, JSObjectRef window_object)
{
notImplemented();
}
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 TabStrip::ShouldDrawStrokes() const {
if (!controller_->CanDrawStrokes())
return false;
return color_utils::GetContrastRatio(
GetTabBackgroundColor(TAB_ACTIVE,
BrowserNonClientFrameView::kActive),
controller_->GetFrameColor(BrowserNonClientFrameView::kActive)) <
1.3;
}
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 iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel,
const struct iw_csdescr *out_csdescr)
{
int i,j;
int z;
int k;
int retval=0;
iw_tmpsample tmpsamp;
iw_tmpsample alphasamp = 0.0;
iw_tmpsample *inpix_tofree = NULL; // Used if we need a separate temp buffer for input samples
iw_tmpsample *outpix_tofree = NULL; // Used if we need a separate temp buffer for output samples
int using_errdiffdither = 0;
int output_channel;
int is_alpha_channel;
int bkgd_has_transparency;
double tmpbkgdalpha=0.0;
int alt_bkgd = 0; // Nonzero if we should use bkgd2 for this sample
struct iw_resize_settings *rs = NULL;
int ditherfamily, dithersubtype;
struct iw_channelinfo_intermed *int_ci;
struct iw_channelinfo_out *out_ci;
iw_tmpsample *in_pix = NULL;
iw_tmpsample *out_pix = NULL;
int num_in_pix;
int num_out_pix;
num_in_pix = ctx->intermed_canvas_width;
num_out_pix = ctx->img2.width;
int_ci = &ctx->intermed_ci[intermed_channel];
output_channel = int_ci->corresponding_output_channel;
out_ci = &ctx->img2_ci[output_channel];
is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA);
bkgd_has_transparency = iw_bkgd_has_transparency(ctx);
inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample));
in_pix = inpix_tofree;
outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample));
if(!outpix_tofree) goto done;
out_pix = outpix_tofree;
if(ctx->nearest_color_table && !is_alpha_channel &&
out_ci->ditherfamily==IW_DITHERFAMILY_NONE &&
out_ci->color_count==0)
{
out_ci->use_nearest_color_table = 1;
}
else {
out_ci->use_nearest_color_table = 0;
}
ditherfamily = out_ci->ditherfamily;
dithersubtype = out_ci->dithersubtype;
if(ditherfamily==IW_DITHERFAMILY_RANDOM) {
if(dithersubtype==IW_DITHERSUBTYPE_SAMEPATTERN && out_ci->channeltype!=IW_CHANNELTYPE_ALPHA)
{
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed);
}
else {
iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed+out_ci->channeltype);
}
}
if(output_channel>=0 && out_ci->ditherfamily==IW_DITHERFAMILY_ERRDIFF) {
using_errdiffdither = 1;
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS;k++) {
ctx->dither_errors[k][i] = 0.0;
}
}
}
rs=&ctx->resize_settings[IW_DIMENSION_H];
if(!rs->rrctx) {
rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype,
num_in_pix, num_out_pix);
if(!rs->rrctx) goto done;
}
for(j=0;j<ctx->intermed_canvas_height;j++) {
if(is_alpha_channel) {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
else {
for(i=0;i<num_in_pix;i++) {
inpix_tofree[i] = ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width+i];
}
}
iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix);
if(ctx->intclamp)
clamp_output_samples(ctx,out_pix,num_out_pix);
if(is_alpha_channel && outpix_tofree && ctx->final_alpha32) {
for(i=0;i<num_out_pix;i++) {
ctx->final_alpha32[((size_t)j)*ctx->img2.width+i] = (iw_float32)outpix_tofree[i];
}
}
if(output_channel == -1) {
goto here;
}
for(z=0;z<ctx->img2.width;z++) {
if(using_errdiffdither && (j%2))
i=ctx->img2.width-1-z;
else
i=z;
tmpsamp = out_pix[i];
if(ctx->bkgd_checkerboard) {
alt_bkgd = (((ctx->bkgd_check_origin[IW_DIMENSION_H]+i)/ctx->bkgd_check_size)%2) !=
(((ctx->bkgd_check_origin[IW_DIMENSION_V]+j)/ctx->bkgd_check_size)%2);
}
if(bkgd_has_transparency) {
tmpbkgdalpha = alt_bkgd ? ctx->bkgd2alpha : ctx->bkgd1alpha;
}
if(int_ci->need_unassoc_alpha_processing) {
alphasamp = ctx->final_alpha32[((size_t)j)*ctx->img2.width + i];
if(alphasamp!=0.0) {
tmpsamp /= alphasamp;
}
if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE) {
double bkcolor;
bkcolor = alt_bkgd ? out_ci->bkgd2_color_lin : out_ci->bkgd1_color_lin;
if(bkgd_has_transparency) {
tmpsamp = tmpsamp*alphasamp + bkcolor*tmpbkgdalpha*(1.0-alphasamp);
}
else {
tmpsamp = tmpsamp*alphasamp + bkcolor*(1.0-alphasamp);
}
}
}
else if(is_alpha_channel && bkgd_has_transparency) {
tmpsamp = tmpsamp + tmpbkgdalpha*(1.0-tmpsamp);
}
if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT)
put_sample_convert_from_linear_flt(ctx,tmpsamp,i,j,output_channel,out_csdescr);
else
put_sample_convert_from_linear(ctx,tmpsamp,i,j,output_channel,out_csdescr);
}
if(using_errdiffdither) {
for(i=0;i<ctx->img2.width;i++) {
for(k=0;k<IW_DITHER_MAXROWS-1;k++) {
ctx->dither_errors[k][i] = ctx->dither_errors[k+1][i];
}
ctx->dither_errors[IW_DITHER_MAXROWS-1][i] = 0.0;
}
}
here:
;
}
retval=1;
done:
if(rs && rs->disable_rrctx_cache && rs->rrctx) {
iwpvt_resize_rows_done(rs->rrctx);
rs->rrctx = NULL;
}
if(inpix_tofree) iw_free(ctx,inpix_tofree);
if(outpix_tofree) iw_free(ctx,outpix_tofree);
return retval;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int megasas_create_frame_pool(struct megasas_instance *instance)
{
int i;
u16 max_cmd;
u32 sge_sz;
u32 frame_count;
struct megasas_cmd *cmd;
max_cmd = instance->max_mfi_cmds;
/*
* Size of our frame is 64 bytes for MFI frame, followed by max SG
* elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
*/
sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
sizeof(struct megasas_sge32);
if (instance->flag_ieee)
sge_sz = sizeof(struct megasas_sge_skinny);
/*
* For MFI controllers.
* max_num_sge = 60
* max_sge_sz = 16 byte (sizeof megasas_sge_skinny)
* Total 960 byte (15 MFI frame of 64 byte)
*
* Fusion adapter require only 3 extra frame.
* max_num_sge = 16 (defined as MAX_IOCTL_SGE)
* max_sge_sz = 12 byte (sizeof megasas_sge64)
* Total 192 byte (3 MFI frame of 64 byte)
*/
frame_count = (instance->adapter_type == MFI_SERIES) ?
(15 + 1) : (3 + 1);
instance->mfi_frame_size = MEGAMFI_FRAME_SIZE * frame_count;
/*
* Use DMA pool facility provided by PCI layer
*/
instance->frame_dma_pool = dma_pool_create("megasas frame pool",
&instance->pdev->dev,
instance->mfi_frame_size, 256, 0);
if (!instance->frame_dma_pool) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup frame pool\n");
return -ENOMEM;
}
instance->sense_dma_pool = dma_pool_create("megasas sense pool",
&instance->pdev->dev, 128,
4, 0);
if (!instance->sense_dma_pool) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "failed to setup sense pool\n");
dma_pool_destroy(instance->frame_dma_pool);
instance->frame_dma_pool = NULL;
return -ENOMEM;
}
/*
* Allocate and attach a frame to each of the commands in cmd_list.
* By making cmd->index as the context instead of the &cmd, we can
* always use 32bit context regardless of the architecture
*/
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
cmd->frame = dma_pool_zalloc(instance->frame_dma_pool,
GFP_KERNEL, &cmd->frame_phys_addr);
cmd->sense = dma_pool_alloc(instance->sense_dma_pool,
GFP_KERNEL, &cmd->sense_phys_addr);
/*
* megasas_teardown_frame_pool() takes care of freeing
* whatever has been allocated
*/
if (!cmd->frame || !cmd->sense) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "dma_pool_alloc failed\n");
megasas_teardown_frame_pool(instance);
return -ENOMEM;
}
cmd->frame->io.context = cpu_to_le32(cmd->index);
cmd->frame->io.pad_0 = 0;
if ((instance->adapter_type == MFI_SERIES) && reset_devices)
cmd->frame->hdr.cmd = MFI_CMD_INVALID;
}
return 0;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: nfs_printfh(netdissect_options *ndo,
register const uint32_t *dp, const u_int len)
{
my_fsid fsid;
uint32_t ino;
const char *sfsname = NULL;
char *spacep;
if (ndo->ndo_uflag) {
u_int i;
char const *sep = "";
ND_PRINT((ndo, " fh["));
for (i=0; i<len; i++) {
ND_PRINT((ndo, "%s%x", sep, dp[i]));
sep = ":";
}
ND_PRINT((ndo, "]"));
return;
}
Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0);
if (sfsname) {
/* file system ID is ASCII, not numeric, for this server OS */
static char temp[NFSX_V3FHMAX+1];
/* Make sure string is null-terminated */
strncpy(temp, sfsname, NFSX_V3FHMAX);
temp[sizeof(temp) - 1] = '\0';
/* Remove trailing spaces */
spacep = strchr(temp, ' ');
if (spacep)
*spacep = '\0';
ND_PRINT((ndo, " fh %s/", temp));
} else {
ND_PRINT((ndo, " fh %d,%d/",
fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor));
}
if(fsid.Fsid_dev.Minor == 257)
/* Print the undecoded handle */
ND_PRINT((ndo, "%s", fsid.Opaque_Handle));
else
ND_PRINT((ndo, "%ld", (long) ino));
}
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 ServerWrapper::OnHttpRequest(int connection_id,
const net::HttpServerRequestInfo& info) {
server_->SetSendBufferSize(connection_id, kSendBufferSizeForDevTools);
if (base::StartsWith(info.path, "/json", base::CompareCase::SENSITIVE)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnJsonRequest,
handler_, connection_id, info));
return;
}
if (info.path.empty() || info.path == "/") {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnDiscoveryPageRequest, handler_,
connection_id));
return;
}
if (!base::StartsWith(info.path, "/devtools/",
base::CompareCase::SENSITIVE)) {
server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation);
return;
}
std::string filename = PathWithoutParams(info.path.substr(10));
std::string mime_type = GetMimeType(filename);
if (!debug_frontend_dir_.empty()) {
base::FilePath path = debug_frontend_dir_.AppendASCII(filename);
std::string data;
base::ReadFileToString(path, &data);
server_->Send200(connection_id, data, mime_type,
kDevtoolsHttpHandlerTrafficAnnotation);
return;
}
if (bundles_resources_) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(&DevToolsHttpHandler::OnFrontendResourceRequest,
handler_, connection_id, filename));
return;
}
server_->Send404(connection_id, kDevtoolsHttpHandlerTrafficAnnotation);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool PaintPropertyTreeBuilder::UpdateForChildren() {
if (!ObjectTypeMightNeedPaintProperties())
return false;
bool property_changed = false;
bool property_added_or_removed = false;
auto* fragment_data = &object_.GetMutableForPainting().FirstFragment();
for (auto& fragment_context : context_.fragments) {
FragmentPaintPropertyTreeBuilder builder(object_, context_,
fragment_context, *fragment_data);
builder.UpdateForChildren();
property_changed |= builder.PropertyChanged();
property_added_or_removed |= builder.PropertyAddedOrRemoved();
context_.force_subtree_update |= object_.SubtreeNeedsPaintPropertyUpdate();
fragment_data = fragment_data->NextFragment();
}
DCHECK(!fragment_data);
if (object_.CanContainAbsolutePositionObjects())
context_.container_for_absolute_position = &object_;
if (object_.CanContainFixedPositionObjects())
context_.container_for_fixed_position = &object_;
if (property_added_or_removed &&
RuntimeEnabledFeatures::SlimmingPaintV175Enabled())
context_.painting_layer->SetNeedsRepaint();
return property_changed;
}
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 wc_ecc_del_point_h(ecc_point* p, void* heap)
{
/* prevents free'ing null arguments */
if (p != NULL) {
mp_clear(p->x);
mp_clear(p->y);
mp_clear(p->z);
XFREE(p, heap, DYNAMIC_TYPE_ECC);
}
(void)heap;
}
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: xmlParseDocument(xmlParserCtxtPtr ctxt) {
xmlChar start[4];
xmlCharEncoding enc;
xmlInitParser();
if ((ctxt == NULL) || (ctxt->input == NULL))
return(-1);
GROW;
/*
* SAX: detecting the level.
*/
xmlDetectSAX2(ctxt);
/*
* SAX: beginning of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) &&
((ctxt->input->end - ctxt->input->cur) >= 4)) {
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
*/
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(&start[0], 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if (CUR == 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL);
}
/*
* Check for the XMLDecl in the Prolog.
* do not GROW here to avoid the detected encoder to decode more
* than just the first line, unless the amount of data is really
* too small to hold "<?xml version="1.0" encoding="foo"
*/
if ((ctxt->input->end - ctxt->input->cur) < 35) {
GROW;
}
if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
/*
* Note that we will switch encoding on the fly.
*/
xmlParseXMLDecl(ctxt);
if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
/*
* The XML REC instructs us to stop parsing right here
*/
return(-1);
}
ctxt->standalone = ctxt->input->standalone;
SKIP_BLANKS;
} else {
ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION);
}
if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX))
ctxt->sax->startDocument(ctxt->userData);
/*
* The Misc part of the Prolog
*/
GROW;
xmlParseMisc(ctxt);
/*
* Then possibly doc type declaration(s) and more Misc
* (doctypedecl Misc*)?
*/
GROW;
if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) {
ctxt->inSubset = 1;
xmlParseDocTypeDecl(ctxt);
if (RAW == '[') {
ctxt->instate = XML_PARSER_DTD;
xmlParseInternalSubset(ctxt);
}
/*
* Create and update the external subset.
*/
ctxt->inSubset = 2;
if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName,
ctxt->extSubSystem, ctxt->extSubURI);
ctxt->inSubset = 0;
xmlCleanSpecialAttr(ctxt);
ctxt->instate = XML_PARSER_PROLOG;
xmlParseMisc(ctxt);
}
/*
* Time to start parsing the tree itself
*/
GROW;
if (RAW != '<') {
xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY,
"Start tag expected, '<' not found\n");
} else {
ctxt->instate = XML_PARSER_CONTENT;
xmlParseElement(ctxt);
ctxt->instate = XML_PARSER_EPILOG;
/*
* The Misc part at the end
*/
xmlParseMisc(ctxt);
if (RAW != 0) {
xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL);
}
ctxt->instate = XML_PARSER_EOF;
}
/*
* SAX: end of the document processing.
*/
if ((ctxt->sax) && (ctxt->sax->endDocument != NULL))
ctxt->sax->endDocument(ctxt->userData);
/*
* Remove locally kept entity definitions if the tree was not built
*/
if ((ctxt->myDoc != NULL) &&
(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) {
xmlFreeDoc(ctxt->myDoc);
ctxt->myDoc = NULL;
}
if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) {
ctxt->myDoc->properties |= XML_DOC_WELLFORMED;
if (ctxt->valid)
ctxt->myDoc->properties |= XML_DOC_DTDVALID;
if (ctxt->nsWellFormed)
ctxt->myDoc->properties |= XML_DOC_NSVALID;
if (ctxt->options & XML_PARSE_OLD10)
ctxt->myDoc->properties |= XML_DOC_OLD10;
}
if (! ctxt->wellFormed) {
ctxt->valid = 0;
return(-1);
}
return(0);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,ExceptionInfo *exception)
{
PrimitiveInfo
linecap[5];
register ssize_t
i;
for (i=0; i < 4; i++)
linecap[i]=(*primitive_info);
linecap[0].coordinates=4;
linecap[1].point.x+=(double) (10.0*MagickEpsilon);
linecap[2].point.x+=(double) (10.0*MagickEpsilon);
linecap[2].point.y+=(double) (10.0*MagickEpsilon);
linecap[3].point.y+=(double) (10.0*MagickEpsilon);
linecap[4].primitive=UndefinedPrimitive;
(void) DrawPolygonPrimitive(image,draw_info,linecap,exception);
}
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 NavigatorServiceWorker::willDetachGlobalObjectFromFrame()
{
if (m_serviceWorker) {
m_serviceWorker->willBeDetachedFromFrame();
m_serviceWorker = nullptr;
}
}
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: NTSTATUS check_reduced_name_with_privilege(connection_struct *conn,
const char *fname,
struct smb_request *smbreq)
{
NTSTATUS status;
TALLOC_CTX *ctx = talloc_tos();
const char *conn_rootdir;
size_t rootdir_len;
char *dir_name = NULL;
const char *last_component = NULL;
char *resolved_name = NULL;
char *saved_dir = NULL;
struct smb_filename *smb_fname_cwd = NULL;
struct privilege_paths *priv_paths = NULL;
int ret;
DEBUG(3,("check_reduced_name_with_privilege [%s] [%s]\n",
fname,
priv_paths = talloc_zero(smbreq, struct privilege_paths);
if (!priv_paths) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (!parent_dirname(ctx, fname, &dir_name, &last_component)) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
priv_paths->parent_name.base_name = talloc_strdup(priv_paths, dir_name);
priv_paths->file_name.base_name = talloc_strdup(priv_paths, last_component);
if (priv_paths->parent_name.base_name == NULL ||
priv_paths->file_name.base_name == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_STAT(conn, &priv_paths->parent_name) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Remember where we were. */
saved_dir = vfs_GetWd(ctx, conn);
if (!saved_dir) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Go to the parent directory to lock in memory. */
if (vfs_ChDir(conn, priv_paths->parent_name.base_name) == -1) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Get the absolute path of the parent directory. */
resolved_name = SMB_VFS_REALPATH(conn,".");
if (!resolved_name) {
status = map_nt_error_from_unix(errno);
goto err;
}
if (*resolved_name != '/') {
DEBUG(0,("check_reduced_name_with_privilege: realpath "
"doesn't return absolute paths !\n"));
status = NT_STATUS_OBJECT_NAME_INVALID;
goto err;
}
DEBUG(10,("check_reduced_name_with_privilege: realpath [%s] -> [%s]\n",
priv_paths->parent_name.base_name,
resolved_name));
/* Now check the stat value is the same. */
smb_fname_cwd = synthetic_smb_fname(talloc_tos(), ".", NULL, NULL);
if (smb_fname_cwd == NULL) {
status = NT_STATUS_NO_MEMORY;
goto err;
}
if (SMB_VFS_LSTAT(conn, smb_fname_cwd) != 0) {
status = map_nt_error_from_unix(errno);
goto err;
}
/* Ensure we're pointing at the same place. */
if (!check_same_stat(&smb_fname_cwd->st, &priv_paths->parent_name.st)) {
DEBUG(0,("check_reduced_name_with_privilege: "
"device/inode/uid/gid on directory %s changed. "
"Denying access !\n",
priv_paths->parent_name.base_name));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
/* Ensure we're below the connect path. */
conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
if (conn_rootdir == NULL) {
DEBUG(2, ("check_reduced_name_with_privilege: Could not get "
"conn_rootdir\n"));
status = NT_STATUS_ACCESS_DENIED;
goto err;
}
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: int ptrace_setregs(struct task_struct *child, void __user *uregs)
{
struct pt_regs *regs = task_pt_regs(child);
xtensa_gregset_t *gregset = uregs;
const unsigned long ps_mask = PS_CALLINC_MASK | PS_OWB_MASK;
unsigned long ps;
unsigned long wb;
if (!access_ok(VERIFY_WRITE, uregs, sizeof(xtensa_gregset_t)))
return -EIO;
__get_user(regs->pc, &gregset->pc);
__get_user(ps, &gregset->ps);
__get_user(regs->lbeg, &gregset->lbeg);
__get_user(regs->lend, &gregset->lend);
__get_user(regs->lcount, &gregset->lcount);
__get_user(regs->windowstart, &gregset->windowstart);
__get_user(wb, &gregset->windowbase);
regs->ps = (regs->ps & ~ps_mask) | (ps & ps_mask) | (1 << PS_EXCM_BIT);
if (wb >= XCHAL_NUM_AREGS / 4)
return -EFAULT;
regs->windowbase = wb;
if (wb != 0 && __copy_from_user(regs->areg + XCHAL_NUM_AREGS - wb * 4,
gregset->a, wb * 16))
return -EFAULT;
if (__copy_from_user(regs->areg, gregset->a + wb*4, (WSBITS-wb) * 16))
return -EFAULT;
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: URLRequestTest() : default_context_(true) {
default_context_.set_network_delegate(&default_network_delegate_);
default_context_.Init();
}
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 PersistentHistogramAllocator::RecordCreateHistogramResult(
CreateHistogramResultType result) {
HistogramBase* result_histogram = GetCreateHistogramResultHistogram();
if (result_histogram)
result_histogram->Add(result);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void SetPictographFontFamilyWrapper(WebSettings* settings,
const base::string16& font,
UScriptCode script) {
settings->SetPictographFontFamily(WebString::FromUTF16(font), script);
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BackendImpl::StoreStats() {
int size = stats_.StorageSize();
std::unique_ptr<char[]> data(new char[size]);
Addr address;
size = stats_.SerializeStats(data.get(), size, &address);
DCHECK(size);
if (!address.is_initialized())
return;
MappedFile* file = File(address);
if (!file)
return;
size_t offset = address.start_block() * address.BlockSize() +
kBlockHeaderSize;
file->Write(data.get(), size, offset); // ignore result.
}
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: UrlData::UrlData(const GURL& url, CORSMode cors_mode, UrlIndex* url_index)
: url_(url),
have_data_origin_(false),
cors_mode_(cors_mode),
url_index_(url_index),
length_(kPositionNotSpecified),
range_supported_(false),
cacheable_(false),
has_opaque_data_(false),
last_used_(),
multibuffer_(this, url_index_->block_shift_) {}
CWE ID: CWE-732
Target: 1
Example 2:
Code: GLES2Decoder* GLES2Decoder::Create(ContextGroup* group) {
return new GLES2DecoderImpl(group);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int install_thread_keyring_to_cred(struct cred *new)
{
struct key *keyring;
keyring = keyring_alloc("_tid", new->uid, new->gid, new,
KEY_POS_ALL | KEY_USR_VIEW,
KEY_ALLOC_QUOTA_OVERRUN,
NULL, NULL);
if (IS_ERR(keyring))
return PTR_ERR(keyring);
new->thread_keyring = keyring;
return 0;
}
CWE ID: CWE-404
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: spnego_gss_wrap_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_wrap_iov_length(minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
return (ret);
}
CWE ID: CWE-18
Target: 1
Example 2:
Code: virtual void PlatformInit() {}
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: Metadata* EntrySync::getMetadata(ExceptionState& exceptionState)
{
RefPtr<MetadataSyncCallbackHelper> helper = MetadataSyncCallbackHelper::create();
m_fileSystem->getMetadata(this, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
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: ref_param_read_signal_error(gs_param_list * plist, gs_param_name pkey, int code)
{
iparam_list *const iplist = (iparam_list *) plist;
iparam_loc loc;
ref_param_read(iplist, pkey, &loc, -1); /* can't fail */
*loc.presult = code;
switch (ref_param_read_get_policy(plist, pkey)) {
case gs_param_policy_ignore:
return 0;
return_error(gs_error_configurationerror);
default:
return code;
}
}
CWE ID: CWE-704
Target: 1
Example 2:
Code: static void raw_close(struct sock *sk, long timeout)
{
/*
* Raw sockets may have direct kernel references. Kill them.
*/
ip_ra_control(sk, 0, NULL);
sk_common_release(sk);
}
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: dissect_hsdpa_capacity_request(packet_info *pinfo, proto_tree *tree,
tvbuff_t *tvb, int offset)
{
guint8 priority;
guint16 user_buffer_size;
/* CmCH-PI */
priority = (tvb_get_guint8(tvb, offset) & 0x0f);
proto_tree_add_item(tree, hf_fp_cmch_pi, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
/* User buffer size */
user_buffer_size = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(tree, hf_fp_user_buffer_size, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
col_append_fstr(pinfo->cinfo, COL_INFO, " CmCH-PI=%u User-Buffer-Size=%u",
priority, user_buffer_size);
return offset;
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry,
struct inode **delegated_inode, unsigned int flags)
{
int error;
bool is_dir = d_is_dir(old_dentry);
const unsigned char *old_name;
struct inode *source = old_dentry->d_inode;
struct inode *target = new_dentry->d_inode;
bool new_is_dir = false;
unsigned max_links = new_dir->i_sb->s_max_links;
if (source == target)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!target) {
error = may_create(new_dir, new_dentry);
} else {
new_is_dir = d_is_dir(new_dentry);
if (!(flags & RENAME_EXCHANGE))
error = may_delete(new_dir, new_dentry, is_dir);
else
error = may_delete(new_dir, new_dentry, new_is_dir);
}
if (error)
return error;
if (!old_dir->i_op->rename)
return -EPERM;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
if (is_dir) {
error = inode_permission(source, MAY_WRITE);
if (error)
return error;
}
if ((flags & RENAME_EXCHANGE) && new_is_dir) {
error = inode_permission(target, MAY_WRITE);
if (error)
return error;
}
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry,
flags);
if (error)
return error;
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
dget(new_dentry);
if (!is_dir || (flags & RENAME_EXCHANGE))
lock_two_nondirectories(source, target);
else if (target)
inode_lock(target);
error = -EBUSY;
if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
goto out;
if (max_links && new_dir != old_dir) {
error = -EMLINK;
if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links)
goto out;
if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir &&
old_dir->i_nlink >= max_links)
goto out;
}
if (is_dir && !(flags & RENAME_EXCHANGE) && target)
shrink_dcache_parent(new_dentry);
if (!is_dir) {
error = try_break_deleg(source, delegated_inode);
if (error)
goto out;
}
if (target && !new_is_dir) {
error = try_break_deleg(target, delegated_inode);
if (error)
goto out;
}
error = old_dir->i_op->rename(old_dir, old_dentry,
new_dir, new_dentry, flags);
if (error)
goto out;
if (!(flags & RENAME_EXCHANGE) && target) {
if (is_dir)
target->i_flags |= S_DEAD;
dont_mount(new_dentry);
detach_mounts(new_dentry);
}
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) {
if (!(flags & RENAME_EXCHANGE))
d_move(old_dentry, new_dentry);
else
d_exchange(old_dentry, new_dentry);
}
out:
if (!is_dir || (flags & RENAME_EXCHANGE))
unlock_two_nondirectories(source, target);
else if (target)
inode_unlock(target);
dput(new_dentry);
if (!error) {
fsnotify_move(old_dir, new_dir, old_name, is_dir,
!(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry);
if (flags & RENAME_EXCHANGE) {
fsnotify_move(new_dir, old_dir, old_dentry->d_name.name,
new_is_dir, NULL, new_dentry);
}
}
fsnotify_oldname_free(old_name);
return error;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: void ChromeContentBrowserClient::SetDefaultQuotaSettingsForTesting(
const storage::QuotaSettings* settings) {
g_default_quota_settings = settings;
}
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: exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt, const xmlChar *prefix)
{
if (ctxt
&& prefix
&& !xmlXPathRegisterNs(ctxt,
prefix,
(const xmlChar *) EXSLT_STRINGS_NAMESPACE)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "encode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrEncodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "decode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrDecodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "padding",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrPaddingFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "align",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrAlignFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "concat",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrConcatFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "replace",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrReplaceFunction)) {
return 0;
}
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: static int nfs4_open_recover_helper(struct nfs4_opendata *opendata, mode_t openflags, struct nfs4_state **res)
{
struct nfs4_state *newstate;
int ret;
opendata->o_arg.open_flags = openflags;
memset(&opendata->o_res, 0, sizeof(opendata->o_res));
memset(&opendata->c_res, 0, sizeof(opendata->c_res));
nfs4_init_opendata_res(opendata);
ret = _nfs4_proc_open(opendata);
if (ret != 0)
return ret;
newstate = nfs4_opendata_to_nfs4_state(opendata);
if (IS_ERR(newstate))
return PTR_ERR(newstate);
nfs4_close_state(&opendata->path, newstate, openflags);
*res = newstate;
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: append_id(char **p, int id)
{
if (id < 0)
id = 0;
if (id > 9)
append_id(p, id / 10);
*(*p)++ = "0123456789"[id % 10];
}
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: int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_mpi r, s;
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
(void) f_rng;
(void) p_rng;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg ) );
#else
(void) md_alg;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#endif
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
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 Sp_search(js_State *J)
{
js_Regexp *re;
const char *text;
Resub m;
text = checkstring(J, 0);
if (js_isregexp(J, 1))
js_copy(J, 1);
else if (js_isundefined(J, 1))
js_newregexp(J, "", 0);
else
js_newregexp(J, js_tostring(J, 1), 0);
re = js_toregexp(J, -1);
if (!js_regexec(re->prog, text, &m, 0))
js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp));
else
js_pushnumber(J, -1);
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
CWE ID: CWE-400
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGLRenderingContextBase::RestoreScissorEnabled() {
if (isContextLost())
return;
if (scissor_enabled_) {
ContextGL()->Enable(GL_SCISSOR_TEST);
} else {
ContextGL()->Disable(GL_SCISSOR_TEST);
}
}
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: modifier_color_encoding_is_sRGB(PNG_CONST png_modifier *pm)
{
return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
pm->current_encoding->gamma == pm->current_gamma;
}
CWE ID:
Target: 1
Example 2:
Code: void put_transaction(struct btrfs_transaction *transaction)
{
WARN_ON(atomic_read(&transaction->use_count) == 0);
if (atomic_dec_and_test(&transaction->use_count)) {
BUG_ON(!list_empty(&transaction->list));
WARN_ON(transaction->delayed_refs.root.rb_node);
memset(transaction, 0, sizeof(*transaction));
kmem_cache_free(btrfs_transaction_cachep, transaction);
}
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Document::writeln(const String& text,
Document* entered_document,
ExceptionState& exception_state) {
write(text, entered_document, exception_state);
if (exception_state.HadException())
return;
write("\n", entered_document);
}
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: DOMHandler::DOMHandler()
: DevToolsDomainHandler(DOM::Metainfo::domainName),
host_(nullptr) {
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: exsltStrConcatFunction (xmlXPathParserContextPtr ctxt, int nargs) {
xmlXPathObjectPtr obj;
xmlChar *ret = NULL;
int i;
if (nargs != 1) {
xmlXPathSetArityError(ctxt);
return;
}
if (!xmlXPathStackIsNodeSet(ctxt)) {
xmlXPathSetTypeError(ctxt);
return;
}
obj = valuePop (ctxt);
if (xmlXPathNodeSetIsEmpty(obj->nodesetval)) {
xmlXPathReturnEmptyString(ctxt);
return;
}
for (i = 0; i < obj->nodesetval->nodeNr; i++) {
xmlChar *tmp;
tmp = xmlXPathCastNodeToString(obj->nodesetval->nodeTab[i]);
ret = xmlStrcat (ret, tmp);
xmlFree(tmp);
}
xmlXPathFreeObject (obj);
xmlXPathReturnString(ctxt, ret);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct dentry *kern_path_locked(const char *name, struct path *path)
{
struct filename *filename;
struct dentry *d;
struct qstr last;
int type;
filename = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path,
&last, &type);
if (IS_ERR(filename))
return ERR_CAST(filename);
if (unlikely(type != LAST_NORM)) {
path_put(path);
putname(filename);
return ERR_PTR(-EINVAL);
}
mutex_lock_nested(&path->dentry->d_inode->i_mutex, I_MUTEX_PARENT);
d = __lookup_hash(&last, path->dentry, 0);
if (IS_ERR(d)) {
mutex_unlock(&path->dentry->d_inode->i_mutex);
path_put(path);
}
putname(filename);
return d;
}
CWE ID: CWE-254
Output:
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.