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 double ipow( double n, int exp )
{
double r;
if ( exp < 0 )
return 1.0 / ipow( n, -exp );
r = 1;
while ( exp > 0 ) {
if ( exp & 1 )
r *= n;
exp >>= 1;
n *= n;
}
return r;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int nfs41_check_expired_stateid(struct nfs4_state *state, nfs4_stateid *stateid, unsigned int flags)
{
int status = NFS_OK;
struct nfs_server *server = NFS_SERVER(state->inode);
if (state->flags & flags) {
status = nfs41_test_stateid(server, stateid);
if (status != NFS_OK) {
nfs41_free_stateid(server, stateid);
state->flags &= ~flags;
}
}
return status;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ChromeContentBrowserClient::CanCreateWindow(
const GURL& opener_url,
const GURL& source_origin,
WindowContainerType container_type,
content::ResourceContext* context,
int render_process_id,
bool* no_javascript_access) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
*no_javascript_access = false;
if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
ExtensionInfoMap* map = io_data->GetExtensionInfoMap();
if (!map->SecurityOriginHasAPIPermission(
source_origin,
render_process_id,
APIPermission::kBackground)) {
return false;
}
const Extension* extension = map->extensions().GetExtensionOrAppByURL(
ExtensionURLInfo(opener_url));
if (extension && !extension->allow_background_js_access())
*no_javascript_access = true;
}
return true;
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE];
jpc_fix_t *buf = splitbuf;
jpc_fix_t *srcptr;
jpc_fix_t *dstptr;
register jpc_fix_t *srcptr2;
register jpc_fix_t *dstptr2;
register int n;
register int i;
int m;
int hstartcol;
/* Get a buffer. */
if (bufsize > QMFB_SPLITBUFSIZE) {
if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) {
/* We have no choice but to commit suicide in this case. */
abort();
}
}
if (numrows >= 2) {
hstartcol = (numrows + 1 - parity) >> 1;
m = numrows - hstartcol;
/* Save the samples destined for the highpass channel. */
n = m;
dstptr = buf;
srcptr = &a[(1 - parity) * stride];
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += JPC_QMFB_COLGRPSIZE;
srcptr += stride << 1;
}
/* Copy the appropriate samples into the lowpass channel. */
dstptr = &a[(1 - parity) * stride];
srcptr = &a[(2 - parity) * stride];
n = numrows - m - (!parity);
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
dstptr2 = dstptr;
srcptr2 = srcptr;
for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
*dstptr2 = *srcptr2;
++dstptr2;
++srcptr2;
}
dstptr += stride;
srcptr += JPC_QMFB_COLGRPSIZE;
}
}
/* If the split buffer was allocated on the heap, free this memory. */
if (buf != splitbuf) {
jas_free(buf);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void OxideQQuickWebView::addMessageHandler(
OxideQQuickScriptMessageHandler* handler) {
Q_D(OxideQQuickWebView);
if (!handler) {
qWarning() << "OxideQQuickWebView::addMessageHandler: NULL handler";
return;
}
OxideQQuickScriptMessageHandlerPrivate* hd =
OxideQQuickScriptMessageHandlerPrivate::get(handler);
if (hd->isActive() && handler->parent() != this) {
qWarning() <<
"OxideQQuickWebView::addMessageHandler: handler can't be added to "
"more than one message target";
return;
}
if (d->messageHandlers().contains(handler)) {
d->messageHandlers().removeOne(handler);
}
handler->setParent(this);
d->messageHandlers().append(handler);
emit messageHandlersChanged();
}
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 AutomationProvider::SendFindRequest(
TabContents* tab_contents,
bool with_json,
const string16& search_string,
bool forward,
bool match_case,
bool find_next,
IPC::Message* reply_message) {
int request_id = FindInPageNotificationObserver::kFindInPageRequestId;
FindInPageNotificationObserver* observer =
new FindInPageNotificationObserver(this,
tab_contents,
with_json,
reply_message);
if (!with_json) {
find_in_page_observer_.reset(observer);
}
TabContentsWrapper* wrapper =
TabContentsWrapper::GetCurrentWrapperForContents(tab_contents);
if (wrapper)
wrapper->GetFindManager()->set_current_find_request_id(request_id);
tab_contents->render_view_host()->StartFinding(
FindInPageNotificationObserver::kFindInPageRequestId,
search_string,
forward,
match_case,
find_next);
}
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 WallpaperManager::OnDefaultWallpaperDecoded(
const base::FilePath& path,
const wallpaper::WallpaperLayout layout,
std::unique_ptr<user_manager::UserImage>* result_out,
MovableOnDestroyCallbackHolder on_finish,
std::unique_ptr<user_manager::UserImage> user_image) {
if (user_image->image().isNull()) {
LOG(ERROR) << "Failed to decode default wallpaper. ";
return;
}
*result_out = std::move(user_image);
WallpaperInfo info(path.value(), layout, wallpaper::DEFAULT,
base::Time::Now().LocalMidnight());
SetWallpaper((*result_out)->image(), info);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void MetricsLog::RecordHistogramDelta(const std::string& histogram_name,
const base::HistogramSamples& snapshot) {
DCHECK(!closed_);
EncodeHistogramDelta(histogram_name, snapshot, &uma_proto_);
}
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: int snmp_helper(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
struct snmp_ctx *ctx = (struct snmp_ctx *)context;
__be32 *pdata = (__be32 *)data;
if (*pdata == ctx->from) {
pr_debug("%s: %pI4 to %pI4\n", __func__,
(void *)&ctx->from, (void *)&ctx->to);
if (*ctx->check)
fast_csum(ctx, (unsigned char *)data - ctx->begin);
*pdata = ctx->to;
}
return 1;
}
CWE ID: CWE-129
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 NaClListener::OnMsgStart(const nacl::NaClStartParams& params) {
struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate();
if (args == NULL) {
LOG(ERROR) << "NaClChromeMainArgsCreate() failed";
return;
}
if (params.enable_ipc_proxy) {
IPC::ChannelHandle channel_handle =
IPC::Channel::GenerateVerifiedChannelID("nacl");
scoped_refptr<NaClIPCAdapter> ipc_adapter(new NaClIPCAdapter(
channel_handle, io_thread_.message_loop_proxy()));
args->initial_ipc_desc = ipc_adapter.get()->MakeNaClDesc();
#if defined(OS_POSIX)
channel_handle.socket = base::FileDescriptor(
ipc_adapter.get()->TakeClientFileDescriptor(), true);
#endif
if (!Send(new NaClProcessHostMsg_PpapiChannelCreated(channel_handle)))
LOG(ERROR) << "Failed to send IPC channel handle to renderer.";
}
std::vector<nacl::FileDescriptor> handles = params.handles;
#if defined(OS_LINUX) || defined(OS_MACOSX)
args->urandom_fd = dup(base::GetUrandomFD());
if (args->urandom_fd < 0) {
LOG(ERROR) << "Failed to dup() the urandom FD";
return;
}
args->create_memory_object_func = CreateMemoryObject;
# if defined(OS_MACOSX)
CHECK(handles.size() >= 1);
g_shm_fd = nacl::ToNativeHandle(handles[handles.size() - 1]);
handles.pop_back();
# endif
#endif
CHECK(handles.size() >= 1);
NaClHandle irt_handle = nacl::ToNativeHandle(handles[handles.size() - 1]);
handles.pop_back();
#if defined(OS_WIN)
args->irt_fd = _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle),
_O_RDONLY | _O_BINARY);
if (args->irt_fd < 0) {
LOG(ERROR) << "_open_osfhandle() failed";
return;
}
#else
args->irt_fd = irt_handle;
#endif
if (params.validation_cache_enabled) {
CHECK_EQ(params.validation_cache_key.length(), (size_t) 64);
args->validation_cache = CreateValidationCache(
new BrowserValidationDBProxy(this), params.validation_cache_key,
params.version);
}
CHECK(handles.size() == 1);
args->imc_bootstrap_handle = nacl::ToNativeHandle(handles[0]);
args->enable_exception_handling = params.enable_exception_handling;
args->enable_debug_stub = params.enable_debug_stub;
#if defined(OS_WIN)
args->broker_duplicate_handle_func = BrokerDuplicateHandle;
args->attach_debug_exception_handler_func = AttachDebugExceptionHandler;
#endif
NaClChromeMainStart(args);
NOTREACHED();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void WebMediaPlayerImpl::OnAddTextTrack(const TextTrackConfig& config,
const AddTextTrackDoneCB& done_cb) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
const WebInbandTextTrackImpl::Kind web_kind =
static_cast<WebInbandTextTrackImpl::Kind>(config.kind());
const blink::WebString web_label = blink::WebString::FromUTF8(config.label());
const blink::WebString web_language =
blink::WebString::FromUTF8(config.language());
const blink::WebString web_id = blink::WebString::FromUTF8(config.id());
std::unique_ptr<WebInbandTextTrackImpl> web_inband_text_track(
new WebInbandTextTrackImpl(web_kind, web_label, web_language, web_id));
std::unique_ptr<media::TextTrack> text_track(new TextTrackImpl(
main_task_runner_, client_, std::move(web_inband_text_track)));
done_cb.Run(std::move(text_track));
}
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: views::View* CardUnmaskPromptViews::CreateFootnoteView() {
if (!controller_->CanStoreLocally())
return nullptr;
storage_row_ = new FadeOutView();
views::BoxLayout* storage_row_layout = new views::BoxLayout(
views::BoxLayout::kHorizontal, kEdgePadding, kEdgePadding, 0);
storage_row_->SetLayoutManager(storage_row_layout);
storage_row_->SetBorder(
views::Border::CreateSolidSidedBorder(1, 0, 0, 0, kSubtleBorderColor));
storage_row_->set_background(
views::Background::CreateSolidBackground(kShadingColor));
storage_checkbox_ = new views::Checkbox(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_CHECKBOX));
storage_checkbox_->SetChecked(controller_->GetStoreLocallyStartState());
storage_row_->AddChildView(storage_checkbox_);
storage_row_layout->SetFlexForView(storage_checkbox_, 1);
storage_row_->AddChildView(new TooltipIcon(l10n_util::GetStringUTF16(
IDS_AUTOFILL_CARD_UNMASK_PROMPT_STORAGE_TOOLTIP)));
return storage_row_;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long long Segment::ParseHeaders()
{
long long total, available;
const int status = m_pReader->Length(&total, &available);
if (status < 0) //error
return status;
assert((total < 0) || (available <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
assert((segment_stop < 0) || (total < 0) || (segment_stop <= total));
assert((segment_stop < 0) || (m_pos <= segment_stop));
for (;;)
{
if ((total >= 0) && (m_pos >= total))
break;
if ((segment_stop >= 0) && (m_pos >= segment_stop))
break;
long long pos = m_pos;
const long long element_start = pos;
if ((pos + 1) > available)
return (pos + 1);
long len;
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return result;
if (result > 0) //underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error
return id;
if (id == 0x0F43B675) //Cluster ID
break;
pos += len; //consume ID
if ((pos + 1) > available)
return (pos + 1);
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return result;
if (result > 0) //underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return size;
pos += len; //consume length of size of element
const long long element_size = size + pos - element_start;
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
if (id == 0x0549A966) //Segment Info ID
{
if (m_pInfo)
return E_FILE_FORMAT_INVALID;
m_pInfo = new (std::nothrow) SegmentInfo(
this,
pos,
size,
element_start,
element_size);
if (m_pInfo == NULL)
return -1;
const long status = m_pInfo->Parse();
if (status)
return status;
}
else if (id == 0x0654AE6B) //Tracks ID
{
if (m_pTracks)
return E_FILE_FORMAT_INVALID;
m_pTracks = new (std::nothrow) Tracks(this,
pos,
size,
element_start,
element_size);
if (m_pTracks == NULL)
return -1;
const long status = m_pTracks->Parse();
if (status)
return status;
}
else if (id == 0x0C53BB6B) //Cues ID
{
if (m_pCues == NULL)
{
m_pCues = new (std::nothrow) Cues(
this,
pos,
size,
element_start,
element_size);
if (m_pCues == NULL)
return -1;
}
}
else if (id == 0x014D9B74) //SeekHead ID
{
if (m_pSeekHead == NULL)
{
m_pSeekHead = new (std::nothrow) SeekHead(
this,
pos,
size,
element_start,
element_size);
if (m_pSeekHead == NULL)
return -1;
const long status = m_pSeekHead->Parse();
if (status)
return status;
}
}
else if (id == 0x0043A770) //Chapters ID
{
if (m_pChapters == NULL)
{
m_pChapters = new (std::nothrow) Chapters(
this,
pos,
size,
element_start,
element_size);
if (m_pChapters == NULL)
return -1;
const long status = m_pChapters->Parse();
if (status)
return status;
}
}
m_pos = pos + size; //consume payload
}
assert((segment_stop < 0) || (m_pos <= segment_stop));
if (m_pInfo == NULL) //TODO: liberalize this behavior
return E_FILE_FORMAT_INVALID;
if (m_pTracks == NULL)
return E_FILE_FORMAT_INVALID;
return 0; //success
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void HTMLMediaElement::removeVideoTrack(WebMediaPlayer::TrackId trackId) {
BLINK_MEDIA_LOG << "removeVideoTrack(" << (void*)this << ")";
videoTracks().remove(trackId);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,
unsigned int epid, unsigned int streamid)
{
XHCIEPContext *epctx;
assert(slotid >= 1 && slotid <= xhci->numslots);
assert(epid >= 1 && epid <= 31);
if (!xhci->slots[slotid-1].enabled) {
DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);
return;
}
epctx = xhci->slots[slotid-1].eps[epid-1];
if (!epctx) {
DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",
epid, slotid);
return;
return;
}
xhci_kick_epctx(epctx, streamid);
}
CWE ID: CWE-835
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ConnectIBusSignals() {
if (!ibus_) {
return;
}
g_signal_connect_after(ibus_,
"connected",
G_CALLBACK(IBusBusConnectedCallback),
this);
g_signal_connect(ibus_,
"disconnected",
G_CALLBACK(IBusBusDisconnectedCallback),
this);
g_signal_connect(ibus_,
"global-engine-changed",
G_CALLBACK(IBusBusGlobalEngineChangedCallback),
this);
g_signal_connect(ibus_,
"name-owner-changed",
G_CALLBACK(IBusBusNameOwnerChangedCallback),
this);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: std::string MakeUserAgentForSyncApi() {
std::string user_agent;
user_agent = "Chrome ";
#if defined(OS_WIN)
user_agent += "WIN ";
#elif defined(OS_CHROMEOS)
user_agent += "CROS ";
#elif defined(OS_LINUX)
user_agent += "LINUX ";
#elif defined(OS_FREEBSD)
user_agent += "FREEBSD ";
#elif defined(OS_OPENBSD)
user_agent += "OPENBSD ";
#elif defined(OS_MACOSX)
user_agent += "MAC ";
#endif
chrome::VersionInfo version_info;
if (!version_info.is_valid()) {
DLOG(ERROR) << "Unable to create chrome::VersionInfo object";
return user_agent;
}
user_agent += version_info.Version();
user_agent += " (" + version_info.LastChange() + ")";
if (!version_info.IsOfficialBuild())
user_agent += "-devel";
return user_agent;
}
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: blink::WebRTCStatsResponse LocalRTCStatsResponse::webKitStatsResponse() const {
return impl_;
}
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: jbig2_end_of_stripe(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_data)
{
Jbig2Page page = ctx->pages[ctx->current_page];
int end_row;
end_row = jbig2_get_int32(segment_data);
if (end_row < page.end_row) {
jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number,
"end of stripe segment with non-positive end row advance" " (new end row %d vs current end row %d)", end_row, page.end_row);
} else {
jbig2_error(ctx, JBIG2_SEVERITY_INFO, segment->number, "end of stripe: advancing end row to %d", end_row);
}
page.end_row = end_row;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void UiSceneCreator::CreateToasts() {
auto* parent = AddTransientParent(kExclusiveScreenToastTransientParent,
k2dBrowsingForeground, kToastTimeoutSeconds,
false, scene_);
parent->AddBinding(VR_BIND_FUNC(bool, Model, model_,
fullscreen && !model->web_vr_mode, UiElement,
parent, SetVisible));
auto element = base::MakeUnique<ExclusiveScreenToast>(512);
element->SetName(kExclusiveScreenToast);
element->SetDrawPhase(kPhaseForeground);
element->SetSize(kToastWidthDMM, kToastHeightDMM);
element->SetTranslate(
0,
kFullscreenVerticalOffset + kFullscreenHeight / 2 +
(kToastOffsetDMM + kToastHeightDMM) * kFullscreenToastDistance,
-kFullscreenToastDistance);
element->SetScale(kFullscreenToastDistance, kFullscreenToastDistance, 1);
element->set_hit_testable(false);
BindColor(model_, element.get(),
&ColorScheme::exclusive_screen_toast_background,
&TexturedElement::SetBackgroundColor);
BindColor(model_, element.get(),
&ColorScheme::exclusive_screen_toast_foreground,
&TexturedElement::SetForegroundColor);
scene_->AddUiElement(kExclusiveScreenToastTransientParent,
std::move(element));
parent = AddTransientParent(kExclusiveScreenToastViewportAwareTransientParent,
kWebVrViewportAwareRoot, kToastTimeoutSeconds,
false, scene_);
parent->AddBinding(
VR_BIND_FUNC(bool, Model, model_,
web_vr_has_produced_frames() && model->web_vr_show_toast,
UiElement, parent, SetVisible));
element = base::MakeUnique<ExclusiveScreenToast>(512);
element->SetName(kExclusiveScreenToastViewportAware);
element->SetDrawPhase(kPhaseOverlayForeground);
element->SetSize(kToastWidthDMM, kToastHeightDMM);
element->SetTranslate(0, kWebVrToastDistance * sin(kWebVrAngleRadians),
-kWebVrToastDistance * cos(kWebVrAngleRadians));
element->SetRotate(1, 0, 0, kWebVrAngleRadians);
element->SetScale(kWebVrToastDistance, kWebVrToastDistance, 1);
element->set_hit_testable(false);
BindColor(model_, element.get(),
&ColorScheme::exclusive_screen_toast_background,
&TexturedElement::SetBackgroundColor);
BindColor(model_, element.get(),
&ColorScheme::exclusive_screen_toast_foreground,
&TexturedElement::SetForegroundColor);
scene_->AddUiElement(kExclusiveScreenToastViewportAwareTransientParent,
std::move(element));
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int dccp_cksum(netdissect_options *ndo, const struct ip *ip,
const struct dccp_hdr *dh, u_int len)
{
return nextproto4_cksum(ndo, ip, (const uint8_t *)(const void *)dh, len,
dccp_csum_coverage(dh, len), IPPROTO_DCCP);
}
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: nfsd4_set_nfs4_acl(struct svc_rqst *rqstp, struct svc_fh *fhp,
struct nfs4_acl *acl)
{
__be32 error;
int host_error;
struct dentry *dentry;
struct inode *inode;
struct posix_acl *pacl = NULL, *dpacl = NULL;
unsigned int flags = 0;
/* Get inode */
error = fh_verify(rqstp, fhp, 0, NFSD_MAY_SATTR);
if (error)
return error;
dentry = fhp->fh_dentry;
inode = d_inode(dentry);
if (!inode->i_op->set_acl || !IS_POSIXACL(inode))
return nfserr_attrnotsupp;
if (S_ISDIR(inode->i_mode))
flags = NFS4_ACL_DIR;
host_error = nfs4_acl_nfsv4_to_posix(acl, &pacl, &dpacl, flags);
if (host_error == -EINVAL)
return nfserr_attrnotsupp;
if (host_error < 0)
goto out_nfserr;
host_error = inode->i_op->set_acl(inode, pacl, ACL_TYPE_ACCESS);
if (host_error < 0)
goto out_release;
if (S_ISDIR(inode->i_mode)) {
host_error = inode->i_op->set_acl(inode, dpacl,
ACL_TYPE_DEFAULT);
}
out_release:
posix_acl_release(pacl);
posix_acl_release(dpacl);
out_nfserr:
if (host_error == -EOPNOTSUPP)
return nfserr_attrnotsupp;
else
return nfserrno(host_error);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: bool WebContentsImpl::ShowingInterstitialPage() const {
return render_manager_.interstitial_page() != NULL;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ssize_t uio_read(struct file *filep, char __user *buf,
size_t count, loff_t *ppos)
{
struct uio_listener *listener = filep->private_data;
struct uio_device *idev = listener->dev;
DECLARE_WAITQUEUE(wait, current);
ssize_t retval;
s32 event_count;
if (!idev->info->irq)
return -EIO;
if (count != sizeof(s32))
return -EINVAL;
add_wait_queue(&idev->wait, &wait);
do {
set_current_state(TASK_INTERRUPTIBLE);
event_count = atomic_read(&idev->event);
if (event_count != listener->event_count) {
if (copy_to_user(buf, &event_count, count))
retval = -EFAULT;
else {
listener->event_count = event_count;
retval = count;
}
break;
}
if (filep->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
schedule();
} while (1);
__set_current_state(TASK_RUNNING);
remove_wait_queue(&idev->wait, &wait);
return retval;
}
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 umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
bool disconnect;
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
disconnect = !IS_MNT_LOCKED_AND_LAZY(p);
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt,
disconnect ? &unmounted : NULL);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
if (!disconnect) {
/* Don't forget about p */
list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
} else {
umount_mnt(p);
}
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: IW_IMPL(int) iw_is_output_fmt_supported(int fmt)
{
switch(fmt) {
#if IW_SUPPORT_PNG == 1
case IW_FORMAT_PNG:
#endif
#if IW_SUPPORT_JPEG == 1
case IW_FORMAT_JPEG:
#endif
#if IW_SUPPORT_WEBP == 1
case IW_FORMAT_WEBP:
#endif
case IW_FORMAT_BMP:
case IW_FORMAT_TIFF:
case IW_FORMAT_MIFF:
case IW_FORMAT_PNM:
case IW_FORMAT_PPM:
case IW_FORMAT_PGM:
case IW_FORMAT_PBM:
case IW_FORMAT_PAM:
return 1;
}
return 0;
}
CWE ID: CWE-682
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 IncrementSiteProcessCount(const GURL& site_url,
int render_process_host_id) {
std::map<ProcessID, Count>& counts_per_process = map_[site_url];
++counts_per_process[render_process_host_id];
#ifndef NDEBUG
RenderProcessHost* host = RenderProcessHost::FromID(render_process_host_id);
if (!HasProcess(host))
host->AddObserver(this);
#endif
}
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: PHP_FUNCTION(locale_accept_from_http)
{
UEnumeration *available;
char *http_accept = NULL;
int http_accept_len;
UErrorCode status = 0;
int len;
char resultLocale[INTL_MAX_LOCALE_LEN+1];
UAcceptResult outResult;
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC );
RETURN_FALSE;
}
available = ures_openAvailableLocales(NULL, &status);
INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list");
len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN,
&outResult, http_accept, available, &status);
uenum_close(available);
INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale");
if (len < 0 || outResult == ULOC_ACCEPT_FAILED) {
RETURN_FALSE;
}
RETURN_STRINGL(resultLocale, len, 1);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static ZIPARCHIVE_METHOD(getStatusString)
{
struct zip *intern;
zval *self = getThis();
#if LIBZIP_VERSION_MAJOR < 1
int zep, syp, len;
char error_string[128];
#else
zip_error_t *err;
#endif
if (!self) {
RETURN_FALSE;
}
ZIP_FROM_OBJECT(intern, self);
#if LIBZIP_VERSION_MAJOR < 1
zip_error_get(intern, &zep, &syp);
len = zip_error_to_str(error_string, 128, zep, syp);
RETVAL_STRINGL(error_string, len);
#else
err = zip_get_error(intern);
RETVAL_STRING(zip_error_strerror(err));
zip_error_fini(err);
#endif
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rtmp_packet_read_one_chunk(URLContext *h, RTMPPacket *p,
int chunk_size, RTMPPacket **prev_pkt_ptr,
int *nb_prev_pkt, uint8_t hdr)
{
uint8_t buf[16];
int channel_id, timestamp, size;
uint32_t ts_field; // non-extended timestamp or delta field
uint32_t extra = 0;
enum RTMPPacketType type;
int written = 0;
int ret, toread;
RTMPPacket *prev_pkt;
written++;
channel_id = hdr & 0x3F;
if (channel_id < 2) { //special case for channel number >= 64
buf[1] = 0;
if (ffurl_read_complete(h, buf, channel_id + 1) != channel_id + 1)
return AVERROR(EIO);
written += channel_id + 1;
channel_id = AV_RL16(buf) + 64;
}
if ((ret = ff_rtmp_check_alloc_array(prev_pkt_ptr, nb_prev_pkt,
channel_id)) < 0)
return ret;
prev_pkt = *prev_pkt_ptr;
size = prev_pkt[channel_id].size;
type = prev_pkt[channel_id].type;
extra = prev_pkt[channel_id].extra;
hdr >>= 6; // header size indicator
if (hdr == RTMP_PS_ONEBYTE) {
ts_field = prev_pkt[channel_id].ts_field;
} else {
if (ffurl_read_complete(h, buf, 3) != 3)
return AVERROR(EIO);
written += 3;
ts_field = AV_RB24(buf);
if (hdr != RTMP_PS_FOURBYTES) {
if (ffurl_read_complete(h, buf, 3) != 3)
return AVERROR(EIO);
written += 3;
size = AV_RB24(buf);
if (ffurl_read_complete(h, buf, 1) != 1)
return AVERROR(EIO);
written++;
type = buf[0];
if (hdr == RTMP_PS_TWELVEBYTES) {
if (ffurl_read_complete(h, buf, 4) != 4)
return AVERROR(EIO);
written += 4;
extra = AV_RL32(buf);
}
}
}
if (ts_field == 0xFFFFFF) {
if (ffurl_read_complete(h, buf, 4) != 4)
return AVERROR(EIO);
timestamp = AV_RB32(buf);
} else {
timestamp = ts_field;
}
if (hdr != RTMP_PS_TWELVEBYTES)
timestamp += prev_pkt[channel_id].timestamp;
if (!prev_pkt[channel_id].read) {
if ((ret = ff_rtmp_packet_create(p, channel_id, type, timestamp,
size)) < 0)
return ret;
p->read = written;
p->offset = 0;
prev_pkt[channel_id].ts_field = ts_field;
prev_pkt[channel_id].timestamp = timestamp;
} else {
RTMPPacket *prev = &prev_pkt[channel_id];
p->data = prev->data;
p->size = prev->size;
p->channel_id = prev->channel_id;
p->type = prev->type;
p->ts_field = prev->ts_field;
p->extra = prev->extra;
p->offset = prev->offset;
p->read = prev->read + written;
p->timestamp = prev->timestamp;
prev->data = NULL;
}
p->extra = extra;
prev_pkt[channel_id].channel_id = channel_id;
prev_pkt[channel_id].type = type;
prev_pkt[channel_id].size = size;
prev_pkt[channel_id].extra = extra;
size = size - p->offset;
toread = FFMIN(size, chunk_size);
if (ffurl_read_complete(h, p->data + p->offset, toread) != toread) {
ff_rtmp_packet_destroy(p);
return AVERROR(EIO);
}
size -= toread;
p->read += toread;
p->offset += toread;
if (size > 0) {
RTMPPacket *prev = &prev_pkt[channel_id];
prev->data = p->data;
prev->read = p->read;
prev->offset = p->offset;
p->data = NULL;
return AVERROR(EAGAIN);
}
prev_pkt[channel_id].read = 0; // read complete; reset if needed
return p->read;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void LogoService::SetLogoCacheForTests(std::unique_ptr<LogoCache> cache) {
logo_cache_for_test_ = std::move(cache);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int setup_16_32bit(struct iwbmpwcontext *wctx,
int mcc_r, int mcc_g, int mcc_b, int mcc_a)
{
int has_alpha;
has_alpha = IW_IMGTYPE_HAS_ALPHA(wctx->img->imgtype);
if(wctx->bmpversion<3) {
iw_set_errorf(wctx->ctx,"Bit depth incompatible with BMP version %d",
wctx->bmpversion);
return 0;
}
if(has_alpha && wctx->bmpversion<5) {
iw_set_error(wctx->ctx,"Internal: Attempt to write v3 16- or 32-bit image with transparency");
return 0;
}
wctx->maxcolor[0] = mcc_r;
wctx->maxcolor[1] = mcc_g;
wctx->maxcolor[2] = mcc_b;
if(has_alpha) wctx->maxcolor[3] = mcc_a;
if(!iwbmp_calc_bitfields_masks(wctx,has_alpha?4:3)) return 0;
if(mcc_r==31 && mcc_g==31 && mcc_b==31 && !has_alpha) {
wctx->bitfields_size = 0;
}
else {
wctx->uses_bitfields = 1;
wctx->bitfields_size = (wctx->bmpversion==3) ? 12 : 0;
}
return 1;
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
{
RenderBlock* flow = continuationBefore(beforeChild);
ASSERT(!beforeChild || beforeChild->parent()->isAnonymousColumnSpanBlock() || beforeChild->parent()->isRenderBlock());
RenderBoxModelObject* beforeChildParent = 0;
if (beforeChild)
beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
else {
RenderBoxModelObject* cont = flow->continuation();
if (cont)
beforeChildParent = cont;
else
beforeChildParent = flow;
}
if (newChild->isFloatingOrOutOfFlowPositioned()) {
beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
return;
}
bool childIsNormal = newChild->isInline() || !newChild->style()->columnSpan();
bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style()->columnSpan();
bool flowIsNormal = flow->isInline() || !flow->style()->columnSpan();
if (flow == beforeChildParent) {
flow->addChildIgnoringContinuation(newChild, beforeChild);
return;
}
if (childIsNormal == bcpIsNormal) {
beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
return;
}
if (flowIsNormal == childIsNormal) {
flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
return;
}
beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
}
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 ExtensionTtsController::SetPlatformImpl(
ExtensionTtsPlatformImpl* platform_impl) {
platform_impl_ = platform_impl;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void OnGetSystemSalt(const GetSystemSaltCallback& callback,
dbus::Response* response) {
if (!response) {
callback.Run(DBUS_METHOD_CALL_FAILURE, std::vector<uint8>());
return;
}
dbus::MessageReader reader(response);
const uint8* bytes = NULL;
size_t length = 0;
if (!reader.PopArrayOfBytes(&bytes, &length)) {
callback.Run(DBUS_METHOD_CALL_FAILURE, std::vector<uint8>());
return;
}
callback.Run(DBUS_METHOD_CALL_SUCCESS,
std::vector<uint8>(bytes, bytes + length));
}
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: MediaRecorder::MediaRecorder(ExecutionContext* context,
MediaStream* stream,
const MediaRecorderOptions* options,
ExceptionState& exception_state)
: PausableObject(context),
stream_(stream),
mime_type_(options->hasMimeType() ? options->mimeType()
: kDefaultMimeType),
stopped_(true),
audio_bits_per_second_(0),
video_bits_per_second_(0),
state_(State::kInactive),
dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create(
this,
&MediaRecorder::DispatchScheduledEvent,
context->GetTaskRunner(TaskType::kDOMManipulation))) {
DCHECK(stream_->getTracks().size());
recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler(
context->GetTaskRunner(TaskType::kInternalMediaRealTime));
DCHECK(recorder_handler_);
if (!recorder_handler_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"No MediaRecorder handler can be created.");
return;
}
AllocateVideoAndAudioBitrates(exception_state, context, options, stream,
&audio_bits_per_second_,
&video_bits_per_second_);
const ContentType content_type(mime_type_);
if (!recorder_handler_->Initialize(
this, stream->Descriptor(), content_type.GetType(),
content_type.Parameter("codecs"), audio_bits_per_second_,
video_bits_per_second_)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Failed to initialize native MediaRecorder the type provided (" +
mime_type_ + ") is not supported.");
return;
}
if (options->mimeType().IsEmpty()) {
const String actual_mime_type = recorder_handler_->ActualMimeType();
if (!actual_mime_type.IsEmpty())
mime_type_ = actual_mime_type;
}
stopped_ = false;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ShowExtensionInstallDialogImpl(
ExtensionInstallPromptShowParams* show_params,
ExtensionInstallPrompt::Delegate* delegate,
scoped_refptr<ExtensionInstallPrompt::Prompt> prompt) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
ExtensionInstallDialogView* dialog =
new ExtensionInstallDialogView(show_params->profile(),
show_params->GetParentWebContents(),
delegate,
prompt);
constrained_window::CreateBrowserModalDialogViews(
dialog, show_params->GetParentWindow())->Show();
}
CWE ID: CWE-17
Target: 1
Example 2:
Code: static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) {
char *key;
size_t nkey;
int i = 0;
item *it;
token_t *key_token = &tokens[KEY_TOKEN];
char *suffix;
assert(c != NULL);
do {
while(key_token->length != 0) {
key = key_token->value;
nkey = key_token->length;
if(nkey > KEY_MAX_LENGTH) {
out_string(c, "CLIENT_ERROR bad command line format");
return;
}
it = item_get(key, nkey);
if (settings.detail_enabled) {
stats_prefix_record_get(key, nkey, NULL != it);
}
if (it) {
if (i >= c->isize) {
item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2);
if (new_list) {
c->isize *= 2;
c->ilist = new_list;
} else {
item_remove(it);
break;
}
}
/*
* Construct the response. Each hit adds three elements to the
* outgoing data list:
* "VALUE "
* key
* " " + flags + " " + data length + "\r\n" + data (with \r\n)
*/
if (return_cas)
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
/* Goofy mid-flight realloc. */
if (i >= c->suffixsize) {
char **new_suffix_list = realloc(c->suffixlist,
sizeof(char *) * c->suffixsize * 2);
if (new_suffix_list) {
c->suffixsize *= 2;
c->suffixlist = new_suffix_list;
} else {
item_remove(it);
break;
}
}
suffix = cache_alloc(c->thread->suffix_cache);
if (suffix == NULL) {
out_string(c, "SERVER_ERROR out of memory making CAS suffix");
item_remove(it);
return;
}
*(c->suffixlist + i) = suffix;
int suffix_len = snprintf(suffix, SUFFIX_SIZE,
" %llu\r\n",
(unsigned long long)ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0 ||
add_iov(c, suffix, suffix_len) != 0 ||
add_iov(c, ITEM_data(it), it->nbytes) != 0)
{
item_remove(it);
break;
}
}
else
{
MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey,
it->nbytes, ITEM_get_cas(it));
if (add_iov(c, "VALUE ", 6) != 0 ||
add_iov(c, ITEM_key(it), it->nkey) != 0 ||
add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0)
{
item_remove(it);
break;
}
}
if (settings.verbose > 1)
fprintf(stderr, ">%d sending key %s\n", c->sfd, ITEM_key(it));
/* item_get() has incremented it->refcount for us */
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.slab_stats[it->slabs_clsid].get_hits++;
c->thread->stats.get_cmds++;
pthread_mutex_unlock(&c->thread->stats.mutex);
item_update(it);
*(c->ilist + i) = it;
i++;
} else {
pthread_mutex_lock(&c->thread->stats.mutex);
c->thread->stats.get_misses++;
pthread_mutex_unlock(&c->thread->stats.mutex);
MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0);
}
key_token++;
}
/*
* If the command string hasn't been fully processed, get the next set
* of tokens.
*/
if(key_token->value != NULL) {
ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS);
key_token = tokens;
}
} while(key_token->value != NULL);
c->icurr = c->ilist;
c->ileft = i;
if (return_cas) {
c->suffixcurr = c->suffixlist;
c->suffixleft = i;
}
if (settings.verbose > 1)
fprintf(stderr, ">%d END\n", c->sfd);
/*
If the loop was terminated because of out-of-memory, it is not
reliable to add END\r\n to the buffer, because it might not end
in \r\n. So we send SERVER_ERROR instead.
*/
if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0
|| (IS_UDP(c->transport) && build_udp_headers(c) != 0)) {
out_string(c, "SERVER_ERROR out of memory writing get response");
}
else {
conn_set_state(c, conn_mwrite);
c->msgcurr = 0;
}
return;
}
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 nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle, struct nfs_fattr *fattr)
{
struct nfs4_exception exception = { };
int err;
do {
err = nfs4_handle_exception(server,
_nfs4_proc_getattr(server, fhandle, fattr),
&exception);
} while (exception.retry);
return err;
}
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 asn1_ex_i2c(ASN1_VALUE **pval, unsigned char *cout, int *putype,
const ASN1_ITEM *it)
{
ASN1_BOOLEAN *tbool = NULL;
ASN1_STRING *strtmp;
ASN1_OBJECT *otmp;
int utype;
const unsigned char *cont;
unsigned char c;
int len;
const ASN1_PRIMITIVE_FUNCS *pf;
pf = it->funcs;
if (pf && pf->prim_i2c)
return pf->prim_i2c(pval, cout, putype, it);
/* Should type be omitted? */
if ((it->itype != ASN1_ITYPE_PRIMITIVE)
|| (it->utype != V_ASN1_BOOLEAN)) {
if (!*pval)
return -1;
}
if (it->itype == ASN1_ITYPE_MSTRING) {
/* If MSTRING type set the underlying type */
strtmp = (ASN1_STRING *)*pval;
utype = strtmp->type;
*putype = utype;
} else if (it->utype == V_ASN1_ANY) {
/* If ANY set type and pointer to value */
ASN1_TYPE *typ;
typ = (ASN1_TYPE *)*pval;
utype = typ->type;
*putype = utype;
pval = &typ->value.asn1_value;
} else
utype = *putype;
switch (utype) {
case V_ASN1_OBJECT:
otmp = (ASN1_OBJECT *)*pval;
cont = otmp->data;
len = otmp->length;
break;
case V_ASN1_NULL:
cont = NULL;
len = 0;
break;
case V_ASN1_BOOLEAN:
tbool = (ASN1_BOOLEAN *)pval;
if (*tbool == -1)
return -1;
if (it->utype != V_ASN1_ANY) {
/*
* Default handling if value == size field then omit
*/
if (*tbool && (it->size > 0))
return -1;
if (!*tbool && !it->size)
return -1;
}
c = (unsigned char)*tbool;
cont = &c;
len = 1;
break;
case V_ASN1_BIT_STRING:
return i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval,
cout ? &cout : NULL);
break;
case V_ASN1_INTEGER:
case V_ASN1_NEG_INTEGER:
case V_ASN1_ENUMERATED:
case V_ASN1_NEG_ENUMERATED:
/*
* These are all have the same content format as ASN1_INTEGER
*/
* These are all have the same content format as ASN1_INTEGER
*/
return i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL);
break;
case V_ASN1_OCTET_STRING:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
default:
/* All based on ASN1_STRING and handled the same */
strtmp = (ASN1_STRING *)*pval;
/* Special handling for NDEF */
if ((it->size == ASN1_TFLG_NDEF)
&& (strtmp->flags & ASN1_STRING_FLAG_NDEF)) {
if (cout) {
strtmp->data = cout;
strtmp->length = 0;
}
/* Special return code */
return -2;
}
cont = strtmp->data;
len = strtmp->length;
break;
}
if (cout && len)
memcpy(cout, cont, len);
return len;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static bool ExecuteMoveToEndOfDocumentAndModifySelection(LocalFrame& frame,
Event*,
EditorCommandSource,
const String&) {
frame.Selection().Modify(
SelectionModifyAlteration::kExtend, SelectionModifyDirection::kForward,
TextGranularity::kDocumentBoundary, SetSelectionBy::kUser);
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: t42_parse_charstrings( T42_Face face,
T42_Loader loader )
{
T42_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_UInt n;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( ft_isdigit( *parser->root.cursor ) )
{
loader->num_glyphs = (FT_UInt)T1_ToInt( parser );
if ( parser->root.error )
return;
}
else if ( *parser->root.cursor == '<' )
{
/* We have `<< ... >>'. Count the number of `/' in the dictionary */
/* to get its size. */
FT_UInt count = 0;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
while ( parser->root.cursor < limit )
{
if ( *parser->root.cursor == '/' )
count++;
else if ( *parser->root.cursor == '>' )
{
loader->num_glyphs = count;
parser->root.cursor = cur; /* rewind */
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
T1_Skip_Spaces( parser );
}
}
else
{
FT_ERROR(( "t42_parse_charstrings: invalid token\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* initialize tables */
error = psaux->ps_table_funcs->init( code_table,
loader->num_glyphs,
memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init( name_table,
loader->num_glyphs,
memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
n = 0;
for (;;)
{
/* The format is simple: */
/* `/glyphname' + index [+ def] */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* We stop when we find an `end' keyword or '>' */
if ( *cur == 'e' &&
cur + 3 < limit &&
cur[1] == 'n' &&
cur[2] == 'd' &&
t42_is_space( cur[3] ) )
break;
if ( *cur == '>' )
break;
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
(void)T1_ToInt( parser );
if ( parser->root.cursor >= limit )
{
FT_ERROR(( "t42_parse_charstrings: out of bounds\n" ));
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
len = parser->root.cursor - cur;
error = T1_Add_Table( code_table, n, cur, len + 1 );
if ( error )
goto Fail;
code_table->elements[n][len] = '\0';
n++;
if ( n >= loader->num_glyphs )
break;
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE SoftAVC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) {
int32_t indexFull = index;
switch (indexFull) {
case OMX_IndexParamVideoBitrate:
{
return internalSetBitrateParams(
(const OMX_VIDEO_PARAM_BITRATETYPE *)params);
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params;
if (avcType->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mEntropyMode = 0;
if (OMX_TRUE == avcType->bEntropyCodingCABAC)
mEntropyMode = 1;
if ((avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) &&
avcType->nPFrames) {
mBframes = avcType->nBFrames / avcType->nPFrames;
}
mIInterval = avcType->nPFrames + avcType->nBFrames;
if (OMX_VIDEO_AVCLoopFilterDisable == avcType->eLoopFilterMode)
mDisableDeblkLevel = 4;
if (avcType->nRefFrames != 1
|| avcType->bUseHadamard != OMX_TRUE
|| avcType->nRefIdx10ActiveMinus1 != 0
|| avcType->nRefIdx11ActiveMinus1 != 0
|| avcType->bWeightedPPrediction != OMX_FALSE
|| avcType->bconstIpred != OMX_FALSE
|| avcType->bDirect8x8Inference != OMX_FALSE
|| avcType->bDirectSpatialTemporal != OMX_FALSE
|| avcType->nCabacInitIdc != 0) {
return OMX_ErrorUndefined;
}
if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalSetParameter(index, params);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool Document::execCommand(const String& commandName, bool userInterface, const String& value)
{
return command(this, commandName, userInterface).execute(value);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline int notify_page_fault(struct pt_regs *regs)
{
int ret = 0;
/* kprobe_running() needs smp_processor_id() */
if (!user_mode(regs)) {
preempt_disable();
if (kprobe_running() && kprobe_fault_handler(regs, 11))
ret = 1;
preempt_enable();
}
return ret;
}
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: media::AudioParameters GetDeviceParametersOnDeviceThread(
media::AudioManager* audio_manager,
const std::string& unique_id) {
DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread());
return media::AudioDeviceDescription::IsDefaultDevice(unique_id)
? audio_manager->GetDefaultOutputStreamParameters()
: audio_manager->GetOutputStreamParameters(unique_id);
}
CWE ID:
Target: 1
Example 2:
Code: Buffer::Buffer(const HostResource& resource,
const base::SharedMemoryHandle& shm_handle,
uint32_t size)
: Resource(OBJECT_IS_PROXY, resource),
shm_(shm_handle, false),
size_(size),
map_count_(0) {
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int uhid_event(btif_hh_device_t *p_dev)
{
struct uhid_event ev;
ssize_t ret;
memset(&ev, 0, sizeof(ev));
if(!p_dev)
{
APPL_TRACE_ERROR("%s: Device not found",__FUNCTION__)
return -1;
}
ret = read(p_dev->fd, &ev, sizeof(ev));
if (ret == 0) {
APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __FUNCTION__,
strerror(errno));
return -EFAULT;
} else if (ret < 0) {
APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __FUNCTION__,
strerror(errno));
return -errno;
} else if ((ev.type == UHID_OUTPUT) || (ev.type==UHID_OUTPUT_EV)) {
if (ret < (ssize_t)sizeof(ev)) {
APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %ld != %lu",
__FUNCTION__, ret, sizeof(ev.type));
return -EFAULT;
}
}
switch (ev.type) {
case UHID_START:
APPL_TRACE_DEBUG("UHID_START from uhid-dev\n");
p_dev->ready_for_data = TRUE;
break;
case UHID_STOP:
APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n");
p_dev->ready_for_data = FALSE;
break;
case UHID_OPEN:
APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n");
break;
case UHID_CLOSE:
APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n");
p_dev->ready_for_data = FALSE;
break;
case UHID_OUTPUT:
if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) {
APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu",
__FUNCTION__, ret,
sizeof(ev.type) + sizeof(ev.u.output));
return -EFAULT;
}
APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d"
,ev.u.output.rtype, ev.u.output.size);
if(ev.u.output.rtype == UHID_FEATURE_REPORT)
btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT,
ev.u.output.size, ev.u.output.data);
else if(ev.u.output.rtype == UHID_OUTPUT_REPORT)
btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT,
ev.u.output.size, ev.u.output.data);
else
btif_hh_setreport(p_dev, BTHH_INPUT_REPORT,
ev.u.output.size, ev.u.output.data);
break;
case UHID_OUTPUT_EV:
APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n");
break;
case UHID_FEATURE:
APPL_TRACE_DEBUG("UHID_FEATURE from uhid-dev\n");
break;
case UHID_FEATURE_ANSWER:
APPL_TRACE_DEBUG("UHID_FEATURE_ANSWER from uhid-dev\n");
break;
default:
APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type);
}
return 0;
}
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) {
if (requested_pos < 0)
return 0;
Cluster** const ii = m_clusters;
Cluster** i = ii;
const long count = m_clusterCount + m_clusterPreloadCount;
Cluster** const jj = ii + count;
Cluster** j = jj;
while (i < j) {
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pCluster = *k;
assert(pCluster);
const long long pos = pCluster->GetPosition();
assert(pos >= 0);
if (pos < requested_pos)
i = k + 1;
else if (pos > requested_pos)
j = k;
else
return pCluster;
}
assert(i == j);
Cluster* const pCluster = Cluster::Create(this, -1, requested_pos);
assert(pCluster);
const ptrdiff_t idx = i - m_clusters;
PreloadCluster(pCluster, idx);
assert(m_clusters);
assert(m_clusterPreloadCount > 0);
assert(m_clusters[idx] == pCluster);
return pCluster;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int sha384_neon_init(struct shash_desc *desc)
{
struct sha512_state *sctx = shash_desc_ctx(desc);
sctx->state[0] = SHA384_H0;
sctx->state[1] = SHA384_H1;
sctx->state[2] = SHA384_H2;
sctx->state[3] = SHA384_H3;
sctx->state[4] = SHA384_H4;
sctx->state[5] = SHA384_H5;
sctx->state[6] = SHA384_H6;
sctx->state[7] = SHA384_H7;
sctx->count[0] = sctx->count[1] = 0;
return 0;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const service_manager::Manifest& GetChromeContentBrowserOverlayManifest() {
static base::NoDestructor<service_manager::Manifest> manifest {
service_manager::ManifestBuilder()
.ExposeCapability("gpu",
service_manager::Manifest::InterfaceList<
metrics::mojom::CallStackProfileCollector>())
.ExposeCapability("renderer",
service_manager::Manifest::InterfaceList<
chrome::mojom::AvailableOfflineContentProvider,
chrome::mojom::CacheStatsRecorder,
chrome::mojom::NetBenchmarking,
data_reduction_proxy::mojom::DataReductionProxy,
metrics::mojom::CallStackProfileCollector,
#if defined(OS_WIN)
mojom::ModuleEventSink,
#endif
rappor::mojom::RapporRecorder,
safe_browsing::mojom::SafeBrowsing>())
.RequireCapability("ash", "system_ui")
.RequireCapability("ash", "test")
.RequireCapability("ash", "display")
.RequireCapability("assistant", "assistant")
.RequireCapability("assistant_audio_decoder", "assistant:audio_decoder")
.RequireCapability("chrome", "input_device_controller")
.RequireCapability("chrome_printing", "converter")
.RequireCapability("cups_ipp_parser", "ipp_parser")
.RequireCapability("device", "device:fingerprint")
.RequireCapability("device", "device:geolocation_config")
.RequireCapability("device", "device:geolocation_control")
.RequireCapability("device", "device:ip_geolocator")
.RequireCapability("ime", "input_engine")
.RequireCapability("mirroring", "mirroring")
.RequireCapability("nacl_broker", "browser")
.RequireCapability("nacl_loader", "browser")
.RequireCapability("noop", "noop")
.RequireCapability("patch", "patch_file")
.RequireCapability("preferences", "pref_client")
.RequireCapability("preferences", "pref_control")
.RequireCapability("profile_import", "import")
.RequireCapability("removable_storage_writer",
"removable_storage_writer")
.RequireCapability("secure_channel", "secure_channel")
.RequireCapability("ui", "ime_registrar")
.RequireCapability("ui", "input_device_controller")
.RequireCapability("ui", "window_manager")
.RequireCapability("unzip", "unzip_file")
.RequireCapability("util_win", "util_win")
.RequireCapability("xr_device_service", "xr_device_provider")
.RequireCapability("xr_device_service", "xr_device_test_hook")
#if defined(OS_CHROMEOS)
.RequireCapability("multidevice_setup", "multidevice_setup")
#endif
.ExposeInterfaceFilterCapability_Deprecated(
"navigation:frame", "renderer",
service_manager::Manifest::InterfaceList<
autofill::mojom::AutofillDriver,
autofill::mojom::PasswordManagerDriver,
chrome::mojom::OfflinePageAutoFetcher,
#if defined(OS_CHROMEOS)
chromeos_camera::mojom::CameraAppHelper,
chromeos::cellular_setup::mojom::CellularSetup,
chromeos::crostini_installer::mojom::PageHandlerFactory,
chromeos::crostini_upgrader::mojom::PageHandlerFactory,
chromeos::ime::mojom::InputEngineManager,
chromeos::machine_learning::mojom::PageHandler,
chromeos::media_perception::mojom::MediaPerception,
chromeos::multidevice_setup::mojom::MultiDeviceSetup,
chromeos::multidevice_setup::mojom::PrivilegedHostDeviceSetter,
chromeos::network_config::mojom::CrosNetworkConfig,
cros::mojom::CameraAppDeviceProvider,
#endif
contextual_search::mojom::ContextualSearchJsApiService,
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::KeepAlive,
#endif
media::mojom::MediaEngagementScoreDetailsProvider,
media_router::mojom::MediaRouter,
page_load_metrics::mojom::PageLoadMetrics,
translate::mojom::ContentTranslateDriver,
downloads::mojom::PageHandlerFactory,
feed_internals::mojom::PageHandler,
new_tab_page::mojom::PageHandlerFactory,
#if defined(OS_ANDROID)
explore_sites_internals::mojom::PageHandler,
#else
app_management::mojom::PageHandlerFactory,
#endif
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
defined(OS_CHROMEOS)
discards::mojom::DetailsProvider, discards::mojom::GraphDump,
#endif
#if defined(OS_CHROMEOS)
add_supervision::mojom::AddSupervisionHandler,
#endif
mojom::BluetoothInternalsHandler,
mojom::InterventionsInternalsPageHandler,
mojom::OmniboxPageHandler, mojom::ResetPasswordHandler,
mojom::SiteEngagementDetailsProvider,
mojom::UsbInternalsPageHandler,
snippets_internals::mojom::PageHandlerFactory>())
.PackageService(prefs::GetManifest())
#if defined(OS_CHROMEOS)
.PackageService(chromeos::multidevice_setup::GetManifest())
#endif // defined(OS_CHROMEOS)
.Build()
};
return *manifest;
}
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: InternalPageInfoBubbleView::InternalPageInfoBubbleView(
views::View* anchor_view,
const gfx::Rect& anchor_rect,
gfx::NativeView parent_window,
const GURL& url)
: BubbleDialogDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT) {
g_shown_bubble_type = PageInfoBubbleView::BUBBLE_INTERNAL_PAGE;
g_page_info_bubble = this;
set_parent_window(parent_window);
if (!anchor_view)
SetAnchorRect(anchor_rect);
int text = IDS_PAGE_INFO_INTERNAL_PAGE;
int icon = IDR_PRODUCT_LOGO_16;
if (url.SchemeIs(extensions::kExtensionScheme)) {
text = IDS_PAGE_INFO_EXTENSION_PAGE;
icon = IDR_PLUGINS_FAVICON;
} else if (url.SchemeIs(content::kViewSourceScheme)) {
text = IDS_PAGE_INFO_VIEW_SOURCE_PAGE;
icon = IDR_PRODUCT_LOGO_16;
} else if (!url.SchemeIs(content::kChromeUIScheme) &&
!url.SchemeIs(content::kChromeDevToolsScheme)) {
NOTREACHED();
}
set_anchor_view_insets(gfx::Insets(
GetLayoutConstant(LOCATION_BAR_BUBBLE_ANCHOR_VERTICAL_INSET), 0));
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal,
gfx::Insets(kSpacing), kSpacing));
set_margins(gfx::Insets());
if (ChromeLayoutProvider::Get()->ShouldShowWindowIcon()) {
views::ImageView* icon_view = new NonAccessibleImageView();
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
icon_view->SetImage(rb.GetImageSkiaNamed(icon));
AddChildView(icon_view);
}
views::Label* label = new views::Label(l10n_util::GetStringUTF16(text));
label->SetMultiLine(true);
label->SetAllowCharacterBreak(true);
label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
AddChildView(label);
views::BubbleDialogDelegateView::CreateBubble(this);
}
CWE ID: CWE-704
Target: 1
Example 2:
Code: Address NormalPageArena::outOfLineAllocate(size_t allocationSize,
size_t gcInfoIndex) {
ASSERT(allocationSize > remainingAllocationSize());
ASSERT(allocationSize >= allocationGranularity);
if (allocationSize >= largeObjectSizeThreshold)
return allocateLargeObject(allocationSize, gcInfoIndex);
updateRemainingAllocationSize();
Address result = allocateFromFreeList(allocationSize, gcInfoIndex);
if (result)
return result;
setAllocationPoint(nullptr, 0);
result = lazySweep(allocationSize, gcInfoIndex);
if (result)
return result;
if (coalesce()) {
result = allocateFromFreeList(allocationSize, gcInfoIndex);
if (result)
return result;
}
getThreadState()->completeSweep();
getThreadState()->scheduleGCIfNeeded();
allocatePage();
result = allocateFromFreeList(allocationSize, gcInfoIndex);
RELEASE_ASSERT(result);
return result;
}
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 attr *bgp_attr_intern(struct attr *attr)
{
struct attr *find;
/* Intern referenced strucutre. */
if (attr->aspath) {
if (!attr->aspath->refcnt)
attr->aspath = aspath_intern(attr->aspath);
else
attr->aspath->refcnt++;
}
if (attr->community) {
if (!attr->community->refcnt)
attr->community = community_intern(attr->community);
else
attr->community->refcnt++;
}
if (attr->ecommunity) {
if (!attr->ecommunity->refcnt)
attr->ecommunity = ecommunity_intern(attr->ecommunity);
else
attr->ecommunity->refcnt++;
}
if (attr->lcommunity) {
if (!attr->lcommunity->refcnt)
attr->lcommunity = lcommunity_intern(attr->lcommunity);
else
attr->lcommunity->refcnt++;
}
if (attr->cluster) {
if (!attr->cluster->refcnt)
attr->cluster = cluster_intern(attr->cluster);
else
attr->cluster->refcnt++;
}
if (attr->transit) {
if (!attr->transit->refcnt)
attr->transit = transit_intern(attr->transit);
else
attr->transit->refcnt++;
}
if (attr->encap_subtlvs) {
if (!attr->encap_subtlvs->refcnt)
attr->encap_subtlvs = encap_intern(attr->encap_subtlvs,
ENCAP_SUBTLV_TYPE);
else
attr->encap_subtlvs->refcnt++;
}
#if ENABLE_BGP_VNC
if (attr->vnc_subtlvs) {
if (!attr->vnc_subtlvs->refcnt)
attr->vnc_subtlvs = encap_intern(attr->vnc_subtlvs,
VNC_SUBTLV_TYPE);
else
attr->vnc_subtlvs->refcnt++;
}
#endif
/* At this point, attr only contains intern'd pointers. that means
* if we find it in attrhash, it has all the same pointers and we
* correctly updated the refcounts on these.
* If we don't find it, we need to allocate a one because in all
* cases this returns a new reference to a hashed attr, but the input
* wasn't on hash. */
find = (struct attr *)hash_get(attrhash, attr, bgp_attr_hash_alloc);
find->refcnt++;
return find;
}
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: PP_Resource ResourceTracker::AddResource(Resource* resource) {
if (last_resource_id_ ==
(std::numeric_limits<PP_Resource>::max() >> kPPIdTypeBits))
return 0;
PP_Resource new_id = MakeTypedId(++last_resource_id_, PP_ID_TYPE_RESOURCE);
live_resources_.insert(std::make_pair(new_id, std::make_pair(resource, 1)));
PP_Instance pp_instance = resource->instance()->pp_instance();
DCHECK(instance_map_.find(pp_instance) != instance_map_.end());
instance_map_[pp_instance]->resources.insert(new_id);
return new_id;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){
uint32 sample_count=0;
uint16 component_count=0;
uint32 palette_offset=0;
uint32 sample_offset=0;
uint32 i=0;
uint32 j=0;
sample_count=t2p->tiff_width*t2p->tiff_length;
component_count=t2p->tiff_samplesperpixel;
if( sample_count * component_count > t2p->tiff_datasize )
{
TIFFError(TIFF2PDF_MODULE, "Error: sample_count * component_count > t2p->tiff_datasize");
t2p->t2p_error = T2P_ERR_ERROR;
return 1;
}
for(i=sample_count;i>0;i--){
palette_offset=buffer[i-1] * component_count;
sample_offset= (i-1) * component_count;
for(j=0;j<component_count;j++){
buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j];
}
}
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: void WebPreferences::Apply(WebView* web_view) const {
WebSettings* settings = web_view->settings();
ApplyFontsFromMap(standard_font_family_map, setStandardFontFamilyWrapper,
settings);
ApplyFontsFromMap(fixed_font_family_map, setFixedFontFamilyWrapper, settings);
ApplyFontsFromMap(serif_font_family_map, setSerifFontFamilyWrapper, settings);
ApplyFontsFromMap(sans_serif_font_family_map, setSansSerifFontFamilyWrapper,
settings);
ApplyFontsFromMap(cursive_font_family_map, setCursiveFontFamilyWrapper,
settings);
ApplyFontsFromMap(fantasy_font_family_map, setFantasyFontFamilyWrapper,
settings);
ApplyFontsFromMap(pictograph_font_family_map, setPictographFontFamilyWrapper,
settings);
settings->setDefaultFontSize(default_font_size);
settings->setDefaultFixedFontSize(default_fixed_font_size);
settings->setMinimumFontSize(minimum_font_size);
settings->setMinimumLogicalFontSize(minimum_logical_font_size);
settings->setDefaultTextEncodingName(ASCIIToUTF16(default_encoding));
settings->setApplyDefaultDeviceScaleFactorInCompositor(
apply_default_device_scale_factor_in_compositor);
settings->setApplyPageScaleFactorInCompositor(
apply_page_scale_factor_in_compositor);
settings->setPerTilePaintingEnabled(per_tile_painting_enabled);
settings->setAcceleratedAnimationEnabled(accelerated_animation_enabled);
settings->setJavaScriptEnabled(javascript_enabled);
settings->setWebSecurityEnabled(web_security_enabled);
settings->setJavaScriptCanOpenWindowsAutomatically(
javascript_can_open_windows_automatically);
settings->setLoadsImagesAutomatically(loads_images_automatically);
settings->setImagesEnabled(images_enabled);
settings->setPluginsEnabled(plugins_enabled);
settings->setDOMPasteAllowed(dom_paste_enabled);
settings->setDeveloperExtrasEnabled(developer_extras_enabled);
settings->setNeedsSiteSpecificQuirks(site_specific_quirks_enabled);
settings->setShrinksStandaloneImagesToFit(shrinks_standalone_images_to_fit);
settings->setUsesEncodingDetector(uses_universal_detector);
settings->setTextAreasAreResizable(text_areas_are_resizable);
settings->setAllowScriptsToCloseWindows(allow_scripts_to_close_windows);
if (user_style_sheet_enabled)
settings->setUserStyleSheetLocation(user_style_sheet_location);
else
settings->setUserStyleSheetLocation(WebURL());
settings->setAuthorAndUserStylesEnabled(author_and_user_styles_enabled);
settings->setUsesPageCache(uses_page_cache);
settings->setPageCacheSupportsPlugins(page_cache_supports_plugins);
settings->setDownloadableBinaryFontsEnabled(remote_fonts_enabled);
settings->setJavaScriptCanAccessClipboard(javascript_can_access_clipboard);
settings->setXSSAuditorEnabled(xss_auditor_enabled);
settings->setDNSPrefetchingEnabled(dns_prefetching_enabled);
settings->setLocalStorageEnabled(local_storage_enabled);
settings->setSyncXHRInDocumentsEnabled(sync_xhr_in_documents_enabled);
WebRuntimeFeatures::enableDatabase(databases_enabled);
settings->setOfflineWebApplicationCacheEnabled(application_cache_enabled);
settings->setCaretBrowsingEnabled(caret_browsing_enabled);
settings->setHyperlinkAuditingEnabled(hyperlink_auditing_enabled);
settings->setCookieEnabled(cookie_enabled);
settings->setEditableLinkBehaviorNeverLive();
settings->setFrameFlatteningEnabled(frame_flattening_enabled);
settings->setFontRenderingModeNormal();
settings->setJavaEnabled(java_enabled);
settings->setAllowUniversalAccessFromFileURLs(
allow_universal_access_from_file_urls);
settings->setAllowFileAccessFromFileURLs(allow_file_access_from_file_urls);
settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded();
settings->setWebAudioEnabled(webaudio_enabled);
settings->setExperimentalWebGLEnabled(experimental_webgl_enabled);
settings->setOpenGLMultisamplingEnabled(gl_multisampling_enabled);
settings->setPrivilegedWebGLExtensionsEnabled(
privileged_webgl_extensions_enabled);
settings->setWebGLErrorsToConsoleEnabled(webgl_errors_to_console_enabled);
settings->setShowDebugBorders(show_composited_layer_borders);
settings->setShowFPSCounter(show_fps_counter);
settings->setAcceleratedCompositingForOverflowScrollEnabled(
accelerated_compositing_for_overflow_scroll_enabled);
settings->setAcceleratedCompositingForScrollableFramesEnabled(
accelerated_compositing_for_scrollable_frames_enabled);
settings->setCompositedScrollingForFramesEnabled(
composited_scrolling_for_frames_enabled);
settings->setShowPlatformLayerTree(show_composited_layer_tree);
settings->setShowPaintRects(show_paint_rects);
settings->setRenderVSyncEnabled(render_vsync_enabled);
settings->setAcceleratedCompositingEnabled(accelerated_compositing_enabled);
settings->setAcceleratedCompositingForFixedPositionEnabled(
fixed_position_compositing_enabled);
settings->setAccelerated2dCanvasEnabled(accelerated_2d_canvas_enabled);
settings->setDeferred2dCanvasEnabled(deferred_2d_canvas_enabled);
settings->setAntialiased2dCanvasEnabled(!antialiased_2d_canvas_disabled);
settings->setAcceleratedPaintingEnabled(accelerated_painting_enabled);
settings->setAcceleratedFiltersEnabled(accelerated_filters_enabled);
settings->setGestureTapHighlightEnabled(gesture_tap_highlight_enabled);
settings->setAcceleratedCompositingFor3DTransformsEnabled(
accelerated_compositing_for_3d_transforms_enabled);
settings->setAcceleratedCompositingForVideoEnabled(
accelerated_compositing_for_video_enabled);
settings->setAcceleratedCompositingForAnimationEnabled(
accelerated_compositing_for_animation_enabled);
settings->setAcceleratedCompositingForPluginsEnabled(
accelerated_compositing_for_plugins_enabled);
settings->setAcceleratedCompositingForCanvasEnabled(
experimental_webgl_enabled || accelerated_2d_canvas_enabled);
settings->setMemoryInfoEnabled(memory_info_enabled);
settings->setAsynchronousSpellCheckingEnabled(
asynchronous_spell_checking_enabled);
settings->setUnifiedTextCheckerEnabled(unified_textchecker_enabled);
for (WebInspectorPreferences::const_iterator it = inspector_settings.begin();
it != inspector_settings.end(); ++it)
web_view->setInspectorSetting(WebString::fromUTF8(it->first),
WebString::fromUTF8(it->second));
web_view->setTabsToLinks(tabs_to_links);
settings->setInteractiveFormValidationEnabled(true);
settings->setFullScreenEnabled(fullscreen_enabled);
settings->setAllowDisplayOfInsecureContent(allow_displaying_insecure_content);
settings->setAllowRunningOfInsecureContent(allow_running_insecure_content);
settings->setPasswordEchoEnabled(password_echo_enabled);
settings->setShouldPrintBackgrounds(should_print_backgrounds);
settings->setEnableScrollAnimator(enable_scroll_animator);
settings->setVisualWordMovementEnabled(visual_word_movement_enabled);
settings->setCSSStickyPositionEnabled(css_sticky_position_enabled);
settings->setExperimentalCSSCustomFilterEnabled(css_shaders_enabled);
settings->setExperimentalCSSVariablesEnabled(css_variables_enabled);
settings->setExperimentalCSSGridLayoutEnabled(css_grid_layout_enabled);
WebRuntimeFeatures::enableTouch(touch_enabled);
settings->setDeviceSupportsTouch(device_supports_touch);
settings->setDeviceSupportsMouse(device_supports_mouse);
settings->setEnableTouchAdjustment(touch_adjustment_enabled);
settings->setDefaultTileSize(
WebSize(default_tile_width, default_tile_height));
settings->setMaxUntiledLayerSize(
WebSize(max_untiled_layer_width, max_untiled_layer_height));
settings->setFixedPositionCreatesStackingContext(
fixed_position_creates_stacking_context);
settings->setDeferredImageDecodingEnabled(deferred_image_decoding_enabled);
settings->setShouldRespectImageOrientation(should_respect_image_orientation);
settings->setEditingBehavior(
static_cast<WebSettings::EditingBehavior>(editing_behavior));
settings->setSupportsMultipleWindows(supports_multiple_windows);
settings->setViewportEnabled(viewport_enabled);
#if defined(OS_ANDROID)
settings->setAllowCustomScrollbarInMainFrame(false);
settings->setTextAutosizingEnabled(text_autosizing_enabled);
settings->setTextAutosizingFontScaleFactor(font_scale_factor);
web_view->setIgnoreViewportTagMaximumScale(force_enable_zoom);
settings->setAutoZoomFocusedNodeToLegibleScale(true);
settings->setDoubleTapToZoomEnabled(true);
settings->setMediaPlaybackRequiresUserGesture(
user_gesture_required_for_media_playback);
#endif
WebNetworkStateNotifier::setOnLine(is_online);
}
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 ssl2_generate_key_material(SSL *s)
{
unsigned int i;
EVP_MD_CTX ctx;
unsigned char *km;
unsigned char c = '0';
const EVP_MD *md5;
int md_size;
md5 = EVP_md5();
# ifdef CHARSET_EBCDIC
c = os_toascii['0']; /* Must be an ASCII '0', not EBCDIC '0', see
* SSLv2 docu */
# endif
EVP_MD_CTX_init(&ctx);
km = s->s2->key_material;
if (s->session->master_key_length < 0 ||
s->session->master_key_length > (int)sizeof(s->session->master_key)) {
SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR);
return 0;
}
md_size = EVP_MD_size(md5);
if (md_size < 0)
return 0;
for (i = 0; i < s->s2->key_material_length; i += md_size) {
if (((km - s->s2->key_material) + md_size) >
(int)sizeof(s->s2->key_material)) {
/*
* EVP_DigestFinal_ex() below would write beyond buffer
*/
SSLerr(SSL_F_SSL2_GENERATE_KEY_MATERIAL, ERR_R_INTERNAL_ERROR);
return 0;
}
EVP_DigestInit_ex(&ctx, md5, NULL);
OPENSSL_assert(s->session->master_key_length >= 0
&& s->session->master_key_length
< (int)sizeof(s->session->master_key));
EVP_DigestUpdate(&ctx, s->session->master_key,
s->session->master_key_length);
EVP_DigestUpdate(&ctx, &c, 1);
c++;
EVP_DigestUpdate(&ctx, s->s2->challenge, s->s2->challenge_length);
EVP_DigestUpdate(&ctx, s->s2->conn_id, s->s2->conn_id_length);
EVP_DigestFinal_ex(&ctx, km, NULL);
km += md_size;
}
EVP_MD_CTX_cleanup(&ctx);
return 1;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, unsigned int optlen)
{
struct sctp_assocparams assocparams;
struct sctp_association *asoc;
if (optlen != sizeof(struct sctp_assocparams))
return -EINVAL;
if (copy_from_user(&assocparams, optval, optlen))
return -EFAULT;
asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
return -EINVAL;
/* Set the values to the specific association */
if (asoc) {
if (assocparams.sasoc_asocmaxrxt != 0) {
__u32 path_sum = 0;
int paths = 0;
struct sctp_transport *peer_addr;
list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list,
transports) {
path_sum += peer_addr->pathmaxrxt;
paths++;
}
/* Only validate asocmaxrxt if we have more than
* one path/transport. We do this because path
* retransmissions are only counted when we have more
* then one path.
*/
if (paths > 1 &&
assocparams.sasoc_asocmaxrxt > path_sum)
return -EINVAL;
asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
}
if (assocparams.sasoc_cookie_life != 0)
asoc->cookie_life = ms_to_ktime(assocparams.sasoc_cookie_life);
} else {
/* Set the values to the endpoint */
struct sctp_sock *sp = sctp_sk(sk);
if (assocparams.sasoc_asocmaxrxt != 0)
sp->assocparams.sasoc_asocmaxrxt =
assocparams.sasoc_asocmaxrxt;
if (assocparams.sasoc_cookie_life != 0)
sp->assocparams.sasoc_cookie_life =
assocparams.sasoc_cookie_life;
}
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: bool FrameLoader::ShouldPerformFragmentNavigation(bool is_form_submission,
const String& http_method,
FrameLoadType load_type,
const KURL& url) {
return DeprecatedEqualIgnoringCase(http_method, HTTPNames::GET) &&
!IsReloadLoadType(load_type) &&
load_type != kFrameLoadTypeBackForward &&
url.HasFragmentIdentifier() &&
EqualIgnoringFragmentIdentifier(frame_->GetDocument()->Url(), url)
&& !frame_->GetDocument()->IsFrameSet();
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct ip_options *tcp_v4_save_options(struct sock *sk,
struct sk_buff *skb)
{
struct ip_options *opt = &(IPCB(skb)->opt);
struct ip_options *dopt = NULL;
if (opt && opt->optlen) {
int opt_size = optlength(opt);
dopt = kmalloc(opt_size, GFP_ATOMIC);
if (dopt) {
if (ip_options_echo(dopt, skb)) {
kfree(dopt);
dopt = NULL;
}
}
}
return dopt;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static void cirrus_update_bank_ptr(CirrusVGAState * s, unsigned bank_index)
{
unsigned offset;
unsigned limit;
if ((s->vga.gr[0x0b] & 0x01) != 0) /* dual bank */
offset = s->vga.gr[0x09 + bank_index];
else /* single bank */
offset = s->vga.gr[0x09];
if ((s->vga.gr[0x0b] & 0x20) != 0)
offset <<= 14;
else
offset <<= 12;
if (s->real_vram_size <= offset)
limit = 0;
else
limit = s->real_vram_size - offset;
if (((s->vga.gr[0x0b] & 0x01) == 0) && (bank_index != 0)) {
if (limit > 0x8000) {
offset += 0x8000;
limit -= 0x8000;
} else {
limit = 0;
}
}
if (limit > 0) {
s->cirrus_bank_base[bank_index] = offset;
s->cirrus_bank_limit[bank_index] = limit;
} else {
s->cirrus_bank_base[bank_index] = 0;
s->cirrus_bank_limit[bank_index] = 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: split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
{
char *p;
int i;
static const char ws[] = " \t";
for (i = 0; i < maxfields; i++)
fields[i] = NULL;
p = str;
i = 0;
while (*p != '\0') {
p += strspn(p, ws);
if (*p == '#' || *p == '\0')
break;
if (i >= maxfields) {
snprintf(msg, msglen, "line has too many fields");
return -1;
}
if (*p == '"') {
char *dst;
dst = ++p;
fields[i] = dst;
while (*p != '"') {
if (*p == '\\') {
p++;
if (*p != '"' && *p != '\\' &&
*p != '\0') {
snprintf(msg, msglen,
"invalid `\\' escape");
return -1;
}
}
if (*p == '\0') {
snprintf(msg, msglen,
"unterminated quoted string");
return -1;
}
*dst++ = *p++;
}
*dst = '\0';
p++;
if (*fields[i] == '\0') {
snprintf(msg, msglen,
"empty quoted string not permitted");
return -1;
}
if (*p != '\0' && strspn(p, ws) == 0) {
snprintf(msg, msglen, "quoted string not"
" followed by white space");
return -1;
}
} else {
fields[i] = p;
p += strcspn(p, ws);
if (*p != '\0')
*p++ = '\0';
}
i++;
}
return i;
}
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: struct r_bin_dyldcache_obj_t* r_bin_dyldcache_from_bytes_new(const ut8* buf, ut64 size) {
struct r_bin_dyldcache_obj_t *bin;
if (!(bin = malloc (sizeof (struct r_bin_dyldcache_obj_t)))) {
return NULL;
}
memset (bin, 0, sizeof (struct r_bin_dyldcache_obj_t));
if (!buf) {
return r_bin_dyldcache_free (bin);
}
bin->b = r_buf_new();
if (!r_buf_set_bytes (bin->b, buf, size)) {
return r_bin_dyldcache_free (bin);
}
if (!r_bin_dyldcache_init (bin)) {
return r_bin_dyldcache_free (bin);
}
bin->size = size;
return bin;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void jsB_initnumber(js_State *J)
{
J->Number_prototype->u.number = 0;
js_pushobject(J, J->Number_prototype);
{
jsB_propf(J, "Number.prototype.valueOf", Np_valueOf, 0);
jsB_propf(J, "Number.prototype.toString", Np_toString, 1);
jsB_propf(J, "Number.prototype.toLocaleString", Np_toString, 0);
jsB_propf(J, "Number.prototype.toFixed", Np_toFixed, 1);
jsB_propf(J, "Number.prototype.toExponential", Np_toExponential, 1);
jsB_propf(J, "Number.prototype.toPrecision", Np_toPrecision, 1);
}
js_newcconstructor(J, jsB_Number, jsB_new_Number, "Number", 0); /* 1 */
{
jsB_propn(J, "MAX_VALUE", 1.7976931348623157e+308);
jsB_propn(J, "MIN_VALUE", 5e-324);
jsB_propn(J, "NaN", NAN);
jsB_propn(J, "NEGATIVE_INFINITY", -INFINITY);
jsB_propn(J, "POSITIVE_INFINITY", INFINITY);
}
js_defglobal(J, "Number", JS_DONTENUM);
}
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 hns_xgmac_get_sset_count(int stringset)
{
if (stringset == ETH_SS_STATS)
return ARRAY_SIZE(g_xgmac_stats_string);
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: ScopedRequest(PepperDeviceEnumerationHostHelper* owner,
const Delegate::EnumerateDevicesCallback& callback)
: owner_(owner),
callback_(callback),
requested_(false),
request_id_(0),
sync_call_(false) {
if (!owner_->document_url_.is_valid())
return;
requested_ = true;
sync_call_ = true;
request_id_ = owner_->delegate_->EnumerateDevices(
owner_->device_type_,
owner_->document_url_,
base::Bind(&ScopedRequest::EnumerateDevicesCallbackBody, AsWeakPtr()));
sync_call_ = false;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: const RenderFrameImpl* RenderFrameImpl::GetLocalRoot() const {
return IsLocalRoot() ? this
: RenderFrameImpl::FromWebFrame(frame_->LocalRoot());
}
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 BrowserTabStripController::IsIncognito() {
return browser_->profile()->IsOffTheRecord();
}
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 copy_xauthority(void) {
char *src = RUN_XAUTHORITY_FILE ;
char *dest;
if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR);
if (rv)
fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
unlink(src);
}
CWE ID: CWE-269
Target: 1
Example 2:
Code: void inet_csk_reqsk_queue_prune(struct sock *parent,
const unsigned long interval,
const unsigned long timeout,
const unsigned long max_rto)
{
struct inet_connection_sock *icsk = inet_csk(parent);
struct request_sock_queue *queue = &icsk->icsk_accept_queue;
struct listen_sock *lopt = queue->listen_opt;
int max_retries = icsk->icsk_syn_retries ? : sysctl_tcp_synack_retries;
int thresh = max_retries;
unsigned long now = jiffies;
struct request_sock **reqp, *req;
int i, budget;
if (lopt == NULL || lopt->qlen == 0)
return;
/* Normally all the openreqs are young and become mature
* (i.e. converted to established socket) for first timeout.
* If synack was not acknowledged for 3 seconds, it means
* one of the following things: synack was lost, ack was lost,
* rtt is high or nobody planned to ack (i.e. synflood).
* When server is a bit loaded, queue is populated with old
* open requests, reducing effective size of queue.
* When server is well loaded, queue size reduces to zero
* after several minutes of work. It is not synflood,
* it is normal operation. The solution is pruning
* too old entries overriding normal timeout, when
* situation becomes dangerous.
*
* Essentially, we reserve half of room for young
* embrions; and abort old ones without pity, if old
* ones are about to clog our table.
*/
if (lopt->qlen>>(lopt->max_qlen_log-1)) {
int young = (lopt->qlen_young<<1);
while (thresh > 2) {
if (lopt->qlen < young)
break;
thresh--;
young <<= 1;
}
}
if (queue->rskq_defer_accept)
max_retries = queue->rskq_defer_accept;
budget = 2 * (lopt->nr_table_entries / (timeout / interval));
i = lopt->clock_hand;
do {
reqp=&lopt->syn_table[i];
while ((req = *reqp) != NULL) {
if (time_after_eq(now, req->expires)) {
int expire = 0, resend = 0;
syn_ack_recalc(req, thresh, max_retries,
queue->rskq_defer_accept,
&expire, &resend);
if (req->rsk_ops->syn_ack_timeout)
req->rsk_ops->syn_ack_timeout(parent, req);
if (!expire &&
(!resend ||
!req->rsk_ops->rtx_syn_ack(parent, req, NULL) ||
inet_rsk(req)->acked)) {
unsigned long timeo;
if (req->retrans++ == 0)
lopt->qlen_young--;
timeo = min((timeout << req->retrans), max_rto);
req->expires = now + timeo;
reqp = &req->dl_next;
continue;
}
/* Drop this request */
inet_csk_reqsk_queue_unlink(parent, req, reqp);
reqsk_queue_removed(queue, req);
reqsk_free(req);
continue;
}
reqp = &req->dl_next;
}
i = (i + 1) & (lopt->nr_table_entries - 1);
} while (--budget > 0);
lopt->clock_hand = i;
if (lopt->qlen)
inet_csk_reset_keepalive_timer(parent, interval);
}
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 ib_cm_init_qp_attr(struct ib_cm_id *cm_id,
struct ib_qp_attr *qp_attr,
int *qp_attr_mask)
{
struct cm_id_private *cm_id_priv;
int ret;
cm_id_priv = container_of(cm_id, struct cm_id_private, id);
switch (qp_attr->qp_state) {
case IB_QPS_INIT:
ret = cm_init_qp_init_attr(cm_id_priv, qp_attr, qp_attr_mask);
break;
case IB_QPS_RTR:
ret = cm_init_qp_rtr_attr(cm_id_priv, qp_attr, qp_attr_mask);
break;
case IB_QPS_RTS:
ret = cm_init_qp_rts_attr(cm_id_priv, qp_attr, qp_attr_mask);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
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 RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ZEND_API void zend_objects_store_call_destructors(zend_objects_store *objects TSRMLS_DC)
{
zend_uint i = 1;
for (i = 1; i < objects->top ; i++) {
if (objects->object_buckets[i].valid) {
struct _store_object *obj = &objects->object_buckets[i].bucket.obj;
if (!objects->object_buckets[i].destructor_called) {
objects->object_buckets[i].destructor_called = 1;
if (obj->dtor && obj->object) {
obj->refcount++;
obj->dtor(obj->object, i TSRMLS_CC);
obj = &objects->object_buckets[i].bucket.obj;
obj->refcount--;
if (obj->refcount == 0) {
/* in case gc_collect_cycle is triggered before free_storage */
GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
}
}
}
}
}
}
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 GLES2Implementation::BindUniformLocationCHROMIUM(GLuint program,
GLint location,
const char* name) {
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glBindUniformLocationCHROMIUM("
<< program << ", " << location << ", " << name << ")");
SetBucketAsString(kResultBucketId, name);
helper_->BindUniformLocationCHROMIUMBucket(program, location,
kResultBucketId);
helper_->SetBucketSize(kResultBucketId, 0);
CheckGLError();
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int msg_flags)
{
struct sock *sk = sock->sk;
struct rds_sock *rs = rds_sk_to_rs(sk);
long timeo;
int ret = 0, nonblock = msg_flags & MSG_DONTWAIT;
struct sockaddr_in *sin;
struct rds_incoming *inc = NULL;
/* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */
timeo = sock_rcvtimeo(sk, nonblock);
rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo);
if (msg_flags & MSG_OOB)
goto out;
while (1) {
/* If there are pending notifications, do those - and nothing else */
if (!list_empty(&rs->rs_notify_queue)) {
ret = rds_notify_queue_get(rs, msg);
break;
}
if (rs->rs_cong_notify) {
ret = rds_notify_cong(rs, msg);
break;
}
if (!rds_next_incoming(rs, &inc)) {
if (nonblock) {
ret = -EAGAIN;
break;
}
timeo = wait_event_interruptible_timeout(*sk_sleep(sk),
(!list_empty(&rs->rs_notify_queue) ||
rs->rs_cong_notify ||
rds_next_incoming(rs, &inc)), timeo);
rdsdebug("recvmsg woke inc %p timeo %ld\n", inc,
timeo);
if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT)
continue;
ret = timeo;
if (ret == 0)
ret = -ETIMEDOUT;
break;
}
rdsdebug("copying inc %p from %pI4:%u to user\n", inc,
&inc->i_conn->c_faddr,
ntohs(inc->i_hdr.h_sport));
ret = inc->i_conn->c_trans->inc_copy_to_user(inc, msg->msg_iov,
size);
if (ret < 0)
break;
/*
* if the message we just copied isn't at the head of the
* recv queue then someone else raced us to return it, try
* to get the next message.
*/
if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) {
rds_inc_put(inc);
inc = NULL;
rds_stats_inc(s_recv_deliver_raced);
continue;
}
if (ret < be32_to_cpu(inc->i_hdr.h_len)) {
if (msg_flags & MSG_TRUNC)
ret = be32_to_cpu(inc->i_hdr.h_len);
msg->msg_flags |= MSG_TRUNC;
}
if (rds_cmsg_recv(inc, msg)) {
ret = -EFAULT;
goto out;
}
rds_stats_inc(s_recv_delivered);
sin = (struct sockaddr_in *)msg->msg_name;
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = inc->i_hdr.h_sport;
sin->sin_addr.s_addr = inc->i_saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
}
break;
}
if (inc)
rds_inc_put(inc);
out:
return ret;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static inline u32 nfsd4_setclientid_rsize(struct svc_rqst *rqstp, struct nfsd4_op *op)
{
return (op_encode_hdr_size + 2 + XDR_QUADLEN(NFS4_VERIFIER_SIZE)) *
sizeof(__be32);
}
CWE ID: CWE-404
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
*root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
/* If the it is not there, just fake it; some docs don't have it */
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
*root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0)
goto out;
return cdf_read_long_sector_chain(info, h, sat,
d->d_stream_first_sector, d->d_size, scn);
out:
scn->sst_tab = NULL;
scn->sst_len = 0;
scn->sst_dirlen = 0;
return 0;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PaintArtifactCompositor::PendingLayer::PendingLayer(
const PaintChunk& first_paint_chunk,
size_t chunk_index,
bool chunk_requires_own_layer)
: bounds(first_paint_chunk.bounds),
rect_known_to_be_opaque(
first_paint_chunk.known_to_be_opaque ? bounds : FloatRect()),
property_tree_state(first_paint_chunk.properties.GetPropertyTreeState()),
requires_own_layer(chunk_requires_own_layer) {
paint_chunk_indices.push_back(chunk_index);
}
CWE ID:
Target: 1
Example 2:
Code: void key_gc_keytype(struct key_type *ktype)
{
kenter("%s", ktype->name);
key_gc_dead_keytype = ktype;
set_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
smp_mb();
set_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags);
kdebug("schedule");
schedule_work(&key_gc_work);
kdebug("sleep");
wait_on_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE,
TASK_UNINTERRUPTIBLE);
key_gc_dead_keytype = NULL;
kleave("");
}
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 CMYKToRGB(int c, int m, int y, int k, int inverted)
{
if (inverted) {
c = 255 - c;
m = 255 - m;
y = 255 - y;
k = 255 - k;
}
return gdTrueColor((255 - c) * (255 - k) / 255, (255 - m) * (255 - k) / 255, (255 - y) * (255 - k) / 255);
}
CWE ID: CWE-415
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: InspectorResourceAgent::InspectorResourceAgent(InspectorPageAgent* pageAgent, InspectorClient* client)
: InspectorBaseAgent<InspectorResourceAgent>("Network")
, m_pageAgent(pageAgent)
, m_client(client)
, m_frontend(0)
, m_resourcesData(adoptPtr(new NetworkResourcesData()))
, m_isRecalculatingStyle(false)
{
}
CWE ID:
Target: 1
Example 2:
Code: cond_continue(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
es_ptr ep = esp;
int code;
/* The top element of the e-stack is the remaining tail of */
/* the cond body. The top element of the o-stack should be */
/* the (boolean) result of the test that is the first element */
/* of the tail. */
check_type(*op, t_boolean);
if (op->value.boolval) { /* true */
array_get(imemory, ep, 1L, ep);
esfile_check_cache();
code = o_pop_estack;
} else if (r_size(ep) > 2) { /* false */
const ref_packed *elts = ep->value.packed;
check_estack(2);
r_dec_size(ep, 2);
elts = packed_next(elts);
elts = packed_next(elts);
ep->value.packed = elts;
array_get(imemory, ep, 0L, ep + 2);
make_op_estack(ep + 1, cond_continue);
esp = ep + 2;
esfile_check_cache();
code = o_push_estack;
} else { /* fall off end of cond */
esp = ep - 1;
code = o_pop_estack;
}
pop(1); /* get rid of the boolean */
return code;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void _xml_characterDataHandler(void *userData, const XML_Char *s, int len)
{
xml_parser *parser = (xml_parser *)userData;
if (parser) {
zval *retval, *args[2];
if (parser->characterDataHandler) {
args[0] = _xml_resource_zval(parser->index);
args[1] = _xml_xmlchar_zval(s, len, parser->target_encoding);
if ((retval = xml_call_handler(parser, parser->characterDataHandler, parser->characterDataPtr, 2, args))) {
zval_ptr_dtor(&retval);
}
}
if (parser->data) {
int i;
int doprint = 0;
char *decoded_value;
int decoded_len;
decoded_value = xml_utf8_decode(s,len,&decoded_len,parser->target_encoding);
for (i = 0; i < decoded_len; i++) {
switch (decoded_value[i]) {
case ' ':
case '\t':
case '\n':
continue;
default:
doprint = 1;
break;
}
if (doprint) {
break;
}
}
if (doprint || (! parser->skipwhite)) {
if (parser->lastwasopen) {
zval **myval;
/* check if the current tag already has a value - if yes append to that! */
if (zend_hash_find(Z_ARRVAL_PP(parser->ctag),"value",sizeof("value"),(void **) &myval) == SUCCESS) {
int newlen = Z_STRLEN_PP(myval) + decoded_len;
Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);
strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);
Z_STRLEN_PP(myval) += decoded_len;
efree(decoded_value);
} else {
add_assoc_string(*(parser->ctag),"value",decoded_value,0);
}
} else {
zval *tag;
zval **curtag, **mytype, **myval;
HashPosition hpos=NULL;
zend_hash_internal_pointer_end_ex(Z_ARRVAL_P(parser->data), &hpos);
if (hpos && (zend_hash_get_current_data_ex(Z_ARRVAL_P(parser->data), (void **) &curtag, &hpos) == SUCCESS)) {
if (zend_hash_find(Z_ARRVAL_PP(curtag),"type",sizeof("type"),(void **) &mytype) == SUCCESS) {
if (!strcmp(Z_STRVAL_PP(mytype), "cdata")) {
if (zend_hash_find(Z_ARRVAL_PP(curtag),"value",sizeof("value"),(void **) &myval) == SUCCESS) {
int newlen = Z_STRLEN_PP(myval) + decoded_len;
Z_STRVAL_PP(myval) = erealloc(Z_STRVAL_PP(myval),newlen+1);
strncpy(Z_STRVAL_PP(myval) + Z_STRLEN_PP(myval), decoded_value, decoded_len + 1);
Z_STRLEN_PP(myval) += decoded_len;
efree(decoded_value);
return;
}
}
}
}
if (parser->level <= XML_MAXLEVEL) {
MAKE_STD_ZVAL(tag);
array_init(tag);
_xml_add_to_info(parser,parser->ltags[parser->level-1] + parser->toffset);
add_assoc_string(tag,"tag",parser->ltags[parser->level-1] + parser->toffset,1);
add_assoc_string(tag,"value",decoded_value,0);
add_assoc_string(tag,"type","cdata",1);
add_assoc_long(tag,"level",parser->level);
zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),NULL);
} else if (parser->level == (XML_MAXLEVEL + 1)) {
TSRMLS_FETCH();
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated");
}
}
} else {
efree(decoded_value);
}
}
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void sctp_v6_get_dst(struct sctp_transport *t, union sctp_addr *saddr,
struct flowi *fl, struct sock *sk)
{
struct sctp_association *asoc = t->asoc;
struct dst_entry *dst = NULL;
struct flowi6 *fl6 = &fl->u.ip6;
struct sctp_bind_addr *bp;
struct sctp_sockaddr_entry *laddr;
union sctp_addr *baddr = NULL;
union sctp_addr *daddr = &t->ipaddr;
union sctp_addr dst_saddr;
__u8 matchlen = 0;
__u8 bmatchlen;
sctp_scope_t scope;
memset(fl6, 0, sizeof(struct flowi6));
fl6->daddr = daddr->v6.sin6_addr;
fl6->fl6_dport = daddr->v6.sin6_port;
fl6->flowi6_proto = IPPROTO_SCTP;
if (ipv6_addr_type(&daddr->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL)
fl6->flowi6_oif = daddr->v6.sin6_scope_id;
pr_debug("%s: dst=%pI6 ", __func__, &fl6->daddr);
if (asoc)
fl6->fl6_sport = htons(asoc->base.bind_addr.port);
if (saddr) {
fl6->saddr = saddr->v6.sin6_addr;
fl6->fl6_sport = saddr->v6.sin6_port;
pr_debug("src=%pI6 - ", &fl6->saddr);
}
dst = ip6_dst_lookup_flow(sk, fl6, NULL, false);
if (!asoc || saddr)
goto out;
bp = &asoc->base.bind_addr;
scope = sctp_scope(daddr);
/* ip6_dst_lookup has filled in the fl6->saddr for us. Check
* to see if we can use it.
*/
if (!IS_ERR(dst)) {
/* Walk through the bind address list and look for a bind
* address that matches the source address of the returned dst.
*/
sctp_v6_to_addr(&dst_saddr, &fl6->saddr, htons(bp->port));
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid || (laddr->state != SCTP_ADDR_SRC))
continue;
/* Do not compare against v4 addrs */
if ((laddr->a.sa.sa_family == AF_INET6) &&
(sctp_v6_cmp_addr(&dst_saddr, &laddr->a))) {
rcu_read_unlock();
goto out;
}
}
rcu_read_unlock();
/* None of the bound addresses match the source address of the
* dst. So release it.
*/
dst_release(dst);
dst = NULL;
}
/* Walk through the bind address list and try to get the
* best source address for a given destination.
*/
rcu_read_lock();
list_for_each_entry_rcu(laddr, &bp->address_list, list) {
if (!laddr->valid)
continue;
if ((laddr->state == SCTP_ADDR_SRC) &&
(laddr->a.sa.sa_family == AF_INET6) &&
(scope <= sctp_scope(&laddr->a))) {
bmatchlen = sctp_v6_addr_match_len(daddr, &laddr->a);
if (!baddr || (matchlen < bmatchlen)) {
baddr = &laddr->a;
matchlen = bmatchlen;
}
}
}
rcu_read_unlock();
if (baddr) {
fl6->saddr = baddr->v6.sin6_addr;
fl6->fl6_sport = baddr->v6.sin6_port;
dst = ip6_dst_lookup_flow(sk, fl6, NULL, false);
}
out:
if (!IS_ERR_OR_NULL(dst)) {
struct rt6_info *rt;
rt = (struct rt6_info *)dst;
t->dst = dst;
t->dst_cookie = rt->rt6i_node ? rt->rt6i_node->fn_sernum : 0;
pr_debug("rt6_dst:%pI6 rt6_src:%pI6\n", &rt->rt6i_dst.addr,
&fl6->saddr);
} else {
t->dst = NULL;
pr_debug("no route\n");
}
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: static inline void print_vma(struct vm_area_struct *vma)
{
printk("vma start 0x%08lx\n", vma->vm_start);
printk("vma end 0x%08lx\n", vma->vm_end);
print_prots(vma->vm_page_prot);
printk("vm_flags 0x%08lx\n", vma->vm_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: nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr,
struct nfsd4_layoutget *lgp)
{
struct xdr_stream *xdr = &resp->xdr;
const struct nfsd4_layout_ops *ops =
nfsd4_layout_ops[lgp->lg_layout_type];
__be32 *p;
dprintk("%s: err %d\n", __func__, nfserr);
if (nfserr)
goto out;
nfserr = nfserr_resource;
p = xdr_reserve_space(xdr, 36 + sizeof(stateid_opaque_t));
if (!p)
goto out;
*p++ = cpu_to_be32(1); /* we always set return-on-close */
*p++ = cpu_to_be32(lgp->lg_sid.si_generation);
p = xdr_encode_opaque_fixed(p, &lgp->lg_sid.si_opaque,
sizeof(stateid_opaque_t));
*p++ = cpu_to_be32(1); /* we always return a single layout */
p = xdr_encode_hyper(p, lgp->lg_seg.offset);
p = xdr_encode_hyper(p, lgp->lg_seg.length);
*p++ = cpu_to_be32(lgp->lg_seg.iomode);
*p++ = cpu_to_be32(lgp->lg_layout_type);
nfserr = ops->encode_layoutget(xdr, lgp);
out:
kfree(lgp->lg_content);
return nfserr;
}
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: void ResetScreenHandler::UpdateStatusChanged(
const UpdateEngineClient::Status& status) {
if (status.status == UpdateEngineClient::UPDATE_STATUS_ERROR) {
base::DictionaryValue params;
params.SetInteger("uiState", kErrorUIStateRollback);
ShowScreen(OobeUI::kScreenErrorMessage, ¶ms);
} else if (status.status ==
UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) {
DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void Document::AddMutationEventListenerTypeIfEnabled(
ListenerType listener_type) {
if (ContextFeatures::MutationEventsEnabled(this))
AddListenerType(listener_type);
}
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 DevToolsSession::DispatchProtocolMessage(
blink::mojom::DevToolsMessageChunkPtr chunk) {
if (chunk->is_first && !response_message_buffer_.empty()) {
ReceivedBadMessage();
return;
}
response_message_buffer_ += std::move(chunk->data);
if (!chunk->is_last)
return;
if (!chunk->post_state.empty())
state_cookie_ = std::move(chunk->post_state);
waiting_for_response_messages_.erase(chunk->call_id);
std::string message;
message.swap(response_message_buffer_);
client_->DispatchProtocolMessage(agent_host_, message);
}
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 Track::Info::Copy(Info& dst) const
{
if (&dst == this)
return 0;
dst.type = type;
dst.number = number;
dst.defaultDuration = defaultDuration;
dst.codecDelay = codecDelay;
dst.seekPreRoll = seekPreRoll;
dst.uid = uid;
dst.lacing = lacing;
dst.settings = settings;
if (int status = CopyStr(&Info::nameAsUTF8, dst))
return status;
if (int status = CopyStr(&Info::language, dst))
return status;
if (int status = CopyStr(&Info::codecId, dst))
return status;
if (int status = CopyStr(&Info::codecNameAsUTF8, dst))
return status;
if (codecPrivateSize > 0)
{
if (codecPrivate == NULL)
return -1;
if (dst.codecPrivate)
return -1;
if (dst.codecPrivateSize != 0)
return -1;
dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize];
if (dst.codecPrivate == NULL)
return -1;
memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize);
dst.codecPrivateSize = codecPrivateSize;
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: explicit DeferredTaskSetColorInput(WebPagePrivate* webPagePrivate, BlackBerry::Platform::String value)
: DeferredTaskType(webPagePrivate)
{
webPagePrivate->m_cachedColorInput = value;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bit_in(PG_FUNCTION_ARGS)
{
char *input_string = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarBit *result; /* The resulting bit string */
char *sp; /* pointer into the character string */
bits8 *r; /* pointer into the result */
int len, /* Length of the whole data structure */
bitlen, /* Number of bits in the bit string */
slen; /* Length of the input string */
bool bit_not_hex; /* false = hex string true = bit string */
int bc;
bits8 x = 0;
/* Check that the first character is a b or an x */
if (input_string[0] == 'b' || input_string[0] == 'B')
{
bit_not_hex = true;
sp = input_string + 1;
}
else if (input_string[0] == 'x' || input_string[0] == 'X')
{
bit_not_hex = false;
sp = input_string + 1;
}
else
{
/*
* Otherwise it's binary. This allows things like cast('1001' as bit)
* to work transparently.
*/
bit_not_hex = true;
sp = input_string;
}
slen = strlen(sp);
/* Determine bitlength from input string */
if (bit_not_hex)
bitlen = slen;
else
bitlen = slen * 4;
/*
* Sometimes atttypmod is not supplied. If it is supplied we need to make
* sure that the bitstring fits.
*/
if (atttypmod <= 0)
atttypmod = bitlen;
else if (bitlen != atttypmod)
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
errmsg("bit string length %d does not match type bit(%d)",
bitlen, atttypmod)));
len = VARBITTOTALLEN(atttypmod);
/* set to 0 so that *r is always initialised and string is zero-padded */
result = (VarBit *) palloc0(len);
SET_VARSIZE(result, len);
VARBITLEN(result) = atttypmod;
r = VARBITS(result);
if (bit_not_hex)
{
/* Parse the bit representation of the string */
/* We know it fits, as bitlen was compared to atttypmod */
x = HIGHBIT;
for (; *sp; sp++)
{
if (*sp == '1')
*r |= x;
else if (*sp != '0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid binary digit",
*sp)));
x >>= 1;
if (x == 0)
{
x = HIGHBIT;
r++;
}
}
}
else
{
/* Parse the hex representation of the string */
for (bc = 0; *sp; sp++)
{
if (*sp >= '0' && *sp <= '9')
x = (bits8) (*sp - '0');
else if (*sp >= 'A' && *sp <= 'F')
x = (bits8) (*sp - 'A') + 10;
else if (*sp >= 'a' && *sp <= 'f')
x = (bits8) (*sp - 'a') + 10;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid hexadecimal digit",
*sp)));
if (bc)
{
*r++ |= x;
bc = 0;
}
else
{
*r = x << 4;
bc = 1;
}
}
}
PG_RETURN_VARBIT_P(result);
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int build_ntlmssp_auth_blob(unsigned char **pbuffer,
u16 *buflen,
struct cifs_ses *ses,
const struct nls_table *nls_cp)
{
int rc;
AUTHENTICATE_MESSAGE *sec_blob;
__u32 flags;
unsigned char *tmp;
rc = setup_ntlmv2_rsp(ses, nls_cp);
if (rc) {
cifs_dbg(VFS, "Error %d during NTLMSSP authentication\n", rc);
*buflen = 0;
goto setup_ntlmv2_ret;
}
*pbuffer = kmalloc(size_of_ntlmssp_blob(ses), GFP_KERNEL);
sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer;
memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
sec_blob->MessageType = NtLmAuthenticate;
flags = NTLMSSP_NEGOTIATE_56 |
NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_TARGET_INFO |
NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC;
if (ses->server->sign) {
flags |= NTLMSSP_NEGOTIATE_SIGN;
if (!ses->server->session_estab ||
ses->ntlmssp->sesskey_per_smbsess)
flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
}
tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE);
sec_blob->NegotiateFlags = cpu_to_le32(flags);
sec_blob->LmChallengeResponse.BufferOffset =
cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE));
sec_blob->LmChallengeResponse.Length = 0;
sec_blob->LmChallengeResponse.MaximumLength = 0;
sec_blob->NtChallengeResponse.BufferOffset =
cpu_to_le32(tmp - *pbuffer);
if (ses->user_name != NULL) {
memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
ses->auth_key.len - CIFS_SESS_KEY_SIZE);
tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
sec_blob->NtChallengeResponse.Length =
cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
sec_blob->NtChallengeResponse.MaximumLength =
cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
} else {
/*
* don't send an NT Response for anonymous access
*/
sec_blob->NtChallengeResponse.Length = 0;
sec_blob->NtChallengeResponse.MaximumLength = 0;
}
if (ses->domainName == NULL) {
sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->DomainName.Length = 0;
sec_blob->DomainName.MaximumLength = 0;
tmp += 2;
} else {
int len;
len = cifs_strtoUTF16((__le16 *)tmp, ses->domainName,
CIFS_MAX_DOMAINNAME_LEN, nls_cp);
len *= 2; /* unicode is 2 bytes each */
sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->DomainName.Length = cpu_to_le16(len);
sec_blob->DomainName.MaximumLength = cpu_to_le16(len);
tmp += len;
}
if (ses->user_name == NULL) {
sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->UserName.Length = 0;
sec_blob->UserName.MaximumLength = 0;
tmp += 2;
} else {
int len;
len = cifs_strtoUTF16((__le16 *)tmp, ses->user_name,
CIFS_MAX_USERNAME_LEN, nls_cp);
len *= 2; /* unicode is 2 bytes each */
sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->UserName.Length = cpu_to_le16(len);
sec_blob->UserName.MaximumLength = cpu_to_le16(len);
tmp += len;
}
sec_blob->WorkstationName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->WorkstationName.Length = 0;
sec_blob->WorkstationName.MaximumLength = 0;
tmp += 2;
if (((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) ||
(ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC))
&& !calc_seckey(ses)) {
memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE);
sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE);
sec_blob->SessionKey.MaximumLength =
cpu_to_le16(CIFS_CPHTXT_SIZE);
tmp += CIFS_CPHTXT_SIZE;
} else {
sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
sec_blob->SessionKey.Length = 0;
sec_blob->SessionKey.MaximumLength = 0;
}
*buflen = tmp - *pbuffer;
setup_ntlmv2_ret:
return rc;
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void willRemoveChild(Node* child)
{
ASSERT(child->parentNode());
ChildListMutationScope(child->parentNode()).willRemoveChild(child);
child->notifyMutationObserversNodeWillDetach();
dispatchChildRemovalEvents(child);
child->document().nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
ChildFrameDisconnector(child).disconnect();
}
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 IsIDNComponentSafe(base::StringPiece16 label, bool is_tld_ascii) {
return g_idn_spoof_checker.Get().SafeToDisplayAsUnicode(label, is_tld_ascii);
}
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: double ConvolverNode::latencyTime() const
{
return m_reverb ? m_reverb->latencyFrames() / static_cast<double>(sampleRate()) : 0;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static PHP_MINFO_FUNCTION(cgi)
{
DISPLAY_INI_ENTRIES();
}
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 remove_bond(const bt_bdaddr_t *bd_addr)
{
/* sanity check */
if (interface_ready() == FALSE)
return BT_STATUS_NOT_READY;
return btif_dm_remove_bond(bd_addr);
}
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 struct file *path_openat(int dfd, struct filename *pathname,
struct nameidata *nd, const struct open_flags *op, int flags)
{
struct file *file;
struct path path;
int opened = 0;
int error;
file = get_empty_filp();
if (IS_ERR(file))
return file;
file->f_flags = op->open_flag;
if (unlikely(file->f_flags & __O_TMPFILE)) {
error = do_tmpfile(dfd, pathname, nd, flags, op, file, &opened);
goto out;
}
error = path_init(dfd, pathname, flags, nd);
if (unlikely(error))
goto out;
error = do_last(nd, &path, file, op, &opened, pathname);
while (unlikely(error > 0)) { /* trailing symlink */
struct path link = path;
void *cookie;
if (!(nd->flags & LOOKUP_FOLLOW)) {
path_put_conditional(&path, nd);
path_put(&nd->path);
error = -ELOOP;
break;
}
error = may_follow_link(&link, nd);
if (unlikely(error))
break;
nd->flags |= LOOKUP_PARENT;
nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL);
error = follow_link(&link, nd, &cookie);
if (unlikely(error))
break;
error = do_last(nd, &path, file, op, &opened, pathname);
put_link(nd, &link, cookie);
}
out:
path_cleanup(nd);
if (!(opened & FILE_OPENED)) {
BUG_ON(!error);
put_filp(file);
}
if (unlikely(error)) {
if (error == -EOPENSTALE) {
if (flags & LOOKUP_RCU)
error = -ECHILD;
else
error = -ESTALE;
}
file = ERR_PTR(error);
}
return file;
}
CWE ID:
Target: 1
Example 2:
Code: error::Error GLES2DecoderImpl::HandlePixelStorei(
uint32 immediate_data_size, const gles2::PixelStorei& c) {
GLenum pname = c.pname;
GLenum param = c.param;
if (!validators_->pixel_store.IsValid(pname)) {
SetGLError(GL_INVALID_ENUM, "glPixelStorei: pname GL_INVALID_ENUM");
return error::kNoError;
}
if (!validators_->pixel_store_alignment.IsValid(param)) {
SetGLError(GL_INVALID_VALUE, "glPixelSTore: param GL_INVALID_VALUE");
return error::kNoError;
}
glPixelStorei(pname, param);
switch (pname) {
case GL_PACK_ALIGNMENT:
pack_alignment_ = param;
break;
case GL_UNPACK_ALIGNMENT:
unpack_alignment_ = param;
break;
default:
NOTREACHED();
break;
}
return error::kNoError;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void op32_tx_suspend(struct b43_dmaring *ring)
{
b43_dma_write(ring, B43_DMA32_TXCTL, b43_dma_read(ring, B43_DMA32_TXCTL)
| B43_DMA32_TXSUSPEND);
}
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 __mkroute_input(struct sk_buff *skb,
const struct fib_result *res,
struct in_device *in_dev,
__be32 daddr, __be32 saddr, u32 tos)
{
struct fib_nh_exception *fnhe;
struct rtable *rth;
int err;
struct in_device *out_dev;
unsigned int flags = 0;
bool do_cache;
u32 itag = 0;
/* get a working reference to the output device */
out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res));
if (out_dev == NULL) {
net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n");
return -EINVAL;
}
err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res),
in_dev->dev, in_dev, &itag);
if (err < 0) {
ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr,
saddr);
goto cleanup;
}
do_cache = res->fi && !itag;
if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) &&
(IN_DEV_SHARED_MEDIA(out_dev) ||
inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) {
flags |= RTCF_DOREDIRECT;
do_cache = false;
}
if (skb->protocol != htons(ETH_P_IP)) {
/* Not IP (i.e. ARP). Do not create route, if it is
* invalid for proxy arp. DNAT routes are always valid.
*
* Proxy arp feature have been extended to allow, ARP
* replies back to the same interface, to support
* Private VLAN switch technologies. See arp.c.
*/
if (out_dev == in_dev &&
IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) {
err = -EINVAL;
goto cleanup;
}
}
fnhe = find_exception(&FIB_RES_NH(*res), daddr);
if (do_cache) {
if (fnhe != NULL)
rth = rcu_dereference(fnhe->fnhe_rth_input);
else
rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input);
if (rt_cache_valid(rth)) {
skb_dst_set_noref(skb, &rth->dst);
goto out;
}
}
rth = rt_dst_alloc(out_dev->dev,
IN_DEV_CONF_GET(in_dev, NOPOLICY),
IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache);
if (!rth) {
err = -ENOBUFS;
goto cleanup;
}
rth->rt_genid = rt_genid_ipv4(dev_net(rth->dst.dev));
rth->rt_flags = flags;
rth->rt_type = res->type;
rth->rt_is_input = 1;
rth->rt_iif = 0;
rth->rt_pmtu = 0;
rth->rt_gateway = 0;
rth->rt_uses_gateway = 0;
INIT_LIST_HEAD(&rth->rt_uncached);
RT_CACHE_STAT_INC(in_slow_tot);
rth->dst.input = ip_forward;
rth->dst.output = ip_output;
rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag);
skb_dst_set(skb, &rth->dst);
out:
err = 0;
cleanup:
return err;
}
CWE ID: CWE-17
Target: 1
Example 2:
Code: static int IsPipeliningPossible(const struct Curl_easy *handle,
const struct connectdata *conn)
{
int avail = 0;
/* If a HTTP protocol and pipelining is enabled */
if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
(!conn->bits.protoconnstart || !conn->bits.close)) {
if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
(handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
(handle->set.httpreq == HTTPREQ_GET ||
handle->set.httpreq == HTTPREQ_HEAD))
/* didn't ask for HTTP/1.0 and a GET or HEAD */
avail |= CURLPIPE_HTTP1;
if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
(handle->set.httpversion >= CURL_HTTP_VERSION_2))
/* allows HTTP/2 */
avail |= CURLPIPE_MULTIPLEX;
}
return avail;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
if (WARN_ON_ONCE(current->flags & PF_EXITING))
goto out;
ewq->ctx = ctx;
init_waitqueue_entry(&ewq->wq, current);
spin_lock(&ctx->event_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->event_wqh, &ewq->wq);
for (;;) {
set_current_state(TASK_KILLABLE);
if (ewq->msg.event == 0)
break;
if (ACCESS_ONCE(ctx->released) ||
fatal_signal_pending(current)) {
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
if (ewq->msg.event == UFFD_EVENT_FORK) {
struct userfaultfd_ctx *new;
new = (struct userfaultfd_ctx *)
(unsigned long)
ewq->msg.arg.reserved.reserved1;
userfaultfd_ctx_put(new);
}
break;
}
spin_unlock(&ctx->event_wqh.lock);
wake_up_poll(&ctx->fd_wqh, POLLIN);
schedule();
spin_lock(&ctx->event_wqh.lock);
}
__set_current_state(TASK_RUNNING);
spin_unlock(&ctx->event_wqh.lock);
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
out:
userfaultfd_ctx_put(ctx);
}
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: grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock)
{
struct grub_ext2_data *data = node->data;
struct grub_ext2_inode *inode = &node->inode;
int blknr = -1;
unsigned int blksz = EXT2_BLOCK_SIZE (data);
int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data);
if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG)
{
#ifndef _MSC_VER
char buf[EXT2_BLOCK_SIZE (data)];
#else
char * buf = grub_malloc (EXT2_BLOCK_SIZE(data));
#endif
struct grub_ext4_extent_header *leaf;
struct grub_ext4_extent *ext;
int i;
leaf = grub_ext4_find_leaf (data, buf,
(struct grub_ext4_extent_header *) inode->blocks.dir_blocks,
fileblock);
if (! leaf)
{
grub_error (GRUB_ERR_BAD_FS, "invalid extent");
return -1;
}
ext = (struct grub_ext4_extent *) (leaf + 1);
for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++)
{
if (fileblock < grub_le_to_cpu32 (ext[i].block))
break;
}
if (--i >= 0)
{
fileblock -= grub_le_to_cpu32 (ext[i].block);
if (fileblock >= grub_le_to_cpu16 (ext[i].len))
return 0;
else
{
grub_disk_addr_t start;
start = grub_le_to_cpu16 (ext[i].start_hi);
start = (start << 32) + grub_le_to_cpu32 (ext[i].start);
return fileblock + start;
}
}
else
{
grub_error (GRUB_ERR_BAD_FS, "something wrong with extent");
return -1;
}
}
/* Direct blocks. */
if (fileblock < INDIRECT_BLOCKS) {
blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]);
/* Indirect. */
} else if (fileblock < INDIRECT_BLOCKS + blksz / 4)
{
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]);
grub_free (indir);
}
/* Double indirect. */
else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \
* (grub_disk_addr_t)(blksz / 4 + 1))
{
unsigned int perblock = blksz / 4;
unsigned int rblock = fileblock - (INDIRECT_BLOCKS
+ blksz / 4);
grub_uint32_t *indir;
indir = grub_malloc (blksz);
if (! indir)
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (inode->blocks.double_indir_block))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
if (grub_disk_read (data->disk,
((grub_disk_addr_t)
grub_le_to_cpu32 (indir[rblock / perblock]))
<< log2_blksz,
0, blksz, indir))
return grub_errno;
blknr = grub_le_to_cpu32 (indir[rblock % perblock]);
grub_free (indir);
}
/* triple indirect. */
else
{
grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
"ext2fs doesn't support triple indirect blocks");
}
return blknr;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void AwFeatureListCreator::CreateFeatureListAndFieldTrials() {
CreateLocalState();
AwMetricsServiceClient::GetInstance()->Initialize(local_state_.get());
SetUpFieldTrials();
}
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 PHP_FUNCTION(xmlwriter_start_element_ns)
{
zval *pind;
xmlwriter_object *intern;
xmlTextWriterPtr ptr;
char *name, *prefix, *uri;
int name_len, prefix_len, uri_len, retval;
#ifdef ZEND_ENGINE_2
zval *this = getThis();
if (this) {
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s!ss!",
&prefix, &prefix_len, &name, &name_len, &uri, &uri_len) == FAILURE) {
return;
}
XMLWRITER_FROM_OBJECT(intern, this);
} else
#endif
{
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs!ss!", &pind,
&prefix, &prefix_len, &name, &name_len, &uri, &uri_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(intern,xmlwriter_object *, &pind, -1, "XMLWriter", le_xmlwriter);
}
XMLW_NAME_CHK("Invalid Element Name");
ptr = intern->ptr;
if (ptr) {
retval = xmlTextWriterStartElementNS(ptr, (xmlChar *)prefix, (xmlChar *)name, (xmlChar *)uri);
if (retval != -1) {
RETURN_TRUE;
}
}
RETURN_FALSE;
}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void get_socket_name(SingleInstData* data, char* buf, int len)
{
const char* dpy = g_getenv("DISPLAY");
char* host = NULL;
int dpynum;
if(dpy)
{
const char* p = strrchr(dpy, ':');
host = g_strndup(dpy, (p - dpy));
dpynum = atoi(p + 1);
}
else
dpynum = 0;
g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s",
g_get_tmp_dir(),
data->prog_name,
host ? host : "",
dpynum,
g_get_user_name());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void HTMLFormElement::submitFromJavaScript()
{
submit(0, false, UserGestureIndicator::processingUserGesture(), SubmittedByJavaScript);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
mbedtls_md_type_t md_alg,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
mbedtls_hmac_drbg_context rng_ctx;
mbedtls_hmac_drbg_context *p_rng = &rng_ctx;
unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES];
size_t grp_len = ( grp->nbits + 7 ) / 8;
const mbedtls_md_info_t *md_info;
mbedtls_mpi h;
if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
mbedtls_mpi_init( &h );
mbedtls_hmac_drbg_init( &rng_ctx );
ECDSA_RS_ENTER( det );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->det != NULL )
{
/* redirect to our context */
p_rng = &rs_ctx->det->rng_ctx;
/* jump to current step */
if( rs_ctx->det->state == ecdsa_det_sign )
goto sign;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
/* Use private key and message hash (reduced) to initialize HMAC_DRBG */
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) );
MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) );
mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->det != NULL )
rs_ctx->det->state = ecdsa_det_sign;
sign:
#endif
#if defined(MBEDTLS_ECDSA_SIGN_ALT)
ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen,
mbedtls_hmac_drbg_random, p_rng );
#else
ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen,
mbedtls_hmac_drbg_random, p_rng, rs_ctx );
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
cleanup:
mbedtls_hmac_drbg_free( &rng_ctx );
mbedtls_mpi_free( &h );
ECDSA_RS_LEAVE( det );
return( ret );
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GDataFileSystem::OnCopyDocumentCompleted(
const FilePath& dir_path,
const FileOperationCallback& callback,
GDataErrorCode status,
scoped_ptr<base::Value> data) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!callback.is_null());
GDataFileError error = util::GDataToGDataFileError(status);
if (error != GDATA_FILE_OK) {
callback.Run(error);
return;
}
scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data));
if (!doc_entry.get()) {
callback.Run(GDATA_FILE_ERROR_FAILED);
return;
}
GDataEntry* entry = GDataEntry::FromDocumentEntry(
NULL, doc_entry.get(), directory_service_.get());
if (!entry) {
callback.Run(GDATA_FILE_ERROR_FAILED);
return;
}
directory_service_->root()->AddEntry(entry);
MoveEntryFromRootDirectory(dir_path,
callback,
GDATA_FILE_OK,
entry->GetFilePath());
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void BaseMultipleFieldsDateAndTimeInputType::forwardEvent(Event* event)
{
if (m_spinButtonElement) {
m_spinButtonElement->forwardEvent(event);
if (event->defaultHandled())
return;
}
if (m_dateTimeEditElement)
m_dateTimeEditElement->defaultEventHandler(event);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: FakePlatformSensor::FakePlatformSensor(mojom::SensorType type,
mojo::ScopedSharedBufferMapping mapping,
PlatformSensorProvider* provider)
: PlatformSensor(type, std::move(mapping), provider) {
ON_CALL(*this, StartSensor(_))
.WillByDefault(
Invoke([this](const PlatformSensorConfiguration& configuration) {
SensorReading reading;
if (GetType() == mojom::SensorType::AMBIENT_LIGHT) {
reading.als.value = configuration.frequency();
UpdateSharedBufferAndNotifyClients(reading);
}
return true;
}));
}
CWE ID: CWE-732
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void fillWidgetStates(AXObject& axObject,
protocol::Array<AXProperty>& properties) {
AccessibilityRole role = axObject.roleValue();
if (roleAllowsChecked(role)) {
AccessibilityButtonState checked = axObject.checkboxOrRadioValue();
switch (checked) {
case ButtonStateOff:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("false", AXValueTypeEnum::Tristate)));
break;
case ButtonStateOn:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("true", AXValueTypeEnum::Tristate)));
break;
case ButtonStateMixed:
properties.addItem(
createProperty(AXWidgetStatesEnum::Checked,
createValue("mixed", AXValueTypeEnum::Tristate)));
break;
}
}
AccessibilityExpanded expanded = axObject.isExpanded();
switch (expanded) {
case ExpandedUndefined:
break;
case ExpandedCollapsed:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined)));
break;
case ExpandedExpanded:
properties.addItem(createProperty(
AXWidgetStatesEnum::Expanded,
createBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined)));
break;
}
if (role == ToggleButtonRole) {
if (!axObject.isPressed()) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("false", AXValueTypeEnum::Tristate)));
} else {
const AtomicString& pressedAttr =
axObject.getAttribute(HTMLNames::aria_pressedAttr);
if (equalIgnoringCase(pressedAttr, "mixed"))
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("mixed", AXValueTypeEnum::Tristate)));
else
properties.addItem(
createProperty(AXWidgetStatesEnum::Pressed,
createValue("true", AXValueTypeEnum::Tristate)));
}
}
if (roleAllowsSelected(role)) {
properties.addItem(
createProperty(AXWidgetStatesEnum::Selected,
createBooleanValue(axObject.isSelected())));
}
if (roleAllowsModal(role)) {
properties.addItem(createProperty(AXWidgetStatesEnum::Modal,
createBooleanValue(axObject.isModal())));
}
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: rngTest(const char *filename,
const char *resul ATTRIBUTE_UNUSED,
const char *errr ATTRIBUTE_UNUSED,
int options) {
const char *base = baseFilename(filename);
const char *base2;
const char *instance;
xmlRelaxNGParserCtxtPtr ctxt;
xmlRelaxNGPtr schemas;
int res = 0, len, ret = 0;
char pattern[500];
char prefix[500];
char result[500];
char err[500];
glob_t globbuf;
size_t i;
char count = 0;
/* first compile the schemas if possible */
ctxt = xmlRelaxNGNewParserCtxt(filename);
xmlRelaxNGSetParserErrors(ctxt,
(xmlRelaxNGValidityErrorFunc) testErrorHandler,
(xmlRelaxNGValidityWarningFunc) testErrorHandler,
ctxt);
schemas = xmlRelaxNGParse(ctxt);
xmlRelaxNGFreeParserCtxt(ctxt);
/*
* most of the mess is about the output filenames generated by the Makefile
*/
len = strlen(base);
if ((len > 499) || (len < 5)) {
xmlRelaxNGFree(schemas);
return(-1);
}
len -= 4; /* remove trailing .rng */
memcpy(prefix, base, len);
prefix[len] = 0;
snprintf(pattern, 499, "./test/relaxng/%s_?.xml", prefix);
pattern[499] = 0;
globbuf.gl_offs = 0;
glob(pattern, GLOB_DOOFFS, NULL, &globbuf);
for (i = 0;i < globbuf.gl_pathc;i++) {
testErrorsSize = 0;
testErrors[0] = 0;
instance = globbuf.gl_pathv[i];
base2 = baseFilename(instance);
len = strlen(base2);
if ((len > 6) && (base2[len - 6] == '_')) {
count = base2[len - 5];
snprintf(result, 499, "result/relaxng/%s_%c",
prefix, count);
result[499] = 0;
snprintf(err, 499, "result/relaxng/%s_%c.err",
prefix, count);
err[499] = 0;
} else {
fprintf(stderr, "don't know how to process %s\n", instance);
continue;
}
if (schemas == NULL) {
} else {
nb_tests++;
ret = rngOneTest(filename, instance, result, err,
options, schemas);
if (res != 0)
ret = res;
}
}
globfree(&globbuf);
xmlRelaxNGFree(schemas);
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: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ipt_entry *)e);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PageInfo::RecordPasswordReuseEvent() {
if (!password_protection_service_) {
return;
}
if (safe_browsing_status_ == SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE) {
safe_browsing::LogWarningAction(
safe_browsing::WarningUIType::PAGE_INFO,
safe_browsing::WarningAction::SHOWN,
safe_browsing::LoginReputationClientRequest::PasswordReuseEvent::
SIGN_IN_PASSWORD,
password_protection_service_->GetSyncAccountType());
} else {
safe_browsing::LogWarningAction(
safe_browsing::WarningUIType::PAGE_INFO,
safe_browsing::WarningAction::SHOWN,
safe_browsing::LoginReputationClientRequest::PasswordReuseEvent::
ENTERPRISE_PASSWORD,
password_protection_service_->GetSyncAccountType());
}
}
CWE ID: CWE-311
Target: 1
Example 2:
Code: TmEcode Detect(ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
DEBUG_VALIDATE_PACKET(p);
DetectEngineCtx *de_ctx = NULL;
DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
if (det_ctx == NULL) {
printf("ERROR: Detect has no thread ctx\n");
goto error;
}
if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) {
(void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1);
SCLogDebug("Detect Engine using new det_ctx - %p",
det_ctx);
}
/* if in MT mode _and_ we have tenants registered, use
* MT logic. */
if (det_ctx->mt_det_ctxs_cnt > 0 && det_ctx->TenantGetId != NULL)
{
uint32_t tenant_id = p->tenant_id;
if (tenant_id == 0)
tenant_id = det_ctx->TenantGetId(det_ctx, p);
if (tenant_id > 0 && tenant_id < det_ctx->mt_det_ctxs_cnt) {
p->tenant_id = tenant_id;
det_ctx = GetTenantById(det_ctx->mt_det_ctxs_hash, tenant_id);
if (det_ctx == NULL)
return TM_ECODE_OK;
de_ctx = det_ctx->de_ctx;
if (de_ctx == NULL)
return TM_ECODE_OK;
if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) {
(void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1);
SCLogDebug("MT de_ctx %p det_ctx %p (tenant %u)", de_ctx, det_ctx, tenant_id);
}
} else {
/* use default if no tenants are registered for this packet */
de_ctx = det_ctx->de_ctx;
}
} else {
de_ctx = det_ctx->de_ctx;
}
if (p->flow) {
DetectFlow(tv, de_ctx, det_ctx, p);
} else {
DetectNoFlow(tv, de_ctx, det_ctx, p);
}
return TM_ECODE_OK;
error:
return TM_ECODE_FAILED;
}
CWE ID: CWE-693
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 regulator_suspend_prepare(suspend_state_t state)
{
struct regulator_dev *rdev;
int ret = 0;
/* ON is handled by regulator active state */
if (state == PM_SUSPEND_ON)
return -EINVAL;
mutex_lock(®ulator_list_mutex);
list_for_each_entry(rdev, ®ulator_list, list) {
mutex_lock(&rdev->mutex);
ret = suspend_prepare(rdev, state);
mutex_unlock(&rdev->mutex);
if (ret < 0) {
rdev_err(rdev, "failed to prepare\n");
goto out;
}
}
out:
mutex_unlock(®ulator_list_mutex);
return ret;
}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
{
/* Error in the linear composition arithmetic - only relevant when
* composition actually happens (0 < alpha < 1).
*/
if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
return pm->maxcalc16;
else if (pm->assume_16_bit_calculations)
return pm->maxcalcG;
else
return pm->maxcalc8;
}
CWE ID:
Target: 1
Example 2:
Code: void av_freep(void *arg)
{
void **ptr = (void **)arg;
av_free(*ptr);
*ptr = NULL;
}
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: PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",
image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
{
return tun->flags & TUN_VNET_BE ? false :
virtio_legacy_is_little_endian();
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ssh_session(void)
{
int type;
int interactive = 0;
int have_tty = 0;
struct winsize ws;
char *cp;
const char *display;
/* Enable compression if requested. */
if (options.compression) {
options.compression_level);
if (options.compression_level < 1 ||
options.compression_level > 9)
fatal("Compression level must be from 1 (fast) to "
"9 (slow, best).");
/* Send the request. */
packet_start(SSH_CMSG_REQUEST_COMPRESSION);
packet_put_int(options.compression_level);
packet_send();
packet_write_wait();
type = packet_read();
if (type == SSH_SMSG_SUCCESS)
packet_start_compression(options.compression_level);
else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host refused compression.");
else
packet_disconnect("Protocol error waiting for "
"compression response.");
}
/* Allocate a pseudo tty if appropriate. */
if (tty_flag) {
debug("Requesting pty.");
/* Start the packet. */
packet_start(SSH_CMSG_REQUEST_PTY);
/* Store TERM in the packet. There is no limit on the
length of the string. */
cp = getenv("TERM");
if (!cp)
cp = "";
packet_put_cstring(cp);
/* Store window size in the packet. */
if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
memset(&ws, 0, sizeof(ws));
packet_put_int((u_int)ws.ws_row);
packet_put_int((u_int)ws.ws_col);
packet_put_int((u_int)ws.ws_xpixel);
packet_put_int((u_int)ws.ws_ypixel);
/* Store tty modes in the packet. */
tty_make_modes(fileno(stdin), NULL);
/* Send the packet, and wait for it to leave. */
packet_send();
packet_write_wait();
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
have_tty = 1;
} else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host failed or refused to "
"allocate a pseudo tty.");
else
packet_disconnect("Protocol error waiting for pty "
"request response.");
}
/* Request X11 forwarding if enabled and DISPLAY is set. */
display = getenv("DISPLAY");
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
if (options.forward_x11 && display != NULL) {
char *proto, *data;
/* Get reasonable local authentication information. */
client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted,
options.forward_x11_timeout,
&proto, &data);
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
x11_request_forwarding_with_spoofing(0, display, proto,
data, 0);
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
} else if (type == SSH_SMSG_FAILURE) {
logit("Warning: Remote host denied X11 forwarding.");
} else {
packet_disconnect("Protocol error waiting for X11 "
"forwarding");
}
}
/* Tell the packet module whether this is an interactive session. */
packet_set_interactive(interactive,
options.ip_qos_interactive, options.ip_qos_bulk);
/* Request authentication agent forwarding if appropriate. */
check_agent_present();
if (options.forward_agent) {
debug("Requesting authentication agent forwarding.");
auth_request_forwarding();
/* Read response from the server. */
type = packet_read();
packet_check_eom();
if (type != SSH_SMSG_SUCCESS)
logit("Warning: Remote host denied authentication agent forwarding.");
}
/* Initiate port forwardings. */
ssh_init_stdio_forwarding();
ssh_init_forwarding();
/* Execute a local command */
if (options.local_command != NULL &&
options.permit_local_command)
ssh_local_cmd(options.local_command);
/*
* If requested and we are not interested in replies to remote
* forwarding requests, then let ssh continue in the background.
*/
if (fork_after_authentication_flag) {
if (options.exit_on_forward_failure &&
options.num_remote_forwards > 0) {
debug("deferring postauth fork until remote forward "
"confirmation received");
} else
fork_postauth();
}
/*
* If a command was specified on the command line, execute the
* command now. Otherwise request the server to start a shell.
*/
if (buffer_len(&command) > 0) {
int len = buffer_len(&command);
if (len > 900)
len = 900;
debug("Sending command: %.*s", len,
(u_char *)buffer_ptr(&command));
packet_start(SSH_CMSG_EXEC_CMD);
packet_put_string(buffer_ptr(&command), buffer_len(&command));
packet_send();
packet_write_wait();
} else {
debug("Requesting shell.");
packet_start(SSH_CMSG_EXEC_SHELL);
packet_send();
packet_write_wait();
}
/* Enter the interactive session. */
return client_loop(have_tty, tty_flag ?
options.escape_char : SSH_ESCAPECHAR_NONE, 0);
}
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: mwifiex_set_wmm_params(struct mwifiex_private *priv,
struct mwifiex_uap_bss_param *bss_cfg,
struct cfg80211_ap_settings *params)
{
const u8 *vendor_ie;
const u8 *wmm_ie;
u8 wmm_oui[] = {0x00, 0x50, 0xf2, 0x02};
vendor_ie = cfg80211_find_vendor_ie(WLAN_OUI_MICROSOFT,
WLAN_OUI_TYPE_MICROSOFT_WMM,
params->beacon.tail,
params->beacon.tail_len);
if (vendor_ie) {
wmm_ie = vendor_ie;
memcpy(&bss_cfg->wmm_info, wmm_ie +
sizeof(struct ieee_types_header), *(wmm_ie + 1));
priv->wmm_enabled = 1;
} else {
memset(&bss_cfg->wmm_info, 0, sizeof(bss_cfg->wmm_info));
memcpy(&bss_cfg->wmm_info.oui, wmm_oui, sizeof(wmm_oui));
bss_cfg->wmm_info.subtype = MWIFIEX_WMM_SUBTYPE;
bss_cfg->wmm_info.version = MWIFIEX_WMM_VERSION;
priv->wmm_enabled = 0;
}
bss_cfg->qos_info = 0x00;
return;
}
CWE ID: CWE-120
Target: 1
Example 2:
Code: static void usb_net_register_types(void)
{
type_register_static(&net_info);
usb_legacy_register(TYPE_USB_NET, "net", usb_net_init);
}
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 png_fixed_warning(png_const_structrp png_ptr, png_const_charp msg)
{
fprintf(stderr, "overflow in: %s\n", msg);
}
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: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
guint pkt_len;
int pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void WebGL2RenderingContextBase::texImage3D(
GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLsizei depth,
GLint border,
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels) {
TexImageHelperDOMArrayBufferView(kTexImage3D, target, level, internalformat,
width, height, depth, border, format, type,
0, 0, 0, pixels.View(), kNullAllowed, 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: link_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CopyMoveJob *job;
CommonJob *common;
GFile *src;
GdkPoint *point;
char *dest_fs_type;
int total, left;
int i;
GList *l;
job = task_data;
common = &job->common;
dest_fs_type = NULL;
nautilus_progress_info_start (job->common.progress);
verify_destination (&job->common,
job->destination,
NULL,
-1);
if (job_aborted (common))
{
goto aborted;
}
total = left = g_list_length (job->files);
report_preparing_link_progress (job, total, left);
i = 0;
for (l = job->files;
l != NULL && !job_aborted (common);
l = l->next)
{
src = l->data;
if (i < job->n_icon_positions)
{
point = &job->icon_positions[i];
}
else
{
point = NULL;
}
link_file (job, src, job->destination,
&dest_fs_type, job->debuting_files,
point, left);
report_preparing_link_progress (job, total, --left);
i++;
}
aborted:
g_free (dest_fs_type);
}
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 fsmVerify(const char *path, rpmfi fi)
{
int rc;
int saveerrno = errno;
struct stat dsb;
mode_t mode = rpmfiFMode(fi);
rc = fsmStat(path, 1, &dsb);
if (rc)
return rc;
if (S_ISREG(mode)) {
/* HP-UX (and other os'es) don't permit unlink on busy files. */
char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL);
rc = fsmRename(path, rmpath);
/* XXX shouldn't we take unlink return code here? */
if (!rc)
(void) fsmUnlink(rmpath);
else
rc = RPMERR_UNLINK_FAILED;
free(rmpath);
return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */
} else if (S_ISDIR(mode)) {
if (S_ISDIR(dsb.st_mode)) return 0;
if (S_ISLNK(dsb.st_mode)) {
rc = fsmStat(path, 0, &dsb);
if (rc == RPMERR_ENOENT) rc = 0;
if (rc) return rc;
errno = saveerrno;
if (S_ISDIR(dsb.st_mode)) return 0;
}
} else if (S_ISLNK(mode)) {
if (S_ISLNK(dsb.st_mode)) {
char buf[8 * BUFSIZ];
size_t len;
rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len);
errno = saveerrno;
if (rc) return rc;
if (rstreq(rpmfiFLink(fi), buf)) return 0;
}
} else if (S_ISFIFO(mode)) {
if (S_ISFIFO(dsb.st_mode)) return 0;
} else if (S_ISCHR(mode) || S_ISBLK(mode)) {
if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) &&
(dsb.st_rdev == rpmfiFRdev(fi))) return 0;
} else if (S_ISSOCK(mode)) {
if (S_ISSOCK(dsb.st_mode)) return 0;
}
/* XXX shouldn't do this with commit/undo. */
rc = fsmUnlink(path);
if (rc == 0) rc = RPMERR_ENOENT;
return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: void DocumentThreadableLoader::redirectBlocked()
{
ThreadableLoaderClient* client = m_client;
clear();
client->didFailRedirectCheck();
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BinaryUploadService::OnGetInstanceID(Request* request,
const std::string& instance_id) {
if (!IsActive(request))
return;
if (instance_id == BinaryFCMService::kInvalidId) {
FinishRequest(request, Result::FAILED_TO_GET_TOKEN,
DeepScanningClientResponse());
return;
}
request->set_fcm_token(instance_id);
request->GetRequestData(base::BindOnce(&BinaryUploadService::OnGetRequestData,
weakptr_factory_.GetWeakPtr(),
request));
}
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 oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx,
struct oz_usb_hdr *usb_hdr, int len)
{
struct oz_data *data_hdr = (struct oz_data *)usb_hdr;
switch (data_hdr->format) {
case OZ_DATA_F_MULTIPLE_FIXED: {
struct oz_multiple_fixed *body =
(struct oz_multiple_fixed *)data_hdr;
u8 *data = body->data;
int n = (len - sizeof(struct oz_multiple_fixed)+1)
/ body->unit_size;
while (n--) {
oz_hcd_data_ind(usb_ctx->hport, body->endpoint,
data, body->unit_size);
data += body->unit_size;
}
}
break;
case OZ_DATA_F_ISOC_FIXED: {
struct oz_isoc_fixed *body =
(struct oz_isoc_fixed *)data_hdr;
int data_len = len-sizeof(struct oz_isoc_fixed)+1;
int unit_size = body->unit_size;
u8 *data = body->data;
int count;
int i;
if (!unit_size)
break;
count = data_len/unit_size;
for (i = 0; i < count; i++) {
oz_hcd_data_ind(usb_ctx->hport,
body->endpoint, data, unit_size);
data += unit_size;
}
}
break;
}
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void MediaRecorderHandler::EncodingInfo(
const blink::WebMediaConfiguration& configuration,
std::unique_ptr<blink::WebMediaCapabilitiesQueryCallbacks> callbacks) {
DCHECK(main_render_thread_checker_.CalledOnValidThread());
DCHECK(configuration.video_configuration ||
configuration.audio_configuration);
auto scoped_callbacks = blink::MakeScopedWebCallbacks(
std::move(callbacks), base::BindOnce(&OnEncodingInfoError));
std::unique_ptr<blink::WebMediaCapabilitiesInfo> info(
new blink::WebMediaCapabilitiesInfo());
blink::WebString mime_type;
blink::WebString codec;
if (configuration.video_configuration) {
mime_type = configuration.video_configuration->mime_type;
codec = configuration.video_configuration->codec;
} else {
mime_type = configuration.audio_configuration->mime_type;
codec = configuration.audio_configuration->codec;
}
info->supported = CanSupportMimeType(mime_type, codec);
if (configuration.video_configuration && info->supported) {
const bool is_likely_accelerated =
VideoTrackRecorder::CanUseAcceleratedEncoder(
VideoStringToCodecId(codec),
configuration.video_configuration->width,
configuration.video_configuration->height);
const float pixels_per_second =
configuration.video_configuration->width *
configuration.video_configuration->height *
configuration.video_configuration->framerate;
const float threshold = base::SysInfo::IsLowEndDevice()
? kNumPixelsPerSecondSmoothnessThresholdLow
: kNumPixelsPerSecondSmoothnessThresholdHigh;
info->smooth = is_likely_accelerated || pixels_per_second <= threshold;
info->power_efficient = info->smooth;
}
DVLOG(1) << "type: " << mime_type.Ascii() << ", params:" << codec.Ascii()
<< " is" << (info->supported ? " supported" : " NOT supported")
<< " and" << (info->smooth ? " smooth" : " NOT smooth");
scoped_callbacks.PassCallbacks()->OnSuccess(std::move(info));
}
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 enum entity_charset determine_charset(char *charset_hint TSRMLS_DC)
{
int i;
enum entity_charset charset = cs_utf_8;
int len = 0;
const zend_encoding *zenc;
/* Default is now UTF-8 */
if (charset_hint == NULL)
return cs_utf_8;
if ((len = strlen(charset_hint)) != 0) {
goto det_charset;
}
zenc = zend_multibyte_get_internal_encoding(TSRMLS_C);
if (zenc != NULL) {
charset_hint = (char *)zend_multibyte_get_encoding_name(zenc);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
if ((len == 4) /* sizeof (none|auto|pass) */ &&
(!memcmp("pass", charset_hint, 4) ||
!memcmp("auto", charset_hint, 4) ||
!memcmp("auto", charset_hint, 4))) {
charset_hint = NULL;
len = 0;
} else {
goto det_charset;
}
}
}
charset_hint = SG(default_charset);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
goto det_charset;
}
/* try to detect the charset for the locale */
#if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET)
charset_hint = nl_langinfo(CODESET);
if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) {
goto det_charset;
}
#endif
#if HAVE_LOCALE_H
/* try to figure out the charset from the locale */
{
char *localename;
char *dot, *at;
/* lang[_territory][.codeset][@modifier] */
localename = setlocale(LC_CTYPE, NULL);
dot = strchr(localename, '.');
if (dot) {
dot++;
/* locale specifies a codeset */
at = strchr(dot, '@');
if (at)
len = at - dot;
else
len = strlen(dot);
charset_hint = dot;
} else {
/* no explicit name; see if the name itself
* is the charset */
charset_hint = localename;
len = strlen(charset_hint);
}
}
#endif
det_charset:
if (charset_hint) {
int found = 0;
/* now walk the charset map and look for the codeset */
for (i = 0; charset_map[i].codeset; i++) {
if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) {
charset = charset_map[i].charset;
found = 1;
break;
}
}
if (!found) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8",
charset_hint);
}
}
return charset;
}
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: static int Downmix_Command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize,
void *pCmdData, uint32_t *replySize, void *pReplyData) {
downmix_module_t *pDwmModule = (downmix_module_t *) self;
downmix_object_t *pDownmixer;
int retsize;
if (pDwmModule == NULL || pDwmModule->context.state == DOWNMIX_STATE_UNINITIALIZED) {
return -EINVAL;
}
pDownmixer = (downmix_object_t*) &pDwmModule->context;
ALOGV("Downmix_Command command %" PRIu32 " cmdSize %" PRIu32, cmdCode, cmdSize);
switch (cmdCode) {
case EFFECT_CMD_INIT:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Init(pDwmModule);
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t)
|| pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
*(int *) pReplyData = Downmix_Configure(pDwmModule,
(effect_config_t *)pCmdData, false);
break;
case EFFECT_CMD_RESET:
Downmix_Reset(pDownmixer, false);
break;
case EFFECT_CMD_GET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM pCmdData %p, *replySize %" PRIu32 ", pReplyData: %p",
pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL ||
*replySize < (int) sizeof(effect_param_t) + 2 * sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *rep = (effect_param_t *) pReplyData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + sizeof(int32_t));
ALOGV("Downmix_Command EFFECT_CMD_GET_PARAM param %" PRId32 ", replySize %" PRIu32,
*(int32_t *)rep->data, rep->vsize);
rep->status = Downmix_getParameter(pDownmixer, *(int32_t *)rep->data, &rep->vsize,
rep->data + sizeof(int32_t));
*replySize = sizeof(effect_param_t) + sizeof(int32_t) + rep->vsize;
break;
case EFFECT_CMD_SET_PARAM:
ALOGV("Downmix_Command EFFECT_CMD_SET_PARAM cmdSize %d pCmdData %p, *replySize %" PRIu32
", pReplyData %p", cmdSize, pCmdData, *replySize, pReplyData);
if (pCmdData == NULL || (cmdSize < (int)(sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || *replySize != (int)sizeof(int32_t)) {
return -EINVAL;
}
effect_param_t *cmd = (effect_param_t *) pCmdData;
*(int *)pReplyData = Downmix_setParameter(pDownmixer, *(int32_t *)cmd->data,
cmd->vsize, cmd->data + sizeof(int32_t));
break;
case EFFECT_CMD_SET_PARAM_DEFERRED:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_DEFERRED not supported, FIXME");
break;
case EFFECT_CMD_SET_PARAM_COMMIT:
ALOGW("Downmix_Command command EFFECT_CMD_SET_PARAM_COMMIT not supported, FIXME");
break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_INITIALIZED) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_ACTIVE;
ALOGV("EFFECT_CMD_ENABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)) {
return -EINVAL;
}
if (pDownmixer->state != DOWNMIX_STATE_ACTIVE) {
return -ENOSYS;
}
pDownmixer->state = DOWNMIX_STATE_INITIALIZED;
ALOGV("EFFECT_CMD_DISABLE() OK");
*(int *)pReplyData = 0;
break;
case EFFECT_CMD_SET_DEVICE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_DEVICE: 0x%08" PRIx32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_VOLUME: {
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t) * 2) {
return -EINVAL;
}
ALOGW("Downmix_Command command EFFECT_CMD_SET_VOLUME not supported, FIXME");
float left = (float)(*(uint32_t *)pCmdData) / (1 << 24);
float right = (float)(*((uint32_t *)pCmdData + 1)) / (1 << 24);
ALOGV("Downmix_Command EFFECT_CMD_SET_VOLUME: left %f, right %f ", left, right);
break;
}
case EFFECT_CMD_SET_AUDIO_MODE:
if (pCmdData == NULL || cmdSize != (int)sizeof(uint32_t)) {
return -EINVAL;
}
ALOGV("Downmix_Command EFFECT_CMD_SET_AUDIO_MODE: %" PRIu32, *(uint32_t *)pCmdData);
break;
case EFFECT_CMD_SET_CONFIG_REVERSE:
case EFFECT_CMD_SET_INPUT_DEVICE:
break;
default:
ALOGW("Downmix_Command invalid command %" PRIu32, cmdCode);
return -EINVAL;
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void migrate_timeout(void *opaque)
{
spice_info(NULL);
spice_assert(reds->mig_wait_connect || reds->mig_wait_disconnect);
if (reds->mig_wait_connect) {
/* we will fall back to the switch host scheme when migration completes */
main_channel_migrate_cancel_wait(reds->main_channel);
/* in case part of the client haven't yet completed the previous migration, disconnect them */
reds_mig_target_client_disconnect_all();
reds_mig_cleanup();
} else {
reds_mig_disconnect();
}
}
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 ewk_frame_request_will_send(Evas_Object* ewkFrame, Ewk_Frame_Resource_Messages* messages)
{
evas_object_smart_callback_call(ewkFrame, "resource,request,willsend", messages);
}
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 ClientControlledShellSurface::OnBoundsChangeEvent(
ash::WindowStateType current_state,
ash::WindowStateType requested_state,
int64_t display_id,
const gfx::Rect& window_bounds,
int bounds_change) {
if (!geometry().IsEmpty() && !window_bounds.IsEmpty() &&
(!widget_->IsMinimized() ||
requested_state != ash::WindowStateType::kMinimized) &&
bounds_changed_callback_) {
ash::NonClientFrameViewAsh* frame_view = GetFrameView();
const bool becoming_snapped =
requested_state == ash::WindowStateType::kLeftSnapped ||
requested_state == ash::WindowStateType::kRightSnapped;
const bool is_tablet_mode =
WMHelper::GetInstance()->IsTabletModeWindowManagerEnabled();
gfx::Rect client_bounds =
becoming_snapped && is_tablet_mode
? window_bounds
: frame_view->GetClientBoundsForWindowBounds(window_bounds);
gfx::Size current_size = frame_view->GetBoundsForClientView().size();
bool is_resize = client_bounds.size() != current_size &&
!widget_->IsMaximized() && !widget_->IsFullscreen();
bounds_changed_callback_.Run(current_state, requested_state, display_id,
client_bounds, is_resize, bounds_change);
auto* window_state = GetWindowState();
if (server_reparent_window_ &&
window_state->GetDisplay().id() != display_id) {
ScopedSetBoundsLocally scoped_set_bounds(this);
int container_id = window_state->window()->parent()->id();
aura::Window* new_parent =
ash::Shell::GetRootWindowControllerWithDisplayId(display_id)
->GetContainer(container_id);
new_parent->AddChild(window_state->window());
}
}
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static void unfold_ifblk(struct block **blk)
{
struct ifblock *ifblk;
struct unfold_elm *ue;
u_int32 a = vlabel++;
u_int32 b = vlabel++;
u_int32 c = vlabel++;
/*
* the virtual labels represent the three points of an if block:
*
* if (conds) {
* a ->
* ...
* jmp c;
* b ->
* } else {
* ...
* }
* c ->
*
* if the conds are true, jump to 'a'
* if the conds are false, jump to 'b'
* 'c' is used to skip the else if the conds were true
*/
/* the progress bar */
ef_debug(1, "#");
/* cast the if block */
ifblk = (*blk)->un.ifb;
/* compile the conditions */
unfold_conds(ifblk->conds, a, b);
/* if the conditions are match, jump here */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
ue->label = a;
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
/* check if the block is empty. i.e. { } */
if (ifblk->blk != NULL) {
/* recursively compile the main block */
unfold_blk(&ifblk->blk);
}
/*
* if there is the else block, we have to skip it
* if the condition was true
*/
if (ifblk->elseblk != NULL) {
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
ue->fop.opcode = FOP_JMP;
ue->fop.op.jmp = c;
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
}
/* if the conditions are NOT match, jump here (after the block) */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
ue->label = b;
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
/* recursively compile the else block */
if (ifblk->elseblk != NULL) {
unfold_blk(&ifblk->elseblk);
/* this is the label to skip the else if the condition was true */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
ue->label = c;
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
}
}
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: gsicc_new_iccsmask(gs_memory_t *memory)
{
gsicc_smask_t *result;
result = (gsicc_smask_t *) gs_alloc_struct(memory, gsicc_smask_t, &st_gsicc_smask, "gsicc_new_iccsmask");
if (result != NULL) {
result->smask_gray = NULL;
result->smask_rgb = NULL;
result->smask_cmyk = NULL;
result->memory = memory;
result->swapped = false;
}
return 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: static void follow_dotdot(struct nameidata *nd)
{
if (!nd->root.mnt)
set_root(nd);
while(1) {
struct dentry *old = nd->path.dentry;
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
if (nd->path.dentry != nd->path.mnt->mnt_root) {
/* rare case of legitimate dget_parent()... */
nd->path.dentry = dget_parent(nd->path.dentry);
dput(old);
break;
}
if (!follow_up(&nd->path))
break;
}
follow_mount(&nd->path);
nd->inode = nd->path.dentry->d_inode;
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: void CSoundFile::PortamentoExtraFineMPT(ModChannel* pChn, int param)
{
if(pChn->isFirstTick)
{
pChn->m_PortamentoFineSteps += param;
pChn->m_CalculateFreq = true;
}
}
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: long Track::Create(
Segment* pSegment,
const Info& info,
long long element_start,
long long element_size,
Track*& pResult)
{
if (pResult)
return -1;
Track* const pTrack = new (std::nothrow) Track(pSegment,
element_start,
element_size);
if (pTrack == NULL)
return -1; //generic error
const int status = info.Copy(pTrack->m_info);
if (status) // error
{
delete pTrack;
return status;
}
pResult = pTrack;
return 0; //success
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) {
DCHECK(pending_start_update_callback_.is_null() &&
pending_swap_cache_callback_.is_null() &&
pending_get_status_callback_.is_null() &&
!is_selection_pending() && !was_select_cache_called_);
was_select_cache_called_ = true;
if (appcache_id != kAppCacheNoCacheId) {
LoadSelectedCache(appcache_id);
return;
}
FinishCacheSelection(NULL, NULL);
}
CWE ID:
Target: 1
Example 2:
Code: static void incomplete_class_unset_property(zval *object, zval *member, const zend_literal *key TSRMLS_DC) /* {{{ */
{
incomplete_class_message(object, E_NOTICE TSRMLS_CC);
}
/* }}} */
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 trusted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct trusted_key_payload *p;
struct trusted_key_payload *new_p;
struct trusted_key_options *new_o;
size_t datalen = prep->datalen;
char *datablob;
int ret = 0;
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags))
return -ENOKEY;
p = key->payload.data[0];
if (!p->migratable)
return -EPERM;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
datablob = kmalloc(datalen + 1, GFP_KERNEL);
if (!datablob)
return -ENOMEM;
new_o = trusted_options_alloc();
if (!new_o) {
ret = -ENOMEM;
goto out;
}
new_p = trusted_payload_alloc(key);
if (!new_p) {
ret = -ENOMEM;
goto out;
}
memcpy(datablob, prep->data, datalen);
datablob[datalen] = '\0';
ret = datablob_parse(datablob, new_p, new_o);
if (ret != Opt_update) {
ret = -EINVAL;
kzfree(new_p);
goto out;
}
if (!new_o->keyhandle) {
ret = -EINVAL;
kzfree(new_p);
goto out;
}
/* copy old key values, and reseal with new pcrs */
new_p->migratable = p->migratable;
new_p->key_len = p->key_len;
memcpy(new_p->key, p->key, p->key_len);
dump_payload(p);
dump_payload(new_p);
ret = key_seal(new_p, new_o);
if (ret < 0) {
pr_info("trusted_key: key_seal failed (%d)\n", ret);
kzfree(new_p);
goto out;
}
if (new_o->pcrlock) {
ret = pcrlock(new_o->pcrlock);
if (ret < 0) {
pr_info("trusted_key: pcrlock failed (%d)\n", ret);
kzfree(new_p);
goto out;
}
}
rcu_assign_keypointer(key, new_p);
call_rcu(&p->rcu, trusted_rcu_free);
out:
kzfree(datablob);
kzfree(new_o);
return ret;
}
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: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
/* Flush temporal reference */
impeg2d_bit_stream_get(ps_stream,10);
/* Picture type */
ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3);
if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC))
{
impeg2d_next_code(ps_dec, PICTURE_START_CODE);
return IMPEG2D_INVALID_PIC_TYPE;
}
/* Flush vbv_delay */
impeg2d_bit_stream_get(ps_stream,16);
if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->u2_is_mpeg2 == 0)
{
ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code;
ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code;
}
/*-----------------------------------------------------------------------*/
/* Flush the extra bit value */
/* */
/* while(impeg2d_bit_stream_nxt() == '1') */
/* { */
/* extra_bit_picture 1 */
/* extra_information_picture 8 */
/* } */
/* extra_bit_picture 1 */
/*-----------------------------------------------------------------------*/
while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 &&
ps_stream->u4_offset < ps_stream->u4_max_offset)
{
impeg2d_bit_stream_get(ps_stream,9);
}
impeg2d_bit_stream_get_bit(ps_stream);
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void hns_xgmac_enable(void *mac_drv, enum mac_commom_mode mode)
{
struct mac_driver *drv = (struct mac_driver *)mac_drv;
hns_xgmac_lf_rf_insert(drv, HNS_XGMAC_NO_LF_RF_INSERT);
/*enable XGE rX/tX */
if (mode == MAC_COMM_MODE_TX) {
hns_xgmac_tx_enable(drv, 1);
} else if (mode == MAC_COMM_MODE_RX) {
hns_xgmac_rx_enable(drv, 1);
} else if (mode == MAC_COMM_MODE_RX_AND_TX) {
hns_xgmac_tx_enable(drv, 1);
hns_xgmac_rx_enable(drv, 1);
} else {
dev_err(drv->dev, "error mac mode:%d\n", mode);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: LowBatteryObserver::~LowBatteryObserver() {
Hide();
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int handle_ldf_stq(u32 insn, struct pt_regs *regs)
{
unsigned long addr = compute_effective_address(regs, insn, 0);
int freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
struct fpustate *f = FPUSTATE;
int asi = decode_asi(insn, regs);
int flag = (freg < 32) ? FPRS_DL : FPRS_DU;
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);
save_and_clear_fpu();
current_thread_info()->xfsr[0] &= ~0x1c000;
if (freg & 3) {
current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */;
do_fpother(regs);
return 0;
}
if (insn & 0x200000) {
/* STQ */
u64 first = 0, second = 0;
if (current_thread_info()->fpsaved[0] & flag) {
first = *(u64 *)&f->regs[freg];
second = *(u64 *)&f->regs[freg+2];
}
if (asi < 0x80) {
do_privact(regs);
return 1;
}
switch (asi) {
case ASI_P:
case ASI_S: break;
case ASI_PL:
case ASI_SL:
{
/* Need to convert endians */
u64 tmp = __swab64p(&first);
first = __swab64p(&second);
second = tmp;
break;
}
default:
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
if (put_user (first >> 32, (u32 __user *)addr) ||
__put_user ((u32)first, (u32 __user *)(addr + 4)) ||
__put_user (second >> 32, (u32 __user *)(addr + 8)) ||
__put_user ((u32)second, (u32 __user *)(addr + 12))) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
} else {
/* LDF, LDDF, LDQF */
u32 data[4] __attribute__ ((aligned(8)));
int size, i;
int err;
if (asi < 0x80) {
do_privact(regs);
return 1;
} else if (asi > ASI_SNFL) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
switch (insn & 0x180000) {
case 0x000000: size = 1; break;
case 0x100000: size = 4; break;
default: size = 2; break;
}
for (i = 0; i < size; i++)
data[i] = 0;
err = get_user (data[0], (u32 __user *) addr);
if (!err) {
for (i = 1; i < size; i++)
err |= __get_user (data[i], (u32 __user *)(addr + 4*i));
}
if (err && !(asi & 0x2 /* NF */)) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
if (asi & 0x8) /* Little */ {
u64 tmp;
switch (size) {
case 1: data[0] = le32_to_cpup(data + 0); break;
default:*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 0));
break;
case 4: tmp = le64_to_cpup((u64 *)(data + 0));
*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 2));
*(u64 *)(data + 2) = tmp;
break;
}
}
if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) {
current_thread_info()->fpsaved[0] = FPRS_FEF;
current_thread_info()->gsr[0] = 0;
}
if (!(current_thread_info()->fpsaved[0] & flag)) {
if (freg < 32)
memset(f->regs, 0, 32*sizeof(u32));
else
memset(f->regs+32, 0, 32*sizeof(u32));
}
memcpy(f->regs + freg, data, size * 4);
current_thread_info()->fpsaved[0] |= flag;
}
advance(regs);
return 1;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int packet_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct packet_sock *po;
struct net *net;
union tpacket_req_u req_u;
if (!sk)
return 0;
net = sock_net(sk);
po = pkt_sk(sk);
mutex_lock(&net->packet.sklist_lock);
sk_del_node_init_rcu(sk);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, sk->sk_prot, -1);
preempt_enable();
spin_lock(&po->bind_lock);
unregister_prot_hook(sk, false);
if (po->prot_hook.dev) {
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
packet_flush_mclist(sk);
if (po->rx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 0);
}
if (po->tx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 1);
}
fanout_release(sk);
synchronize_net();
/*
* Now the socket is dead. No more input will appear.
*/
sock_orphan(sk);
sock->sk = NULL;
/* Purge queues */
skb_queue_purge(&sk->sk_receive_queue);
sk_refcnt_debug_release(sk);
sock_put(sk);
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 set_queue_events(bool queue) { queue_events_ = queue; }
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: choose_volume(struct archive_read *a, struct iso9660 *iso9660)
{
struct file_info *file;
int64_t skipsize;
struct vd *vd;
const void *block;
char seenJoliet;
vd = &(iso9660->primary);
if (!iso9660->opt_support_joliet)
iso9660->seenJoliet = 0;
if (iso9660->seenJoliet &&
vd->location > iso9660->joliet.location)
/* This condition is unlikely; by way of caution. */
vd = &(iso9660->joliet);
skipsize = LOGICAL_BLOCK_SIZE * vd->location;
skipsize = __archive_read_consume(a, skipsize);
if (skipsize < 0)
return ((int)skipsize);
iso9660->current_position = skipsize;
block = __archive_read_ahead(a, vd->size, NULL);
if (block == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to read full block when scanning "
"ISO9660 directory list");
return (ARCHIVE_FATAL);
}
/*
* While reading Root Directory, flag seenJoliet must be zero to
* avoid converting special name 0x00(Current Directory) and
* next byte to UCS2.
*/
seenJoliet = iso9660->seenJoliet;/* Save flag. */
iso9660->seenJoliet = 0;
file = parse_file_info(a, NULL, block);
if (file == NULL)
return (ARCHIVE_FATAL);
iso9660->seenJoliet = seenJoliet;
/*
* If the iso image has both RockRidge and Joliet, we preferentially
* use RockRidge Extensions rather than Joliet ones.
*/
if (vd == &(iso9660->primary) && iso9660->seenRockridge
&& iso9660->seenJoliet)
iso9660->seenJoliet = 0;
if (vd == &(iso9660->primary) && !iso9660->seenRockridge
&& iso9660->seenJoliet) {
/* Switch reading data from primary to joliet. */
vd = &(iso9660->joliet);
skipsize = LOGICAL_BLOCK_SIZE * vd->location;
skipsize -= iso9660->current_position;
skipsize = __archive_read_consume(a, skipsize);
if (skipsize < 0)
return ((int)skipsize);
iso9660->current_position += skipsize;
block = __archive_read_ahead(a, vd->size, NULL);
if (block == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to read full block when scanning "
"ISO9660 directory list");
return (ARCHIVE_FATAL);
}
iso9660->seenJoliet = 0;
file = parse_file_info(a, NULL, block);
if (file == NULL)
return (ARCHIVE_FATAL);
iso9660->seenJoliet = seenJoliet;
}
/* Store the root directory in the pending list. */
if (add_entry(a, iso9660, file) != ARCHIVE_OK)
return (ARCHIVE_FATAL);
if (iso9660->seenRockridge) {
a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;
a->archive.archive_format_name =
"ISO9660 with Rockridge extensions";
}
return (ARCHIVE_OK);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: CastCastView* cast_view() { return cast_view_; }
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: void ExtensionRegistry::SetDisabledModificationCallback(
const ExtensionSet::ModificationCallback& callback) {
disabled_extensions_.set_modification_callback(callback);
}
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 sysMapFD(int fd, MemMapping* pMap)
{
off_t start;
size_t length;
void* memPtr;
assert(pMap != NULL);
if (getFileStartAndLength(fd, &start, &length) < 0)
return -1;
memPtr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, start);
if (memPtr == MAP_FAILED) {
LOGW("mmap(%d, R, PRIVATE, %d, %d) failed: %s\n", (int) length,
fd, (int) start, strerror(errno));
return -1;
}
pMap->addr = memPtr;
pMap->length = length;
pMap->range_count = 1;
pMap->ranges = malloc(sizeof(MappedRange));
pMap->ranges[0].addr = memPtr;
pMap->ranges[0].length = length;
return 0;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void RenderWidgetHostViewGtk::RenderViewGone(base::TerminationStatus status,
int error_code) {
Destroy();
plugin_container_manager_.set_host_widget(NULL);
}
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: unsigned long safe_compute_effective_address(struct pt_regs *regs,
unsigned int insn)
{
unsigned int rs1 = (insn >> 14) & 0x1f;
unsigned int rs2 = insn & 0x1f;
unsigned int rd = (insn >> 25) & 0x1f;
if(insn & 0x2000) {
maybe_flush_windows(rs1, 0, rd);
return (safe_fetch_reg(rs1, regs) + sign_extend_imm13(insn));
} else {
maybe_flush_windows(rs1, rs2, rd);
return (safe_fetch_reg(rs1, regs) + safe_fetch_reg(rs2, regs));
}
}
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: CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)
{
bool ok;
XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };
enum xkb_file_type type;
struct xkb_context *ctx = keymap->ctx;
/* Collect section files and check for duplicates. */
for (file = (XkbFile *) file->defs; file;
file = (XkbFile *) file->common.next) {
if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||
file->file_type > LAST_KEYMAP_FILE_TYPE) {
log_err(ctx, "Cannot define %s in a keymap file\n",
xkb_file_type_to_string(file->file_type));
continue;
}
if (files[file->file_type]) {
log_err(ctx,
"More than one %s section in keymap file; "
"All sections after the first ignored\n",
xkb_file_type_to_string(file->file_type));
continue;
}
files[file->file_type] = file;
}
/*
* Check that all required section were provided.
* Report everything before failing.
*/
ok = true;
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
if (files[type] == NULL) {
log_err(ctx, "Required section %s missing from keymap\n",
xkb_file_type_to_string(type));
ok = false;
}
}
if (!ok)
return false;
/* Compile sections. */
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
log_dbg(ctx, "Compiling %s \"%s\"\n",
xkb_file_type_to_string(type), files[type]->name);
ok = compile_file_fns[type](files[type], keymap, merge);
if (!ok) {
log_err(ctx, "Failed to compile %s\n",
xkb_file_type_to_string(type));
return false;
}
}
return UpdateDerivedKeymapFields(keymap);
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: static TIFFMethodType GetJpegMethod(Image* image,TIFF *tiff,uint16 photometric,
uint16 bits_per_sample,uint16 samples_per_pixel)
{
#define BUFFER_SIZE 2048
MagickOffsetType
position,
offset;
register size_t
i;
TIFFMethodType
method;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
**value;
unsigned char
buffer[BUFFER_SIZE+1];
unsigned short
length;
/* only support 8 bit for now */
if (photometric != PHOTOMETRIC_SEPARATED || bits_per_sample != 8 ||
samples_per_pixel != 4)
return(ReadGenericMethod);
/* Search for Adobe APP14 JPEG Marker */
if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value))
return(ReadRGBAMethod);
position=TellBlob(image);
offset=(MagickOffsetType)value[0];
if (SeekBlob(image,offset,SEEK_SET) != offset)
return(ReadRGBAMethod);
method=ReadRGBAMethod;
if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE)
{
for (i=0; i < BUFFER_SIZE; i++)
{
while (i < BUFFER_SIZE)
{
if (buffer[i++] == 255)
break;
}
while (i < BUFFER_SIZE)
{
if (buffer[++i] != 255)
break;
}
if (buffer[i++] == 216) /* JPEG_MARKER_SOI */
continue;
length=(unsigned short) (((unsigned int) (buffer[i] << 8) |
(unsigned int) buffer[i+1]) & 0xffff);
if (i+(size_t) length >= BUFFER_SIZE)
break;
if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */
{
if (length != 14)
break;
/* 0 == CMYK, 1 == YCbCr, 2 = YCCK */
if (buffer[i+13] == 2)
method=ReadYCCKMethod;
break;
}
i+=(size_t) length;
}
}
SeekBlob(image,position,SEEK_SET);
return(method);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const PaintArtifact& PaintController::GetPaintArtifact() const {
DCHECK(new_display_item_list_.IsEmpty());
DCHECK(new_paint_chunks_.IsInInitialState());
return current_paint_artifact_;
}
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 do_io_accounting(struct task_struct *task, char *buffer, int whole)
{
struct task_io_accounting acct = task->ioac;
unsigned long flags;
if (whole && lock_task_sighand(task, &flags)) {
struct task_struct *t = task;
task_io_accounting_add(&acct, &task->signal->ioac);
while_each_thread(task, t)
task_io_accounting_add(&acct, &t->ioac);
unlock_task_sighand(task, &flags);
}
return sprintf(buffer,
"rchar: %llu\n"
"wchar: %llu\n"
"syscr: %llu\n"
"syscw: %llu\n"
"read_bytes: %llu\n"
"write_bytes: %llu\n"
"cancelled_write_bytes: %llu\n",
(unsigned long long)acct.rchar,
(unsigned long long)acct.wchar,
(unsigned long long)acct.syscr,
(unsigned long long)acct.syscw,
(unsigned long long)acct.read_bytes,
(unsigned long long)acct.write_bytes,
(unsigned long long)acct.cancelled_write_bytes);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: zsetrgbcolor(i_ctx_t * i_ctx_p)
{
os_ptr op = osp; /* required by "push" macro */
int code, i;
float values[3];
/* Gather numeric operand value(s) (also checks type) */
code = float_params(op, 3, (float *)&values);
if (code < 0)
return code;
/* Clamp numeric operand range(s) */
for (i = 0;i < 3; i++) {
if (values[i] < 0)
values[i] = 0;
else if (values[i] > 1)
values[i] = 1;
}
code = make_floats(&op[-2], (const float *)&values, 3);
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);
push_mark_estack(es_other, colour_cleanup);
esp++;
/* variable to hold base type (1 = RGB) */
make_int(esp, 1);
esp++;
/* Store the 'stage' of processing (initially 0) */
make_int(esp, 0);
/* Finally, the actual continuation routine */
push_op_estack(setdevicecolor_cont);
return o_push_estack;
}
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: MagickExport QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info,
Image *image)
{
MagickBooleanType
status;
QuantumInfo
*quantum_info;
quantum_info=(QuantumInfo *) AcquireMagickMemory(sizeof(*quantum_info));
if (quantum_info == (QuantumInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
quantum_info->signature=MagickCoreSignature;
GetQuantumInfo(image_info,quantum_info);
if (image == (const Image *) NULL)
return(quantum_info);
status=SetQuantumDepth(image,quantum_info,image->depth);
quantum_info->endian=image->endian;
if (status == MagickFalse)
quantum_info=DestroyQuantumInfo(quantum_info);
return(quantum_info);
}
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: PaintImage AcceleratedStaticBitmapImage::PaintImageForCurrentFrame() {
CheckThread();
if (!IsValid())
return PaintImage();
sk_sp<SkImage> image;
if (original_skia_image_ &&
original_skia_image_thread_id_ ==
Platform::Current()->CurrentThread()->ThreadId()) {
image = original_skia_image_;
} else {
CreateImageFromMailboxIfNeeded();
image = texture_holder_->GetSkImage();
}
return CreatePaintImageBuilder()
.set_image(image, paint_image_content_id_)
.set_completion_state(PaintImage::CompletionState::DONE)
.TakePaintImage();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: SoftVPX::~SoftVPX() {
destroyDecoder();
}
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 long do_get_mempolicy(int *policy, nodemask_t *nmask,
unsigned long addr, unsigned long flags)
{
int err;
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = NULL;
struct mempolicy *pol = current->mempolicy;
if (flags &
~(unsigned long)(MPOL_F_NODE|MPOL_F_ADDR|MPOL_F_MEMS_ALLOWED))
return -EINVAL;
if (flags & MPOL_F_MEMS_ALLOWED) {
if (flags & (MPOL_F_NODE|MPOL_F_ADDR))
return -EINVAL;
*policy = 0; /* just so it's initialized */
task_lock(current);
*nmask = cpuset_current_mems_allowed;
task_unlock(current);
return 0;
}
if (flags & MPOL_F_ADDR) {
/*
* Do NOT fall back to task policy if the
* vma/shared policy at addr is NULL. We
* want to return MPOL_DEFAULT in this case.
*/
down_read(&mm->mmap_sem);
vma = find_vma_intersection(mm, addr, addr+1);
if (!vma) {
up_read(&mm->mmap_sem);
return -EFAULT;
}
if (vma->vm_ops && vma->vm_ops->get_policy)
pol = vma->vm_ops->get_policy(vma, addr);
else
pol = vma->vm_policy;
} else if (addr)
return -EINVAL;
if (!pol)
pol = &default_policy; /* indicates default behavior */
if (flags & MPOL_F_NODE) {
if (flags & MPOL_F_ADDR) {
err = lookup_node(addr);
if (err < 0)
goto out;
*policy = err;
} else if (pol == current->mempolicy &&
pol->mode == MPOL_INTERLEAVE) {
*policy = next_node_in(current->il_prev, pol->v.nodes);
} else {
err = -EINVAL;
goto out;
}
} else {
*policy = pol == &default_policy ? MPOL_DEFAULT :
pol->mode;
/*
* Internal mempolicy flags must be masked off before exposing
* the policy to userspace.
*/
*policy |= (pol->flags & MPOL_MODE_FLAGS);
}
if (vma) {
up_read(¤t->mm->mmap_sem);
vma = NULL;
}
err = 0;
if (nmask) {
if (mpol_store_user_nodemask(pol)) {
*nmask = pol->w.user_nodemask;
} else {
task_lock(current);
get_policy_nodemask(pol, nmask);
task_unlock(current);
}
}
out:
mpol_cond_put(pol);
if (vma)
up_read(¤t->mm->mmap_sem);
return err;
}
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: int jas_memdump(FILE *out, void *data, size_t len)
{
size_t i;
size_t j;
uchar *dp;
dp = data;
for (i = 0; i < len; i += 16) {
fprintf(out, "%04zx:", i);
for (j = 0; j < 16; ++j) {
if (i + j < len) {
fprintf(out, " %02x", dp[i + j]);
}
}
fprintf(out, "\n");
}
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: BaseMultipleFieldsDateAndTimeInputType::BaseMultipleFieldsDateAndTimeInputType(HTMLInputElement* element)
: BaseDateAndTimeInputType(element)
, m_dateTimeEditElement(0)
, m_spinButtonElement(0)
, m_clearButton(0)
, m_pickerIndicatorElement(0)
, m_pickerIndicatorIsVisible(false)
, m_pickerIndicatorIsAlwaysVisible(false)
{
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CheckEmbargo(const GURL& url,
ContentSettingsType permission,
ContentSetting expected_setting) {
EXPECT_EQ(expected_setting,
autoblocker_->GetEmbargoResult(url, permission).content_setting);
}
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: static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_support) /* {{{ */
{
xml_parser *parser;
int auto_detect = 0;
char *encoding_param = NULL;
int encoding_param_len = 0;
char *ns_param = NULL;
int ns_param_len = 0;
XML_Char *encoding;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (ns_support ? "|ss": "|s"), &encoding_param, &encoding_param_len, &ns_param, &ns_param_len) == FAILURE) {
RETURN_FALSE;
}
if (encoding_param != NULL) {
/* The supported encoding types are hardcoded here because
* we are limited to the encodings supported by expat/xmltok.
*/
if (encoding_param_len == 0) {
encoding = XML(default_encoding);
auto_detect = 1;
} else if (strcasecmp(encoding_param, "ISO-8859-1") == 0) {
encoding = "ISO-8859-1";
} else if (strcasecmp(encoding_param, "UTF-8") == 0) {
encoding = "UTF-8";
} else if (strcasecmp(encoding_param, "US-ASCII") == 0) {
encoding = "US-ASCII";
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "unsupported source encoding \"%s\"", encoding_param);
RETURN_FALSE;
}
} else {
encoding = XML(default_encoding);
}
if (ns_support && ns_param == NULL){
ns_param = ":";
}
parser = ecalloc(1, sizeof(xml_parser));
parser->parser = XML_ParserCreate_MM((auto_detect ? NULL : encoding),
&php_xml_mem_hdlrs, ns_param);
parser->target_encoding = encoding;
parser->case_folding = 1;
parser->object = NULL;
parser->isparsing = 0;
XML_SetUserData(parser->parser, parser);
ZEND_REGISTER_RESOURCE(return_value, parser,le_xml_parser);
parser->index = Z_LVAL_P(return_value);
}
/* }}} */
CWE ID: CWE-119
Target: 1
Example 2:
Code: ChromeServiceWorkerFetchTest() {}
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 yr_object_copy(
YR_OBJECT* object,
YR_OBJECT** object_copy)
{
YR_OBJECT* copy;
YR_OBJECT* o;
YR_STRUCTURE_MEMBER* structure_member;
YR_OBJECT_FUNCTION* func;
YR_OBJECT_FUNCTION* func_copy;
int i;
*object_copy = NULL;
FAIL_ON_ERROR(yr_object_create(
object->type,
object->identifier,
NULL,
©));
switch(object->type)
{
case OBJECT_TYPE_INTEGER:
((YR_OBJECT_INTEGER*) copy)->value = UNDEFINED;
break;
case OBJECT_TYPE_STRING:
((YR_OBJECT_STRING*) copy)->value = NULL;
break;
case OBJECT_TYPE_FUNCTION:
func = (YR_OBJECT_FUNCTION*) object;
func_copy = (YR_OBJECT_FUNCTION*) copy;
FAIL_ON_ERROR_WITH_CLEANUP(
yr_object_copy(func->return_obj, &func_copy->return_obj),
yr_object_destroy(copy));
for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++)
func_copy->prototypes[i] = func->prototypes[i];
break;
case OBJECT_TYPE_STRUCTURE:
structure_member = ((YR_OBJECT_STRUCTURE*) object)->members;
while (structure_member != NULL)
{
FAIL_ON_ERROR_WITH_CLEANUP(
yr_object_copy(structure_member->object, &o),
yr_object_destroy(copy));
FAIL_ON_ERROR_WITH_CLEANUP(
yr_object_structure_set_member(copy, o),
yr_free(o);
yr_object_destroy(copy));
structure_member = structure_member->next;
}
break;
case OBJECT_TYPE_ARRAY:
yr_object_copy(
((YR_OBJECT_ARRAY *) object)->prototype_item,
&o);
((YR_OBJECT_ARRAY *)copy)->prototype_item = o;
break;
case OBJECT_TYPE_DICTIONARY:
yr_object_copy(
((YR_OBJECT_DICTIONARY *) object)->prototype_item,
&o);
((YR_OBJECT_DICTIONARY *)copy)->prototype_item = o;
break;
default:
assert(FALSE);
}
*object_copy = copy;
return ERROR_SUCCESS;
}
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int string_scan_range(RList *list, RBinFile *bf, int min,
const ut64 from, const ut64 to, int type) {
ut8 tmp[R_STRING_SCAN_BUFFER_SIZE];
ut64 str_start, needle = from;
int count = 0, i, rc, runes;
int str_type = R_STRING_TYPE_DETECT;
if (type == -1) {
type = R_STRING_TYPE_DETECT;
}
if (from >= to) {
eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to);
return -1;
}
ut8 *buf = calloc (to - from, 1);
if (!buf || !min) {
return -1;
}
r_buf_read_at (bf->buf, from, buf, to - from);
while (needle < to) {
rc = r_utf8_decode (buf + needle - from, to - needle, NULL);
if (!rc) {
needle++;
continue;
}
if (type == R_STRING_TYPE_DETECT) {
char *w = (char *)buf + needle + rc - from;
if ((to - needle) > 5) {
bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];
if (is_wide32) {
str_type = R_STRING_TYPE_WIDE32;
} else {
bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];
str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;
}
} else {
str_type = R_STRING_TYPE_ASCII;
}
} else {
str_type = type;
}
runes = 0;
str_start = needle;
/* Eat a whole C string */
for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {
RRune r = {0};
if (str_type == R_STRING_TYPE_WIDE32) {
rc = r_utf32le_decode (buf + needle - from, to - needle, &r);
if (rc) {
rc = 4;
}
} else if (str_type == R_STRING_TYPE_WIDE) {
rc = r_utf16le_decode (buf + needle - from, to - needle, &r);
if (rc == 1) {
rc = 2;
}
} else {
rc = r_utf8_decode (buf + needle - from, to - needle, &r);
if (rc > 1) {
str_type = R_STRING_TYPE_UTF8;
}
}
/* Invalid sequence detected */
if (!rc) {
needle++;
break;
}
needle += rc;
if (r_isprint (r) && r != '\\') {
if (str_type == R_STRING_TYPE_WIDE32) {
if (r == 0xff) {
r = 0;
}
}
rc = r_utf8_encode (&tmp[i], r);
runes++;
/* Print the escape code */
} else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) {
if ((i + 32) < sizeof (tmp) && r < 93) {
tmp[i + 0] = '\\';
tmp[i + 1] = " abtnvfr e "
" "
" "
" \\"[r];
} else {
break;
}
rc = 2;
runes++;
} else {
/* \0 marks the end of C-strings */
break;
}
}
tmp[i++] = '\0';
if (runes >= min) {
if (str_type == R_STRING_TYPE_ASCII) {
int j;
for (j = 0; j < i; j++) {
char ch = tmp[j];
if (ch != '\n' && ch != '\r' && ch != '\t') {
if (!IS_PRINTABLE (tmp[j])) {
continue;
}
}
}
}
RBinString *bs = R_NEW0 (RBinString);
if (!bs) {
break;
}
bs->type = str_type;
bs->length = runes;
bs->size = needle - str_start;
bs->ordinal = count++;
switch (str_type) {
case R_STRING_TYPE_WIDE:
if (str_start -from> 1) {
const ut8 *p = buf + str_start - 2 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 2; // \xff\xfe
}
}
break;
case R_STRING_TYPE_WIDE32:
if (str_start -from> 3) {
const ut8 *p = buf + str_start - 4 - from;
if (p[0] == 0xff && p[1] == 0xfe) {
str_start -= 4; // \xff\xfe\x00\x00
}
}
break;
}
bs->paddr = bs->vaddr = str_start;
bs->string = r_str_ndup ((const char *)tmp, i);
if (list) {
r_list_append (list, bs);
} else {
print_string (bs, bf);
r_bin_string_free (bs);
}
}
}
free (buf);
return count;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: searchKeyData(void)
{
char *data = NULL;
if (CurrentKeyData != NULL && *CurrentKeyData != '\0')
data = CurrentKeyData;
else if (CurrentCmdData != NULL && *CurrentCmdData != '\0')
data = CurrentCmdData;
else if (CurrentKey >= 0)
data = getKeyData(CurrentKey);
CurrentKeyData = NULL;
CurrentCmdData = NULL;
if (data == NULL || *data == '\0')
return NULL;
return allocStr(data, -1);
}
CWE ID: CWE-59
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AddMainWebResources(content::WebUIDataSource* html_source) {
html_source->AddResourcePath("media_router.js", IDR_MEDIA_ROUTER_JS);
html_source->AddResourcePath("media_router_common.css",
IDR_MEDIA_ROUTER_COMMON_CSS);
html_source->AddResourcePath("media_router.css",
IDR_MEDIA_ROUTER_CSS);
html_source->AddResourcePath("media_router_data.js",
IDR_MEDIA_ROUTER_DATA_JS);
html_source->AddResourcePath("media_router_ui_interface.js",
IDR_MEDIA_ROUTER_UI_INTERFACE_JS);
html_source->AddResourcePath("polymer_config.js",
IDR_MEDIA_ROUTER_POLYMER_CONFIG_JS);
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int 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-20
Target: 1
Example 2:
Code: static inline void hwsim_net_set_wmediumd(struct net *net, u32 portid)
{
struct hwsim_net *hwsim_net = net_generic(net, hwsim_net_id);
hwsim_net->wmediumd = portid;
}
CWE ID: CWE-772
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ExtensionTtsController::SpeakNextUtterance() {
while (!utterance_queue_.empty() && !current_utterance_) {
Utterance* utterance = utterance_queue_.front();
utterance_queue_.pop();
SpeakNow(utterance);
}
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_aead raead;
struct aead_alg *aead = &alg->cra_aead;
snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "aead");
snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s",
aead->geniv ?: "<built-in>");
raead.blocksize = alg->cra_blocksize;
raead.maxauthsize = aead->maxauthsize;
raead.ivsize = aead->ivsize;
if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD,
sizeof(struct crypto_report_aead), &raead))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
CWE ID: CWE-310
Target: 1
Example 2:
Code: HRESULT CGaiaCredentialBase::IsWindowsPasswordValidForStoredUser(
BSTR password) const {
if (username_.Length() == 0 || user_sid_.Length() == 0)
return S_FALSE;
if (::SysStringLen(password) == 0)
return S_FALSE;
OSUserManager* manager = OSUserManager::Get();
return manager->IsWindowsPasswordValid(domain_, username_, password);
}
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: xfs_acl_from_disk(struct xfs_acl *aclp)
{
struct posix_acl_entry *acl_e;
struct posix_acl *acl;
struct xfs_acl_entry *ace;
int count, i;
count = be32_to_cpu(aclp->acl_cnt);
acl = posix_acl_alloc(count, GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
for (i = 0; i < count; i++) {
acl_e = &acl->a_entries[i];
ace = &aclp->acl_entry[i];
/*
* The tag is 32 bits on disk and 16 bits in core.
*
* Because every access to it goes through the core
* format first this is not a problem.
*/
acl_e->e_tag = be32_to_cpu(ace->ae_tag);
acl_e->e_perm = be16_to_cpu(ace->ae_perm);
switch (acl_e->e_tag) {
case ACL_USER:
case ACL_GROUP:
acl_e->e_id = be32_to_cpu(ace->ae_id);
break;
case ACL_USER_OBJ:
case ACL_GROUP_OBJ:
case ACL_MASK:
case ACL_OTHER:
acl_e->e_id = ACL_UNDEFINED_ID;
break;
default:
goto fail;
}
}
return acl;
fail:
posix_acl_release(acl);
return ERR_PTR(-EINVAL);
}
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 virtnet_probe(struct virtio_device *vdev)
{
int i, err;
struct net_device *dev;
struct virtnet_info *vi;
u16 max_queue_pairs;
if (!vdev->config->get) {
dev_err(&vdev->dev, "%s failure: config access disabled\n",
__func__);
return -EINVAL;
}
if (!virtnet_validate_features(vdev))
return -EINVAL;
/* Find if host supports multiqueue virtio_net device */
err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ,
struct virtio_net_config,
max_virtqueue_pairs, &max_queue_pairs);
/* We need at least 2 queue's */
if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
!virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
max_queue_pairs = 1;
/* Allocate ourselves a network device with room for our info */
dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs);
if (!dev)
return -ENOMEM;
/* Set up network device as normal. */
dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE;
dev->netdev_ops = &virtnet_netdev;
dev->features = NETIF_F_HIGHDMA;
dev->ethtool_ops = &virtnet_ethtool_ops;
SET_NETDEV_DEV(dev, &vdev->dev);
/* Do we support "hardware" checksums? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
/* This opens up the world of extra features. */
dev->hw_features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (csum)
dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO
| NETIF_F_TSO_ECN | NETIF_F_TSO6;
}
/* Individual feature bits: what can host handle? */
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
dev->hw_features |= NETIF_F_TSO;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
dev->hw_features |= NETIF_F_TSO6;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
dev->hw_features |= NETIF_F_TSO_ECN;
if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
dev->hw_features |= NETIF_F_UFO;
dev->features |= NETIF_F_GSO_ROBUST;
if (gso)
dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO);
/* (!csum && gso) case will be fixed by register_netdev() */
}
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM))
dev->features |= NETIF_F_RXCSUM;
dev->vlan_features = dev->features;
/* Configuration may specify what MAC to use. Otherwise random. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
virtio_cread_bytes(vdev,
offsetof(struct virtio_net_config, mac),
dev->dev_addr, dev->addr_len);
else
eth_hw_addr_random(dev);
/* Set up our device-specific information */
vi = netdev_priv(dev);
vi->dev = dev;
vi->vdev = vdev;
vdev->priv = vi;
vi->stats = alloc_percpu(struct virtnet_stats);
err = -ENOMEM;
if (vi->stats == NULL)
goto free;
for_each_possible_cpu(i) {
struct virtnet_stats *virtnet_stats;
virtnet_stats = per_cpu_ptr(vi->stats, i);
u64_stats_init(&virtnet_stats->tx_syncp);
u64_stats_init(&virtnet_stats->rx_syncp);
}
INIT_WORK(&vi->config_work, virtnet_config_changed_work);
/* If we can receive ANY GSO packets, we must allocate large ones. */
if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) ||
virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO))
vi->big_packets = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
vi->mergeable_rx_bufs = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf);
else
vi->hdr_len = sizeof(struct virtio_net_hdr);
if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) ||
virtio_has_feature(vdev, VIRTIO_F_VERSION_1))
vi->any_header_sg = true;
if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ))
vi->has_cvq = true;
if (vi->any_header_sg)
dev->needed_headroom = vi->hdr_len;
/* Use single tx/rx queue pair as default */
vi->curr_queue_pairs = 1;
vi->max_queue_pairs = max_queue_pairs;
/* Allocate/initialize the rx/tx queues, and invoke find_vqs */
err = init_vqs(vi);
if (err)
goto free_stats;
#ifdef CONFIG_SYSFS
if (vi->mergeable_rx_bufs)
dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group;
#endif
netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs);
netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs);
err = register_netdev(dev);
if (err) {
pr_debug("virtio_net: registering device failed\n");
goto free_vqs;
}
virtio_device_ready(vdev);
/* Last of all, set up some receive buffers. */
for (i = 0; i < vi->curr_queue_pairs; i++) {
try_fill_recv(vi, &vi->rq[i], GFP_KERNEL);
/* If we didn't even get one input buffer, we're useless. */
if (vi->rq[i].vq->num_free ==
virtqueue_get_vring_size(vi->rq[i].vq)) {
free_unused_bufs(vi);
err = -ENOMEM;
goto free_recv_bufs;
}
}
vi->nb.notifier_call = &virtnet_cpu_callback;
err = register_hotcpu_notifier(&vi->nb);
if (err) {
pr_debug("virtio_net: registering cpu notifier failed\n");
goto free_recv_bufs;
}
/* Assume link up if device can't report link status,
otherwise get link status from config. */
if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) {
netif_carrier_off(dev);
schedule_work(&vi->config_work);
} else {
vi->status = VIRTIO_NET_S_LINK_UP;
netif_carrier_on(dev);
}
pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
dev->name, max_queue_pairs);
return 0;
free_recv_bufs:
vi->vdev->config->reset(vdev);
free_receive_bufs(vi);
unregister_netdev(dev);
free_vqs:
cancel_delayed_work_sync(&vi->refill);
free_receive_page_frags(vi);
virtnet_del_vqs(vi);
free_stats:
free_percpu(vi->stats);
free:
free_netdev(dev);
return err;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: VOID ParaNdis_PadPacketToMinimalLength(PNET_PACKET_INFO packetInfo)
{
if(packetInfo->dataLength < ETH_MIN_PACKET_SIZE)
{
RtlZeroMemory(
RtlOffsetToPointer(packetInfo->headersBuffer, packetInfo->dataLength),
ETH_MIN_PACKET_SIZE - packetInfo->dataLength);
packetInfo->dataLength = ETH_MIN_PACKET_SIZE;
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ContainerNode::appendChildCommon(Node& child)
{
child.setParentOrShadowHostNode(this);
if (m_lastChild) {
child.setPreviousSibling(m_lastChild);
m_lastChild->setNextSibling(&child);
} else {
setFirstChild(&child);
}
setLastChild(&child);
}
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: PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec)
{
if (!attrNode) {
ec = TYPE_MISMATCH_ERR;
return 0;
}
RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName());
if (oldAttrNode.get() == attrNode)
return attrNode; // This Attr is already attached to the element.
if (attrNode->ownerElement()) {
ec = INUSE_ATTRIBUTE_ERR;
return 0;
}
synchronizeAllAttributes();
UniqueElementData* elementData = ensureUniqueElementData();
size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName());
if (index != notFound) {
if (oldAttrNode)
detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
else
oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value());
}
setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
attrNode->attachToElement(this);
ensureAttrNodeListForElement(this)->append(attrNode);
return oldAttrNode.release();
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void parse_cat_blob(const char *p)
{
struct object_entry *oe = oe;
unsigned char sha1[20];
/* cat-blob SP <object> LF */
if (*p == ':') {
oe = find_mark(parse_mark_ref_eol(p));
if (!oe)
die("Unknown mark: %s", command_buf.buf);
hashcpy(sha1, oe->idx.sha1);
} else {
if (get_sha1_hex(p, sha1))
die("Invalid dataref: %s", command_buf.buf);
if (p[40])
die("Garbage after SHA1: %s", command_buf.buf);
oe = find_object(sha1);
}
cat_blob(oe, sha1);
}
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 HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition)
{
ASSERT(m_document);
ASSERT(!hasParserBlockingScript());
{
ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script);
ASSERT(scriptLoader);
if (!scriptLoader)
return;
ASSERT(scriptLoader->isParserInserted());
if (!isExecutingScript())
Microtask::performCheckpoint();
InsertionPointRecord insertionPointRecord(m_host->inputStream());
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
scriptLoader->prepareScript(scriptStartPosition);
if (!scriptLoader->willBeParserExecuted())
return;
if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) {
requestDeferredScript(script);
} else if (scriptLoader->readyToBeParserExecuted()) {
if (m_scriptNestingLevel == 1) {
m_parserBlockingScript.setElement(script);
m_parserBlockingScript.setStartingPosition(scriptStartPosition);
} else {
ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition);
scriptLoader->executeScript(sourceCode);
}
} else {
requestParsingBlockingScript(script);
}
}
}
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: BGD_DECLARE(gdImagePtr) gdImageCropThreshold(gdImagePtr im, const unsigned int color, const float threshold)
{
const int width = gdImageSX(im);
const int height = gdImageSY(im);
int x,y;
int match;
gdRect crop;
crop.x = 0;
crop.y = 0;
crop.width = 0;
crop.height = 0;
/* Pierre: crop everything sounds bad */
if (threshold > 100.0) {
return NULL;
}
/* TODO: Add gdImageGetRowPtr and works with ptr at the row level
* for the true color and palette images
* new formats will simply work with ptr
*/
match = 1;
for (y = 0; match && y < height; y++) {
for (x = 0; match && x < width; x++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
/* Pierre
* Nothing to do > bye
* Duplicate the image?
*/
if (y == height - 1) {
return NULL;
}
crop.y = y -1;
match = 1;
for (y = height - 1; match && y >= 0; y--) {
for (x = 0; match && x < width; x++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x, y), threshold)) > 0;
}
}
if (y == 0) {
crop.height = height - crop.y + 1;
} else {
crop.height = y - crop.y + 2;
}
match = 1;
for (x = 0; match && x < width; x++) {
for (y = 0; match && y < crop.y + crop.height - 1; y++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
crop.x = x - 1;
match = 1;
for (x = width - 1; match && x >= 0; x--) {
for (y = 0; match && y < crop.y + crop.height - 1; y++) {
match = (gdColorMatch(im, color, gdImageGetPixel(im, x,y), threshold)) > 0;
}
}
crop.width = x - crop.x + 2;
return gdImageCrop(im, &crop);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void json_delete_integer(json_integer_t *integer)
{
jsonp_free(integer);
}
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: DownloadItemTest()
: ui_thread_(BrowserThread::UI, &loop_),
file_thread_(BrowserThread::FILE, &loop_) {
}
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 mbedtls_ecdsa_write_signature_restartable( 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,
mbedtls_ecdsa_restart_ctx *rs_ctx )
{
int ret;
mbedtls_mpi r, s;
ECDSA_VALIDATE_RET( ctx != NULL );
ECDSA_VALIDATE_RET( hash != NULL );
ECDSA_VALIDATE_RET( sig != NULL );
ECDSA_VALIDATE_RET( slen != NULL );
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
(void) f_rng;
(void) p_rng;
MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg, rs_ctx ) );
#else
(void) md_alg;
#if defined(MBEDTLS_ECDSA_SIGN_ALT)
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#else
MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng, rs_ctx ) );
#endif /* MBEDTLS_ECDSA_SIGN_ALT */
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
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
Target: 1
Example 2:
Code: process_dynamic_configs()
{
int per_rval = 0;
int run_rval = 0;
init_dynamic_config();
if( enable_persistent ) {
per_rval = process_persistent_configs();
}
if( enable_runtime ) {
run_rval = process_runtime_configs();
}
if( per_rval < 0 || run_rval < 0 ) {
return -1;
}
if( per_rval || run_rval ) {
return 1;
}
return 0;
}
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: PHP_NAMED_FUNCTION(zif_locale_set_default)
{
char* locale_name = NULL;
int len=0;
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&locale_name ,&len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_set_default: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(len == 0) {
locale_name = (char *)uloc_getDefault() ;
len = strlen(locale_name);
}
zend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
RETURN_TRUE;
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType ConcatenateImages(int argc,char **argv,
ExceptionInfo *exception )
{
FILE
*input,
*output;
int
c;
register ssize_t
i;
if (ExpandFilenames(&argc,&argv) == MagickFalse)
ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
output=fopen_utf8(argv[argc-1],"wb");
if (output == (FILE *) NULL) {
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[argc-1]);
return(MagickFalse);
}
for (i=2; i < (ssize_t) (argc-1); i++) {
#if 0
fprintf(stderr, "DEBUG: Concatenate Image: \"%s\"\n", argv[i]);
#endif
input=fopen_utf8(argv[i],"rb");
if (input == (FILE *) NULL) {
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]);
continue;
}
for (c=fgetc(input); c != EOF; c=fgetc(input))
(void) fputc((char) c,output);
(void) fclose(input);
(void) remove_utf8(argv[i]);
}
(void) fclose(output);
return(MagickTrue);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void Resource::DidChangePriority(ResourceLoadPriority load_priority,
int intra_priority_value) {
resource_request_.SetPriority(load_priority, intra_priority_value);
if (loader_)
loader_->DidChangePriority(load_priority, intra_priority_value);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int vmci_transport_dgram_dequeue(struct kiocb *kiocb,
struct vsock_sock *vsk,
struct msghdr *msg, size_t len,
int flags)
{
int err;
int noblock;
struct vmci_datagram *dg;
size_t payload_len;
struct sk_buff *skb;
noblock = flags & MSG_DONTWAIT;
if (flags & MSG_OOB || flags & MSG_ERRQUEUE)
return -EOPNOTSUPP;
/* Retrieve the head sk_buff from the socket's receive queue. */
err = 0;
skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err);
if (err)
return err;
if (!skb)
return -EAGAIN;
dg = (struct vmci_datagram *)skb->data;
if (!dg)
/* err is 0, meaning we read zero bytes. */
goto out;
payload_len = dg->payload_size;
/* Ensure the sk_buff matches the payload size claimed in the packet. */
if (payload_len != skb->len - sizeof(*dg)) {
err = -EINVAL;
goto out;
}
if (payload_len > len) {
payload_len = len;
msg->msg_flags |= MSG_TRUNC;
}
/* Place the datagram payload in the user's iovec. */
err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov,
payload_len);
if (err)
goto out;
msg->msg_namelen = 0;
if (msg->msg_name) {
struct sockaddr_vm *vm_addr;
/* Provide the address of the sender. */
vm_addr = (struct sockaddr_vm *)msg->msg_name;
vsock_addr_init(vm_addr, dg->src.context, dg->src.resource);
msg->msg_namelen = sizeof(*vm_addr);
}
err = payload_len;
out:
skb_free_datagram(&vsk->sk, skb);
return err;
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int board_early_init_r(void)
{
int ret = 0;
/* Flush d-cache and invalidate i-cache of any FLASH data */
flush_dcache();
invalidate_icache();
set_liodns();
setup_qbman_portals();
ret = trigger_fpga_config();
if (ret)
printf("error triggering PCIe FPGA config\n");
/* enable the Unit LED (red) & Boot LED (on) */
qrio_set_leds();
/* enable Application Buffer */
qrio_enable_app_buffer();
return ret;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static void methodWithEnforceRangeUInt16MethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
TestObjectV8Internal::methodWithEnforceRangeUInt16Method(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static BOOLEAN ProcessReceiveQueue(PARANDIS_ADAPTER *pContext,
PULONG pnPacketsToIndicateLeft,
CCHAR nQueueIndex,
PNET_BUFFER_LIST *indicate,
PNET_BUFFER_LIST *indicateTail,
ULONG *nIndicate)
{
pRxNetDescriptor pBufferDescriptor;
PPARANDIS_RECEIVE_QUEUE pTargetReceiveQueue = &pContext->ReceiveQueues[nQueueIndex];
if(NdisInterlockedIncrement(&pTargetReceiveQueue->ActiveProcessorsCount) == 1)
{
while( (*pnPacketsToIndicateLeft > 0) &&
(NULL != (pBufferDescriptor = ReceiveQueueGetBuffer(pTargetReceiveQueue))) )
{
PNET_PACKET_INFO pPacketInfo = &pBufferDescriptor->PacketInfo;
if( !pContext->bSurprizeRemoved &&
pContext->ReceiveState == srsEnabled &&
pContext->bConnected &&
ShallPassPacket(pContext, pPacketInfo))
{
UINT nCoalescedSegmentsCount;
PNET_BUFFER_LIST packet = ParaNdis_PrepareReceivedPacket(pContext, pBufferDescriptor, &nCoalescedSegmentsCount);
if(packet != NULL)
{
UpdateReceiveSuccessStatistics(pContext, pPacketInfo, nCoalescedSegmentsCount);
if (*indicate == nullptr)
{
*indicate = *indicateTail = packet;
}
else
{
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = packet;
*indicateTail = packet;
}
NET_BUFFER_LIST_NEXT_NBL(*indicateTail) = NULL;
(*pnPacketsToIndicateLeft)--;
(*nIndicate)++;
}
else
{
UpdateReceiveFailStatistics(pContext, nCoalescedSegmentsCount);
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
else
{
pContext->extraStatistics.framesFilteredOut++;
pBufferDescriptor->Queue->ReuseReceiveBuffer(pContext->ReuseBufferRegular, pBufferDescriptor);
}
}
}
NdisInterlockedDecrement(&pTargetReceiveQueue->ActiveProcessorsCount);
return ReceiveQueueHasBuffers(pTargetReceiveQueue);
}
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: set_string_2_svc(sstring_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY,
arg->princ, NULL)) {
ret.code = KADM5_AUTH_MODIFY;
log_unauth("kadm5_mod_strings", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_set_string((void *)handle, arg->princ, arg->key,
arg->value);
if (ret.code != 0)
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_mod_strings", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void MetricsWebContentsObserver::FrameReceivedFirstUserActivation(
content::RenderFrameHost* render_frame_host) {
if (committed_load_)
committed_load_->FrameReceivedFirstUserActivation(render_frame_host);
}
CWE ID: CWE-79
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void t1_check_unusual_charstring(void)
{
char *p = strstr(t1_line_array, charstringname) + strlen(charstringname);
int i;
/* if no number follows "/CharStrings", let's read the next line */
if (sscanf(p, "%i", &i) != 1) {
/* pdftex_warn("no number found after `%s', I assume it's on the next line",
charstringname); */
strcpy(t1_buf_array, t1_line_array);
/* t1_getline always appends EOL to t1_line_array; let's change it to
* space before appending the next line
*/
*(strend(t1_buf_array) - 1) = ' ';
t1_getline();
strcat(t1_buf_array, t1_line_array);
strcpy(t1_line_array, t1_buf_array);
t1_line_ptr = eol(t1_line_array);
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GCInfoTable::Init() {
CHECK(!g_gc_info_table);
Resize();
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: void AXObject::detach() {
clearChildren();
m_axObjectCache = nullptr;
}
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 FrameLoader::startLoad(FrameLoadRequest& frameLoadRequest, FrameLoadType type, NavigationPolicy navigationPolicy)
{
ASSERT(client()->hasWebView());
if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
return;
NavigationType navigationType = determineNavigationType(type, frameLoadRequest.resourceRequest().httpBody() || frameLoadRequest.form(), frameLoadRequest.triggeringEvent());
frameLoadRequest.resourceRequest().setRequestContext(determineRequestContextFromNavigationType(navigationType));
frameLoadRequest.resourceRequest().setFrameType(m_frame->isMainFrame() ? WebURLRequest::FrameTypeTopLevel : WebURLRequest::FrameTypeNested);
ResourceRequest& request = frameLoadRequest.resourceRequest();
if (!shouldContinueForNavigationPolicy(request, frameLoadRequest.substituteData(), nullptr, frameLoadRequest.shouldCheckMainWorldContentSecurityPolicy(), navigationType, navigationPolicy, type == FrameLoadTypeReplaceCurrentItem, frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect))
return;
if (!shouldClose(navigationType == NavigationTypeReload))
return;
m_frame->document()->cancelParsing();
detachDocumentLoader(m_provisionalDocumentLoader);
if (!m_frame->host())
return;
m_provisionalDocumentLoader = client()->createDocumentLoader(m_frame, request, frameLoadRequest.substituteData().isValid() ? frameLoadRequest.substituteData() : defaultSubstituteDataForURL(request.url()));
m_provisionalDocumentLoader->setNavigationType(navigationType);
m_provisionalDocumentLoader->setReplacesCurrentHistoryItem(type == FrameLoadTypeReplaceCurrentItem);
m_provisionalDocumentLoader->setIsClientRedirect(frameLoadRequest.clientRedirect() == ClientRedirectPolicy::ClientRedirect);
InspectorInstrumentation::didStartProvisionalLoad(m_frame);
m_frame->navigationScheduler().cancel();
m_checkTimer.stop();
m_loadType = type;
if (frameLoadRequest.form())
client()->dispatchWillSubmitForm(frameLoadRequest.form());
m_progressTracker->progressStarted();
if (m_provisionalDocumentLoader->isClientRedirect())
m_provisionalDocumentLoader->appendRedirect(m_frame->document()->url());
m_provisionalDocumentLoader->appendRedirect(m_provisionalDocumentLoader->request().url());
double triggeringEventTime = frameLoadRequest.triggeringEvent() ? frameLoadRequest.triggeringEvent()->platformTimeStamp() : 0;
client()->dispatchDidStartProvisionalLoad(triggeringEventTime);
ASSERT(m_provisionalDocumentLoader);
m_provisionalDocumentLoader->startLoadingMainResource();
takeObjectSnapshot();
}
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: setup_server_realm(krb5_principal sprinc)
{
krb5_error_code kret;
kdc_realm_t *newrealm;
kret = 0;
if (kdc_numrealms > 1) {
if (!(newrealm = find_realm_data(sprinc->realm.data,
(krb5_ui_4) sprinc->realm.length)))
kret = ENOENT;
else
kdc_active_realm = newrealm;
}
else
kdc_active_realm = kdc_realmlist[0];
return(kret);
}
CWE ID:
Target: 1
Example 2:
Code: const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void)
{
return NULL;
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void tsc210x_reset(TSC210xState *s)
{
s->state = 0;
s->pin_func = 2;
s->enabled = 0;
s->busy = 0;
s->nextfunction = 0;
s->ref = 0;
s->timing = 0;
s->irq = 0;
s->dav = 0;
s->audio_ctrl1 = 0x0000;
s->audio_ctrl2 = 0x4410;
s->audio_ctrl3 = 0x0000;
s->pll[0] = 0x1004;
s->pll[1] = 0x0000;
s->pll[2] = 0x1fff;
s->volume = 0xffff;
s->dac_power = 0x8540;
s->softstep = 1;
s->volume_change = 0;
s->powerdown = 0;
s->filter_data[0x00] = 0x6be3;
s->filter_data[0x01] = 0x9666;
s->filter_data[0x02] = 0x675d;
s->filter_data[0x03] = 0x6be3;
s->filter_data[0x04] = 0x9666;
s->filter_data[0x05] = 0x675d;
s->filter_data[0x06] = 0x7d83;
s->filter_data[0x07] = 0x84ee;
s->filter_data[0x08] = 0x7d83;
s->filter_data[0x09] = 0x84ee;
s->filter_data[0x0a] = 0x6be3;
s->filter_data[0x0b] = 0x9666;
s->filter_data[0x0c] = 0x675d;
s->filter_data[0x0d] = 0x6be3;
s->filter_data[0x0e] = 0x9666;
s->filter_data[0x0f] = 0x675d;
s->filter_data[0x10] = 0x7d83;
s->filter_data[0x11] = 0x84ee;
s->filter_data[0x12] = 0x7d83;
s->filter_data[0x13] = 0x84ee;
s->i2s_tx_rate = 0;
s->i2s_rx_rate = 0;
s->kb.scan = 1;
s->kb.debounce = 0;
s->kb.mask = 0x0000;
s->kb.mode = 3;
s->kb.intr = 0;
qemu_set_irq(s->pint, !s->irq);
qemu_set_irq(s->davint, !s->dav);
qemu_irq_raise(s->kbint);
}
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: DECLAREcpFunc(cpDecodedStrips)
{
tsize_t stripsize = TIFFStripSize(in);
tdata_t buf = _TIFFmalloc(stripsize);
(void) imagewidth; (void) spp;
if (buf) {
tstrip_t s, ns = TIFFNumberOfStrips(in);
uint32 row = 0;
_TIFFmemset(buf, 0, stripsize);
for (s = 0; s < ns; s++) {
tsize_t cc = (row + rowsperstrip > imagelength) ?
TIFFVStripSize(in, imagelength - row) : stripsize;
if (TIFFReadEncodedStrip(in, s, buf, cc) < 0
&& !ignore) {
TIFFError(TIFFFileName(in),
"Error, can't read strip %lu",
(unsigned long) s);
goto bad;
}
if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write strip %lu",
(unsigned long) s);
goto bad;
}
row += rowsperstrip;
}
_TIFFfree(buf);
return 1;
} else {
TIFFError(TIFFFileName(in),
"Error, can't allocate memory buffer of size %lu "
"to read strips", (unsigned long) stripsize);
return 0;
}
bad:
_TIFFfree(buf);
return 0;
}
CWE ID: CWE-191
Target: 1
Example 2:
Code: static void hash_messagepad(struct hash_device_data *device_data,
const u32 *message, u8 index_bytes)
{
int nwords = 1;
/*
* Clear hash str register, only clear NBLW
* since DCAL will be reset by hardware.
*/
HASH_CLEAR_BITS(&device_data->base->str, HASH_STR_NBLW_MASK);
/* Main loop */
while (index_bytes >= 4) {
HASH_SET_DIN(message, nwords);
index_bytes -= 4;
message++;
}
if (index_bytes)
HASH_SET_DIN(message, nwords);
while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
cpu_relax();
/* num_of_bytes == 0 => NBLW <- 0 (32 bits valid in DATAIN) */
HASH_SET_NBLW(index_bytes * 8);
dev_dbg(device_data->dev, "%s: DIN=0x%08x NBLW=%lu\n",
__func__, readl_relaxed(&device_data->base->din),
readl_relaxed(&device_data->base->str) & HASH_STR_NBLW_MASK);
HASH_SET_DCAL;
dev_dbg(device_data->dev, "%s: after dcal -> DIN=0x%08x NBLW=%lu\n",
__func__, readl_relaxed(&device_data->base->din),
readl_relaxed(&device_data->base->str) & HASH_STR_NBLW_MASK);
while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
cpu_relax();
}
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: pango_glyph_string_get_width (PangoGlyphString *glyphs)
{
int i;
int width = 0;
for (i = 0; i < glyphs->num_glyphs; i++)
width += glyphs->glyphs[i].geometry.width;
return width;
}
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: AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,
void *dummy,
const char *arg)
{
const char *endp = ap_strrchr_c(arg, '>');
const char *limited_methods;
void *tog = cmd->cmd->cmd_data;
apr_int64_t limited = 0;
apr_int64_t old_limited = cmd->limited;
const char *errmsg;
if (endp == NULL) {
return unclosed_directive(cmd);
}
limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg);
if (!limited_methods[0]) {
return missing_container_arg(cmd);
}
while (limited_methods[0]) {
char *method = ap_getword_conf(cmd->temp_pool, &limited_methods);
int methnum;
/* check for builtin or module registered method number */
methnum = ap_method_number_of(method);
if (methnum == M_TRACE && !tog) {
return "TRACE cannot be controlled by <Limit>, see TraceEnable";
}
else if (methnum == M_INVALID) {
/* method has not been registered yet, but resource restriction
* is always checked before method handling, so register it.
*/
methnum = ap_method_register(cmd->pool,
apr_pstrdup(cmd->pool, method));
}
limited |= (AP_METHOD_BIT << methnum);
}
/* Killing two features with one function,
* if (tog == NULL) <Limit>, else <LimitExcept>
*/
limited = tog ? ~limited : limited;
if (!(old_limited & limited)) {
return apr_pstrcat(cmd->pool, cmd->cmd->name,
"> directive excludes all methods", NULL);
}
else if ((old_limited & limited) == old_limited) {
return apr_pstrcat(cmd->pool, cmd->cmd->name,
"> directive specifies methods already excluded",
NULL);
}
cmd->limited &= limited;
errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
cmd->limited = old_limited;
return errmsg;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void H264SwDecMemcpy(void *dest, void *src, u32 count)
{
memcpy(dest, src, count);
}
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 do_replace_finish(struct net *net, struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
int ret, i;
struct ebt_counter *counterstmp = NULL;
/* used to be able to unlock earlier */
struct ebt_table_info *table;
struct ebt_table *t;
/* the user wants counters back
* the check on the size is done later, when we have the lock
*/
if (repl->num_counters) {
unsigned long size = repl->num_counters * sizeof(*counterstmp);
counterstmp = vmalloc(size);
if (!counterstmp)
return -ENOMEM;
}
newinfo->chainstack = NULL;
ret = ebt_verify_pointers(repl, newinfo);
if (ret != 0)
goto free_counterstmp;
ret = translate_table(net, repl->name, newinfo);
if (ret != 0)
goto free_counterstmp;
t = find_table_lock(net, repl->name, &ret, &ebt_mutex);
if (!t) {
ret = -ENOENT;
goto free_iterate;
}
/* the table doesn't like it */
if (t->check && (ret = t->check(newinfo, repl->valid_hooks)))
goto free_unlock;
if (repl->num_counters && repl->num_counters != t->private->nentries) {
BUGPRINT("Wrong nr. of counters requested\n");
ret = -EINVAL;
goto free_unlock;
}
/* we have the mutex lock, so no danger in reading this pointer */
table = t->private;
/* make sure the table can only be rmmod'ed if it contains no rules */
if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) {
ret = -ENOENT;
goto free_unlock;
} else if (table->nentries && !newinfo->nentries)
module_put(t->me);
/* we need an atomic snapshot of the counters */
write_lock_bh(&t->lock);
if (repl->num_counters)
get_counters(t->private->counters, counterstmp,
t->private->nentries);
t->private = newinfo;
write_unlock_bh(&t->lock);
mutex_unlock(&ebt_mutex);
/* so, a user can change the chains while having messed up her counter
* allocation. Only reason why this is done is because this way the lock
* is held only once, while this doesn't bring the kernel into a
* dangerous state.
*/
if (repl->num_counters &&
copy_to_user(repl->counters, counterstmp,
repl->num_counters * sizeof(struct ebt_counter))) {
/* Silent error, can't fail, new table is already in place */
net_warn_ratelimited("ebtables: counters copy to user failed while replacing table\n");
}
/* decrease module count and free resources */
EBT_ENTRY_ITERATE(table->entries, table->entries_size,
ebt_cleanup_entry, net, NULL);
vfree(table->entries);
if (table->chainstack) {
for_each_possible_cpu(i)
vfree(table->chainstack[i]);
vfree(table->chainstack);
}
vfree(table);
vfree(counterstmp);
#ifdef CONFIG_AUDIT
if (audit_enabled) {
audit_log(current->audit_context, GFP_KERNEL,
AUDIT_NETFILTER_CFG,
"table=%s family=%u entries=%u",
repl->name, AF_BRIDGE, repl->nentries);
}
#endif
return ret;
free_unlock:
mutex_unlock(&ebt_mutex);
free_iterate:
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, NULL);
free_counterstmp:
vfree(counterstmp);
/* can be initialized in translate_table() */
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
return ret;
}
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: krb5_gss_pseudo_random(OM_uint32 *minor_status,
gss_ctx_id_t context,
int prf_key,
const gss_buffer_t prf_in,
ssize_t desired_output_len,
gss_buffer_t prf_out)
{
krb5_error_code code;
krb5_key key = NULL;
krb5_gss_ctx_id_t ctx;
int i;
OM_uint32 minor;
size_t prflen;
krb5_data t, ns;
unsigned char *p;
prf_out->length = 0;
prf_out->value = NULL;
t.length = 0;
t.data = NULL;
ns.length = 0;
ns.data = NULL;
ctx = (krb5_gss_ctx_id_t)context;
switch (prf_key) {
case GSS_C_PRF_KEY_FULL:
if (ctx->have_acceptor_subkey) {
key = ctx->acceptor_subkey;
break;
}
/* fallthrough */
case GSS_C_PRF_KEY_PARTIAL:
key = ctx->subkey;
break;
default:
code = EINVAL;
goto cleanup;
}
if (key == NULL) {
code = EINVAL;
goto cleanup;
}
if (desired_output_len == 0)
return GSS_S_COMPLETE;
prf_out->value = k5alloc(desired_output_len, &code);
if (prf_out->value == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
prf_out->length = desired_output_len;
code = krb5_c_prf_length(ctx->k5_context,
krb5_k_key_enctype(ctx->k5_context, key),
&prflen);
if (code != 0)
goto cleanup;
ns.length = 4 + prf_in->length;
ns.data = k5alloc(ns.length, &code);
if (ns.data == NULL) {
code = KG_INPUT_TOO_LONG;
goto cleanup;
}
t.length = prflen;
t.data = k5alloc(t.length, &code);
if (t.data == NULL)
goto cleanup;
memcpy(ns.data + 4, prf_in->value, prf_in->length);
i = 0;
p = (unsigned char *)prf_out->value;
while (desired_output_len > 0) {
store_32_be(i, ns.data);
code = krb5_k_prf(ctx->k5_context, key, &ns, &t);
if (code != 0)
goto cleanup;
memcpy(p, t.data, MIN(t.length, desired_output_len));
p += t.length;
desired_output_len -= t.length;
i++;
}
cleanup:
if (code != 0)
gss_release_buffer(&minor, prf_out);
krb5_free_data_contents(ctx->k5_context, &ns);
krb5_free_data_contents(ctx->k5_context, &t);
*minor_status = (OM_uint32)code;
return (code == 0) ? GSS_S_COMPLETE : GSS_S_FAILURE;
}
CWE ID:
Target: 1
Example 2:
Code: DOMMessageQueue::~DOMMessageQueue() {}
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: explicit TestSaveCardBubbleControllerImpl(content::WebContents* web_contents)
: SaveCardBubbleControllerImpl(web_contents) {}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int btsock_thread_wakeup(int h)
{
if(h < 0 || h >= MAX_THREAD)
{
APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
return FALSE;
}
if(ts[h].cmd_fdw == -1)
{
APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h);
return FALSE;
}
sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0};
return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: ~MockTabStripModelObserver() {
STLDeleteContainerPointers(states_.begin(), states_.end());
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void sdp_copy_raw_data(tCONN_CB* p_ccb, bool offset) {
unsigned int cpy_len, rem_len;
uint32_t list_len;
uint8_t* p;
uint8_t type;
#if (SDP_DEBUG_RAW == TRUE)
uint8_t num_array[SDP_MAX_LIST_BYTE_COUNT];
uint32_t i;
for (i = 0; i < p_ccb->list_len; i++) {
snprintf((char*)&num_array[i * 2], sizeof(num_array) - i * 2, "%02X",
(uint8_t)(p_ccb->rsp_list[i]));
}
SDP_TRACE_WARNING("result :%s", num_array);
#endif
if (p_ccb->p_db->raw_data) {
cpy_len = p_ccb->p_db->raw_size - p_ccb->p_db->raw_used;
list_len = p_ccb->list_len;
p = &p_ccb->rsp_list[0];
if (offset) {
type = *p++;
p = sdpu_get_len_from_type(p, type, &list_len);
}
if (list_len < cpy_len) {
cpy_len = list_len;
}
rem_len = SDP_MAX_LIST_BYTE_COUNT - (unsigned int)(p - &p_ccb->rsp_list[0]);
if (cpy_len > rem_len) {
SDP_TRACE_WARNING("rem_len :%d less than cpy_len:%d", rem_len, cpy_len);
cpy_len = rem_len;
}
SDP_TRACE_WARNING(
"%s: list_len:%d cpy_len:%d p:%p p_ccb:%p p_db:%p raw_size:%d "
"raw_used:%d raw_data:%p",
__func__, list_len, cpy_len, p, p_ccb, p_ccb->p_db,
p_ccb->p_db->raw_size, p_ccb->p_db->raw_used, p_ccb->p_db->raw_data);
memcpy(&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len);
p_ccb->p_db->raw_used += cpy_len;
}
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType SetGrayscaleImage(Image *image)
{
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
PixelPacket
*colormap;
register ssize_t
i;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace);
colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
ExceptionInfo
*exception;
(void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
sizeof(*colormap_index));
if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
image->colors=0;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=GetPixelRed(q);
image->colormap[image->colors].green=GetPixelGreen(q);
image->colormap[image->colors].blue=GetPixelBlue(q);
image->colors++;
}
}
SetPixelIndex(indexes+x,colormap_index[intensity]);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].opacity=(unsigned short) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
IntensityCompare);
colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
sizeof(*colormap));
if (colormap == (PixelPacket *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].opacity]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
SetPixelIndex(indexes+x,colormap_index[ScaleQuantumToMap(GetPixelIndex(
indexes+x))]);
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (SetImageMonochrome(image,&image->exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
CWE ID: CWE-772
Target: 1
Example 2:
Code: std::string BrowserViewRenderer::ToString() const {
std::string str;
base::StringAppendF(&str, "is_paused: %d ", is_paused_);
base::StringAppendF(&str, "view_visible: %d ", view_visible_);
base::StringAppendF(&str, "window_visible: %d ", window_visible_);
base::StringAppendF(&str, "dip_scale: %f ", dip_scale_);
base::StringAppendF(&str, "page_scale_factor: %f ", page_scale_factor_);
base::StringAppendF(&str, "fallback_tick_pending: %d ",
fallback_tick_pending_);
base::StringAppendF(&str, "view size: %s ", size_.ToString().c_str());
base::StringAppendF(&str, "attached_to_window: %d ", attached_to_window_);
base::StringAppendF(&str,
"global visible rect: %s ",
last_on_draw_global_visible_rect_.ToString().c_str());
base::StringAppendF(
&str, "scroll_offset_dip: %s ", scroll_offset_dip_.ToString().c_str());
base::StringAppendF(&str,
"overscroll_rounding_error_: %s ",
overscroll_rounding_error_.ToString().c_str());
base::StringAppendF(
&str, "on_new_picture_enable: %d ", on_new_picture_enable_);
base::StringAppendF(&str, "clear_view: %d ", clear_view_);
return str;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int get_default_root(pool *p, int allow_symlinks, const char **root) {
config_rec *c = NULL;
const char *dir = NULL;
int res;
c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE);
while (c != NULL) {
pr_signals_handle();
/* Check the groups acl */
if (c->argc < 2) {
dir = c->argv[0];
break;
}
res = pr_expr_eval_group_and(((char **) c->argv)+1);
if (res) {
dir = c->argv[0];
break;
}
c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE);
}
if (dir != NULL) {
const char *new_dir;
/* Check for any expandable variables. */
new_dir = path_subst_uservar(p, &dir);
if (new_dir != NULL) {
dir = new_dir;
}
if (strncmp(dir, "/", 2) == 0) {
dir = NULL;
} else {
char *realdir;
int xerrno = 0;
if (allow_symlinks == FALSE) {
char *path, target_path[PR_TUNABLE_PATH_MAX + 1];
struct stat st;
size_t pathlen;
/* First, deal with any possible interpolation. dir_realpath() will
* do this for us, but dir_realpath() ALSO automatically follows
* symlinks, which is what we do NOT want to do here.
*/
path = pstrdup(p, dir);
if (*path != '/') {
if (*path == '~') {
if (pr_fs_interpolate(dir, target_path,
sizeof(target_path)-1) < 0) {
return -1;
}
path = target_path;
}
}
/* Note: lstat(2) is sensitive to the presence of a trailing slash on
* the path, particularly in the case of a symlink to a directory.
* Thus to get the correct test, we need to remove any trailing slash
* that might be present. Subtle.
*/
pathlen = strlen(path);
if (pathlen > 1 &&
path[pathlen-1] == '/') {
path[pathlen-1] = '\0';
}
pr_fs_clear_cache2(path);
res = pr_fsio_lstat(path, &st);
if (res < 0) {
xerrno = errno;
pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path,
strerror(xerrno));
errno = xerrno;
return -1;
}
if (S_ISLNK(st.st_mode)) {
pr_log_pri(PR_LOG_WARNING,
"error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks "
"config)", path);
errno = EPERM;
return -1;
}
}
/* We need to be the final user here so that if the user has their home
* directory with a mode the user proftpd is running (i.e. the User
* directive) as can not traverse down, we can still have the default
* root.
*/
pr_fs_clear_cache2(dir);
PRIVS_USER
realdir = dir_realpath(p, dir);
xerrno = errno;
PRIVS_RELINQUISH
if (realdir) {
dir = realdir;
} else {
/* Try to provide a more informative message. */
char interp_dir[PR_TUNABLE_PATH_MAX + 1];
memset(interp_dir, '\0', sizeof(interp_dir));
(void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1);
pr_log_pri(PR_LOG_NOTICE,
"notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s",
dir, interp_dir, strerror(xerrno));
errno = xerrno;
}
}
}
*root = dir;
return 0;
}
CWE ID: CWE-59
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,
const iw_byte *d, size_t d_len)
{
struct iw_exif_state e;
iw_uint32 ifd;
if(d_len<8) return;
iw_zeromem(&e,sizeof(struct iw_exif_state));
e.d = d;
e.d_len = d_len;
e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;
ifd = iw_get_ui32_e(&d[4],e.endian);
iwjpeg_scan_exif_ifd(rctx,&e,ifd);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: char *find_cookie_value_end(char *s, const char *e)
{
int quoted, qdpair;
quoted = qdpair = 0;
for (; s < e; s++) {
if (qdpair) qdpair = 0;
else if (quoted) {
if (*s == '\\') qdpair = 1;
else if (*s == '"') quoted = 0;
}
else if (*s == '"') quoted = 1;
else if (*s == ',' || *s == ';') return s;
}
return s;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int netlink_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
int flags)
{
struct scm_cookie scm;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int noblock = flags&MSG_DONTWAIT;
size_t copied;
struct sk_buff *skb, *data_skb;
int err, ret;
if (flags&MSG_OOB)
return -EOPNOTSUPP;
copied = 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (skb == NULL)
goto out;
data_skb = skb;
#ifdef CONFIG_COMPAT_NETLINK_MESSAGES
if (unlikely(skb_shinfo(skb)->frag_list)) {
/*
* If this skb has a frag_list, then here that means that we
* will have to use the frag_list skb's data for compat tasks
* and the regular skb's data for normal (non-compat) tasks.
*
* If we need to send the compat skb, assign it to the
* 'data_skb' variable so that it will be used below for data
* copying. We keep 'skb' for everything else, including
* freeing both later.
*/
if (flags & MSG_CMSG_COMPAT)
data_skb = skb_shinfo(skb)->frag_list;
}
#endif
/* Record the max length of recvmsg() calls for future allocations */
nlk->max_recvmsg_len = max(nlk->max_recvmsg_len, len);
nlk->max_recvmsg_len = min_t(size_t, nlk->max_recvmsg_len,
16384);
copied = data_skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(data_skb);
err = skb_copy_datagram_msg(data_skb, 0, msg, copied);
if (msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
addr->nl_family = AF_NETLINK;
addr->nl_pad = 0;
addr->nl_pid = NETLINK_CB(skb).portid;
addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
msg->msg_namelen = sizeof(*addr);
}
if (nlk->flags & NETLINK_F_RECV_PKTINFO)
netlink_cmsg_recv_pktinfo(msg, skb);
if (nlk->flags & NETLINK_F_LISTEN_ALL_NSID)
netlink_cmsg_listen_all_nsid(sk, msg, skb);
memset(&scm, 0, sizeof(scm));
scm.creds = *NETLINK_CREDS(skb);
if (flags & MSG_TRUNC)
copied = data_skb->len;
skb_free_datagram(sk, skb);
if (nlk->cb_running &&
atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
ret = netlink_dump(sk);
if (ret) {
sk->sk_err = -ret;
sk->sk_error_report(sk);
}
}
scm_recv(sock, msg, &scm, flags);
out:
netlink_rcv_wake(sk);
return err ? : copied;
}
CWE ID: CWE-415
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: pkinit_check_kdc_pkid(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *pdid_buf,
unsigned int pkid_len,
int *valid_kdcPkId)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
const unsigned char *p = pdid_buf;
int status = 1;
X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
*valid_kdcPkId = 0;
pkiDebug("found kdcPkId in AS REQ\n");
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len);
if (is == NULL)
goto cleanup;
status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer);
if (!status) {
status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial);
if (!status)
*valid_kdcPkId = 1;
}
retval = 0;
cleanup:
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return retval;
}
CWE ID:
Target: 1
Example 2:
Code: MG_INTERNAL void altbuf_reset(struct altbuf *ab) {
mbuf_free(&ab->m);
ab->len = 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int sample_conv_q_prefered(const struct arg *args, struct sample *smp, void *private)
{
const char *al = smp->data.u.str.str;
const char *end = al + smp->data.u.str.len;
const char *token;
int toklen;
int qvalue;
const char *str;
const char *w;
int best_q = 0;
/* Set the constant to the sample, because the output of the
* function will be peek in the constant configuration string.
*/
smp->flags |= SMP_F_CONST;
smp->data.u.str.size = 0;
smp->data.u.str.str = "";
smp->data.u.str.len = 0;
/* Parse the accept language */
while (1) {
/* Jump spaces, quit if the end is detected. */
while (al < end && isspace((unsigned char)*al))
al++;
if (al >= end)
break;
/* Start of the fisrt word. */
token = al;
/* Look for separator: isspace(), ',' or ';'. Next value if 0 length word. */
while (al < end && *al != ';' && *al != ',' && !isspace((unsigned char)*al))
al++;
if (al == token)
goto expect_comma;
/* Length of the token. */
toklen = al - token;
qvalue = 1000;
/* Check if the token exists in the list. If the token not exists,
* jump to the next token.
*/
str = args[0].data.str.str;
w = str;
while (1) {
if (*str == ';' || *str == '\0') {
if (language_range_match(token, toklen, w, str-w))
goto look_for_q;
if (*str == '\0')
goto expect_comma;
w = str + 1;
}
str++;
}
goto expect_comma;
look_for_q:
/* Jump spaces, quit if the end is detected. */
while (al < end && isspace((unsigned char)*al))
al++;
if (al >= end)
goto process_value;
/* If ',' is found, process the result */
if (*al == ',')
goto process_value;
/* If the character is different from ';', look
* for the end of the header part in best effort.
*/
if (*al != ';')
goto expect_comma;
/* Assumes that the char is ';', now expect "q=". */
al++;
/* Jump spaces, process value if the end is detected. */
while (al < end && isspace((unsigned char)*al))
al++;
if (al >= end)
goto process_value;
/* Expect 'q'. If no 'q', continue in best effort */
if (*al != 'q')
goto process_value;
al++;
/* Jump spaces, process value if the end is detected. */
while (al < end && isspace((unsigned char)*al))
al++;
if (al >= end)
goto process_value;
/* Expect '='. If no '=', continue in best effort */
if (*al != '=')
goto process_value;
al++;
/* Jump spaces, process value if the end is detected. */
while (al < end && isspace((unsigned char)*al))
al++;
if (al >= end)
goto process_value;
/* Parse the q value. */
qvalue = parse_qvalue(al, &al);
process_value:
/* If the new q value is the best q value, then store the associated
* language in the response. If qvalue is the biggest value (1000),
* break the process.
*/
if (qvalue > best_q) {
smp->data.u.str.str = (char *)w;
smp->data.u.str.len = str - w;
if (qvalue >= 1000)
break;
best_q = qvalue;
}
expect_comma:
/* Expect comma or end. If the end is detected, quit the loop. */
while (al < end && *al != ',')
al++;
if (al >= end)
break;
/* Comma is found, jump it and restart the analyzer. */
al++;
}
/* Set default value if required. */
if (smp->data.u.str.len == 0 && args[1].type == ARGT_STR) {
smp->data.u.str.str = args[1].data.str.str;
smp->data.u.str.len = args[1].data.str.len;
}
/* Return true only if a matching language was found. */
return smp->data.u.str.len != 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: OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
(void)s;
if (sp->libjpeg_jpeg_query_style==0)
{
if (OJPEGDecodeRaw(tif,buf,cc)==0)
return(0);
}
else
{
if (OJPEGDecodeScanlines(tif,buf,cc)==0)
return(0);
}
return(1);
}
CWE ID: CWE-369
Target: 1
Example 2:
Code: XcursorFilenameLoad (const char *file,
XcursorComments **commentsp,
XcursorImages **imagesp)
{
FILE *f;
XcursorBool ret;
if (!file)
return XcursorFalse;
f = fopen (file, "r");
if (!f)
return 0;
ret = XcursorFileLoad (f, commentsp, imagesp);
fclose (f);
return ret;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
int err;
struct sk_buff *skb;
struct sock *sk = sock->sk;
err = -EIO;
if (sk->sk_state & PPPOX_BOUND)
goto end;
msg->msg_namelen = 0;
err = 0;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
goto end;
if (len > skb->len)
len = skb->len;
else if (len < skb->len)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len);
if (likely(err == 0))
err = len;
kfree_skb(skb);
end:
return err;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int tcp_v6_do_rcv(struct sock *sk, struct sk_buff *skb)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct tcp_sock *tp;
struct sk_buff *opt_skb = NULL;
/* Imagine: socket is IPv6. IPv4 packet arrives,
goes to IPv4 receive handler and backlogged.
From backlog it always goes here. Kerboom...
Fortunately, tcp_rcv_established and rcv_established
handle them correctly, but it is not case with
tcp_v6_hnd_req and tcp_v6_send_reset(). --ANK
*/
if (skb->protocol == htons(ETH_P_IP))
return tcp_v4_do_rcv(sk, skb);
if (sk_filter(sk, skb))
goto discard;
/*
* socket locking is here for SMP purposes as backlog rcv
* is currently called with bh processing disabled.
*/
/* Do Stevens' IPV6_PKTOPTIONS.
Yes, guys, it is the only place in our code, where we
may make it not affecting IPv4.
The rest of code is protocol independent,
and I do not like idea to uglify IPv4.
Actually, all the idea behind IPV6_PKTOPTIONS
looks not very well thought. For now we latch
options, received in the last packet, enqueued
by tcp. Feel free to propose better solution.
--ANK (980728)
*/
if (np->rxopt.all)
opt_skb = skb_clone(skb, sk_gfp_mask(sk, GFP_ATOMIC));
if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */
struct dst_entry *dst = sk->sk_rx_dst;
sock_rps_save_rxhash(sk, skb);
sk_mark_napi_id(sk, skb);
if (dst) {
if (inet_sk(sk)->rx_dst_ifindex != skb->skb_iif ||
dst->ops->check(dst, np->rx_dst_cookie) == NULL) {
dst_release(dst);
sk->sk_rx_dst = NULL;
}
}
tcp_rcv_established(sk, skb, tcp_hdr(skb), skb->len);
if (opt_skb)
goto ipv6_pktoptions;
return 0;
}
if (tcp_checksum_complete(skb))
goto csum_err;
if (sk->sk_state == TCP_LISTEN) {
struct sock *nsk = tcp_v6_cookie_check(sk, skb);
if (!nsk)
goto discard;
if (nsk != sk) {
sock_rps_save_rxhash(nsk, skb);
sk_mark_napi_id(nsk, skb);
if (tcp_child_process(sk, nsk, skb))
goto reset;
if (opt_skb)
__kfree_skb(opt_skb);
return 0;
}
} else
sock_rps_save_rxhash(sk, skb);
if (tcp_rcv_state_process(sk, skb))
goto reset;
if (opt_skb)
goto ipv6_pktoptions;
return 0;
reset:
tcp_v6_send_reset(sk, skb);
discard:
if (opt_skb)
__kfree_skb(opt_skb);
kfree_skb(skb);
return 0;
csum_err:
TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
goto discard;
ipv6_pktoptions:
/* Do you ask, what is it?
1. skb was enqueued by tcp.
2. skb is added to tail of read queue, rather than out of order.
3. socket is not in passive state.
4. Finally, it really contains options, which user wants to receive.
*/
tp = tcp_sk(sk);
if (TCP_SKB_CB(opt_skb)->end_seq == tp->rcv_nxt &&
!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) {
if (np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo)
np->mcast_oif = tcp_v6_iif(opt_skb);
if (np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim)
np->mcast_hops = ipv6_hdr(opt_skb)->hop_limit;
if (np->rxopt.bits.rxflow || np->rxopt.bits.rxtclass)
np->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(opt_skb));
if (np->repflow)
np->flow_label = ip6_flowlabel(ipv6_hdr(opt_skb));
if (ipv6_opt_accepted(sk, opt_skb, &TCP_SKB_CB(opt_skb)->header.h6)) {
skb_set_owner_r(opt_skb, sk);
tcp_v6_restore_cb(opt_skb);
opt_skb = xchg(&np->pktoptions, opt_skb);
} else {
__kfree_skb(opt_skb);
opt_skb = xchg(&np->pktoptions, NULL);
}
}
kfree_skb(opt_skb);
return 0;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: TopSitesImpl* top_sites() { return top_sites_impl_.get(); }
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderView::didNavigateWithinPage(
WebFrame* frame, bool is_new_navigation) {
didCreateDataSource(frame, frame->dataSource());
NavigationState* new_state =
NavigationState::FromDataSource(frame->dataSource());
new_state->set_was_within_same_page(true);
didCommitProvisionalLoad(frame, is_new_navigation);
UpdateTitle(frame, frame->view()->mainFrame()->dataSource()->pageTitle());
}
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 kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
{
u32 data;
void *vapic;
if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
return;
vapic = kmap_atomic(vcpu->arch.apic->vapic_page);
data = *(u32 *)(vapic + offset_in_page(vcpu->arch.apic->vapic_addr));
kunmap_atomic(vapic);
apic_set_tpr(vcpu->arch.apic, data & 0xff);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: e1000e_msix_notify(E1000ECore *core, uint32_t causes)
{
if (causes & E1000_ICR_RXQ0) {
e1000e_msix_notify_one(core, E1000_ICR_RXQ0,
E1000_IVAR_RXQ0(core->mac[IVAR]));
}
if (causes & E1000_ICR_RXQ1) {
e1000e_msix_notify_one(core, E1000_ICR_RXQ1,
E1000_IVAR_RXQ1(core->mac[IVAR]));
}
if (causes & E1000_ICR_TXQ0) {
e1000e_msix_notify_one(core, E1000_ICR_TXQ0,
E1000_IVAR_TXQ0(core->mac[IVAR]));
}
if (causes & E1000_ICR_TXQ1) {
e1000e_msix_notify_one(core, E1000_ICR_TXQ1,
E1000_IVAR_TXQ1(core->mac[IVAR]));
}
if (causes & E1000_ICR_OTHER) {
e1000e_msix_notify_one(core, E1000_ICR_OTHER,
E1000_IVAR_OTHER(core->mac[IVAR]));
}
}
CWE ID: CWE-835
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
skb_dst_drop(skb);
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void finish_object(struct object *obj,
struct strbuf *path, const char *name,
void *cb_data)
{
struct rev_list_info *info = cb_data;
if (obj->type == OBJ_BLOB && !has_object_file(&obj->oid))
die("missing blob object '%s'", oid_to_hex(&obj->oid));
if (info->revs->verify_objects && !obj->parsed && obj->type != OBJ_COMMIT)
parse_object(obj->oid.hash);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: list_update_cgroup_event(struct perf_event *event,
struct perf_event_context *ctx, bool add)
{
struct perf_cpu_context *cpuctx;
struct list_head *cpuctx_entry;
if (!is_cgroup_event(event))
return;
if (add && ctx->nr_cgroups++)
return;
else if (!add && --ctx->nr_cgroups)
return;
/*
* Because cgroup events are always per-cpu events,
* this will always be called from the right CPU.
*/
cpuctx = __get_cpu_context(ctx);
cpuctx_entry = &cpuctx->cgrp_cpuctx_entry;
/* cpuctx->cgrp is NULL unless a cgroup event is active in this CPU .*/
if (add) {
list_add(cpuctx_entry, this_cpu_ptr(&cgrp_cpuctx_list));
if (perf_cgroup_from_task(current, ctx) == event->cgrp)
cpuctx->cgrp = event->cgrp;
} else {
list_del(cpuctx_entry);
cpuctx->cgrp = NULL;
}
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int m88rs2000_frontend_attach(struct dvb_usb_adapter *d)
{
u8 obuf[] = { 0x51 };
u8 ibuf[] = { 0 };
if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0)
err("command 0x51 transfer failed.");
d->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config,
&d->dev->i2c_adap);
if (d->fe_adap[0].fe == NULL)
return -EIO;
if (dvb_attach(ts2020_attach, d->fe_adap[0].fe,
&dw2104_ts2020_config,
&d->dev->i2c_adap)) {
info("Attached RS2000/TS2020!");
return 0;
}
info("Failed to attach RS2000/TS2020!");
return -EIO;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: mipspmu_map_general_event(int idx)
{
const struct mips_perf_event *pev;
pev = ((*mipspmu->general_event_map)[idx].event_id ==
UNSUPPORTED_PERF_EVENT_ID ? ERR_PTR(-EOPNOTSUPP) :
&(*mipspmu->general_event_map)[idx]);
return pev;
}
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: Document& Document::TopDocument() const {
Document* doc = const_cast<Document*>(this);
for (HTMLFrameOwnerElement* element = doc->LocalOwner(); element;
element = doc->LocalOwner())
doc = &element->GetDocument();
DCHECK(doc);
return *doc;
}
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: PlatformSensorProviderBase::MapSharedBufferForType(mojom::SensorType type) {
mojo::ScopedSharedBufferMapping mapping = shared_buffer_handle_->MapAtOffset(
kReadingBufferSize, SensorReadingSharedBuffer::GetOffset(type));
if (mapping)
memset(mapping.get(), 0, kReadingBufferSize);
return mapping;
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: ftrace_match_record(struct dyn_ftrace *rec, char *mod,
char *regex, int len, int type)
{
char str[KSYM_SYMBOL_LEN];
char *modname;
kallsyms_lookup(rec->ip, NULL, NULL, &modname, str);
if (mod) {
/* module lookup requires matching the module */
if (!modname || strcmp(modname, mod))
return 0;
/* blank search means to match all funcs in the mod */
if (!len)
return 1;
}
return ftrace_match(str, regex, len, type);
}
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: ssize_t NuPlayer::NuPlayerStreamListener::read(
void *data, size_t size, sp<AMessage> *extra) {
CHECK_GT(size, 0u);
extra->clear();
Mutex::Autolock autoLock(mLock);
if (mEOS) {
return 0;
}
if (mQueue.empty()) {
mSendDataNotification = true;
return -EWOULDBLOCK;
}
QueueEntry *entry = &*mQueue.begin();
if (entry->mIsCommand) {
switch (entry->mCommand) {
case EOS:
{
mQueue.erase(mQueue.begin());
entry = NULL;
mEOS = true;
return 0;
}
case DISCONTINUITY:
{
*extra = entry->mExtra;
mQueue.erase(mQueue.begin());
entry = NULL;
return INFO_DISCONTINUITY;
}
default:
TRESPASS();
break;
}
}
size_t copy = entry->mSize;
if (copy > size) {
copy = size;
}
memcpy(data,
(const uint8_t *)mBuffers.editItemAt(entry->mIndex)->pointer()
+ entry->mOffset,
copy);
entry->mOffset += copy;
entry->mSize -= copy;
if (entry->mSize == 0) {
mSource->onBufferAvailable(entry->mIndex);
mQueue.erase(mQueue.begin());
entry = NULL;
}
return copy;
}
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: ssize_t nbd_wr_syncv(QIOChannel *ioc,
struct iovec *iov,
size_t niov,
size_t length,
bool do_read)
{
ssize_t done = 0;
Error *local_err = NULL;
struct iovec *local_iov = g_new(struct iovec, niov);
struct iovec *local_iov_head = local_iov;
unsigned int nlocal_iov = niov;
nlocal_iov = iov_copy(local_iov, nlocal_iov, iov, niov, 0, length);
while (nlocal_iov > 0) {
ssize_t len;
if (do_read) {
len = qio_channel_readv(ioc, local_iov, nlocal_iov, &local_err);
} else {
len = qio_channel_writev(ioc, local_iov, nlocal_iov, &local_err);
}
if (len == QIO_CHANNEL_ERR_BLOCK) {
if (qemu_in_coroutine()) {
/* XXX figure out if we can create a variant on
* qio_channel_yield() that works with AIO contexts
* and consider using that in this branch */
qemu_coroutine_yield();
} else if (done) {
/* XXX this is needed by nbd_reply_ready. */
qio_channel_wait(ioc,
do_read ? G_IO_IN : G_IO_OUT);
} else {
return -EAGAIN;
}
} else if (done) {
/* XXX this is needed by nbd_reply_ready. */
qio_channel_wait(ioc,
do_read ? G_IO_IN : G_IO_OUT);
} else {
return -EAGAIN;
}
continue;
}
if (len < 0) {
TRACE("I/O error: %s", error_get_pretty(local_err));
error_free(local_err);
/* XXX handle Error objects */
done = -EIO;
goto cleanup;
}
if (do_read && len == 0) {
break;
}
iov_discard_front(&local_iov, &nlocal_iov, len);
done += len;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: const SVGDocumentExtensions* Document::svgExtensions()
{
return m_svgExtensions.get();
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __exit exit_f2fs_fs(void)
{
remove_proc_entry("fs/f2fs", NULL);
f2fs_destroy_root_stats();
unregister_filesystem(&f2fs_fs_type);
unregister_shrinker(&f2fs_shrinker_info);
kset_unregister(f2fs_kset);
destroy_extent_cache();
destroy_checkpoint_caches();
destroy_segment_manager_caches();
destroy_node_manager_caches();
destroy_inodecache();
f2fs_destroy_trace_ios();
}
CWE ID: CWE-129
Output: | 0 |
Here are some example code snippets. Analyze the following 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 copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
{
struct xfrm_algo *algo;
struct nlattr *nla;
nla = nla_reserve(skb, XFRMA_ALG_AUTH,
sizeof(*algo) + (auth->alg_key_len + 7) / 8);
if (!nla)
return -EMSGSIZE;
algo = nla_data(nla);
strcpy(algo->alg_name, auth->alg_name);
memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8);
algo->alg_key_len = auth->alg_key_len;
return 0;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: BOOLEAN ParaNdis_AnalyzeReceivedPacket(
PVOID headersBuffer,
ULONG dataLength,
PNET_PACKET_INFO packetInfo)
{
NdisZeroMemory(packetInfo, sizeof(*packetInfo));
packetInfo->headersBuffer = headersBuffer;
packetInfo->dataLength = dataLength;
if(!AnalyzeL2Hdr(packetInfo))
return FALSE;
if (!AnalyzeL3Hdr(packetInfo))
return FALSE;
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: fbFetchPixel_a4 (const FbBits *bits, int offset, miIndexedPtr indexed)
{
CARD32 pixel = Fetch4(bits, offset);
pixel |= pixel << 4;
return pixel << 24;
}
CWE ID: CWE-189
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi,
HB_GPOS_SubTable* st,
HB_Buffer buffer,
HB_UShort flags,
HB_UShort context_length,
int nesting_level )
{
HB_UShort i, j, mark1_index, mark2_index, property, class;
HB_Fixed x_mark1_value, y_mark1_value,
x_mark2_value, y_mark2_value;
HB_Error error;
HB_GPOSHeader* gpos = gpi->gpos;
HB_MarkMarkPos* mmp = &st->markmark;
HB_MarkArray* ma1;
HB_Mark2Array* ma2;
HB_Mark2Record* m2r;
HB_Anchor* mark1_anchor;
HB_Anchor* mark2_anchor;
HB_Position o;
HB_UNUSED(nesting_level);
if ( context_length != 0xFFFF && context_length < 1 )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS )
return HB_Err_Not_Covered;
if ( CHECK_Property( gpos->gdef, IN_CURITEM(),
flags, &property ) )
return error;
error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(),
&mark1_index );
if ( error )
return error;
/* now we search backwards for a suitable mark glyph until a non-mark
glyph */
if ( buffer->in_pos == 0 )
return HB_Err_Not_Covered;
i = 1;
j = buffer->in_pos - 1;
while ( i <= buffer->in_pos )
{
error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ),
&property );
if ( error )
return error;
if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) )
return HB_Err_Not_Covered;
if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS )
{
if ( property == (flags & 0xFF00) )
break;
}
else
break;
i++;
j--;
}
error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ),
&mark2_index );
if ( error )
if ( mark1_index >= ma1->MarkCount )
return ERR(HB_Err_Invalid_SubTable);
class = ma1->MarkRecord[mark1_index].Class;
mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor;
if ( class >= mmp->ClassCount )
return ERR(HB_Err_Invalid_SubTable);
ma2 = &mmp->Mark2Array;
if ( mark2_index >= ma2->Mark2Count )
return ERR(HB_Err_Invalid_SubTable);
m2r = &ma2->Mark2Record[mark2_index];
mark2_anchor = &m2r->Mark2Anchor[class];
error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(),
&x_mark1_value, &y_mark1_value );
if ( error )
return error;
error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ),
&x_mark2_value, &y_mark2_value );
if ( error )
return error;
/* anchor points are not cumulative */
o = POSITION( buffer->in_pos );
o->x_pos = x_mark2_value - x_mark1_value;
o->y_pos = y_mark2_value - y_mark1_value;
o->x_advance = 0;
o->y_advance = 0;
o->back = 1;
(buffer->in_pos)++;
return HB_Err_Ok;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: append_text_move(pdf_text_state_t *pts, double dw)
{
int count = pts->buffer.count_moves;
int pos = pts->buffer.count_chars;
double rounded;
if (count > 0 && pts->buffer.moves[count - 1].index == pos) {
/* Merge adjacent moves. */
dw += pts->buffer.moves[--count].amount;
}
/* Round dw if it's very close to an integer. */
rounded = floor(dw + 0.5);
if (fabs(dw - rounded) < 0.001)
dw = rounded;
if (dw < -MAX_USER_COORD) {
/* Acrobat reader 4.0c, 5.0 can't handle big offsets.
Adobe Reader 6 can. */
return -1;
}
if (dw != 0) {
if (count == MAX_TEXT_BUFFER_MOVES)
return -1;
pts->buffer.moves[count].index = pos;
pts->buffer.moves[count].amount = dw;
++count;
}
pts->buffer.count_moves = count;
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderThreadImpl::OnAssociatedInterfaceRequest(
const std::string& name,
mojo::ScopedInterfaceEndpointHandle handle) {
if (associated_interfaces_.CanBindRequest(name))
associated_interfaces_.BindRequest(name, std::move(handle));
else
ChildThreadImpl::OnAssociatedInterfaceRequest(name, std::move(handle));
}
CWE ID: CWE-310
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static GIOChannel *irssi_ssl_get_iochannel(GIOChannel *handle, const char *mycert, const char *mypkey, const char *cafile, const char *capath, gboolean verify)
{
GIOSSLChannel *chan;
GIOChannel *gchan;
int fd;
SSL *ssl;
SSL_CTX *ctx = NULL;
g_return_val_if_fail(handle != NULL, NULL);
if(!ssl_ctx && !irssi_ssl_init())
return NULL;
if(!(fd = g_io_channel_unix_get_fd(handle)))
return NULL;
if (mycert && *mycert) {
char *scert = NULL, *spkey = NULL;
if ((ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
scert = convert_home(mycert);
if (mypkey && *mypkey)
spkey = convert_home(mypkey);
if (! SSL_CTX_use_certificate_file(ctx, scert, SSL_FILETYPE_PEM))
g_warning("Loading of client certificate '%s' failed", mycert);
else if (! SSL_CTX_use_PrivateKey_file(ctx, spkey ? spkey : scert, SSL_FILETYPE_PEM))
g_warning("Loading of private key '%s' failed", mypkey ? mypkey : mycert);
else if (! SSL_CTX_check_private_key(ctx))
g_warning("Private key does not match the certificate");
g_free(scert);
g_free(spkey);
}
if ((cafile && *cafile) || (capath && *capath)) {
char *scafile = NULL;
char *scapath = NULL;
if (! ctx && (ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
if (cafile && *cafile)
scafile = convert_home(cafile);
if (capath && *capath)
scapath = convert_home(capath);
if (! SSL_CTX_load_verify_locations(ctx, scafile, scapath)) {
g_warning("Could not load CA list for verifying SSL server certificate");
g_free(scafile);
g_free(scapath);
SSL_CTX_free(ctx);
return NULL;
}
g_free(scafile);
g_free(scapath);
verify = TRUE;
}
if (ctx == NULL)
ctx = ssl_ctx;
if(!(ssl = SSL_new(ctx)))
{
g_warning("Failed to allocate SSL structure");
return NULL;
}
if(!SSL_set_fd(ssl, fd))
{
g_warning("Failed to associate socket to SSL stream");
SSL_free(ssl);
if (ctx != ssl_ctx)
SSL_CTX_free(ctx);
return NULL;
}
SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
chan = g_new0(GIOSSLChannel, 1);
chan->fd = fd;
chan->giochan = handle;
chan->ssl = ssl;
chan->ctx = ctx;
chan->verify = verify;
gchan = (GIOChannel *)chan;
gchan->funcs = &irssi_ssl_channel_funcs;
g_io_channel_init(gchan);
gchan->is_readable = gchan->is_writeable = TRUE;
gchan->use_buffer = FALSE;
return gchan;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void Unpack<WebGLImageConversion::kDataFormatBGRA8, uint8_t, uint8_t>(
const uint8_t* source,
uint8_t* destination,
unsigned pixels_per_row) {
const uint32_t* source32 = reinterpret_cast_ptr<const uint32_t*>(source);
uint32_t* destination32 = reinterpret_cast_ptr<uint32_t*>(destination);
#if defined(ARCH_CPU_X86_FAMILY)
SIMD::UnpackOneRowOfBGRA8LittleToRGBA8(source32, destination32,
pixels_per_row);
#endif
#if HAVE_MIPS_MSA_INTRINSICS
SIMD::unpackOneRowOfBGRA8LittleToRGBA8MSA(source32, destination32,
pixels_per_row);
#endif
for (unsigned i = 0; i < pixels_per_row; ++i) {
uint32_t bgra = source32[i];
#if defined(ARCH_CPU_BIG_ENDIAN)
uint32_t brMask = 0xff00ff00;
uint32_t gaMask = 0x00ff00ff;
#else
uint32_t br_mask = 0x00ff00ff;
uint32_t ga_mask = 0xff00ff00;
#endif
uint32_t rgba =
(((bgra >> 16) | (bgra << 16)) & br_mask) | (bgra & ga_mask);
destination32[i] = rgba;
}
}
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: ~RemovePasswordsTester() { OSCryptMocker::TearDown(); }
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: int Chapters::Atom::GetDisplayCount() const
{
return m_displays_count;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: e1000e_rx_descr_threshold_hit(E1000ECore *core, const E1000E_RingInfo *rxi)
{
return e1000e_ring_free_descr_num(core, rxi) ==
e1000e_ring_len(core, rxi) >> core->rxbuf_min_shift;
}
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: static void gamma_composition_test(png_modifier *pm,
PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth,
PNG_CONST int palette_number,
PNG_CONST int interlace_type, PNG_CONST double file_gamma,
PNG_CONST double screen_gamma,
PNG_CONST int use_input_precision, PNG_CONST int do_background,
PNG_CONST int expand_16)
{
size_t pos = 0;
png_const_charp base;
double bg;
char name[128];
png_color_16 background;
/* Make up a name and get an appropriate background gamma value. */
switch (do_background)
{
default:
base = "";
bg = 4; /* should not be used */
break;
case PNG_BACKGROUND_GAMMA_SCREEN:
base = " bckg(Screen):";
bg = 1/screen_gamma;
break;
case PNG_BACKGROUND_GAMMA_FILE:
base = " bckg(File):";
bg = file_gamma;
break;
case PNG_BACKGROUND_GAMMA_UNIQUE:
base = " bckg(Unique):";
/* This tests the handling of a unique value, the math is such that the
* value tends to be <1, but is neither screen nor file (even if they
* match!)
*/
bg = (file_gamma + screen_gamma) / 3;
break;
#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
case ALPHA_MODE_OFFSET + PNG_ALPHA_PNG:
base = " alpha(PNG)";
bg = 4; /* should not be used */
break;
case ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD:
base = " alpha(Porter-Duff)";
bg = 4; /* should not be used */
break;
case ALPHA_MODE_OFFSET + PNG_ALPHA_OPTIMIZED:
base = " alpha(Optimized)";
bg = 4; /* should not be used */
break;
case ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN:
base = " alpha(Broken)";
bg = 4; /* should not be used */
break;
#endif
}
/* Use random background values - the background is always presented in the
* output space (8 or 16 bit components).
*/
if (expand_16 || bit_depth == 16)
{
png_uint_32 r = random_32();
background.red = (png_uint_16)r;
background.green = (png_uint_16)(r >> 16);
r = random_32();
background.blue = (png_uint_16)r;
background.gray = (png_uint_16)(r >> 16);
/* In earlier libpng versions, those where DIGITIZE is set, any background
* gamma correction in the expand16 case was done using 8-bit gamma
* correction tables, resulting in larger errors. To cope with those
* cases use a 16-bit background value which will handle this gamma
* correction.
*/
# if DIGITIZE
if (expand_16 && (do_background == PNG_BACKGROUND_GAMMA_UNIQUE ||
do_background == PNG_BACKGROUND_GAMMA_FILE) &&
fabs(bg*screen_gamma-1) > PNG_GAMMA_THRESHOLD)
{
/* The background values will be looked up in an 8-bit table to do
* the gamma correction, so only select values which are an exact
* match for the 8-bit table entries:
*/
background.red = (png_uint_16)((background.red >> 8) * 257);
background.green = (png_uint_16)((background.green >> 8) * 257);
background.blue = (png_uint_16)((background.blue >> 8) * 257);
background.gray = (png_uint_16)((background.gray >> 8) * 257);
}
# endif
}
else /* 8 bit colors */
{
png_uint_32 r = random_32();
background.red = (png_byte)r;
background.green = (png_byte)(r >> 8);
background.blue = (png_byte)(r >> 16);
background.gray = (png_byte)(r >> 24);
}
background.index = 193; /* rgb(193,193,193) to detect errors */
if (!(colour_type & PNG_COLOR_MASK_COLOR))
{
/* Grayscale input, we do not convert to RGB (TBD), so we must set the
* background to gray - else libpng seems to fail.
*/
background.red = background.green = background.blue = background.gray;
}
pos = safecat(name, sizeof name, pos, "gamma ");
pos = safecatd(name, sizeof name, pos, file_gamma, 3);
pos = safecat(name, sizeof name, pos, "->");
pos = safecatd(name, sizeof name, pos, screen_gamma, 3);
pos = safecat(name, sizeof name, pos, base);
if (do_background < ALPHA_MODE_OFFSET)
{
/* Include the background color and gamma in the name: */
pos = safecat(name, sizeof name, pos, "(");
/* This assumes no expand gray->rgb - the current code won't handle that!
*/
if (colour_type & PNG_COLOR_MASK_COLOR)
{
pos = safecatn(name, sizeof name, pos, background.red);
pos = safecat(name, sizeof name, pos, ",");
pos = safecatn(name, sizeof name, pos, background.green);
pos = safecat(name, sizeof name, pos, ",");
pos = safecatn(name, sizeof name, pos, background.blue);
}
else
pos = safecatn(name, sizeof name, pos, background.gray);
pos = safecat(name, sizeof name, pos, ")^");
pos = safecatd(name, sizeof name, pos, bg, 3);
}
gamma_test(pm, colour_type, bit_depth, palette_number, interlace_type,
file_gamma, screen_gamma, 0/*sBIT*/, 0, name, use_input_precision,
0/*strip 16*/, expand_16, do_background, &background, bg);
}
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: PHP_FUNCTION(mcrypt_module_self_test)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir);
if (mcrypt_module_self_test(module, dir) == 0) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: gsicc_profile_new(stream *s, gs_memory_t *memory, const char* pname,
int namelen)
{
cmm_profile_t *result;
int code;
char *nameptr = NULL;
gs_memory_t *mem_nongc = memory->non_gc_memory;
result = (cmm_profile_t*) gs_alloc_bytes(mem_nongc, sizeof(cmm_profile_t),
"gsicc_profile_new");
if (result == NULL)
return result;
memset(result, 0, GSICC_SERIALIZED_SIZE);
if (namelen > 0) {
nameptr = (char*) gs_alloc_bytes(mem_nongc, namelen+1,
"gsicc_profile_new");
if (nameptr == NULL) {
gs_free_object(mem_nongc, result, "gsicc_profile_new");
return NULL;
}
memcpy(nameptr, pname, namelen);
nameptr[namelen] = '\0';
result->name = nameptr;
} else {
result->name = NULL;
}
result->name_length = namelen;
/* We may not have a stream if we are creating this
object from our own constructed buffer. For
example if we are converting CalRGB to an ICC type */
if ( s != NULL) {
code = gsicc_load_profile_buffer(result, s, mem_nongc);
if (code < 0) {
gs_free_object(mem_nongc, result, "gsicc_profile_new");
gs_free_object(mem_nongc, nameptr, "gsicc_profile_new");
return NULL;
}
} else {
result->buffer = NULL;
result->buffer_size = 0;
}
rc_init_free(result, mem_nongc, 1, rc_free_icc_profile);
result->profile_handle = NULL;
result->spotnames = NULL;
result->rend_is_valid = false;
result->isdevlink = false; /* only used for srcgtag profiles */
result->dev = NULL;
result->memory = mem_nongc;
result->lock = gx_monitor_label(gx_monitor_alloc(mem_nongc),
"gsicc_manage");
result->vers = ICCVERS_UNKNOWN;
result->v2_data = NULL;
result->v2_size = 0;
result->release = gscms_release_profile; /* Default case */
if (result->lock == NULL) {
gs_free_object(mem_nongc, result, "gsicc_profile_new");
gs_free_object(mem_nongc, nameptr, "gsicc_profile_new");
return NULL;
}
if_debug1m(gs_debug_flag_icc, mem_nongc,
"[icc] allocating ICC profile = 0x%p\n", result);
return result;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
int scaledWidth, int scaledHeight,
SplashBitmap *dest) {
Guchar *lineBuf;
Guint pix;
Guchar *destPtr0, *destPtr;
int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1;
int i;
yp = scaledHeight / srcHeight;
yq = scaledHeight % srcHeight;
xp = srcWidth / scaledWidth;
xq = srcWidth % scaledWidth;
lineBuf = (Guchar *)gmalloc(srcWidth);
yt = 0;
destPtr0 = dest->data;
for (y = 0; y < srcHeight; ++y) {
if ((yt += yq) >= srcHeight) {
yt -= srcHeight;
yStep = yp + 1;
} else {
yStep = yp;
}
(*src)(srcData, lineBuf);
xt = 0;
d0 = (255 << 23) / xp;
d1 = (255 << 23) / (xp + 1);
xx = 0;
for (x = 0; x < scaledWidth; ++x) {
if ((xt += xq) >= scaledWidth) {
xt -= scaledWidth;
xStep = xp + 1;
d = d1;
} else {
xStep = xp;
d = d0;
}
pix = 0;
for (i = 0; i < xStep; ++i) {
pix += lineBuf[xx++];
}
pix = (pix * d) >> 23;
for (i = 0; i < yStep; ++i) {
destPtr = destPtr0 + i * scaledWidth + x;
*destPtr = (Guchar)pix;
}
}
destPtr0 += yStep * scaledWidth;
}
gfree(lineBuf);
}
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 OnSuggestionModelAdded(UiScene* scene,
UiBrowserInterface* browser,
Model* model,
SuggestionBinding* element_binding) {
auto icon = base::MakeUnique<VectorIcon>(100);
icon->SetDrawPhase(kPhaseForeground);
icon->SetType(kTypeOmniboxSuggestionIcon);
icon->set_hit_testable(false);
icon->SetSize(kSuggestionIconSizeDMM, kSuggestionIconSizeDMM);
BindColor(model, icon.get(), &ColorScheme::omnibox_icon,
&VectorIcon::SetColor);
VectorIcon* p_icon = icon.get();
auto icon_box = base::MakeUnique<UiElement>();
icon_box->SetDrawPhase(kPhaseNone);
icon_box->SetType(kTypeOmniboxSuggestionIconField);
icon_box->SetSize(kSuggestionIconFieldWidthDMM, kSuggestionHeightDMM);
icon_box->AddChild(std::move(icon));
auto content_text = base::MakeUnique<Text>(kSuggestionContentTextHeightDMM);
content_text->SetDrawPhase(kPhaseForeground);
content_text->SetType(kTypeOmniboxSuggestionContentText);
content_text->set_hit_testable(false);
content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth);
content_text->SetSize(kSuggestionTextFieldWidthDMM, 0);
content_text->SetTextAlignment(UiTexture::kTextAlignmentLeft);
BindColor(model, content_text.get(), &ColorScheme::omnibox_suggestion_content,
&Text::SetColor);
Text* p_content_text = content_text.get();
auto description_text =
base::MakeUnique<Text>(kSuggestionDescriptionTextHeightDMM);
description_text->SetDrawPhase(kPhaseForeground);
description_text->SetType(kTypeOmniboxSuggestionDescriptionText);
description_text->set_hit_testable(false);
content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth);
description_text->SetSize(kSuggestionTextFieldWidthDMM, 0);
description_text->SetTextAlignment(UiTexture::kTextAlignmentLeft);
BindColor(model, description_text.get(),
&ColorScheme::omnibox_suggestion_description, &Text::SetColor);
Text* p_description_text = description_text.get();
auto text_layout = base::MakeUnique<LinearLayout>(LinearLayout::kDown);
text_layout->SetType(kTypeOmniboxSuggestionTextLayout);
text_layout->set_hit_testable(false);
text_layout->set_margin(kSuggestionLineGapDMM);
text_layout->AddChild(std::move(content_text));
text_layout->AddChild(std::move(description_text));
auto right_margin = base::MakeUnique<UiElement>();
right_margin->SetDrawPhase(kPhaseNone);
right_margin->SetSize(kSuggestionRightMarginDMM, kSuggestionHeightDMM);
auto suggestion_layout = base::MakeUnique<LinearLayout>(LinearLayout::kRight);
suggestion_layout->SetType(kTypeOmniboxSuggestionLayout);
suggestion_layout->set_hit_testable(false);
suggestion_layout->AddChild(std::move(icon_box));
suggestion_layout->AddChild(std::move(text_layout));
suggestion_layout->AddChild(std::move(right_margin));
auto background = Create<Button>(
kNone, kPhaseForeground,
base::BindRepeating(
[](UiBrowserInterface* b, Model* m, SuggestionBinding* e) {
b->Navigate(e->model()->destination);
m->omnibox_input_active = false;
},
base::Unretained(browser), base::Unretained(model),
base::Unretained(element_binding)));
background->SetType(kTypeOmniboxSuggestionBackground);
background->set_hit_testable(true);
background->set_bubble_events(true);
background->set_bounds_contain_children(true);
background->set_hover_offset(0.0);
BindButtonColors(model, background.get(),
&ColorScheme::suggestion_button_colors,
&Button::SetButtonColors);
background->AddChild(std::move(suggestion_layout));
element_binding->bindings().push_back(
VR_BIND_FUNC(base::string16, SuggestionBinding, element_binding,
model()->content, Text, p_content_text, SetText));
element_binding->bindings().push_back(
base::MakeUnique<Binding<base::string16>>(
base::BindRepeating(
[](SuggestionBinding* m) { return m->model()->description; },
base::Unretained(element_binding)),
base::BindRepeating(
[](Text* v, const base::string16& text) {
v->SetVisibleImmediately(!text.empty());
v->set_requires_layout(!text.empty());
if (!text.empty()) {
v->SetText(text);
}
},
base::Unretained(p_description_text))));
element_binding->bindings().push_back(
VR_BIND(AutocompleteMatch::Type, SuggestionBinding, element_binding,
model()->type, VectorIcon, p_icon,
SetIcon(AutocompleteMatch::TypeToVectorIcon(value))));
element_binding->set_view(background.get());
scene->AddUiElement(kOmniboxSuggestions, std::move(background));
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int blkdev_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
int ret;
ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
unlock_page(page);
page_cache_release(page);
return ret;
}
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: rx_cache_insert(netdissect_options *ndo,
const u_char *bp, const struct ip *ip, int dport)
{
struct rx_cache_entry *rxent;
const struct rx_header *rxh = (const struct rx_header *) bp;
if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t)))
return;
rxent = &rx_cache[rx_cache_next];
if (++rx_cache_next >= RX_CACHE_SIZE)
rx_cache_next = 0;
rxent->callnum = EXTRACT_32BITS(&rxh->callNumber);
UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t));
UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t));
rxent->dport = dport;
rxent->serviceId = EXTRACT_32BITS(&rxh->serviceId);
rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header));
}
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 void GetCSI(const v8::FunctionCallbackInfo<v8::Value>& args) {
WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
if (frame) {
WebDataSource* data_source = frame->dataSource();
if (data_source) {
DocumentState* document_state =
DocumentState::FromDataSource(data_source);
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> csi = v8::Object::New(isolate);
base::Time now = base::Time::Now();
base::Time start = document_state->request_time().is_null() ?
document_state->start_load_time() :
document_state->request_time();
base::Time onload = document_state->finish_document_load_time();
base::TimeDelta page = now - start;
csi->Set(v8::String::NewFromUtf8(isolate, "startE"),
v8::Number::New(isolate, floor(start.ToDoubleT() * 1000)));
csi->Set(v8::String::NewFromUtf8(isolate, "onloadT"),
v8::Number::New(isolate, floor(onload.ToDoubleT() * 1000)));
csi->Set(v8::String::NewFromUtf8(isolate, "pageT"),
v8::Number::New(isolate, page.InMillisecondsF()));
csi->Set(
v8::String::NewFromUtf8(isolate, "tran"),
v8::Number::New(
isolate, GetCSITransitionType(data_source->navigationType())));
args.GetReturnValue().Set(csi);
return;
}
}
args.GetReturnValue().SetNull();
return;
}
CWE ID:
Target: 1
Example 2:
Code: unicode_oslm_strings(char **pbcc_area, const struct nls_table *nls_cp)
{
char *bcc_ptr = *pbcc_area;
int bytes_ret = 0;
/* Copy OS version */
bytes_ret = cifs_strtoUTF16((__le16 *)bcc_ptr, "Linux version ", 32,
nls_cp);
bcc_ptr += 2 * bytes_ret;
bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, init_utsname()->release,
32, nls_cp);
bcc_ptr += 2 * bytes_ret;
bcc_ptr += 2; /* trailing null */
bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS,
32, nls_cp);
bcc_ptr += 2 * bytes_ret;
bcc_ptr += 2; /* trailing null */
*pbcc_area = bcc_ptr;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
uint8_t wct, const uint16_t *vwv,
size_t bytes_alignment,
uint32_t num_bytes, const uint8_t *bytes)
{
uint8_t *outbuf;
size_t old_size, new_size;
size_t ofs;
size_t chain_padding = 0;
size_t bytes_padding = 0;
bool first_request;
old_size = talloc_get_size(*poutbuf);
/*
* old_size == smb_wct means we're pushing the first request in for
* libsmb/
*/
first_request = (old_size == smb_wct);
if (!first_request && ((old_size % 4) != 0)) {
/*
* Align the wct field of subsequent requests to a 4-byte
* boundary
*/
chain_padding = 4 - (old_size % 4);
}
/*
* After the old request comes the new wct field (1 byte), the vwv's
* and the num_bytes field. After at we might need to align the bytes
* given to us to "bytes_alignment", increasing the num_bytes value.
*/
new_size = old_size + chain_padding + 1 + wct * sizeof(uint16_t) + 2;
if ((bytes_alignment != 0) && ((new_size % bytes_alignment) != 0)) {
bytes_padding = bytes_alignment - (new_size % bytes_alignment);
}
new_size += bytes_padding + num_bytes;
if ((smb_command != SMBwriteX) && (new_size > 0xffff)) {
DEBUG(1, ("splice_chain: %u bytes won't fit\n",
(unsigned)new_size));
return false;
}
outbuf = TALLOC_REALLOC_ARRAY(NULL, *poutbuf, uint8_t, new_size);
if (outbuf == NULL) {
DEBUG(0, ("talloc failed\n"));
return false;
}
*poutbuf = outbuf;
if (first_request) {
SCVAL(outbuf, smb_com, smb_command);
} else {
size_t andx_cmd_ofs;
if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
DEBUG(1, ("invalid command chain\n"));
*poutbuf = TALLOC_REALLOC_ARRAY(
NULL, *poutbuf, uint8_t, old_size);
return false;
}
if (chain_padding != 0) {
memset(outbuf + old_size, 0, chain_padding);
old_size += chain_padding;
}
SCVAL(outbuf, andx_cmd_ofs, smb_command);
SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
}
ofs = old_size;
/*
* Push the chained request:
*
* wct field
*/
SCVAL(outbuf, ofs, wct);
ofs += 1;
/*
* vwv array
*/
memcpy(outbuf + ofs, vwv, sizeof(uint16_t) * wct);
ofs += sizeof(uint16_t) * wct;
/*
* bcc (byte count)
*/
SSVAL(outbuf, ofs, num_bytes + bytes_padding);
ofs += sizeof(uint16_t);
/*
* padding
*/
if (bytes_padding != 0) {
memset(outbuf + ofs, 0, bytes_padding);
ofs += bytes_padding;
}
/*
* The bytes field
*/
memcpy(outbuf + ofs, bytes, num_bytes);
return true;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void unix_inflight(struct file *fp)
{
struct sock *s = unix_get_socket(fp);
if (s) {
struct unix_sock *u = unix_sk(s);
spin_lock(&unix_gc_lock);
if (atomic_long_inc_return(&u->inflight) == 1) {
BUG_ON(!list_empty(&u->link));
list_add_tail(&u->link, &gc_inflight_list);
} else {
BUG_ON(list_empty(&u->link));
}
unix_tot_inflight++;
spin_unlock(&unix_gc_lock);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: SoftMPEG4::~SoftMPEG4() {
if (mInitialized) {
PVCleanUpVideoDecoder(mHandle);
}
delete mHandle;
mHandle = NULL;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ProcRenderQueryFilters (ClientPtr client)
{
REQUEST (xRenderQueryFiltersReq);
DrawablePtr pDrawable;
xRenderQueryFiltersReply *reply;
int nbytesName;
int nnames;
ScreenPtr pScreen;
PictureScreenPtr ps;
int i, j, len, total_bytes, rc;
INT16 *aliases;
char *names;
REQUEST_SIZE_MATCH(xRenderQueryFiltersReq);
rc = dixLookupDrawable(&pDrawable, stuff->drawable, client, 0,
DixGetAttrAccess);
if (rc != Success)
return rc;
pScreen = pDrawable->pScreen;
nbytesName = 0;
nnames = 0;
ps = GetPictureScreenIfSet(pScreen);
if (ps)
{
for (i = 0; i < ps->nfilters; i++)
nbytesName += 1 + strlen (ps->filters[i].name);
for (i = 0; i < ps->nfilterAliases; i++)
nbytesName += 1 + strlen (ps->filterAliases[i].alias);
nnames = ps->nfilters + ps->nfilterAliases;
}
len = ((nnames + 1) >> 1) + bytes_to_int32(nbytesName);
total_bytes = sizeof (xRenderQueryFiltersReply) + (len << 2);
reply = (xRenderQueryFiltersReply *) malloc(total_bytes);
if (!reply)
return BadAlloc;
aliases = (INT16 *) (reply + 1);
names = (char *) (aliases + ((nnames + 1) & ~1));
reply->type = X_Reply;
reply->sequenceNumber = client->sequence;
reply->length = len;
reply->numAliases = nnames;
reply->numFilters = nnames;
if (ps)
{
/* fill in alias values */
for (i = 0; i < ps->nfilters; i++)
aliases[i] = FilterAliasNone;
for (i = 0; i < ps->nfilterAliases; i++)
{
for (j = 0; j < ps->nfilters; j++)
if (ps->filterAliases[i].filter_id == ps->filters[j].id)
break;
if (j == ps->nfilters)
{
for (j = 0; j < ps->nfilterAliases; j++)
if (ps->filterAliases[i].filter_id ==
ps->filterAliases[j].alias_id)
{
break;
}
if (j == ps->nfilterAliases)
j = FilterAliasNone;
else
j = j + ps->nfilters;
}
aliases[i + ps->nfilters] = j;
}
/* fill in filter names */
for (i = 0; i < ps->nfilters; i++)
{
j = strlen (ps->filters[i].name);
*names++ = j;
strncpy (names, ps->filters[i].name, j);
names += j;
}
/* fill in filter alias names */
for (i = 0; i < ps->nfilterAliases; i++)
{
j = strlen (ps->filterAliases[i].alias);
*names++ = j;
strncpy (names, ps->filterAliases[i].alias, j);
names += j;
}
}
if (client->swapped)
{
register int n;
for (i = 0; i < reply->numAliases; i++)
{
swaps (&aliases[i], n);
}
swaps(&reply->sequenceNumber, n);
swapl(&reply->length, n);
swapl(&reply->numAliases, n);
swapl(&reply->numFilters, n);
}
WriteToClient(client, total_bytes, (char *) reply);
free(reply);
return Success;
}
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 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;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
/* 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_INFILE:
infile = jas_optarg;
break;
case OPT_HELP:
default:
usage();
break;
}
}
/* 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))) {
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
numcmpts = jas_image_numcmpts(image);
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 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-476
Target: 1
Example 2:
Code: fmov_reg_idx(struct sh_fpu_soft_struct *fregs, struct pt_regs *regs, int m,
int n)
{
if (FPSCR_SZ) {
FMOV_EXT(m);
WRITE(FRm, Rn + R0 + 4);
m++;
WRITE(FRm, Rn + R0);
} else {
WRITE(FRm, Rn + R0);
}
return 0;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MaybeChangeCurrentKeyboardLayout(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
ContainOnlyOneKeyboardLayout(value)) {
ChangeCurrentInputMethodFromId(value.string_list_value[0]);
}
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static UINT32 nsc_rle_encode(BYTE* in, BYTE* out, UINT32 originalSize)
{
UINT32 left;
UINT32 runlength = 1;
UINT32 planeSize = 0;
left = originalSize;
/**
* We quit the loop if the running compressed size is larger than the original.
* In such cases data will be sent uncompressed.
*/
while (left > 4 && planeSize < originalSize - 4)
{
if (left > 5 && *in == *(in + 1))
{
runlength++;
}
else if (runlength == 1)
{
*out++ = *in;
planeSize++;
}
else if (runlength < 256)
{
*out++ = *in;
*out++ = *in;
*out++ = runlength - 2;
runlength = 1;
planeSize += 3;
}
else
{
*out++ = *in;
*out++ = *in;
*out++ = 0xFF;
*out++ = (runlength & 0x000000FF);
*out++ = (runlength & 0x0000FF00) >> 8;
*out++ = (runlength & 0x00FF0000) >> 16;
*out++ = (runlength & 0xFF000000) >> 24;
runlength = 1;
planeSize += 7;
}
in++;
left--;
}
if (planeSize < originalSize - 4)
CopyMemory(out, in, 4);
planeSize += 4;
return planeSize;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static void InitLibcLocaltimeFunctions() {
g_libc_localtime = reinterpret_cast<LocaltimeFunction>(
dlsym(RTLD_NEXT, "localtime"));
g_libc_localtime64 = reinterpret_cast<LocaltimeFunction>(
dlsym(RTLD_NEXT, "localtime64"));
g_libc_localtime_r = reinterpret_cast<LocaltimeRFunction>(
dlsym(RTLD_NEXT, "localtime_r"));
g_libc_localtime64_r = reinterpret_cast<LocaltimeRFunction>(
dlsym(RTLD_NEXT, "localtime64_r"));
if (!g_libc_localtime || !g_libc_localtime_r) {
LOG(ERROR) << "Your system is broken: dlsym doesn't work! This has been "
"reported to be caused by Nvidia's libGL. You should expect"
" time related functions to misbehave. "
"http://code.google.com/p/chromium/issues/detail?id=16800";
}
if (!g_libc_localtime)
g_libc_localtime = gmtime;
if (!g_libc_localtime64)
g_libc_localtime64 = g_libc_localtime;
if (!g_libc_localtime_r)
g_libc_localtime_r = gmtime_r;
if (!g_libc_localtime64_r)
g_libc_localtime64_r = g_libc_localtime_r;
}
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 ocfs2_dir_release(struct inode *inode, struct file *file)
{
ocfs2_free_file_private(inode, file);
return 0;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AppCacheDatabase::ReadEntryRecord(
const sql::Statement& statement, EntryRecord* record) {
record->cache_id = statement.ColumnInt64(0);
record->url = GURL(statement.ColumnString(1));
record->flags = statement.ColumnInt(2);
record->response_id = statement.ColumnInt64(3);
record->response_size = statement.ColumnInt64(4);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: xsltForEachComp(xsltStylesheetPtr style, xmlNodePtr inst) {
#ifdef XSLT_REFACTORED
xsltStyleItemForEachPtr comp;
#else
xsltStylePreCompPtr comp;
#endif
if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE))
return;
#ifdef XSLT_REFACTORED
comp = (xsltStyleItemForEachPtr)
xsltNewStylePreComp(style, XSLT_FUNC_FOREACH);
#else
comp = xsltNewStylePreComp(style, XSLT_FUNC_FOREACH);
#endif
if (comp == NULL)
return;
inst->psvi = comp;
comp->inst = inst;
comp->select = xsltGetCNsProp(style, inst, (const xmlChar *)"select",
XSLT_NAMESPACE);
if (comp->select == NULL) {
xsltTransformError(NULL, style, inst,
"xsl:for-each : select is missing\n");
if (style != NULL) style->errors++;
} else {
comp->comp = xsltXPathCompile(style, comp->select);
if (comp->comp == NULL) {
xsltTransformError(NULL, style, inst,
"xsl:for-each : could not compile select expression '%s'\n",
comp->select);
if (style != NULL) style->errors++;
}
}
/* TODO: handle and skip the xsl:sort */
}
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 ACodec::BaseState::getMoreInputDataIfPossible() {
if (mCodec->mPortEOS[kPortIndexInput]) {
return;
}
BufferInfo *eligible = NULL;
for (size_t i = 0; i < mCodec->mBuffers[kPortIndexInput].size(); ++i) {
BufferInfo *info = &mCodec->mBuffers[kPortIndexInput].editItemAt(i);
#if 0
if (info->mStatus == BufferInfo::OWNED_BY_UPSTREAM) {
return;
}
#endif
if (info->mStatus == BufferInfo::OWNED_BY_US) {
eligible = info;
}
}
if (eligible == NULL) {
return;
}
postFillThisBuffer(eligible);
}
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 AwContents::ScrollContainerViewTo(gfx::Vector2d new_value) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
ScopedJavaLocalRef<jobject> obj = java_ref_.get(env);
if (obj.is_null())
return;
Java_AwContents_scrollContainerViewTo(
env, obj.obj(), new_value.x(), new_value.y());
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void Browser::DuplicateContentsAt(int index) {
TabContentsWrapper* contents = GetTabContentsWrapperAt(index);
CHECK(contents);
TabContentsWrapper* contents_dupe = contents->Clone();
TabContents* new_contents = contents_dupe->tab_contents();
bool pinned = false;
if (CanSupportWindowFeature(FEATURE_TABSTRIP)) {
int index = tab_handler_->GetTabStripModel()->
GetIndexOfTabContents(contents);
pinned = tab_handler_->GetTabStripModel()->IsTabPinned(index);
int add_types = TabStripModel::ADD_ACTIVE |
TabStripModel::ADD_INHERIT_GROUP |
(pinned ? TabStripModel::ADD_PINNED : 0);
tab_handler_->GetTabStripModel()->InsertTabContentsAt(index + 1,
contents_dupe,
add_types);
} else {
Browser* browser = NULL;
if (type_ & TYPE_APP) {
CHECK_EQ((type_ & TYPE_POPUP), 0);
CHECK_NE(type_, TYPE_APP_PANEL);
browser = Browser::CreateForApp(app_name_, gfx::Size(), profile_,
false);
} else if (type_ == TYPE_POPUP) {
browser = Browser::CreateForType(TYPE_POPUP, profile_);
}
BrowserWindow* new_window = browser->window();
new_window->SetBounds(gfx::Rect(new_window->GetRestoredBounds().origin(),
window()->GetRestoredBounds().size()));
browser->window()->Show();
browser->AddTab(contents_dupe, PageTransition::LINK);
}
if (profile_->HasSessionService()) {
SessionService* session_service = profile_->GetSessionService();
if (session_service)
session_service->TabRestored(&new_contents->controller(), pinned);
}
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void cliRefreshPrompt(void) {
int len;
if (config.eval_ldb) return;
if (config.hostsocket != NULL)
len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
config.hostsocket);
else
len = anetFormatAddr(config.prompt, sizeof(config.prompt),
config.hostip, config.hostport);
/* Add [dbnum] if needed */
if (config.dbnum != 0)
len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
config.dbnum);
snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
}
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: XSharedMemoryId AttachSharedMemory(Display* display, int shared_memory_key) {
DCHECK(QuerySharedMemorySupport(display));
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shared_memory_key;
if (!XShmAttach(display, &shminfo))
NOTREACHED();
return shminfo.shmseg;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void bf_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct bf_ctx *ctx = crypto_tfm_ctx(tfm);
const __be32 *in_blk = (const __be32 *)src;
__be32 *const out_blk = (__be32 *)dst;
const u32 *P = ctx->p;
const u32 *S = ctx->s;
u32 yl = be32_to_cpu(in_blk[0]);
u32 yr = be32_to_cpu(in_blk[1]);
ROUND(yr, yl, 17);
ROUND(yl, yr, 16);
ROUND(yr, yl, 15);
ROUND(yl, yr, 14);
ROUND(yr, yl, 13);
ROUND(yl, yr, 12);
ROUND(yr, yl, 11);
ROUND(yl, yr, 10);
ROUND(yr, yl, 9);
ROUND(yl, yr, 8);
ROUND(yr, yl, 7);
ROUND(yl, yr, 6);
ROUND(yr, yl, 5);
ROUND(yl, yr, 4);
ROUND(yr, yl, 3);
ROUND(yl, yr, 2);
yl ^= P[1];
yr ^= P[0];
out_blk[0] = cpu_to_be32(yr);
out_blk[1] = cpu_to_be32(yl);
}
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 MediaControlPanelElement::didBecomeVisible() {
DCHECK(m_isDisplayed && m_opaque);
mediaElement().mediaControlsDidBecomeVisible();
}
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 nick_hash_remove(CHANNEL_REC *channel, NICK_REC *nick)
{
NICK_REC *list;
list = g_hash_table_lookup(channel->nicks, nick->nick);
if (list == NULL)
return;
if (list == nick || list->next == NULL) {
g_hash_table_remove(channel->nicks, nick->nick);
if (list->next != NULL) {
g_hash_table_insert(channel->nicks, nick->next->nick,
nick->next);
}
} else {
while (list->next != nick)
list = list->next;
list->next = nick->next;
}
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: update_person(person_t* person, bool* out_has_moved)
{
struct command command;
double delta_x, delta_y;
int facing;
bool has_moved;
bool is_finished;
const person_t* last_person;
struct step step;
int vector;
int i;
person->mv_x = 0; person->mv_y = 0;
if (person->revert_frames > 0 && --person->revert_frames <= 0)
person->frame = 0;
if (person->leader == NULL) { // no leader; use command queue
if (person->num_commands == 0)
person_activate(person, PERSON_SCRIPT_GENERATOR, NULL, true);
is_finished = !does_person_exist(person) || person->num_commands == 0;
while (!is_finished) {
command = person->commands[0];
--person->num_commands;
for (i = 0; i < person->num_commands; ++i)
person->commands[i] = person->commands[i + 1];
last_person = s_current_person;
s_current_person = person;
if (command.type != COMMAND_RUN_SCRIPT)
command_person(person, command.type);
else
script_run(command.script, false);
s_current_person = last_person;
script_unref(command.script);
is_finished = !does_person_exist(person) // stop if person was destroyed
|| !command.is_immediate || person->num_commands == 0;
}
}
else { // leader set; follow the leader!
step = person->leader->steps[person->follow_distance - 1];
delta_x = step.x - person->x;
delta_y = step.y - person->y;
if (fabs(delta_x) > person->speed_x)
command_person(person, delta_x > 0 ? COMMAND_MOVE_EAST : COMMAND_MOVE_WEST);
if (!does_person_exist(person)) return;
if (fabs(delta_y) > person->speed_y)
command_person(person, delta_y > 0 ? COMMAND_MOVE_SOUTH : COMMAND_MOVE_NORTH);
if (!does_person_exist(person)) return;
vector = person->mv_x + person->mv_y * 3;
facing = vector == -3 ? COMMAND_FACE_NORTH
: vector == -2 ? COMMAND_FACE_NORTHEAST
: vector == 1 ? COMMAND_FACE_EAST
: vector == 4 ? COMMAND_FACE_SOUTHEAST
: vector == 3 ? COMMAND_FACE_SOUTH
: vector == 2 ? COMMAND_FACE_SOUTHWEST
: vector == -1 ? COMMAND_FACE_WEST
: vector == -4 ? COMMAND_FACE_NORTHWEST
: COMMAND_WAIT;
if (facing != COMMAND_WAIT)
command_person(person, COMMAND_ANIMATE);
if (!does_person_exist(person)) return;
command_person(person, facing);
}
if (!does_person_exist(person))
return; // they probably got eaten by a pig.
*out_has_moved = person_has_moved(person);
if (*out_has_moved)
record_step(person);
for (i = 0; i < s_num_persons; ++i) {
if (s_persons[i]->leader != person)
continue;
update_person(s_persons[i], &has_moved);
*out_has_moved |= has_moved;
}
}
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: MultibufferDataSource::Preload preload() { return data_source_->preload_; }
CWE ID: CWE-732
Output: | 0 |
Here are some example code snippets. Analyze the following 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 readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight)
{
uch sig[8];
/* first do a quick check that the file really is a PNG image; could
* have used slightly more general png_sig_cmp() function instead */
fread(sig, 1, 8, infile);
if (png_sig_cmp(sig, 0, 8))
return 1; /* bad signature */
/* could pass pointers to user-defined error handlers instead of NULLs: */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, NULL, NULL);
return 4; /* out of memory */
}
/* we could create a second info struct here (end_info), but it's only
* useful if we want to keep pre- and post-IDAT chunk info separated
* (mainly for PNG-aware image editors and converters) */
/* setjmp() must be called in every function that calls a PNG-reading
* libpng function */
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return 2;
}
png_init_io(png_ptr, infile);
png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */
png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */
/* alternatively, could make separate calls to png_get_image_width(),
* etc., but want bit_depth and color_type for later [don't care about
* compression_type and filter_type => NULLs] */
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
NULL, NULL, NULL);
*pWidth = width;
*pHeight = height;
/* OK, that's all we need for now; return happy */
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: NuPlayer::GenericSource::~GenericSource() {
if (mLooper != NULL) {
mLooper->unregisterHandler(id());
mLooper->stop();
}
}
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: ShelfLayoutManager::AutoHideEventFilter::~AutoHideEventFilter() {
Shell::GetInstance()->RemoveEnvEventFilter(this);
}
CWE ID: CWE-119
Output: | 0 |
Subsets and Splits