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 int write_empty_blocks(struct page *page, unsigned from, unsigned to,
int mode)
{
struct inode *inode = page->mapping->host;
unsigned start, end, next, blksize;
sector_t block = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
int ret;
blksize = 1 << inode->i_blkbits;
next = end = 0;
while (next < from) {
next += blksize;
block++;
}
start = next;
do {
next += blksize;
ret = needs_empty_write(block, inode);
if (unlikely(ret < 0))
return ret;
if (ret == 0) {
if (end) {
ret = __block_write_begin(page, start, end - start,
gfs2_block_map);
if (unlikely(ret))
return ret;
ret = empty_write_end(page, start, end, mode);
if (unlikely(ret))
return ret;
end = 0;
}
start = next;
}
else
end = next;
block++;
} while (next < to);
if (end) {
ret = __block_write_begin(page, start, end - start, gfs2_block_map);
if (unlikely(ret))
return ret;
ret = empty_write_end(page, start, end, mode);
if (unlikely(ret))
return ret;
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);}
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: define_function(match)
{
return_integer(yr_re_match(regexp_argument(1), string_argument(2)));
}
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: BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name)
: PluginInfoBarDelegate(tab_contents, utf16_name) {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer"));
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool PostScript_CheckFormat ( XMP_FileFormat format,
XMP_StringPtr filePath,
XMP_IO* fileRef,
XMPFiles * parent )
{
IgnoreParam(filePath); IgnoreParam(parent);
XMP_Assert ( (format == kXMP_EPSFile) || (format == kXMP_PostScriptFile) );
return PostScript_Support::IsValidPSFile(fileRef,format) ;
} // PostScript_CheckFormat
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int queue_pages_hugetlb(pte_t *pte, unsigned long hmask,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
#ifdef CONFIG_HUGETLB_PAGE
struct queue_pages *qp = walk->private;
unsigned long flags = qp->flags;
int nid;
struct page *page;
spinlock_t *ptl;
pte_t entry;
ptl = huge_pte_lock(hstate_vma(walk->vma), walk->mm, pte);
entry = huge_ptep_get(pte);
if (!pte_present(entry))
goto unlock;
page = pte_page(entry);
nid = page_to_nid(page);
if (node_isset(nid, *qp->nmask) == !!(flags & MPOL_MF_INVERT))
goto unlock;
/* With MPOL_MF_MOVE, we migrate only unshared hugepage. */
if (flags & (MPOL_MF_MOVE_ALL) ||
(flags & MPOL_MF_MOVE && page_mapcount(page) == 1))
isolate_huge_page(page, qp->pagelist);
unlock:
spin_unlock(ptl);
#else
BUG();
#endif
return 0;
}
CWE ID: CWE-388
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: header_put_marker (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4)
{ psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_marker */
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void request_key_auth_free_preparse(struct key_preparsed_payload *prep)
{
}
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 RTCSessionDescriptionRequestImpl::clear()
{
m_successCallback.clear();
m_errorCallback.clear();
}
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: gss_context_time (minor_status,
context_handle,
time_rec)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
OM_uint32 * time_rec;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
if (minor_status == NULL)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
*minor_status = 0;
if (time_rec == NULL)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
if (context_handle == GSS_C_NO_CONTEXT)
return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_context_time) {
status = mech->gss_context_time(
minor_status,
ctx->internal_ctx_id,
time_rec);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
return (GSS_S_BAD_MECH);
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: static bool ima_match_rules(struct ima_measure_rule_entry *rule,
struct inode *inode, enum ima_hooks func, int mask)
{
struct task_struct *tsk = current;
int i;
if ((rule->flags & IMA_FUNC) && rule->func != func)
return false;
if ((rule->flags & IMA_MASK) && rule->mask != mask)
return false;
if ((rule->flags & IMA_FSMAGIC)
&& rule->fsmagic != inode->i_sb->s_magic)
return false;
if ((rule->flags & IMA_UID) && rule->uid != tsk->cred->uid)
return false;
for (i = 0; i < MAX_LSM_RULES; i++) {
int rc = 0;
u32 osid, sid;
if (!rule->lsm[i].rule)
continue;
switch (i) {
case LSM_OBJ_USER:
case LSM_OBJ_ROLE:
case LSM_OBJ_TYPE:
security_inode_getsecid(inode, &osid);
rc = security_filter_rule_match(osid,
rule->lsm[i].type,
Audit_equal,
rule->lsm[i].rule,
NULL);
break;
case LSM_SUBJ_USER:
case LSM_SUBJ_ROLE:
case LSM_SUBJ_TYPE:
security_task_getsecid(tsk, &sid);
rc = security_filter_rule_match(sid,
rule->lsm[i].type,
Audit_equal,
rule->lsm[i].rule,
NULL);
default:
break;
}
if (!rc)
return false;
}
return true;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ScopedTextureBinder::~ScopedTextureBinder() {
ScopedGLErrorSuppressor suppressor(
"ScopedTextureBinder::dtor", state_->GetErrorState());
RestoreCurrentTextureBindings(state_, target_);
}
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: image_transform_png_set_tRNS_to_alpha_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_tRNS_to_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
CWE ID:
Target: 1
Example 2:
Code: UsbTransferStatus status() const { return status_; }
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void pdf_run_gs_end(fz_context *ctx, pdf_processor *proc)
{
}
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: Response StorageHandler::UntrackCacheStorageForOrigin(
const std::string& origin) {
if (!process_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&CacheStorageObserver::UntrackOriginOnIOThread,
base::Unretained(GetCacheStorageObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool IsSigninFrameClientCertUserSelectionEnabled() {
return !base::CommandLine::ForCurrentProcess()->HasSwitch(
kDisableSigninFrameClientCertUserSelection);
}
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: LinearHistogram::LinearHistogram(const std::string& name,
Sample minimum,
Sample maximum,
const BucketRanges* ranges,
HistogramBase::AtomicCount* counts,
HistogramBase::AtomicCount* logged_counts,
uint32_t counts_size,
HistogramSamples::Metadata* meta,
HistogramSamples::Metadata* logged_meta)
: Histogram(name, minimum, maximum, ranges, counts, logged_counts,
counts_size, meta, logged_meta) {}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: MirrorMockURLRequestJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const base::FilePath& file_path,
ReportResponseHeadersOnUI report_on_ui)
: net::URLRequestMockHTTPJob(request, network_delegate, file_path),
report_on_ui_(report_on_ui) {}
CWE ID:
Target: 1
Example 2:
Code: void FileSystemOperation::DidGetMetadata(
const GetMetadataCallback& callback,
base::PlatformFileError rv,
const base::PlatformFileInfo& file_info,
const FilePath& platform_path) {
callback.Run(rv, file_info, platform_path);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int get_sda(void)
{
return qrio_get_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1);
}
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 is_rndis(USBNetState *s)
{
return s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE;
}
CWE ID:
Target: 1
Example 2:
Code: void initialize() { admin = config = NULL; }
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGL2RenderingContextBase::clearBufferiv(GLenum buffer,
GLint drawbuffer,
const Vector<GLint>& value,
GLuint src_offset) {
if (isContextLost() ||
!ValidateClearBuffer("clearBufferiv", buffer, value.size(), src_offset))
return;
ScopedRGBEmulationColorMask emulation_color_mask(this, color_mask_,
drawing_buffer_.get());
ContextGL()->ClearBufferiv(buffer, drawbuffer, value.data() + src_offset);
UpdateBuffersToAutoClear(kClearBufferiv, buffer, drawbuffer);
}
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 WarmupURLFetcher::FetchWarmupURLNow(
const DataReductionProxyServer& proxy_server) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
UMA_HISTOGRAM_EXACT_LINEAR("DataReductionProxy.WarmupURL.FetchInitiated", 1,
2);
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("data_reduction_proxy_warmup", R"(
semantics {
sender: "Data Reduction Proxy"
description:
"Sends a request to the Data Reduction Proxy server to warm up "
"the connection to the proxy."
trigger:
"A network change while the data reduction proxy is enabled will "
"trigger this request."
data: "A specific URL, not related to user data."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users can control Data Saver on Android via the 'Data Saver' "
"setting. Data Saver is not available on iOS, and on desktop it "
"is enabled by installing the Data Saver extension."
policy_exception_justification: "Not implemented."
})");
GURL warmup_url_with_query_params;
GetWarmupURLWithQueryParam(&warmup_url_with_query_params);
url_loader_.reset();
fetch_timeout_timer_.Stop();
is_fetch_in_flight_ = true;
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = warmup_url_with_query_params;
resource_request->load_flags = net::LOAD_BYPASS_CACHE;
resource_request->render_frame_id = MSG_ROUTING_CONTROL;
url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
traffic_annotation);
static const int kMaxRetries = 5;
url_loader_->SetRetryOptions(
kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE);
url_loader_->SetAllowHttpErrorResults(true);
fetch_timeout_timer_.Start(FROM_HERE, GetFetchTimeout(), this,
&WarmupURLFetcher::OnFetchTimeout);
url_loader_->SetOnResponseStartedCallback(base::BindOnce(
&WarmupURLFetcher::OnURLLoadResponseStarted, base::Unretained(this)));
url_loader_->SetOnRedirectCallback(base::BindRepeating(
&WarmupURLFetcher::OnURLLoaderRedirect, base::Unretained(this)));
url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
GetNetworkServiceURLLoaderFactory(proxy_server),
base::BindOnce(&WarmupURLFetcher::OnURLLoadComplete,
base::Unretained(this)));
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: iakerb_gss_verify_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_buffer_t msg_buffer, gss_buffer_t token_buffer,
gss_qop_t *qop_state)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_verify_mic(minor_status, ctx->gssc, msg_buffer,
token_buffer, qop_state);
}
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: GpuProcessHost::SurfaceRef::SurfaceRef(gfx::PluginWindowHandle surface)
: surface_(surface) {
GtkNativeViewManager* manager = GtkNativeViewManager::GetInstance();
if (!manager->AddRefPermanentXID(surface_)) {
LOG(ERROR) << "Surface " << surface << " cannot be referenced.";
}
}
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 jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride,
int parity)
{
int bufsize = JPC_CEILDIVPOW2(numrows, 1);
jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE];
jpc_fix_t *buf = splitbuf;
register jpc_fix_t *srcptr;
register jpc_fix_t *dstptr;
register int n;
register 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) {
*dstptr = *srcptr;
++dstptr;
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) {
*dstptr = *srcptr;
dstptr += stride;
srcptr += stride << 1;
}
/* Copy the saved samples into the highpass channel. */
dstptr = &a[hstartcol * stride];
srcptr = buf;
n = m;
while (n-- > 0) {
*dstptr = *srcptr;
dstptr += stride;
++srcptr;
}
}
/* 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: double GetFrameDeviceScaleFactor(const ToRenderFrameHost& adapter) {
return EvalJs(adapter, "window.devicePixelRatio;").ExtractDouble();
}
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: sd2_parse_rsrc_fork (SF_PRIVATE *psf)
{ SD2_RSRC rsrc ;
int k, marker, error = 0 ;
psf_use_rsrc (psf, SF_TRUE) ;
memset (&rsrc, 0, sizeof (rsrc)) ;
rsrc.rsrc_len = psf_get_filelen (psf) ;
psf_log_printf (psf, "Resource length : %d (0x%04X)\n", rsrc.rsrc_len, rsrc.rsrc_len) ;
if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header))
{ rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ;
rsrc.need_to_free_rsrc_data = SF_TRUE ;
}
else
{
rsrc.rsrc_data = psf->header ;
rsrc.need_to_free_rsrc_data = SF_FALSE ;
} ;
/* Read in the whole lot. */
psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ;
/* Reset the header storage because we have changed to the rsrcdes. */
psf->headindex = psf->headend = rsrc.rsrc_len ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0) ;
rsrc.map_offset = read_rsrc_int (&rsrc, 4) ;
rsrc.data_length = read_rsrc_int (&rsrc, 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 12) ;
if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000)
{ psf_log_printf (psf, "Trying offset of 0x52 bytes.\n") ;
rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ;
rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ;
rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ;
rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ;
} ;
psf_log_printf (psf, " data offset : 0x%04X\n map offset : 0x%04X\n"
" data length : 0x%04X\n map length : 0x%04X\n",
rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ;
if (rsrc.data_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_offset (%d, 0x%x) > len\n", rsrc.data_offset, rsrc.data_offset) ;
error = SFE_SD2_BAD_DATA_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_offset > len\n") ;
error = SFE_SD2_BAD_MAP_OFFSET ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.data_length > len\n") ;
error = SFE_SD2_BAD_DATA_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_length > rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : rsrc.map_length > len\n") ;
error = SFE_SD2_BAD_MAP_LENGTH ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len)
{ psf_log_printf (psf, "Error : This does not look like a MacOSX resource fork.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
if (rsrc.map_offset + 28 >= rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad map offset (%d + 28 > %d).\n", rsrc.map_offset, rsrc.rsrc_len) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ;
if (rsrc.string_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad string offset (%d).\n", rsrc.string_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.type_offset = rsrc.map_offset + 30 ;
rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ;
if (rsrc.type_count < 1)
{ psf_log_printf (psf, "Bad type count.\n") ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ;
if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len)
{ psf_log_printf (psf, "Bad item offset (%d).\n", rsrc.item_offset) ;
error = SFE_SD2_BAD_RSRC ;
goto parse_rsrc_fork_cleanup ;
} ;
rsrc.str_index = -1 ;
for (k = 0 ; k < rsrc.type_count ; k ++)
{ marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ;
if (marker == STR_MARKER)
{ rsrc.str_index = k ;
rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ;
error = parse_str_rsrc (psf, &rsrc) ;
goto parse_rsrc_fork_cleanup ;
} ;
} ;
psf_log_printf (psf, "No 'STR ' resource.\n") ;
error = SFE_SD2_BAD_RSRC ;
parse_rsrc_fork_cleanup :
psf_use_rsrc (psf, SF_FALSE) ;
if (rsrc.need_to_free_rsrc_data)
free (rsrc.rsrc_data) ;
return error ;
} /* sd2_parse_rsrc_fork */
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: txid_current_snapshot(PG_FUNCTION_ARGS)
{
TxidSnapshot *snap;
uint32 nxip,
i,
size;
TxidEpoch state;
Snapshot cur;
cur = GetActiveSnapshot();
if (cur == NULL)
elog(ERROR, "no active snapshot set");
load_xid_epoch(&state);
/* allocate */
nxip = cur->xcnt;
size = TXID_SNAPSHOT_SIZE(nxip);
snap = palloc(size);
SET_VARSIZE(snap, size);
/* fill */
snap->xmin = convert_xid(cur->xmin, &state);
snap->xmax = convert_xid(cur->xmax, &state);
snap->nxip = nxip;
for (i = 0; i < nxip; i++)
snap->xip[i] = convert_xid(cur->xip[i], &state);
/* we want them guaranteed to be in ascending order */
sort_snapshot(snap);
PG_RETURN_POINTER(snap);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: unsigned long long task_sched_runtime(struct task_struct *p)
{
unsigned long flags;
struct rq *rq;
u64 ns = 0;
#if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
/*
* 64-bit doesn't need locks to atomically read a 64bit value.
* So we have a optimization chance when the task's delta_exec is 0.
* Reading ->on_cpu is racy, but this is ok.
*
* If we race with it leaving cpu, we'll take a lock. So we're correct.
* If we race with it entering cpu, unaccounted time is 0. This is
* indistinguishable from the read occurring a few cycles earlier.
*/
if (!p->on_cpu)
return p->se.sum_exec_runtime;
#endif
rq = task_rq_lock(p, &flags);
ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
task_rq_unlock(rq, p, &flags);
return ns;
}
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: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_);
}
if (cfg_.ts_number_layers > 1) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_SVC, 1);
}
vpx_svc_layer_id_t layer_id = {0, 0};
layer_id.spatial_layer_id = 0;
frame_flags_ = SetFrameFlags(video->frame(), cfg_.ts_number_layers);
layer_id.temporal_layer_id = SetLayerId(video->frame(),
cfg_.ts_number_layers);
if (video->frame() > 0) {
encoder->Control(VP9E_SET_SVC_LAYER_ID, &layer_id);
}
}
const vpx_rational_t tb = video->timebase();
timebase_ = static_cast<double>(tb.num) / tb.den;
duration_ = 0;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void merge_param(HashTable *params, zval *zdata, zval ***current_param, zval ***current_args TSRMLS_DC)
{
zval **ptr, **zdata_ptr;
php_http_array_hashkey_t hkey = php_http_array_hashkey_init(0);
#if 0
{
zval tmp;
INIT_PZVAL_ARRAY(&tmp, params);
fprintf(stderr, "params = ");
zend_print_zval_r(&tmp, 1 TSRMLS_CC);
fprintf(stderr, "\n");
}
#endif
hkey.type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zdata), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL);
if ((hkey.type == HASH_KEY_IS_STRING && !zend_hash_exists(params, hkey.str, hkey.len))
|| (hkey.type == HASH_KEY_IS_LONG && !zend_hash_index_exists(params, hkey.num))
) {
zval *tmp, *arg, **args;
/* create the entry if it doesn't exist */
zend_hash_get_current_data(Z_ARRVAL_P(zdata), (void *) &ptr);
Z_ADDREF_PP(ptr);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(tmp, ZEND_STRS("value"), *ptr);
MAKE_STD_ZVAL(arg);
array_init(arg);
zend_hash_update(Z_ARRVAL_P(tmp), "arguments", sizeof("arguments"), (void *) &arg, sizeof(zval *), (void *) &args);
*current_args = args;
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_update(params, hkey.str, hkey.len, (void *) &tmp, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_index_update(params, hkey.num, (void *) &tmp, sizeof(zval *), (void *) &ptr);
}
} else {
/* merge */
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_find(params, hkey.str, hkey.len, (void *) &ptr);
} else {
zend_hash_index_find(params, hkey.num, (void *) &ptr);
}
zdata_ptr = &zdata;
if (Z_TYPE_PP(ptr) == IS_ARRAY
&& SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), "value", sizeof("value"), (void *) &ptr)
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &zdata_ptr)
) {
/*
* params = [arr => [value => [0 => 1]]]
* ^- ptr
* zdata = [arr => [0 => NULL]]
* ^- zdata_ptr
*/
zval **test_ptr;
while (Z_TYPE_PP(zdata_ptr) == IS_ARRAY
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &test_ptr)
) {
if (Z_TYPE_PP(test_ptr) == IS_ARRAY) {
/* now find key in ptr */
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
if (SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
} else {
if (SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(ptr), hkey.num, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else if (hkey.num) {
Z_ADDREF_PP(test_ptr);
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
}
} else {
/* this is the leaf */
Z_ADDREF_PP(test_ptr);
if (Z_TYPE_PP(ptr) != IS_ARRAY) {
zval_dtor(*ptr);
array_init(*ptr);
}
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else if (hkey.num) {
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
}
break;
}
}
}
}
/* bubble up */
while (Z_TYPE_PP(ptr) == IS_ARRAY && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(ptr), (void *) &ptr));
*current_param = ptr;
}
CWE ID: CWE-704
Target: 1
Example 2:
Code: static void PerWorldBindingsVoidMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
TestObject* impl = V8TestObject::ToImpl(info.Holder());
impl->perWorldBindingsVoidMethod();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void fb_set_logo_directpalette(struct fb_info *info,
const struct linux_logo *logo,
u32 *palette)
{
int redshift, greenshift, blueshift;
int i;
redshift = info->var.red.offset;
greenshift = info->var.green.offset;
blueshift = info->var.blue.offset;
for (i = 32; i < 32 + logo->clutsize; i++)
palette[i] = i << redshift | i << greenshift | i << blueshift;
}
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: bool FileBrowserPrivateGetShareUrlFunction::RunAsync() {
using extensions::api::file_browser_private::GetShareUrl::Params;
const scoped_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
const base::FilePath path = file_manager::util::GetLocalPathFromURL(
render_view_host(), GetProfile(), GURL(params->url));
DCHECK(drive::util::IsUnderDriveMountPoint(path));
const base::FilePath drive_path = drive::util::ExtractDrivePath(path);
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) {
return false;
}
file_system->GetShareUrl(
drive_path,
file_manager::util::GetFileManagerBaseUrl(), // embed origin
base::Bind(&FileBrowserPrivateGetShareUrlFunction::OnGetShareUrl, this));
return true;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int tcp4_seq_show(struct seq_file *seq, void *v)
{
struct tcp_iter_state *st;
struct sock *sk = v;
seq_setwidth(seq, TMPSZ - 1);
if (v == SEQ_START_TOKEN) {
seq_puts(seq, " sl local_address rem_address st tx_queue "
"rx_queue tr tm->when retrnsmt uid timeout "
"inode");
goto out;
}
st = seq->private;
if (sk->sk_state == TCP_TIME_WAIT)
get_timewait4_sock(v, seq, st->num);
else if (sk->sk_state == TCP_NEW_SYN_RECV)
get_openreq4(v, seq, st->num);
else
get_tcp4_sock(v, seq, st->num);
out:
seq_pad(seq, '\n');
return 0;
}
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: transform_test(png_modifier *pmIn, PNG_CONST png_uint_32 idIn,
PNG_CONST image_transform* transform_listIn, PNG_CONST char * volatile name)
{
transform_display d;
context(&pmIn->this, fault);
transform_display_init(&d, pmIn, idIn, transform_listIn);
Try
{
size_t pos = 0;
png_structp pp;
png_infop pi;
char full_name[256];
/* Make sure the encoding fields are correct and enter the required
* modifications.
*/
transform_set_encoding(&d);
/* Add any modifications required by the transform list. */
d.transform_list->ini(d.transform_list, &d);
/* Add the color space information, if any, to the name. */
pos = safecat(full_name, sizeof full_name, pos, name);
pos = safecat_current_encoding(full_name, sizeof full_name, pos, d.pm);
/* Get a png_struct for reading the image. */
pp = set_modifier_for_read(d.pm, &pi, d.this.id, full_name);
standard_palette_init(&d.this);
# if 0
/* Logging (debugging only) */
{
char buffer[256];
(void)store_message(&d.pm->this, pp, buffer, sizeof buffer, 0,
"running test");
fprintf(stderr, "%s\n", buffer);
}
# endif
/* Introduce the correct read function. */
if (d.pm->this.progressive)
{
/* Share the row function with the standard implementation. */
png_set_progressive_read_fn(pp, &d, transform_info, progressive_row,
transform_end);
/* Now feed data into the reader until we reach the end: */
modifier_progressive_read(d.pm, pp, pi);
}
else
{
/* modifier_read expects a png_modifier* */
png_set_read_fn(pp, d.pm, modifier_read);
/* Check the header values: */
png_read_info(pp, pi);
/* Process the 'info' requirements. Only one image is generated */
transform_info_imp(&d, pp, pi);
sequential_row(&d.this, pp, pi, -1, 0);
if (!d.this.speed)
transform_image_validate(&d, pp, pi);
else
d.this.ps->validated = 1;
}
modifier_reset(d.pm);
}
Catch(fault)
{
modifier_reset(voidcast(png_modifier*,(void*)fault));
}
}
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_enc_is_block_algorithm)
{
MCRYPT_GET_TD_ARG
if (mcrypt_enc_is_block_algorithm(pm->td) == 1) {
RETURN_TRUE
} else {
RETURN_FALSE
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
struct proto *prot)
{
struct sock *sk;
sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
if (sk) {
sk->sk_family = family;
/*
* See comment in struct sock definition to understand
* why we need sk_prot_creator -acme
*/
sk->sk_prot = sk->sk_prot_creator = prot;
sock_lock_init(sk);
sock_net_set(sk, get_net(net));
atomic_set(&sk->sk_wmem_alloc, 1);
sock_update_classid(sk);
sock_update_netprioidx(sk);
}
return sk;
}
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 RenderWidgetHostViewGuest::AcceleratedSurfaceNew(int32 width_in_pixel,
int32 height_in_pixel,
uint64 surface_handle) {
NOTIMPLEMENTED();
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderFrameImpl::DidAddMessageToConsole(
const blink::WebConsoleMessage& message,
const blink::WebString& source_name,
unsigned source_line,
const blink::WebString& stack_trace) {
logging::LogSeverity log_severity = logging::LOG_VERBOSE;
switch (message.level) {
case blink::mojom::ConsoleMessageLevel::kVerbose:
log_severity = logging::LOG_VERBOSE;
break;
case blink::mojom::ConsoleMessageLevel::kInfo:
log_severity = logging::LOG_INFO;
break;
case blink::mojom::ConsoleMessageLevel::kWarning:
log_severity = logging::LOG_WARNING;
break;
case blink::mojom::ConsoleMessageLevel::kError:
log_severity = logging::LOG_ERROR;
break;
default:
log_severity = logging::LOG_VERBOSE;
}
if (ShouldReportDetailedMessageForSource(source_name)) {
for (auto& observer : observers_) {
observer.DetailedConsoleMessageAdded(
message.text.Utf16(), source_name.Utf16(), stack_trace.Utf16(),
source_line, static_cast<uint32_t>(log_severity));
}
}
Send(new FrameHostMsg_DidAddMessageToConsole(
routing_id_, static_cast<int32_t>(log_severity), message.text.Utf16(),
static_cast<int32_t>(source_line), source_name.Utf16()));
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: ar6000_close(struct net_device *dev)
{
struct ar6_softc *ar = (struct ar6_softc *)ar6k_priv(dev);
netif_stop_queue(dev);
ar6000_disconnect(ar);
if(ar->arWmiReady == true) {
if (wmi_scanparams_cmd(ar->arWmi, 0xFFFF, 0,
0, 0, 0, 0, 0, 0, 0, 0) != 0) {
return -EIO;
}
ar->arWlanState = WLAN_DISABLED;
}
ar6k_cfg80211_scanComplete_event(ar, A_ECANCELED);
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: BOOL ValidateIOBufferSize (PIRP irp, size_t requiredBufferSize, ValidateIOBufferSizeType type)
{
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (irp);
BOOL input = (type == ValidateInput || type == ValidateInputOutput);
BOOL output = (type == ValidateOutput || type == ValidateInputOutput);
if ((input && irpSp->Parameters.DeviceIoControl.InputBufferLength < requiredBufferSize)
|| (output && irpSp->Parameters.DeviceIoControl.OutputBufferLength < requiredBufferSize))
{
Dump ("STATUS_BUFFER_TOO_SMALL ioctl=0x%x,%d in=%d out=%d reqsize=%d insize=%d outsize=%d\n", (int) (irpSp->Parameters.DeviceIoControl.IoControlCode >> 16), (int) ((irpSp->Parameters.DeviceIoControl.IoControlCode & 0x1FFF) >> 2), input, output, requiredBufferSize, irpSp->Parameters.DeviceIoControl.InputBufferLength, irpSp->Parameters.DeviceIoControl.OutputBufferLength);
irp->IoStatus.Status = STATUS_BUFFER_TOO_SMALL;
irp->IoStatus.Information = 0;
return FALSE;
}
if (!input && output)
memset (irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength);
return TRUE;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: LayoutUnit RenderBox::availableLogicalHeightUsing(const Length& h) const
{
if (h.isFixed())
return computeContentBoxLogicalHeight(h.value());
if (isRenderView())
return isHorizontalWritingMode() ? toRenderView(this)->frameView()->visibleHeight() : toRenderView(this)->frameView()->visibleWidth();
if (isTableCell() && (h.isAuto() || h.isPercent()))
return overrideHeight() - borderAndPaddingLogicalWidth();
if (h.isPercent())
return computeContentBoxLogicalHeight(h.calcValue(containingBlock()->availableLogicalHeight()));
if (isRenderBlock() && isPositioned() && style()->height().isAuto() && !(style()->top().isAuto() || style()->bottom().isAuto())) {
RenderBlock* block = const_cast<RenderBlock*>(toRenderBlock(this));
LayoutUnit oldHeight = block->logicalHeight();
block->computeLogicalHeight();
LayoutUnit newHeight = block->computeContentBoxLogicalHeight(block->contentLogicalHeight());
block->setLogicalHeight(oldHeight);
return computeContentBoxLogicalHeight(newHeight);
}
return containingBlock()->availableLogicalHeight();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: testing::AssertionResult ExtensionTabsZoomTest::RunGetZoom(
int tab_id,
double* zoom_factor) {
scoped_refptr<TabsGetZoomFunction> get_zoom_function(
new TabsGetZoomFunction());
get_zoom_function->set_extension(extension_.get());
get_zoom_function->set_has_callback(true);
std::unique_ptr<base::Value> get_zoom_result(
utils::RunFunctionAndReturnSingleResult(
get_zoom_function.get(), base::StringPrintf("[%u]", tab_id),
browser()));
if (!get_zoom_result)
return testing::AssertionFailure() << "no result";
if (!get_zoom_result->GetAsDouble(zoom_factor))
return testing::AssertionFailure() << "result was not a double";
return testing::AssertionSuccess();
}
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: menu_add_separator_image(WebKitWebView *page, GArray *argv, GString *result) {
(void) page;
(void) result;
add_separator_to_menu(argv, WEBKIT_HIT_TEST_RESULT_CONTEXT_IMAGE);
}
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: xmlParse3986Port(xmlURIPtr uri, const char **str)
{
const char *cur = *str;
unsigned port = 0; /* unsigned for defined overflow behavior */
if (ISA_DIGIT(cur)) {
while (ISA_DIGIT(cur)) {
port = port * 10 + (*cur - '0');
cur++;
}
if (uri != NULL)
uri->port = port & INT_MAX; /* port value modulo INT_MAX+1 */
*str = cur;
return(0);
}
return(1);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool UsbTabHelper::IsDeviceConnected() const {
for (const auto& map_entry : frame_usb_services_) {
if (map_entry.second->device_connection_count_ > 0)
return true;
}
return false;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void VerifyProcessIsForegrounded(WebContents* web_contents) {
constexpr bool kExpectedIsBackground = false;
VerifyProcessPriority(web_contents->GetMainFrame()->GetProcess(),
kExpectedIsBackground);
}
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: next_format(png_bytep colour_type, png_bytep bit_depth,
unsigned int* palette_number, int no_low_depth_gray)
{
if (*bit_depth == 0)
{
*colour_type = 0;
if (no_low_depth_gray)
*bit_depth = 8;
else
*bit_depth = 1;
*palette_number = 0;
return 1;
}
if (*colour_type == 3)
{
/* Add multiple palettes for colour type 3. */
if (++*palette_number < PALETTE_COUNT(*bit_depth))
return 1;
*palette_number = 0;
}
*bit_depth = (png_byte)(*bit_depth << 1);
/* Palette images are restricted to 8 bit depth */
if (*bit_depth <= 8
# ifdef DO_16BIT
|| (*colour_type != 3 && *bit_depth <= 16)
# endif
)
return 1;
/* Move to the next color type, or return 0 at the end. */
switch (*colour_type)
{
case 0:
*colour_type = 2;
*bit_depth = 8;
return 1;
case 2:
*colour_type = 3;
*bit_depth = 1;
return 1;
case 3:
*colour_type = 4;
*bit_depth = 8;
return 1;
case 4:
*colour_type = 6;
*bit_depth = 8;
return 1;
default:
return 0;
}
}
CWE ID:
Target: 1
Example 2:
Code: static inline zend_long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
zend_long elements;
if( *p >= max - 2) {
zend_error(E_WARNING, "Bad unserialize data");
return -1;
}
elements = parse_iv2((*p) + 2, p);
(*p) += 2;
if (ce->serialize == NULL) {
object_init_ex(rval, ce);
} else {
/* If this class implements Serializable, it should not land here but in object_custom(). The passed string
obviously doesn't descend from the regular serializer. */
zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ZSTR_VAL(ce->name));
return -1;
}
return elements;
}
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: GuestViewBase* ExtensionViewGuest::Create(WebContents* owner_web_contents) {
return new ExtensionViewGuest(owner_web_contents);
}
CWE ID: CWE-284
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool HTMLFormElement::prepareForSubmission(Event* event)
{
Frame* frame = document().frame();
if (m_isSubmittingOrPreparingForSubmission || !frame)
return m_isSubmittingOrPreparingForSubmission;
m_isSubmittingOrPreparingForSubmission = true;
m_shouldSubmit = false;
if (!validateInteractively(event)) {
m_isSubmittingOrPreparingForSubmission = false;
return false;
}
StringPairVector controlNamesAndValues;
getTextFieldValues(controlNamesAndValues);
RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), NotSubmittedByJavaScript);
frame->loader()->client()->dispatchWillSendSubmitEvent(formState.release());
if (dispatchEvent(Event::createCancelableBubble(eventNames().submitEvent)))
m_shouldSubmit = true;
m_isSubmittingOrPreparingForSubmission = false;
if (m_shouldSubmit)
submit(event, true, true, NotSubmittedByJavaScript);
return m_shouldSubmit;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void DownloadController::DangerousDownloadValidated(
WebContents* web_contents,
const std::string& download_guid,
bool accept) {
if (!web_contents)
return;
DownloadManager* dlm =
BrowserContext::GetDownloadManager(web_contents->GetBrowserContext());
DownloadItem* item = dlm->GetDownloadByGuid(download_guid);
if (!item)
return;
if (accept) {
item->ValidateDangerousDownload();
} else {
DownloadController::RecordDownloadCancelReason(
DownloadController::CANCEL_REASON_DANGEROUS_DOWNLOAD_INFOBAR_DISMISSED);
item->Remove();
}
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ax25_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
ax25_cb *ax25;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
switch (sock->type) {
case SOCK_DGRAM:
if (protocol == 0 || protocol == PF_AX25)
protocol = AX25_P_TEXT;
break;
case SOCK_SEQPACKET:
switch (protocol) {
case 0:
case PF_AX25: /* For CLX */
protocol = AX25_P_TEXT;
break;
case AX25_P_SEGMENT:
#ifdef CONFIG_INET
case AX25_P_ARP:
case AX25_P_IP:
#endif
#ifdef CONFIG_NETROM
case AX25_P_NETROM:
#endif
#ifdef CONFIG_ROSE
case AX25_P_ROSE:
#endif
return -ESOCKTNOSUPPORT;
#ifdef CONFIG_NETROM_MODULE
case AX25_P_NETROM:
if (ax25_protocol_is_registered(AX25_P_NETROM))
return -ESOCKTNOSUPPORT;
break;
#endif
#ifdef CONFIG_ROSE_MODULE
case AX25_P_ROSE:
if (ax25_protocol_is_registered(AX25_P_ROSE))
return -ESOCKTNOSUPPORT;
#endif
default:
break;
}
break;
case SOCK_RAW:
break;
default:
return -ESOCKTNOSUPPORT;
}
sk = sk_alloc(net, PF_AX25, GFP_ATOMIC, &ax25_proto, kern);
if (sk == NULL)
return -ENOMEM;
ax25 = ax25_sk(sk)->cb = ax25_create_cb();
if (!ax25) {
sk_free(sk);
return -ENOMEM;
}
sock_init_data(sock, sk);
sk->sk_destruct = ax25_free_sock;
sock->ops = &ax25_proto_ops;
sk->sk_protocol = protocol;
ax25->sk = sk;
return 0;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline void CopyPixels(PixelPacket *destination,
const PixelPacket *source,const MagickSizeType number_pixels)
{
#if !defined(MAGICKCORE_OPENMP_SUPPORT) || (MAGICKCORE_QUANTUM_DEPTH <= 8)
(void) memcpy(destination,source,(size_t) number_pixels*sizeof(*source));
#else
{
register MagickOffsetType
i;
if ((number_pixels*sizeof(*source)) < MagickMaxBufferExtent)
{
(void) memcpy(destination,source,(size_t) number_pixels*
sizeof(*source));
return;
}
#pragma omp parallel for
for (i=0; i < (MagickOffsetType) number_pixels; i++)
destination[i]=source[i];
}
#endif
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void MACH0_(kv_loadlibs)(struct MACH0_(obj_t)* bin) {
int i;
for (i = 0; i < bin->nlibs; i++) {
sdb_set (bin->kv, sdb_fmt ("libs.%d.name", i), bin->libs[i], 0);
}
}
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: WindowOpenDisposition TestBrowserWindow::GetDispositionForPopupBounds(
const gfx::Rect& bounds) {
return WindowOpenDisposition::NEW_POPUP;
}
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 key *construct_key_and_link(struct keyring_search_context *ctx,
const char *callout_info,
size_t callout_len,
void *aux,
struct key *dest_keyring,
unsigned long flags)
{
struct key_user *user;
struct key *key;
int ret;
kenter("");
user = key_user_lookup(current_fsuid());
if (!user)
return ERR_PTR(-ENOMEM);
construct_get_dest_keyring(&dest_keyring);
ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
key_user_put(user);
if (ret == 0) {
ret = construct_key(key, callout_info, callout_len, aux,
dest_keyring);
if (ret < 0) {
kdebug("cons failed");
goto construction_failed;
}
} else if (ret == -EINPROGRESS) {
ret = 0;
} else {
goto couldnt_alloc_key;
}
key_put(dest_keyring);
kleave(" = key %d", key_serial(key));
return key;
construction_failed:
key_negate_and_link(key, key_negative_timeout, NULL, NULL);
key_put(key);
couldnt_alloc_key:
key_put(dest_keyring);
kleave(" = %d", ret);
return ERR_PTR(ret);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void Com_WriteCDKey( const char *filename, const char *ikey ) {
fileHandle_t f;
char fbuffer[MAX_OSPATH];
char key[17];
#ifndef _WIN32
mode_t savedumask;
#endif
Com_sprintf(fbuffer, sizeof(fbuffer), "%s/rtcwkey", filename);
Q_strncpyz( key, ikey, 17 );
if ( !CL_CDKeyValidate( key, NULL ) ) {
return;
}
#ifndef _WIN32
savedumask = umask(0077);
#endif
f = FS_SV_FOpenFileWrite( fbuffer );
if ( !f ) {
Com_Printf ("Couldn't write CD key to %s.\n", fbuffer );
goto out;
}
FS_Write( key, 16, f );
FS_Printf( f, "\n// generated by RTCW, do not modify\r\n" );
FS_Printf( f, "// Do not give this file to ANYONE.\r\n" );
#ifdef __APPLE__
FS_Printf( f, "// Aspyr will NOT ask you to send this file to them.\r\n" );
#else
FS_Printf( f, "// id Software and Activision will NOT ask you to send this file to them.\r\n" );
#endif
FS_FCloseFile( f );
out:
#ifndef _WIN32
umask(savedumask);
#else
;
#endif
}
CWE ID: CWE-269
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void address_space_stl_internal(AddressSpace *as,
hwaddr addr, uint32_t val,
MemTxAttrs attrs,
MemTxResult *result,
enum device_endian endian)
{
uint8_t *ptr;
MemoryRegion *mr;
hwaddr l = 4;
hwaddr addr1;
MemTxResult r;
bool release_lock = false;
rcu_read_lock();
mr = address_space_translate(as, addr, &addr1, &l,
true);
if (l < 4 || !memory_access_is_direct(mr, true)) {
release_lock |= prepare_mmio_access(mr);
#if defined(TARGET_WORDS_BIGENDIAN)
if (endian == DEVICE_LITTLE_ENDIAN) {
val = bswap32(val);
}
#else
if (endian == DEVICE_BIG_ENDIAN) {
val = bswap32(val);
}
#endif
r = memory_region_dispatch_write(mr, addr1, val, 4, attrs);
} else {
/* RAM case */
addr1 += memory_region_get_ram_addr(mr) & TARGET_PAGE_MASK;
ptr = qemu_get_ram_ptr(addr1);
switch (endian) {
case DEVICE_LITTLE_ENDIAN:
stl_le_p(ptr, val);
break;
case DEVICE_BIG_ENDIAN:
stl_be_p(ptr, val);
break;
default:
stl_p(ptr, val);
break;
}
invalidate_and_set_dirty(mr, addr1, 4);
r = MEMTX_OK;
}
if (result) {
*result = r;
}
if (release_lock) {
qemu_mutex_unlock_iothread();
}
rcu_read_unlock();
}
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: PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
size_t dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, iter, iteriter, regexiter;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
if (SUCCESS != object_init_ex(&iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg, dir, dir_len);
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
zval_ptr_dtor(&arg);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
if (SUCCESS != object_init_ex(&iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, &iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
if (SUCCESS != object_init_ex(®exiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(®exiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate regex iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg2, regex, regex_len);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, &iteriter, &arg2);
zval_ptr_dtor(&arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE(regexiter) : Z_OBJCE(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" unable to create temporary file", phar_obj->archive->fname);
return;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? ®exiter : &iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->archive->ufp = pass.fp;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int decodeFlags(MemPage *pPage, int flagByte){
BtShared *pBt; /* A copy of pPage->pBt */
assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
assert( sqlite3_mutex_held(pPage->pBt->mutex) );
pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
flagByte &= ~PTF_LEAF;
pPage->childPtrSize = 4-4*pPage->leaf;
pPage->xCellSize = cellSizePtr;
pBt = pPage->pBt;
if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
/* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
** interior table b-tree page. */
assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
/* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
** leaf table b-tree page. */
assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
pPage->intKey = 1;
if( pPage->leaf ){
pPage->intKeyLeaf = 1;
pPage->xParseCell = btreeParseCellPtr;
}else{
pPage->intKeyLeaf = 0;
pPage->xCellSize = cellSizePtrNoPayload;
pPage->xParseCell = btreeParseCellPtrNoPayload;
}
pPage->maxLocal = pBt->maxLeaf;
pPage->minLocal = pBt->minLeaf;
}else if( flagByte==PTF_ZERODATA ){
/* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
** interior index b-tree page. */
assert( (PTF_ZERODATA)==2 );
/* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
** leaf index b-tree page. */
assert( (PTF_ZERODATA|PTF_LEAF)==10 );
pPage->intKey = 0;
pPage->intKeyLeaf = 0;
pPage->xParseCell = btreeParseCellPtrIndex;
pPage->maxLocal = pBt->maxLocal;
pPage->minLocal = pBt->minLocal;
}else{
/* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
** an error. */
return SQLITE_CORRUPT_PAGE(pPage);
}
pPage->max1bytePayload = pBt->max1bytePayload;
return SQLITE_OK;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DOMWindow::Trace(blink::Visitor* visitor) {
visitor->Trace(frame_);
visitor->Trace(window_proxy_manager_);
visitor->Trace(input_capabilities_);
visitor->Trace(location_);
EventTargetWithInlineData::Trace(visitor);
}
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: gamma_info_imp(gamma_display *dp, png_structp pp, png_infop pi)
{
/* Reuse the standard stuff as appropriate. */
standard_info_part1(&dp->this, pp, pi);
/* If requested strip 16 to 8 bits - this is handled automagically below
* because the output bit depth is read from the library. Note that there
* are interactions with sBIT but, internally, libpng makes sbit at most
* PNG_MAX_GAMMA_8 when doing the following.
*/
if (dp->scale16)
# ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
png_set_scale_16(pp);
# else
/* The following works both in 1.5.4 and earlier versions: */
# ifdef PNG_READ_16_TO_8_SUPPORTED
png_set_strip_16(pp);
# else
png_error(pp, "scale16 (16 to 8 bit conversion) not supported");
# endif
# endif
if (dp->expand16)
# ifdef PNG_READ_EXPAND_16_SUPPORTED
png_set_expand_16(pp);
# else
png_error(pp, "expand16 (8 to 16 bit conversion) not supported");
# endif
if (dp->do_background >= ALPHA_MODE_OFFSET)
{
# ifdef PNG_READ_ALPHA_MODE_SUPPORTED
{
/* This tests the alpha mode handling, if supported. */
int mode = dp->do_background - ALPHA_MODE_OFFSET;
/* The gamma value is the output gamma, and is in the standard,
* non-inverted, represenation. It provides a default for the PNG file
* gamma, but since the file has a gAMA chunk this does not matter.
*/
PNG_CONST double sg = dp->screen_gamma;
# ifndef PNG_FLOATING_POINT_SUPPORTED
PNG_CONST png_fixed_point g = fix(sg);
# endif
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_alpha_mode(pp, mode, sg);
# else
png_set_alpha_mode_fixed(pp, mode, g);
# endif
/* However, for the standard Porter-Duff algorithm the output defaults
* to be linear, so if the test requires non-linear output it must be
* corrected here.
*/
if (mode == PNG_ALPHA_STANDARD && sg != 1)
{
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_gamma(pp, sg, dp->file_gamma);
# else
png_fixed_point f = fix(dp->file_gamma);
png_set_gamma_fixed(pp, g, f);
# endif
}
}
# else
png_error(pp, "alpha mode handling not supported");
# endif
}
else
{
/* Set up gamma processing. */
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_gamma(pp, dp->screen_gamma, dp->file_gamma);
# else
{
png_fixed_point s = fix(dp->screen_gamma);
png_fixed_point f = fix(dp->file_gamma);
png_set_gamma_fixed(pp, s, f);
}
# endif
if (dp->do_background)
{
# ifdef PNG_READ_BACKGROUND_SUPPORTED
/* NOTE: this assumes the caller provided the correct background gamma!
*/
PNG_CONST double bg = dp->background_gamma;
# ifndef PNG_FLOATING_POINT_SUPPORTED
PNG_CONST png_fixed_point g = fix(bg);
# endif
# ifdef PNG_FLOATING_POINT_SUPPORTED
png_set_background(pp, &dp->background_color, dp->do_background,
0/*need_expand*/, bg);
# else
png_set_background_fixed(pp, &dp->background_color,
dp->do_background, 0/*need_expand*/, g);
# endif
# else
png_error(pp, "png_set_background not supported");
# endif
}
}
{
int i = dp->this.use_update_info;
/* Always do one call, even if use_update_info is 0. */
do
png_read_update_info(pp, pi);
while (--i > 0);
}
/* Now we may get a different cbRow: */
standard_info_part2(&dp->this, pp, pi, 1 /*images*/);
}
CWE ID:
Target: 1
Example 2:
Code: static int decode_attr_fs_locations(struct xdr_stream *xdr, uint32_t *bitmap, struct nfs4_fs_locations *res)
{
int n;
__be32 *p;
int status = -EIO;
if (unlikely(bitmap[0] & (FATTR4_WORD0_FS_LOCATIONS -1U)))
goto out;
status = 0;
if (unlikely(!(bitmap[0] & FATTR4_WORD0_FS_LOCATIONS)))
goto out;
dprintk("%s: fsroot ", __func__);
status = decode_pathname(xdr, &res->fs_path);
if (unlikely(status != 0))
goto out;
READ_BUF(4);
READ32(n);
if (n <= 0)
goto out_eio;
res->nlocations = 0;
while (res->nlocations < n) {
u32 m;
struct nfs4_fs_location *loc = &res->locations[res->nlocations];
READ_BUF(4);
READ32(m);
loc->nservers = 0;
dprintk("%s: servers ", __func__);
while (loc->nservers < m) {
struct nfs4_string *server = &loc->servers[loc->nservers];
status = decode_opaque_inline(xdr, &server->len, &server->data);
if (unlikely(status != 0))
goto out_eio;
dprintk("%s ", server->data);
if (loc->nservers < NFS4_FS_LOCATION_MAXSERVERS)
loc->nservers++;
else {
unsigned int i;
dprintk("%s: using first %u of %u servers "
"returned for location %u\n",
__func__,
NFS4_FS_LOCATION_MAXSERVERS,
m, res->nlocations);
for (i = loc->nservers; i < m; i++) {
unsigned int len;
char *data;
status = decode_opaque_inline(xdr, &len, &data);
if (unlikely(status != 0))
goto out_eio;
}
}
}
status = decode_pathname(xdr, &loc->rootpath);
if (unlikely(status != 0))
goto out_eio;
if (res->nlocations < NFS4_FS_LOCATIONS_MAXENTRIES)
res->nlocations++;
}
out:
dprintk("%s: fs_locations done, error = %d\n", __func__, status);
return status;
out_eio:
status = -EIO;
goto out;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd)
{
QXLDevSurfaceCreate surface;
memset(&surface, 0, sizeof(surface));
dprint(1, "%s/%d: %dx%d\n", __func__, ssd->qxl.id,
surface_width(ssd->ds), surface_height(ssd->ds));
surface.format = SPICE_SURFACE_FMT_32_xRGB;
surface.width = surface_width(ssd->ds);
{
dprint(1, "%s/%d:\n", __func__, ssd->qxl.id);
qemu_spice_destroy_primary_surface(ssd, 0, QXL_SYNC);
}
void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd)
{
qemu_mutex_init(&ssd->lock);
QTAILQ_INIT(&ssd->updates);
ssd->mouse_x = -1;
ssd->mouse_y = -1;
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
ssd->bufsize = (16 * 1024 * 1024);
ssd->buf = g_malloc(ssd->bufsize);
}
/* display listener callbacks */
void qemu_spice_display_update(SimpleSpiceDisplay *ssd,
int x, int y, int w, int h)
{
if (ssd->num_surfaces == 0) {
ssd->num_surfaces = 1024;
}
ssd->bufsize = (16 * 1024 * 1024);
ssd->buf = g_malloc(ssd->bufsize);
}
/* display listener callbacks */
update_area.top = y;
update_area.bottom = y + h;
if (qemu_spice_rect_is_empty(&ssd->dirty)) {
ssd->notify++;
}
qemu_spice_rect_union(&ssd->dirty, &update_area);
}
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: build_unc_path_to_root(const struct smb_vol *vol,
const struct cifs_sb_info *cifs_sb)
{
char *full_path, *pos;
unsigned int pplen = vol->prepath ? strlen(vol->prepath) + 1 : 0;
unsigned int unc_len = strnlen(vol->UNC, MAX_TREE_SIZE + 1);
full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
if (full_path == NULL)
return ERR_PTR(-ENOMEM);
strncpy(full_path, vol->UNC, unc_len);
pos = full_path + unc_len;
if (pplen) {
*pos++ = CIFS_DIR_SEP(cifs_sb);
strncpy(pos, vol->prepath, pplen);
pos += pplen;
}
*pos = '\0'; /* add trailing null */
convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
return full_path;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: OMX_ERRORTYPE SoftMPEG4Encoder::initEncParams() {
CHECK(mHandle != NULL);
memset(mHandle, 0, sizeof(tagvideoEncControls));
CHECK(mEncParams != NULL);
memset(mEncParams, 0, sizeof(tagvideoEncOptions));
if (!PVGetDefaultEncOption(mEncParams, 0)) {
ALOGE("Failed to get default encoding parameters");
return OMX_ErrorUndefined;
}
if (mVideoFrameRate == 0) {
ALOGE("Framerate should not be 0");
return OMX_ErrorUndefined;
}
mEncParams->encMode = mEncodeMode;
mEncParams->encWidth[0] = mVideoWidth;
mEncParams->encHeight[0] = mVideoHeight;
mEncParams->encFrameRate[0] = mVideoFrameRate;
mEncParams->rcType = VBR_1;
mEncParams->vbvDelay = 5.0f;
mEncParams->profile_level = CORE_PROFILE_LEVEL2;
mEncParams->packetSize = 32;
mEncParams->rvlcEnable = PV_OFF;
mEncParams->numLayers = 1;
mEncParams->timeIncRes = 1000;
mEncParams->tickPerSrc = mEncParams->timeIncRes / mVideoFrameRate;
mEncParams->bitRate[0] = mVideoBitRate;
mEncParams->iQuant[0] = 15;
mEncParams->pQuant[0] = 12;
mEncParams->quantType[0] = 0;
mEncParams->noFrameSkipped = PV_OFF;
if (mVideoColorFormat != OMX_COLOR_FormatYUV420Planar
|| mStoreMetaDataInBuffers) {
free(mInputFrameData);
mInputFrameData = NULL;
if (((uint64_t)mVideoWidth * mVideoHeight) > ((uint64_t)INT32_MAX / 3)) {
ALOGE("b/25812794, Buffer size is too big.");
return OMX_ErrorBadParameter;
}
mInputFrameData =
(uint8_t *) malloc((mVideoWidth * mVideoHeight * 3 ) >> 1);
CHECK(mInputFrameData != NULL);
}
if (mVideoWidth % 16 != 0 || mVideoHeight % 16 != 0) {
ALOGE("Video frame size %dx%d must be a multiple of 16",
mVideoWidth, mVideoHeight);
return OMX_ErrorBadParameter;
}
if (mIDRFrameRefreshIntervalInSec < 0) {
mEncParams->intraPeriod = -1;
} else if (mIDRFrameRefreshIntervalInSec == 0) {
mEncParams->intraPeriod = 1; // All I frames
} else {
mEncParams->intraPeriod =
(mIDRFrameRefreshIntervalInSec * mVideoFrameRate);
}
mEncParams->numIntraMB = 0;
mEncParams->sceneDetect = PV_ON;
mEncParams->searchRange = 16;
mEncParams->mv8x8Enable = PV_OFF;
mEncParams->gobHeaderInterval = 0;
mEncParams->useACPred = PV_ON;
mEncParams->intraDCVlcTh = 0;
return OMX_ErrorNone;
}
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 ecc_check_privkey_gen_helper(ecc_key* key)
{
int err;
#ifndef WOLFSSL_ATECC508A
DECLARE_CURVE_SPECS(2)
#endif
if (key == NULL)
return BAD_FUNC_ARG;
#ifdef WOLFSSL_ATECC508A
/* TODO: Implement equiv call to ATECC508A */
err = BAD_COND_E;
#else
/* load curve info */
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF));
if (err == MP_OKAY)
err = ecc_check_privkey_gen(key, curve->Af, curve->prime);
wc_ecc_curve_free(curve);
#endif /* WOLFSSL_ATECC508A */
return err;
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Con_Dump_f( void ) {
int l, x, i;
short *line;
fileHandle_t f;
int bufferlen;
char *buffer;
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "usage: condump <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".txt" );
f = FS_FOpenFileWrite( filename );
if ( !f ) {
Com_Printf ("ERROR: couldn't open %s.\n", filename);
return;
}
Com_Printf ("Dumped console text to %s.\n", filename );
for ( l = con.current - con.totallines + 1 ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( x = 0 ; x < con.linewidth ; x++ )
if ( ( line[x] & 0xff ) != ' ' ) {
break;
}
if ( x != con.linewidth ) {
break;
}
}
#ifdef _WIN32
bufferlen = con.linewidth + 3 * sizeof ( char );
#else
bufferlen = con.linewidth + 2 * sizeof ( char );
#endif
buffer = Hunk_AllocateTempMemory( bufferlen );
buffer[bufferlen-1] = 0;
for ( ; l <= con.current ; l++ )
{
line = con.text + ( l % con.totallines ) * con.linewidth;
for ( i = 0; i < con.linewidth; i++ )
buffer[i] = line[i] & 0xff;
for ( x = con.linewidth - 1 ; x >= 0 ; x-- )
{
if ( buffer[x] == ' ' ) {
buffer[x] = 0;
} else {
break;
}
}
#ifdef _WIN32
Q_strcat(buffer, bufferlen, "\r\n");
#else
Q_strcat(buffer, bufferlen, "\n");
#endif
FS_Write( buffer, strlen( buffer ), f );
}
Hunk_FreeTempMemory( buffer );
FS_FCloseFile( f );
}
CWE ID: CWE-269
Target: 1
Example 2:
Code: void AutocompleteProvider::UpdateStarredStateOfMatches() {
if (matches_.empty())
return;
if (!profile_)
return;
BookmarkModel* bookmark_model = profile_->GetBookmarkModel();
if (!bookmark_model || !bookmark_model->IsLoaded())
return;
for (ACMatches::iterator i = matches_.begin(); i != matches_.end(); ++i)
i->starred = bookmark_model->IsBookmarked(GURL(i->destination_url));
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FileSystemOperation::DoCreateFile(
const StatusCallback& callback,
bool exclusive) {
FileSystemFileUtilProxy::EnsureFileExists(
&operation_context_,
src_util_, src_path_,
base::Bind(
exclusive ? &FileSystemOperation::DidEnsureFileExistsExclusive
: &FileSystemOperation::DidEnsureFileExistsNonExclusive,
base::Owned(this), 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: chpass_principal3_2_svc(chpass3_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 (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) {
ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
arg->pass);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_chpass_principal_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
arg->pass);
} else {
log_unauth("kadm5_chpass_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if(ret.code != KADM5_AUTH_CHANGEPW) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_chpass_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: vpx_enc_frame_flags_t SoftVPXEncoder::getEncodeFlags() {
vpx_enc_frame_flags_t flags = 0;
int patternIdx = mTemporalPatternIdx % mTemporalPatternLength;
mTemporalPatternIdx++;
switch (mTemporalPattern[patternIdx]) {
case kTemporalUpdateLast:
flags |= VP8_EFLAG_NO_UPD_GF;
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_REF_GF;
flags |= VP8_EFLAG_NO_REF_ARF;
break;
case kTemporalUpdateGoldenWithoutDependency:
flags |= VP8_EFLAG_NO_REF_GF;
case kTemporalUpdateGolden:
flags |= VP8_EFLAG_NO_REF_ARF;
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_UPD_LAST;
break;
case kTemporalUpdateAltrefWithoutDependency:
flags |= VP8_EFLAG_NO_REF_ARF;
flags |= VP8_EFLAG_NO_REF_GF;
case kTemporalUpdateAltref:
flags |= VP8_EFLAG_NO_UPD_GF;
flags |= VP8_EFLAG_NO_UPD_LAST;
break;
case kTemporalUpdateNoneNoRefAltref:
flags |= VP8_EFLAG_NO_REF_ARF;
case kTemporalUpdateNone:
flags |= VP8_EFLAG_NO_UPD_GF;
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_UPD_LAST;
flags |= VP8_EFLAG_NO_UPD_ENTROPY;
break;
case kTemporalUpdateNoneNoRefGoldenRefAltRef:
flags |= VP8_EFLAG_NO_REF_GF;
flags |= VP8_EFLAG_NO_UPD_GF;
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_UPD_LAST;
flags |= VP8_EFLAG_NO_UPD_ENTROPY;
break;
case kTemporalUpdateGoldenWithoutDependencyRefAltRef:
flags |= VP8_EFLAG_NO_REF_GF;
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_UPD_LAST;
break;
case kTemporalUpdateLastRefAltRef:
flags |= VP8_EFLAG_NO_UPD_GF;
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_REF_GF;
break;
case kTemporalUpdateGoldenRefAltRef:
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_UPD_LAST;
break;
case kTemporalUpdateLastAndGoldenRefAltRef:
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_REF_GF;
break;
case kTemporalUpdateLastRefAll:
flags |= VP8_EFLAG_NO_UPD_ARF;
flags |= VP8_EFLAG_NO_UPD_GF;
break;
}
return flags;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int hugepage_madvise(struct vm_area_struct *vma,
unsigned long *vm_flags, int advice)
{
switch (advice) {
case MADV_HUGEPAGE:
/*
* Be somewhat over-protective like KSM for now!
*/
if (*vm_flags & (VM_HUGEPAGE |
VM_SHARED | VM_MAYSHARE |
VM_PFNMAP | VM_IO | VM_DONTEXPAND |
VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |
VM_MIXEDMAP | VM_SAO))
return -EINVAL;
*vm_flags &= ~VM_NOHUGEPAGE;
*vm_flags |= VM_HUGEPAGE;
/*
* If the vma become good for khugepaged to scan,
* register it here without waiting a page fault that
* may not happen any time soon.
*/
if (unlikely(khugepaged_enter_vma_merge(vma)))
return -ENOMEM;
break;
case MADV_NOHUGEPAGE:
/*
* Be somewhat over-protective like KSM for now!
*/
if (*vm_flags & (VM_NOHUGEPAGE |
VM_SHARED | VM_MAYSHARE |
VM_PFNMAP | VM_IO | VM_DONTEXPAND |
VM_RESERVED | VM_HUGETLB | VM_INSERTPAGE |
VM_MIXEDMAP | VM_SAO))
return -EINVAL;
*vm_flags &= ~VM_HUGEPAGE;
*vm_flags |= VM_NOHUGEPAGE;
/*
* Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
* this vma even if we leave the mm registered in khugepaged if
* it got registered before VM_NOHUGEPAGE was set.
*/
break;
}
return 0;
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PlatformSensorProviderAndroid::CreateRelativeOrientationEulerAnglesSensor(
JNIEnv* env,
mojo::ScopedSharedBufferMapping mapping,
const CreateSensorCallback& callback) {
if (static_cast<bool>(Java_PlatformSensorProvider_hasSensorType(
env, j_object_,
static_cast<jint>(
mojom::SensorType::RELATIVE_ORIENTATION_QUATERNION)))) {
auto sensor_fusion_algorithm =
std::make_unique<OrientationEulerAnglesFusionAlgorithmUsingQuaternion>(
false /* absolute */);
PlatformSensorFusion::Create(std::move(mapping), this,
std::move(sensor_fusion_algorithm), callback);
} else {
callback.Run(nullptr);
}
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: static int __init evm_set_fixmode(char *str)
{
if (strncmp(str, "fix", 3) == 0)
evm_fixmode = 1;
return 0;
}
CWE ID: CWE-19
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Track::Info::Clear()
{
delete[] nameAsUTF8;
nameAsUTF8 = NULL;
delete[] language;
language = NULL;
delete[] codecId;
codecId = NULL;
delete[] codecPrivate;
codecPrivate = NULL;
codecPrivateSize = 0;
delete[] codecNameAsUTF8;
codecNameAsUTF8 = NULL;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool WebPagePrivate::dispatchTouchEventToFullScreenPlugin(PluginView* plugin, const Platform::TouchEvent& event)
{
if (!event.neverHadMultiTouch())
return false;
if (event.isDoubleTap() || event.isTouchHold() || event.m_type == Platform::TouchEvent::TouchCancel) {
NPTouchEvent npTouchEvent;
if (event.isDoubleTap())
npTouchEvent.type = TOUCH_EVENT_DOUBLETAP;
else if (event.isTouchHold())
npTouchEvent.type = TOUCH_EVENT_TOUCHHOLD;
else if (event.m_type == Platform::TouchEvent::TouchCancel)
npTouchEvent.type = TOUCH_EVENT_CANCEL;
npTouchEvent.points = 0;
npTouchEvent.size = event.m_points.size();
if (npTouchEvent.size) {
npTouchEvent.points = new NPTouchPoint[npTouchEvent.size];
for (int i = 0; i < npTouchEvent.size; i++) {
npTouchEvent.points[i].touchId = event.m_points[i].m_id;
npTouchEvent.points[i].clientX = event.m_points[i].m_screenPos.x();
npTouchEvent.points[i].clientY = event.m_points[i].m_screenPos.y();
npTouchEvent.points[i].screenX = event.m_points[i].m_screenPos.x();
npTouchEvent.points[i].screenY = event.m_points[i].m_screenPos.y();
npTouchEvent.points[i].pageX = event.m_points[i].m_pos.x();
npTouchEvent.points[i].pageY = event.m_points[i].m_pos.y();
}
}
NPEvent npEvent;
npEvent.type = NP_TouchEvent;
npEvent.data = &npTouchEvent;
plugin->dispatchFullScreenNPEvent(npEvent);
delete[] npTouchEvent.points;
return true;
}
dispatchTouchPointAsMouseEventToFullScreenPlugin(plugin, event.m_points[0]);
return true;
}
CWE ID:
Target: 1
Example 2:
Code: void RenderFrameImpl::OnVisualStateRequest(uint64_t id) {
GetRenderWidget()->QueueMessage(
new FrameHostMsg_VisualStateResponse(routing_id_, id),
MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
}
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 cac_read_binary(sc_card_t *card, unsigned int idx,
unsigned char *buf, size_t count, unsigned long flags)
{
cac_private_data_t * priv = CAC_DATA(card);
int r = 0;
u8 *tl = NULL, *val = NULL;
u8 *tl_ptr, *val_ptr, *tlv_ptr, *tl_start;
u8 *cert_ptr;
size_t tl_len, val_len, tlv_len;
size_t len, tl_head_len, cert_len;
u8 cert_type, tag;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* if we didn't return it all last time, return the remainder */
if (priv->cached) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (idx > priv->cache_buf_len) {
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_END_REACHED);
}
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, len);
}
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
idx, count);
if (priv->cache_buf) {
free(priv->cache_buf);
priv->cache_buf = NULL;
priv->cache_buf_len = 0;
}
if (priv->object_type <= 0)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INTERNAL);
r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
if (r < 0) {
goto done;
}
r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
if (r < 0)
goto done;
switch (priv->object_type) {
case CAC_OBJECT_TYPE_TLV_FILE:
tlv_len = tl_len + val_len;
priv->cache_buf = malloc(tlv_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = tlv_len;
for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf;
tl_len >= 2 && tlv_len > 0;
val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) {
/* get the tag and the length */
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = (tl_ptr - tl_start);
sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr);
tlv_len -= tl_head_len;
tl_len -= tl_head_len;
/* don't crash on bad data */
if (val_len < len) {
len = val_len;
}
/* if we run out of return space, truncate */
if (tlv_len < len) {
len = tlv_len;
}
memcpy(tlv_ptr, val_ptr, len);
}
break;
case CAC_OBJECT_TYPE_CERT:
/* read file */
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
" obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)",
val_len, val_len);
cert_len = 0;
cert_ptr = NULL;
cert_type = 0;
for (tl_ptr = tl, val_ptr=val; tl_len >= 2;
val_len -= len, val_ptr += len, tl_len -= tl_head_len) {
tl_start = tl_ptr;
if (sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len) != SC_SUCCESS)
break;
tl_head_len = tl_ptr - tl_start;
if (tag == CAC_TAG_CERTIFICATE) {
cert_len = len;
cert_ptr = val_ptr;
}
if (tag == CAC_TAG_CERTINFO) {
if ((len >= 1) && (val_len >=1)) {
cert_type = *val_ptr;
}
}
if (tag == CAC_TAG_MSCUID) {
sc_log_hex(card->ctx, "MSCUID", val_ptr, len);
}
if ((val_len < len) || (tl_len < tl_head_len)) {
break;
}
}
/* if the info byte is 1, then the cert is compressed, decompress it */
if ((cert_type & 0x3) == 1) {
#ifdef ENABLE_ZLIB
r = sc_decompress_alloc(&priv->cache_buf, &priv->cache_buf_len,
cert_ptr, cert_len, COMPRESSION_AUTO);
#else
sc_log(card->ctx, "CAC compression not supported, no zlib");
r = SC_ERROR_NOT_SUPPORTED;
#endif
if (r)
goto done;
} else if (cert_len > 0) {
priv->cache_buf = malloc(cert_len);
if (priv->cache_buf == NULL) {
r = SC_ERROR_OUT_OF_MEMORY;
goto done;
}
priv->cache_buf_len = cert_len;
memcpy(priv->cache_buf, cert_ptr, cert_len);
} else {
sc_log(card->ctx, "Can't read zero-length certificate");
goto done;
}
break;
case CAC_OBJECT_TYPE_GENERIC:
/* TODO
* We have some two buffers in unknown encoding that we
* need to present in PKCS#15 layer.
*/
default:
/* Unknown object type */
sc_log(card->ctx, "Unknown object type: %x", priv->object_type);
r = SC_ERROR_INTERNAL;
goto done;
}
/* OK we've read the data, now copy the required portion out to the callers buffer */
priv->cached = 1;
len = MIN(count, priv->cache_buf_len-idx);
memcpy(buf, &priv->cache_buf[idx], len);
r = len;
done:
if (tl)
free(tl);
if (val)
free(val);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Initialize(bool can_respond_to_crypto_handshake = true) {
clock_.AdvanceTime(quic::QuicTime::Delta::FromMilliseconds(1000));
runner_ = new net::test::TestTaskRunner(&clock_);
net::QuicChromiumAlarmFactory* alarm_factory =
new net::QuicChromiumAlarmFactory(runner_.get(), &clock_);
quic_transport_factory_ = std::make_unique<P2PQuicTransportFactoryImpl>(
&clock_, std::unique_ptr<net::QuicChromiumAlarmFactory>(alarm_factory));
auto client_packet_transport =
std::make_unique<FakePacketTransport>(alarm_factory, &clock_);
auto server_packet_transport =
std::make_unique<FakePacketTransport>(alarm_factory, &clock_);
client_packet_transport->ConnectPeerTransport(
server_packet_transport.get());
server_packet_transport->ConnectPeerTransport(
client_packet_transport.get());
rtc::scoped_refptr<rtc::RTCCertificate> client_cert =
CreateTestCertificate();
auto client_quic_transport_delegate =
std::make_unique<MockP2PQuicTransportDelegate>();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> client_certificates;
client_certificates.push_back(client_cert);
P2PQuicTransportConfig client_config(client_quic_transport_delegate.get(),
client_packet_transport.get(),
client_certificates);
client_config.is_server = false;
client_config.can_respond_to_crypto_handshake =
can_respond_to_crypto_handshake;
P2PQuicTransportImpl* client_quic_transport_ptr =
static_cast<P2PQuicTransportImpl*>(
quic_transport_factory_
->CreateQuicTransport(std::move(client_config))
.release());
std::unique_ptr<P2PQuicTransportImpl> client_quic_transport =
std::unique_ptr<P2PQuicTransportImpl>(client_quic_transport_ptr);
client_peer_ = std::make_unique<QuicPeerForTest>(
std::move(client_packet_transport),
std::move(client_quic_transport_delegate),
std::move(client_quic_transport), client_cert);
auto server_quic_transport_delegate =
std::make_unique<MockP2PQuicTransportDelegate>();
rtc::scoped_refptr<rtc::RTCCertificate> server_cert =
CreateTestCertificate();
std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> server_certificates;
server_certificates.push_back(server_cert);
P2PQuicTransportConfig server_config(server_quic_transport_delegate.get(),
server_packet_transport.get(),
server_certificates);
server_config.is_server = true;
server_config.can_respond_to_crypto_handshake =
can_respond_to_crypto_handshake;
P2PQuicTransportImpl* server_quic_transport_ptr =
static_cast<P2PQuicTransportImpl*>(
quic_transport_factory_
->CreateQuicTransport(std::move(server_config))
.release());
std::unique_ptr<P2PQuicTransportImpl> server_quic_transport =
std::unique_ptr<P2PQuicTransportImpl>(server_quic_transport_ptr);
server_peer_ = std::make_unique<QuicPeerForTest>(
std::move(server_packet_transport),
std::move(server_quic_transport_delegate),
std::move(server_quic_transport), server_cert);
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: ScopedResolvedFrameBufferBinder::ScopedResolvedFrameBufferBinder(
GLES2DecoderImpl* decoder, bool enforce_internal_framebuffer, bool internal)
: decoder_(decoder) {
resolve_and_bind_ = (
decoder_->offscreen_target_frame_buffer_.get() &&
decoder_->IsOffscreenBufferMultisampled() &&
(!decoder_->framebuffer_state_.bound_read_framebuffer.get() ||
enforce_internal_framebuffer));
if (!resolve_and_bind_)
return;
ScopedGLErrorSuppressor suppressor(
"ScopedResolvedFrameBufferBinder::ctor", decoder_->GetErrorState());
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT,
decoder_->offscreen_target_frame_buffer_->id());
GLuint targetid;
if (internal) {
if (!decoder_->offscreen_resolved_frame_buffer_.get()) {
decoder_->offscreen_resolved_frame_buffer_.reset(
new BackFramebuffer(decoder_));
decoder_->offscreen_resolved_frame_buffer_->Create();
decoder_->offscreen_resolved_color_texture_.reset(
new BackTexture(decoder->memory_tracker(), &decoder->state_));
decoder_->offscreen_resolved_color_texture_->Create();
DCHECK(decoder_->offscreen_saved_color_format_);
decoder_->offscreen_resolved_color_texture_->AllocateStorage(
decoder_->offscreen_size_, decoder_->offscreen_saved_color_format_,
false);
decoder_->offscreen_resolved_frame_buffer_->AttachRenderTexture(
decoder_->offscreen_resolved_color_texture_.get());
if (decoder_->offscreen_resolved_frame_buffer_->CheckStatus() !=
GL_FRAMEBUFFER_COMPLETE) {
LOG(ERROR) << "ScopedResolvedFrameBufferBinder failed "
<< "because offscreen resolved FBO was incomplete.";
return;
}
}
targetid = decoder_->offscreen_resolved_frame_buffer_->id();
} else {
targetid = decoder_->offscreen_saved_frame_buffer_->id();
}
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, targetid);
const int width = decoder_->offscreen_size_.width();
const int height = decoder_->offscreen_size_.height();
decoder->state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false);
decoder->BlitFramebufferHelper(0,
0,
width,
height,
0,
0,
width,
height,
GL_COLOR_BUFFER_BIT,
GL_NEAREST);
glBindFramebufferEXT(GL_FRAMEBUFFER, targetid);
}
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 documentTypeAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
TestObjectPythonV8Internal::documentTypeAttributeAttributeSetter(jsValue, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: hstoreArrayToPairs(ArrayType *a, int *npairs)
{
Datum *key_datums;
bool *key_nulls;
int key_count;
Pairs *key_pairs;
int bufsiz;
int i,
j;
deconstruct_array(a,
TEXTOID, -1, false, 'i',
&key_datums, &key_nulls, &key_count);
if (key_count == 0)
{
*npairs = 0;
return NULL;
}
key_pairs = palloc(sizeof(Pairs) * key_count);
for (i = 0, j = 0; i < key_count; i++)
{
if (!key_nulls[i])
{
key_pairs[j].key = VARDATA(key_datums[i]);
key_pairs[j].keylen = VARSIZE(key_datums[i]) - VARHDRSZ;
key_pairs[j].val = NULL;
key_pairs[j].vallen = 0;
key_pairs[j].needfree = 0;
key_pairs[j].isnull = 1;
j++;
}
}
*npairs = hstoreUniquePairs(key_pairs, j, &bufsiz);
return key_pairs;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: base::OnceClosure DesktopWindowTreeHostX11::DisableEventListening() {
modal_dialog_counter_++;
if (modal_dialog_counter_ == 1) {
targeter_for_modal_ = std::make_unique<aura::ScopedWindowTargeter>(
window(), std::make_unique<aura::NullWindowTargeter>());
}
return base::BindOnce(&DesktopWindowTreeHostX11::EnableEventListening,
weak_factory_.GetWeakPtr());
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void xrangeGenericCommand(client *c, int rev) {
robj *o;
stream *s;
streamID startid, endid;
long long count = 0;
robj *startarg = rev ? c->argv[3] : c->argv[2];
robj *endarg = rev ? c->argv[2] : c->argv[3];
if (streamParseIDOrReply(c,startarg,&startid,0) == C_ERR) return;
if (streamParseIDOrReply(c,endarg,&endid,UINT64_MAX) == C_ERR) return;
/* Parse the COUNT option if any. */
if (c->argc > 4) {
for (int j = 4; j < c->argc; j++) {
int additional = c->argc-j-1;
if (strcasecmp(c->argv[j]->ptr,"COUNT") == 0 && additional >= 1) {
if (getLongLongFromObjectOrReply(c,c->argv[j+1],&count,NULL)
!= C_OK) return;
if (count < 0) count = 0;
j++; /* Consume additional arg. */
} else {
addReply(c,shared.syntaxerr);
return;
}
}
}
/* Return the specified range to the user. */
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
|| checkType(c,o,OBJ_STREAM)) return;
s = o->ptr;
streamReplyWithRange(c,s,&startid,&endid,count,rev,NULL,NULL,0,NULL);
}
CWE ID: CWE-704
Output: | 0 |
Here are some example code snippets. Analyze the following 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 cg_getattr(const char *path, struct stat *sb)
{
struct timespec now;
struct fuse_context *fc = fuse_get_context();
char * cgdir = NULL;
char *fpath = NULL, *path1, *path2;
struct cgfs_files *k = NULL;
const char *cgroup;
const char *controller = NULL;
int ret = -ENOENT;
if (!fc)
return -EIO;
memset(sb, 0, sizeof(struct stat));
if (clock_gettime(CLOCK_REALTIME, &now) < 0)
return -EINVAL;
sb->st_uid = sb->st_gid = 0;
sb->st_atim = sb->st_mtim = sb->st_ctim = now;
sb->st_size = 0;
if (strcmp(path, "/cgroup") == 0) {
sb->st_mode = S_IFDIR | 00755;
sb->st_nlink = 2;
return 0;
}
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EIO;
cgroup = find_cgroup_in_path(path);
if (!cgroup) {
/* this is just /cgroup/controller, return it as a dir */
sb->st_mode = S_IFDIR | 00755;
sb->st_nlink = 2;
return 0;
}
get_cgdir_and_path(cgroup, &cgdir, &fpath);
if (!fpath) {
path1 = "/";
path2 = cgdir;
} else {
path1 = cgdir;
path2 = fpath;
}
/* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
* Then check that caller's cgroup is under path if fpath is a child
* cgroup, or cgdir if fpath is a file */
if (is_child_cgroup(controller, path1, path2)) {
if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) {
/* this is just /cgroup/controller, return it as a dir */
sb->st_mode = S_IFDIR | 00555;
sb->st_nlink = 2;
ret = 0;
goto out;
}
if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) {
ret = -EACCES;
goto out;
}
sb->st_mode = S_IFDIR | 00755;
k = cgfs_get_key(controller, cgroup, "tasks");
if (!k) {
sb->st_uid = sb->st_gid = 0;
} else {
sb->st_uid = k->uid;
sb->st_gid = k->gid;
}
free_key(k);
sb->st_nlink = 2;
ret = 0;
goto out;
}
if ((k = cgfs_get_key(controller, path1, path2)) != NULL) {
sb->st_mode = S_IFREG | k->mode;
sb->st_nlink = 1;
sb->st_uid = k->uid;
sb->st_gid = k->gid;
sb->st_size = 0;
free_key(k);
if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) {
ret = -ENOENT;
goto out;
}
if (!fc_may_access(fc, controller, path1, path2, O_RDONLY)) {
ret = -EACCES;
goto out;
}
ret = 0;
}
out:
free(cgdir);
return ret;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: void WebGraphicsContext3DCommandBufferImpl::prepareTexture() {
if (ShouldUseSwapClient())
swap_client_->OnViewContextSwapBuffersPosted();
context_->SwapBuffers();
context_->Echo(base::Bind(
&WebGraphicsContext3DCommandBufferImpl::OnSwapBuffersComplete,
weak_ptr_factory_.GetWeakPtr()));
#if defined(OS_MACOSX)
gl_->Flush();
#endif
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const Extension* ExtensionService::GetExtensionByURL(const GURL& url) {
return url.scheme() != chrome::kExtensionScheme ? NULL :
GetExtensionById(url.host(), false);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintWebViewHelper::OnInitiatePrintPreview(bool selection_only) {
blink::WebLocalFrame* frame = NULL;
GetPrintFrame(&frame);
DCHECK(frame);
auto plugin = delegate_->GetPdfElement(frame);
if (!plugin.isNull()) {
PrintNode(plugin);
return;
}
print_preview_context_.InitWithFrame(frame);
RequestPrintPreview(selection_only
? PRINT_PREVIEW_USER_INITIATED_SELECTION
: PRINT_PREVIEW_USER_INITIATED_ENTIRE_FRAME);
}
CWE ID:
Target: 1
Example 2:
Code: void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
{
unsigned long flags;
spin_lock_irqsave(&md->uevent_lock, flags);
list_add(elist, &md->uevent_list);
spin_unlock_irqrestore(&md->uevent_lock, flags);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void NotificationsEngine::init()
{
}
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: ScriptPromise VRDisplay::requestPresent(ScriptState* script_state,
const HeapVector<VRLayer>& layers) {
ExecutionContext* execution_context = ExecutionContext::From(script_state);
UseCounter::Count(execution_context, UseCounter::kVRRequestPresent);
if (!execution_context->IsSecureContext()) {
UseCounter::Count(execution_context,
UseCounter::kVRRequestPresentInsecureOrigin);
}
ReportPresentationResult(PresentationResult::kRequested);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state);
ScriptPromise promise = resolver->Promise();
if (!capabilities_->canPresent()) {
DOMException* exception =
DOMException::Create(kInvalidStateError, "VRDisplay cannot present.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kVRDisplayCannotPresent);
return promise;
}
bool first_present = !is_presenting_;
if (first_present && !UserGestureIndicator::UtilizeUserGesture() &&
!in_display_activate_) {
DOMException* exception = DOMException::Create(
kInvalidStateError, "API can only be initiated by a user gesture.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kNotInitiatedByUserGesture);
return promise;
}
if (layers.size() == 0 || layers.size() > capabilities_->maxLayers()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid number of layers.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidNumberOfLayers);
return promise;
}
if (layers[0].source().isNull()) {
ForceExitPresent();
DOMException* exception =
DOMException::Create(kInvalidStateError, "Invalid layer source.");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerSource);
return promise;
}
layer_ = layers[0];
CanvasRenderingContext* rendering_context;
if (layer_.source().isHTMLCanvasElement()) {
rendering_context =
layer_.source().getAsHTMLCanvasElement()->RenderingContext();
} else {
DCHECK(layer_.source().isOffscreenCanvas());
rendering_context =
layer_.source().getAsOffscreenCanvas()->RenderingContext();
}
if (!rendering_context || !rendering_context->Is3d()) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "Layer source must have a WebGLRenderingContext");
resolver->Reject(exception);
ReportPresentationResult(
PresentationResult::kLayerSourceMissingWebGLContext);
return promise;
}
rendering_context_ = ToWebGLRenderingContextBase(rendering_context);
context_gl_ = rendering_context_->ContextGL();
if ((layer_.leftBounds().size() != 0 && layer_.leftBounds().size() != 4) ||
(layer_.rightBounds().size() != 0 && layer_.rightBounds().size() != 4)) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError,
"Layer bounds must either be an empty array or have 4 values");
resolver->Reject(exception);
ReportPresentationResult(PresentationResult::kInvalidLayerBounds);
return promise;
}
if (!pending_present_resolvers_.IsEmpty()) {
pending_present_resolvers_.push_back(resolver);
} else if (first_present) {
bool secure_context =
ExecutionContext::From(script_state)->IsSecureContext();
if (!display_) {
ForceExitPresent();
DOMException* exception = DOMException::Create(
kInvalidStateError, "The service is no longer active.");
resolver->Reject(exception);
return promise;
}
pending_present_resolvers_.push_back(resolver);
submit_frame_client_binding_.Close();
display_->RequestPresent(
secure_context,
submit_frame_client_binding_.CreateInterfacePtrAndBind(),
ConvertToBaseCallback(
WTF::Bind(&VRDisplay::OnPresentComplete, WrapPersistent(this))));
} else {
UpdateLayerBounds();
resolver->Resolve();
ReportPresentationResult(PresentationResult::kSuccessAlreadyPresenting);
}
return promise;
}
CWE ID:
Target: 1
Example 2:
Code: static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
{
if (flags & MSG_OOB)
tp->snd_up = tp->write_seq;
}
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: LayoutUnit LayoutBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTop, LayoutBox& child, bool atBeforeSideOfBlock)
{
LayoutBlockFlow* childBlockFlow = child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child) : 0;
LayoutUnit newLogicalTop = applyBeforeBreak(child, logicalTop);
LayoutUnit logicalTopBeforeUnsplittableAdjustment = newLogicalTop;
LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, newLogicalTop);
LayoutUnit paginationStrut = 0;
LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
LayoutUnit childLogicalHeight = child.logicalHeight();
if (unsplittableAdjustmentDelta) {
setPageBreak(newLogicalTop, childLogicalHeight - unsplittableAdjustmentDelta);
paginationStrut = unsplittableAdjustmentDelta;
} else if (childBlockFlow && childBlockFlow->paginationStrut()) {
paginationStrut = childBlockFlow->paginationStrut();
}
if (paginationStrut) {
if (atBeforeSideOfBlock && logicalTop == newLogicalTop && !isOutOfFlowPositioned() && !isTableCell()) {
paginationStrut += logicalTop;
if (isFloating())
paginationStrut += marginBefore(); // Floats' margins do not collapse with page or column boundaries.
setPaginationStrut(paginationStrut);
if (childBlockFlow)
childBlockFlow->setPaginationStrut(0);
} else {
newLogicalTop += paginationStrut;
}
}
if (!unsplittableAdjustmentDelta) {
if (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(newLogicalTop)) {
LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(newLogicalTop, AssociateWithLatterPage);
LayoutUnit spaceShortage = childLogicalHeight - remainingLogicalHeight;
if (spaceShortage > 0) {
LayoutUnit spaceShortageInLastColumn = intMod(spaceShortage, pageLogicalHeight);
setPageBreak(newLogicalTop, spaceShortageInLastColumn ? spaceShortageInLastColumn : spaceShortage);
} else if (remainingLogicalHeight == pageLogicalHeight && offsetFromLogicalTopOfFirstPage() + child.logicalTop()) {
setPageBreak(newLogicalTop, childLogicalHeight);
}
}
}
setLogicalHeight(logicalHeight() + (newLogicalTop - logicalTop));
return newLogicalTop;
}
CWE ID: CWE-22
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 RunAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs);
for (int j = 0; j < kNumCoeffs; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
const uint32_t diff = dst[j] - src[j];
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1u, max_error)
<< "Error: 16x16 FHT/IHT has an individual round trip error > 1";
EXPECT_GE(count_test_block , total_error)
<< "Error: 16x16 FHT/IHT has average round trip error > 1 per block";
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void V8TestObject::ShortAttributeAttributeSetterCallback(
const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_shortAttribute_Setter");
v8::Local<v8::Value> v8_value = info[0];
test_object_v8_internal::ShortAttributeAttributeSetter(v8_value, info);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
mask->matte=MagickFalse;
channel_image=mask;
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
}
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ChromeMockRenderThread::OnMsgOpenChannelToExtension(
int routing_id, const std::string& source_extension_id,
const std::string& target_extension_id,
const std::string& channel_name, int* port_id) {
*port_id = 0;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: base::string16 ExtensionInstallPrompt::Prompt::GetPermissionsDetails(
size_t index,
PermissionsType permissions_type) const {
const InstallPromptPermissions& install_permissions =
GetPermissionsForType(permissions_type);
CHECK_LT(index, install_permissions.details.size());
return install_permissions.details[index];
}
CWE ID: CWE-17
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Element* Document::ScrollingElementNoLayout() {
if (RuntimeEnabledFeatures::ScrollTopLeftInteropEnabled()) {
if (InQuirksMode()) {
DCHECK(lifecycle_.GetState() >= DocumentLifecycle::kStyleClean);
HTMLBodyElement* body = FirstBodyElement();
if (body && body->GetLayoutObject() &&
body->GetLayoutObject()->HasOverflowClip())
return nullptr;
return body;
}
return documentElement();
}
return body();
}
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 int DefragMfIpv6Test(void)
{
int retval = 0;
int ip_id = 9;
Packet *p = NULL;
DefragInit();
Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8);
Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8);
Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8);
if (p1 == NULL || p2 == NULL || p3 == NULL) {
goto end;
}
p = Defrag(NULL, NULL, p1, NULL);
if (p != NULL) {
goto end;
}
p = Defrag(NULL, NULL, p2, NULL);
if (p != NULL) {
goto end;
}
/* This should return a packet as MF=0. */
p = Defrag(NULL, NULL, p3, NULL);
if (p == NULL) {
goto end;
}
/* For IPv6 the expected length is just the length of the payload
* of 2 fragments, so 16. */
if (IPV6_GET_PLEN(p) != 16) {
goto end;
}
retval = 1;
end:
if (p1 != NULL) {
SCFree(p1);
}
if (p2 != NULL) {
SCFree(p2);
}
if (p3 != NULL) {
SCFree(p3);
}
if (p != NULL) {
SCFree(p);
}
DefragDestroy();
return retval;
}
CWE ID: CWE-358
Target: 1
Example 2:
Code: IntSize WebPagePrivate::screenSize() const
{
return Platform::Graphics::Screen::primaryScreen()->size();
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool WebGLRenderingContextBase::ValidateCopyTexFormat(const char* function_name,
GLenum internalformat) {
if (!is_web_gl2_internal_formats_copy_tex_image_added_ &&
IsWebGL2OrHigher()) {
ADD_VALUES_TO_SET(supported_internal_formats_copy_tex_image_,
kSupportedInternalFormatsES3);
is_web_gl2_internal_formats_copy_tex_image_added_ = true;
}
if (!is_ext_color_buffer_float_formats_added_ &&
ExtensionEnabled(kEXTColorBufferFloatName)) {
ADD_VALUES_TO_SET(supported_internal_formats_copy_tex_image_,
kSupportedInternalFormatsCopyTexImageFloatES3);
is_ext_color_buffer_float_formats_added_ = true;
}
if (supported_internal_formats_copy_tex_image_.find(internalformat) ==
supported_internal_formats_copy_tex_image_.end()) {
SynthesizeGLError(GL_INVALID_ENUM, function_name, "invalid internalformat");
return false;
}
return true;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(SplFileObject, current)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!intern->u.file.current_line && !intern->u.file.current_zval) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
}
if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) {
RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1);
} else if (intern->u.file.current_zval) {
RETURN_ZVAL(intern->u.file.current_zval, 1, 0);
}
RETURN_FALSE;
} /* }}} */
/* {{{ proto int SplFileObject::key()
CWE ID: CWE-190
Target: 1
Example 2:
Code: StateBase* writeDenseArray(uint32_t numProperties, uint32_t length, StateBase* state)
{
m_writer.writeDenseArray(numProperties, length);
return pop(state);
}
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 Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
MagickBooleanType
status;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=1;
image->endian=MSBEndian;
(void) ReadBlobLSBShort(image);
image->columns=(size_t) ReadBlobLSBShort(image);
(void) ReadBlobLSBShort(image);
image->rows=(size_t) ReadBlobLSBShort(image);
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image colormap.
*/
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert bi-level image to pixel packets.
*/
SetImageColorspace(image,GRAYColorspace);
quantum_type=IndexQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
if (count != (ssize_t) length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
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 enum integrity_status evm_verify_hmac(struct dentry *dentry,
const char *xattr_name,
char *xattr_value,
size_t xattr_value_len,
struct integrity_iint_cache *iint)
{
struct evm_ima_xattr_data *xattr_data = NULL;
struct evm_ima_xattr_data calc;
enum integrity_status evm_status = INTEGRITY_PASS;
int rc, xattr_len;
if (iint && iint->evm_status == INTEGRITY_PASS)
return iint->evm_status;
/* if status is not PASS, try to check again - against -ENOMEM */
/* first need to know the sig type */
rc = vfs_getxattr_alloc(dentry, XATTR_NAME_EVM, (char **)&xattr_data, 0,
GFP_NOFS);
if (rc <= 0) {
evm_status = INTEGRITY_FAIL;
if (rc == -ENODATA) {
rc = evm_find_protected_xattrs(dentry);
if (rc > 0)
evm_status = INTEGRITY_NOLABEL;
else if (rc == 0)
evm_status = INTEGRITY_NOXATTRS; /* new file */
} else if (rc == -EOPNOTSUPP) {
evm_status = INTEGRITY_UNKNOWN;
}
goto out;
}
xattr_len = rc;
/* check value type */
switch (xattr_data->type) {
case EVM_XATTR_HMAC:
rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = memcmp(xattr_data->digest, calc.digest,
sizeof(calc.digest));
if (rc)
rc = -EINVAL;
break;
case EVM_IMA_XATTR_DIGSIG:
rc = evm_calc_hash(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM,
(const char *)xattr_data, xattr_len,
calc.digest, sizeof(calc.digest));
if (!rc) {
/* Replace RSA with HMAC if not mounted readonly and
* not immutable
*/
if (!IS_RDONLY(d_backing_inode(dentry)) &&
!IS_IMMUTABLE(d_backing_inode(dentry)))
evm_update_evmxattr(dentry, xattr_name,
xattr_value,
xattr_value_len);
}
break;
default:
rc = -EINVAL;
break;
}
if (rc)
evm_status = (rc == -ENODATA) ?
INTEGRITY_NOXATTRS : INTEGRITY_FAIL;
out:
if (iint)
iint->evm_status = evm_status;
kfree(xattr_data);
return evm_status;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: CronTab::CronTab( ClassAd *ad )
{
for ( int ctr = 0; ctr < CRONTAB_FIELDS; ctr++ ) {
MyString buffer;
if ( ad->LookupString( this->attributes[ctr], buffer ) ) {
dprintf( D_FULLDEBUG, "CronTab: Pulled out '%s' for %s\n",
buffer.Value(), this->attributes[ctr] );
this->parameters[ctr] = new MyString( buffer.Value() );
} else {
dprintf( D_FULLDEBUG, "CronTab: No attribute for %s, using wildcard\n",
this->attributes[ctr] );
this->parameters[ctr] = new MyString( CRONTAB_WILDCARD );
}
} // FOR
this->init();
}
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: void GpuDataManager::UpdateGpuInfo(const GPUInfo& gpu_info) {
{
base::AutoLock auto_lock(gpu_info_lock_);
if (!gpu_info_.Merge(gpu_info))
return;
RunGpuInfoUpdateCallbacks();
content::GetContentClient()->SetGpuInfo(gpu_info_);
}
UpdateGpuFeatureFlags();
}
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 llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
unsigned int copied, rlen;
struct sk_buff *skb, *cskb;
int err = 0;
pr_debug("%p %zu\n", sk, len);
lock_sock(sk);
if (sk->sk_state == LLCP_CLOSED &&
skb_queue_empty(&sk->sk_receive_queue)) {
release_sock(sk);
return 0;
}
release_sock(sk);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb) {
pr_err("Recv datagram failed state %d %d %d",
sk->sk_state, err, sock_error(sk));
if (sk->sk_shutdown & RCV_SHUTDOWN)
return 0;
return err;
}
rlen = skb->len; /* real length of skb */
copied = min_t(unsigned int, rlen, len);
cskb = skb;
if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) {
if (!(flags & MSG_PEEK))
skb_queue_head(&sk->sk_receive_queue, skb);
return -EFAULT;
}
sock_recv_timestamp(msg, sk, skb);
if (sk->sk_type == SOCK_DGRAM && msg->msg_name) {
struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb);
struct sockaddr_nfc_llcp *sockaddr =
(struct sockaddr_nfc_llcp *) msg->msg_name;
msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp);
pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap);
sockaddr->sa_family = AF_NFC;
sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP;
sockaddr->dsap = ui_cb->dsap;
sockaddr->ssap = ui_cb->ssap;
}
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
/* SOCK_STREAM: re-queue skb if it contains unreceived data */
if (sk->sk_type == SOCK_STREAM ||
sk->sk_type == SOCK_DGRAM ||
sk->sk_type == SOCK_RAW) {
skb_pull(skb, copied);
if (skb->len) {
skb_queue_head(&sk->sk_receive_queue, skb);
goto done;
}
}
kfree_skb(skb);
}
/* XXX Queue backlogged skbs */
done:
/* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */
if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC))
copied = rlen;
return copied;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int config_boot_dev(struct usb_device *dev)
{
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: void* ipc_alloc(int size)
{
void* out;
if(size > PAGE_SIZE)
out = vmalloc(size);
else
out = kmalloc(size, GFP_KERNEL);
return out;
}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void GLSurfaceEGLSurfaceControl::CommitOverlayPlanesAsync(
SwapCompletionCallback completion_callback,
PresentationCallback presentation_callback) {
CommitPendingTransaction(std::move(completion_callback),
std::move(presentation_callback));
}
CWE ID:
Target: 1
Example 2:
Code: static void calc_gauss(double *res, int n, double r2)
{
double alpha = 0.5 / r2;
double mul = exp(-alpha), mul2 = mul * mul;
double cur = sqrt(alpha / M_PI);
res[0] = cur;
cur *= mul;
res[1] = cur;
for (int i = 2; i <= n; ++i) {
mul *= mul2;
cur *= mul;
res[i] = cur;
}
}
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: virtual void SetUp() {
video_ = new libvpx_test::WebMVideoSource(kVP9TestFile);
ASSERT_TRUE(video_ != NULL);
video_->Init();
video_->Begin();
vpx_codec_dec_cfg_t cfg = {0};
decoder_ = new libvpx_test::VP9Decoder(cfg, 0);
ASSERT_TRUE(decoder_ != NULL);
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual std::string GetKeyboardOverlayId(const std::string& input_method_id) {
if (!initialized_successfully_)
return "";
return chromeos::GetKeyboardOverlayId(input_method_id);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: ReplaceCursor(CursorPtr pCursor, TestCursorFunc testCursor, void *closure)
{
int clientIndex;
int resIndex;
ReplaceCursorLookupRec rcl;
/*
* Cursors exist only in the resource database, windows and grabs.
* All of these are always pointed at by the resource database. Walk
* the whole thing looking for cursors
*/
rcl.testCursor = testCursor;
rcl.pNew = pCursor;
rcl.closure = closure;
/* for each client */
for (clientIndex = 0; clientIndex < currentMaxClients; clientIndex++) {
if (!clients[clientIndex])
continue;
for (resIndex = 0; resIndex < NUM_CURSOR_RESTYPES; resIndex++) {
rcl.type = CursorRestypes[resIndex];
/*
* This function walks the entire client resource database
*/
LookupClientResourceComplex(clients[clientIndex],
rcl.type,
ReplaceCursorLookup, (void *) &rcl);
}
}
/* this "knows" that WindowHasNewCursor doesn't depend on it's argument */
WindowHasNewCursor(screenInfo.screens[0]->root);
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: v8::Handle<v8::Value> V8AudioContext::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.AudioContext.Contructor");
if (!args.IsConstructCall())
return V8Proxy::throwTypeError("AudioContext constructor cannot be called as a function.");
if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
return args.Holder();
Frame* frame = V8Proxy::retrieveFrameForCurrentContext();
if (!frame)
return V8Proxy::throwError(V8Proxy::ReferenceError, "AudioContext constructor associated frame is unavailable", args.GetIsolate());
Document* document = frame->document();
if (!document)
return V8Proxy::throwError(V8Proxy::ReferenceError, "AudioContext constructor associated document is unavailable", args.GetIsolate());
RefPtr<AudioContext> audioContext;
if (!args.Length()) {
ExceptionCode ec = 0;
audioContext = AudioContext::create(document, ec);
if (ec)
return throwError(ec, args.GetIsolate());
if (!audioContext.get())
return V8Proxy::throwError(V8Proxy::SyntaxError, "audio resources unavailable for AudioContext construction", args.GetIsolate());
} else {
if (args.Length() < 3)
return V8Proxy::throwNotEnoughArgumentsError();
bool ok = false;
int32_t numberOfChannels = toInt32(args[0], ok);
if (!ok || numberOfChannels <= 0 || numberOfChannels > 10)
return V8Proxy::throwError(V8Proxy::SyntaxError, "Invalid number of channels", args.GetIsolate());
int32_t numberOfFrames = toInt32(args[1], ok);
if (!ok || numberOfFrames <= 0)
return V8Proxy::throwError(V8Proxy::SyntaxError, "Invalid number of frames", args.GetIsolate());
float sampleRate = toFloat(args[2]);
if (sampleRate <= 0)
return V8Proxy::throwError(V8Proxy::SyntaxError, "Invalid sample rate", args.GetIsolate());
ExceptionCode ec = 0;
audioContext = AudioContext::createOfflineContext(document, numberOfChannels, numberOfFrames, sampleRate, ec);
if (ec)
return throwError(ec, args.GetIsolate());
}
if (!audioContext.get())
return V8Proxy::throwError(V8Proxy::SyntaxError, "Error creating AudioContext", args.GetIsolate());
V8DOMWrapper::setDOMWrapper(args.Holder(), &info, audioContext.get());
audioContext->ref();
return args.Holder();
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void TabStripGtk::TabDetachedAt(TabContents* contents, int index) {
GenerateIdealBounds();
StartRemoveTabAnimation(index, contents->web_contents());
GetTabAt(index)->set_closing(true);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int check_gecos_string(const char *msg, char *gecos)
{
const size_t len = strlen(gecos);
if (MAX_FIELD_SIZE < len) {
warnx(_("field %s is too long"), msg);
return -1;
}
if (illegal_passwd_chars(gecos)) {
warnx(_("%s: has illegal characters"), gecos);
return -1;
}
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: static void webkit_web_view_settings_notify(WebKitWebSettings* webSettings, GParamSpec* pspec, WebKitWebView* webView)
{
Settings* settings = core(webView)->settings();
const gchar* name = g_intern_string(pspec->name);
GValue value = { 0, { { 0 } } };
g_value_init(&value, pspec->value_type);
g_object_get_property(G_OBJECT(webSettings), name, &value);
if (name == g_intern_string("default-encoding"))
settings->setDefaultTextEncodingName(g_value_get_string(&value));
else if (name == g_intern_string("cursive-font-family"))
settings->setCursiveFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-family"))
settings->setStandardFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("fantasy-font-family"))
settings->setFantasyFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("monospace-font-family"))
settings->setFixedFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("sans-serif-font-family"))
settings->setSansSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("serif-font-family"))
settings->setSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-size"))
settings->setDefaultFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("default-monospace-font-size"))
settings->setDefaultFixedFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-font-size"))
settings->setMinimumFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-logical-font-size"))
settings->setMinimumLogicalFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("enforce-96-dpi"))
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
else if (name == g_intern_string("auto-load-images"))
settings->setLoadsImagesAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("auto-shrink-images"))
settings->setShrinksStandaloneImagesToFit(g_value_get_boolean(&value));
else if (name == g_intern_string("print-backgrounds"))
settings->setShouldPrintBackgrounds(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-scripts"))
settings->setJavaScriptEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-plugins"))
settings->setPluginsEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dns-prefetching"))
settings->setDNSPrefetchingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("resizable-text-areas"))
settings->setTextAreasAreResizable(g_value_get_boolean(&value));
else if (name == g_intern_string("user-stylesheet-uri"))
settings->setUserStyleSheetLocation(KURL(KURL(), g_value_get_string(&value)));
else if (name == g_intern_string("enable-developer-extras"))
settings->setDeveloperExtrasEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-private-browsing"))
settings->setPrivateBrowsingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-caret-browsing"))
settings->setCaretBrowsingEnabled(g_value_get_boolean(&value));
#if ENABLE(DATABASE)
else if (name == g_intern_string("enable-html5-database")) {
AbstractDatabase::setIsAvailable(g_value_get_boolean(&value));
}
#endif
else if (name == g_intern_string("enable-html5-local-storage"))
settings->setLocalStorageEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-xss-auditor"))
settings->setXSSAuditorEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-spatial-navigation"))
settings->setSpatialNavigationEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-frame-flattening"))
settings->setFrameFlatteningEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-open-windows-automatically"))
settings->setJavaScriptCanOpenWindowsAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-access-clipboard"))
settings->setJavaScriptCanAccessClipboard(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-offline-web-application-cache"))
settings->setOfflineWebApplicationCacheEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("editing-behavior"))
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(g_value_get_enum(&value)));
else if (name == g_intern_string("enable-universal-access-from-file-uris"))
settings->setAllowUniversalAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-file-access-from-file-uris"))
settings->setAllowFileAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dom-paste"))
settings->setDOMPasteAllowed(g_value_get_boolean(&value));
else if (name == g_intern_string("tab-key-cycles-through-elements")) {
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(g_value_get_boolean(&value));
} else if (name == g_intern_string("enable-site-specific-quirks"))
settings->setNeedsSiteSpecificQuirks(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-page-cache"))
settings->setUsesPageCache(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-java-applet"))
settings->setJavaEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-hyperlink-auditing"))
settings->setHyperlinkAuditingEnabled(g_value_get_boolean(&value));
#if ENABLE(SPELLCHECK)
else if (name == g_intern_string("spell-checking-languages")) {
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(g_value_get_string(&value));
}
#endif
#if ENABLE(WEBGL)
else if (name == g_intern_string("enable-webgl"))
settings->setWebGLEnabled(g_value_get_boolean(&value));
#endif
else if (!g_object_class_find_property(G_OBJECT_GET_CLASS(webSettings), name))
g_warning("Unexpected setting '%s'", name);
g_value_unset(&value);
}
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 MagickBooleanType load_tile(Image *image,Image *tile_image,
XCFDocInfo *inDocInfo,XCFLayerInfo *inLayerInfo,size_t data_length,
ExceptionInfo *exception)
{
ssize_t
y;
register ssize_t
x;
register Quantum
*q;
ssize_t
count;
unsigned char
*graydata;
XCFPixelInfo
*xcfdata,
*xcfodata;
xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata));
if (xcfdata == (XCFPixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
xcfodata=xcfdata;
graydata=(unsigned char *) xcfdata; /* used by gray and indexed */
count=ReadBlob(image,data_length,(unsigned char *) xcfdata);
if (count != (ssize_t) data_length)
ThrowBinaryException(CorruptImageError,"NotEnoughPixelData",
image->filename);
for (y=0; y < (ssize_t) tile_image->rows; y++)
{
q=GetAuthenticPixels(tile_image,0,y,tile_image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
if (inDocInfo->image_type == GIMP_GRAY)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelGray(tile_image,ScaleCharToQuantum(*graydata),q);
SetPixelAlpha(tile_image,ScaleCharToQuantum((unsigned char)
inLayerInfo->alpha),q);
graydata++;
q+=GetPixelChannels(tile_image);
}
}
else
if (inDocInfo->image_type == GIMP_RGB)
{
for (x=0; x < (ssize_t) tile_image->columns; x++)
{
SetPixelRed(tile_image,ScaleCharToQuantum(xcfdata->red),q);
SetPixelGreen(tile_image,ScaleCharToQuantum(xcfdata->green),q);
SetPixelBlue(tile_image,ScaleCharToQuantum(xcfdata->blue),q);
SetPixelAlpha(tile_image,xcfdata->alpha == 255U ? TransparentAlpha :
ScaleCharToQuantum((unsigned char) inLayerInfo->alpha),q);
xcfdata++;
q+=GetPixelChannels(tile_image);
}
}
if (SyncAuthenticPixels(tile_image,exception) == MagickFalse)
break;
}
xcfodata=(XCFPixelInfo *) RelinquishMagickMemory(xcfodata);
return MagickTrue;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: chrm_modify(png_modifier *pm, png_modification *me, int add)
{
UNUSED(add)
/* As with gAMA this just adds the required cHRM chunk to the buffer. */
png_save_uint_32(pm->buffer , 32);
png_save_uint_32(pm->buffer+ 4, CHUNK_cHRM);
png_save_uint_32(pm->buffer+ 8, ((chrm_modification*)me)->wx);
png_save_uint_32(pm->buffer+12, ((chrm_modification*)me)->wy);
png_save_uint_32(pm->buffer+16, ((chrm_modification*)me)->rx);
png_save_uint_32(pm->buffer+20, ((chrm_modification*)me)->ry);
png_save_uint_32(pm->buffer+24, ((chrm_modification*)me)->gx);
png_save_uint_32(pm->buffer+28, ((chrm_modification*)me)->gy);
png_save_uint_32(pm->buffer+32, ((chrm_modification*)me)->bx);
png_save_uint_32(pm->buffer+36, ((chrm_modification*)me)->by);
return 1;
}
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: mp_join_print(netdissect_options *ndo,
const u_char *opt, u_int opt_len, u_char flags)
{
const struct mp_join *mpj = (const struct mp_join *) opt;
if (!(opt_len == 12 && flags & TH_SYN) &&
!(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) &&
!(opt_len == 24 && flags & TH_ACK))
return 0;
if (opt_len != 24) {
if (mpj->sub_b & MP_JOIN_B)
ND_PRINT((ndo, " backup"));
ND_PRINT((ndo, " id %u", mpj->addr_id));
}
switch (opt_len) {
case 12: /* SYN */
ND_PRINT((ndo, " token 0x%x" " nonce 0x%x",
EXTRACT_32BITS(mpj->u.syn.token),
EXTRACT_32BITS(mpj->u.syn.nonce)));
break;
case 16: /* SYN/ACK */
ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x",
EXTRACT_64BITS(mpj->u.synack.mac),
EXTRACT_32BITS(mpj->u.synack.nonce)));
break;
case 24: {/* ACK */
size_t i;
ND_PRINT((ndo, " hmac 0x"));
for (i = 0; i < sizeof(mpj->u.ack.mac); ++i)
ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i]));
}
default:
break;
}
return 1;
}
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int validation_muldiv(int count, int argc, char **argv)
{
int tested = 0;
int overflow = 0;
int error = 0;
int error64 = 0;
int passed = 0;
int randbits = 0;
png_uint_32 randbuffer;
png_fixed_point a;
png_int_32 times, div;
while (--argc > 0)
{
fprintf(stderr, "unknown argument %s\n", *++argv);
return 1;
}
/* Find out about the random number generator. */
randbuffer = RAND_MAX;
while (randbuffer != 0) ++randbits, randbuffer >>= 1;
printf("Using random number generator that makes %d bits\n", randbits);
for (div=0; div<32; div += randbits)
randbuffer = (randbuffer << randbits) ^ rand();
a = 0;
times = div = 0;
do
{
png_fixed_point result;
/* NOTE: your mileage may vary, a type is required below that can
* hold 64 bits or more, if floating point is used a 64 bit or
* better mantissa is required.
*/
long long int fp, fpround;
unsigned long hi, lo;
int ok;
/* Check the values, png_64bit_product can only handle positive
* numbers, so correct for that here.
*/
{
long u1, u2;
int n = 0;
if (a < 0) u1 = -a, n = 1; else u1 = a;
if (times < 0) u2 = -times, n = !n; else u2 = times;
png_64bit_product(u1, u2, &hi, &lo);
if (n)
{
/* -x = ~x+1 */
lo = ((~lo) + 1) & 0xffffffff;
hi = ~hi;
if (lo == 0) ++hi;
}
}
fp = a;
fp *= times;
if ((fp & 0xffffffff) != lo || ((fp >> 32) & 0xffffffff) != hi)
{
fprintf(stderr, "png_64bit_product %d * %d -> %lx|%.8lx not %llx\n",
a, times, hi, lo, fp);
++error64;
}
if (div != 0)
{
/* Round - this is C round to zero. */
if ((fp < 0) != (div < 0))
fp -= div/2;
else
fp += div/2;
fp /= div;
fpround = fp;
/* Assume 2's complement here: */
ok = fpround <= PNG_UINT_31_MAX &&
fpround >= -1-(long long int)PNG_UINT_31_MAX;
if (!ok) ++overflow;
}
else
ok = 0, ++overflow, fpround = fp/*misleading*/;
if (verbose)
fprintf(stderr, "TEST %d * %d / %d -> %lld (%s)\n", a, times, div,
fp, ok ? "ok" : "overflow");
++tested;
if (png_muldiv(&result, a, times, div) != ok)
{
++error;
if (ok)
fprintf(stderr, "%d * %d / %d -> overflow (expected %lld)\n", a,
times, div, fp);
else
fprintf(stderr, "%d * %d / %d -> %d (expected overflow %lld)\n", a,
times, div, result, fp);
}
else if (ok && result != fpround)
{
++error;
fprintf(stderr, "%d * %d / %d -> %d not %lld\n", a, times, div, result,
fp);
}
else
++passed;
/* Generate three new values, this uses rand() and rand() only returns
* up to RAND_MAX.
*/
/* CRUDE */
a += times;
times += div;
div = randbuffer;
randbuffer = (randbuffer << randbits) ^ rand();
}
while (--count > 0);
printf("%d tests including %d overflows, %d passed, %d failed (%d 64 bit "
"errors)\n", tested, overflow, passed, error, error64);
return 0;
}
CWE ID:
Target: 1
Example 2:
Code: void MediaRecorder::died()
{
ALOGV("died");
notify(MEDIA_RECORDER_EVENT_ERROR, MEDIA_ERROR_SERVER_DIED, 0);
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void fake_update_pmtu(struct dst_entry *dst, u32 mtu)
{
}
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: gss_unwrap (minor_status,
context_handle,
input_message_buffer,
output_message_buffer,
conf_state,
qop_state)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t input_message_buffer;
gss_buffer_t output_message_buffer;
int * conf_state;
gss_qop_t * qop_state;
{
/* EXPORT DELETE START */
OM_uint32 status;
gss_union_ctx_id_t ctx;
gss_mechanism mech;
if (minor_status != NULL)
*minor_status = 0;
if (output_message_buffer != GSS_C_NO_BUFFER) {
output_message_buffer->length = 0;
output_message_buffer->value = NULL;
}
if (minor_status == NULL)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
if (context_handle == GSS_C_NO_CONTEXT)
return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);
if (input_message_buffer == GSS_C_NO_BUFFER ||
GSS_EMPTY_BUFFER(input_message_buffer))
return (GSS_S_CALL_INACCESSIBLE_READ);
if (output_message_buffer == GSS_C_NO_BUFFER)
return (GSS_S_CALL_INACCESSIBLE_WRITE);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (mech) {
if (mech->gss_unwrap) {
status = mech->gss_unwrap(minor_status,
ctx->internal_ctx_id,
input_message_buffer,
output_message_buffer,
conf_state,
qop_state);
if (status != GSS_S_COMPLETE)
map_error(minor_status, mech);
} else if (mech->gss_unwrap_aead || mech->gss_unwrap_iov) {
status = gssint_unwrap_aead(mech,
minor_status,
ctx,
input_message_buffer,
GSS_C_NO_BUFFER,
output_message_buffer,
conf_state,
(gss_qop_t *)qop_state);
} else
status = GSS_S_UNAVAILABLE;
return(status);
}
/* EXPORT DELETE END */
return (GSS_S_BAD_MECH);
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: Element* HTMLFormElement::ElementFromPastNamesMap(
const AtomicString& past_name) {
if (past_name.IsEmpty() || !past_names_map_)
return nullptr;
Element* element = past_names_map_->at(past_name);
#if DCHECK_IS_ON()
if (!element)
return nullptr;
SECURITY_DCHECK(ToHTMLElement(element)->formOwner() == this);
if (IsHTMLImageElement(*element)) {
SECURITY_DCHECK(ImageElements().Find(element) != kNotFound);
} else if (IsHTMLObjectElement(*element)) {
SECURITY_DCHECK(ListedElements().Find(ToHTMLObjectElement(element)) !=
kNotFound);
} else {
SECURITY_DCHECK(ListedElements().Find(ToHTMLFormControlElement(element)) !=
kNotFound);
}
#endif
return element;
}
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: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8)
{ psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = 0 ;
psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_be_8byte */
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 Document::DispatchUnloadEvents() {
PluginScriptForbiddenScope forbid_plugin_destructor_scripting;
if (parser_)
parser_->StopParsing();
if (load_event_progress_ == kLoadEventNotRun)
return;
if (load_event_progress_ <= kUnloadEventInProgress) {
Element* current_focused_element = FocusedElement();
if (auto* input = ToHTMLInputElementOrNull(current_focused_element))
input->EndEditing();
if (load_event_progress_ < kPageHideInProgress) {
load_event_progress_ = kPageHideInProgress;
if (LocalDOMWindow* window = domWindow()) {
const TimeTicks pagehide_event_start = CurrentTimeTicks();
window->DispatchEvent(
PageTransitionEvent::Create(EventTypeNames::pagehide, false), this);
const TimeTicks pagehide_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, pagehide_histogram,
("DocumentEventTiming.PageHideDuration", 0, 10000000, 50));
pagehide_histogram.Count(
(pagehide_event_end - pagehide_event_start).InMicroseconds());
}
if (!frame_)
return;
mojom::PageVisibilityState visibility_state = GetPageVisibilityState();
load_event_progress_ = kUnloadVisibilityChangeInProgress;
if (visibility_state != mojom::PageVisibilityState::kHidden) {
const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks();
DispatchEvent(Event::CreateBubble(EventTypeNames::visibilitychange));
const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram,
("DocumentEventTiming.PageVibilityHiddenDuration",
0, 10000000, 50));
pagevisibility_histogram.Count((pagevisibility_hidden_event_end -
pagevisibility_hidden_event_start)
.InMicroseconds());
DispatchEvent(
Event::CreateBubble(EventTypeNames::webkitvisibilitychange));
}
if (!frame_)
return;
frame_->Loader().SaveScrollAnchor();
DocumentLoader* document_loader =
frame_->Loader().GetProvisionalDocumentLoader();
load_event_progress_ = kUnloadEventInProgress;
Event* unload_event(Event::Create(EventTypeNames::unload));
if (document_loader &&
document_loader->GetTiming().UnloadEventStart().is_null() &&
document_loader->GetTiming().UnloadEventEnd().is_null()) {
DocumentLoadTiming& timing = document_loader->GetTiming();
DCHECK(!timing.NavigationStart().is_null());
const TimeTicks unload_event_start = CurrentTimeTicks();
timing.MarkUnloadEventStart(unload_event_start);
frame_->DomWindow()->DispatchEvent(unload_event, this);
const TimeTicks unload_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, unload_histogram,
("DocumentEventTiming.UnloadDuration", 0, 10000000, 50));
unload_histogram.Count(
(unload_event_end - unload_event_start).InMicroseconds());
timing.MarkUnloadEventEnd(unload_event_end);
} else {
frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument());
}
}
load_event_progress_ = kUnloadEventHandled;
}
if (!frame_)
return;
bool keep_event_listeners =
frame_->Loader().GetProvisionalDocumentLoader() &&
frame_->ShouldReuseDefaultView(
frame_->Loader().GetProvisionalDocumentLoader()->Url());
if (!keep_event_listeners)
RemoveAllEventListenersRecursively();
}
CWE ID: CWE-285
Target: 1
Example 2:
Code: int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
{
float **output;
int len;
if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
len = stb_vorbis_get_frame_float(f, NULL, &output);
if (len) {
if (len*num_c > num_shorts) len = num_shorts / num_c;
convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
}
return len;
}
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: double AffineTransform::yScale() const
{
return sqrt(m_transform[2] * m_transform[2] + m_transform[3] * m_transform[3]);
}
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: hstore_from_array(PG_FUNCTION_ARGS)
{
ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
int ndims = ARR_NDIM(in_array);
int count;
int32 buflen;
HStore *out;
Pairs *pairs;
Datum *in_datums;
bool *in_nulls;
int in_count;
int i;
Assert(ARR_ELEMTYPE(in_array) == TEXTOID);
switch (ndims)
{
case 0:
out = hstorePairs(NULL, 0, 0);
PG_RETURN_POINTER(out);
case 1:
if ((ARR_DIMS(in_array)[0]) % 2)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("array must have even number of elements")));
break;
case 2:
if ((ARR_DIMS(in_array)[1]) != 2)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("array must have two columns")));
break;
default:
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
}
deconstruct_array(in_array,
TEXTOID, -1, false, 'i',
&in_datums, &in_nulls, &in_count);
count = in_count / 2;
pairs = palloc(count * sizeof(Pairs));
for (i = 0; i < count; ++i)
{
if (in_nulls[i * 2])
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null value not allowed for hstore key")));
if (in_nulls[i * 2 + 1])
{
pairs[i].key = VARDATA_ANY(in_datums[i * 2]);
pairs[i].val = NULL;
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));
pairs[i].vallen = 4;
pairs[i].isnull = true;
pairs[i].needfree = false;
}
else
{
pairs[i].key = VARDATA_ANY(in_datums[i * 2]);
pairs[i].val = VARDATA_ANY(in_datums[i * 2 + 1]);
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(in_datums[i * 2]));
pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(in_datums[i * 2 + 1]));
pairs[i].isnull = false;
pairs[i].needfree = false;
}
}
count = hstoreUniquePairs(pairs, count, &buflen);
out = hstorePairs(pairs, count, buflen);
PG_RETURN_POINTER(out);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: GfxFunctionShading *GfxFunctionShading::parse(Dict *dict) {
GfxFunctionShading *shading;
double x0A, y0A, x1A, y1A;
double matrixA[6];
Function *funcsA[gfxColorMaxComps];
int nFuncsA;
Object obj1, obj2;
int i;
x0A = y0A = 0;
x1A = y1A = 1;
if (dict->lookup("Domain", &obj1)->isArray() &&
obj1.arrayGetLength() == 4) {
x0A = obj1.arrayGet(0, &obj2)->getNum();
obj2.free();
x1A = obj1.arrayGet(1, &obj2)->getNum();
obj2.free();
y0A = obj1.arrayGet(2, &obj2)->getNum();
obj2.free();
y1A = obj1.arrayGet(3, &obj2)->getNum();
obj2.free();
}
obj1.free();
matrixA[0] = 1; matrixA[1] = 0;
matrixA[2] = 0; matrixA[3] = 1;
matrixA[4] = 0; matrixA[5] = 0;
if (dict->lookup("Matrix", &obj1)->isArray() &&
obj1.arrayGetLength() == 6) {
matrixA[0] = obj1.arrayGet(0, &obj2)->getNum();
obj2.free();
matrixA[1] = obj1.arrayGet(1, &obj2)->getNum();
obj2.free();
matrixA[2] = obj1.arrayGet(2, &obj2)->getNum();
obj2.free();
matrixA[3] = obj1.arrayGet(3, &obj2)->getNum();
obj2.free();
matrixA[4] = obj1.arrayGet(4, &obj2)->getNum();
obj2.free();
matrixA[5] = obj1.arrayGet(5, &obj2)->getNum();
obj2.free();
}
obj1.free();
dict->lookup("Function", &obj1);
if (obj1.isArray()) {
nFuncsA = obj1.arrayGetLength();
if (nFuncsA > gfxColorMaxComps) {
error(-1, "Invalid Function array in shading dictionary");
goto err1;
}
for (i = 0; i < nFuncsA; ++i) {
obj1.arrayGet(i, &obj2);
if (!(funcsA[i] = Function::parse(&obj2))) {
goto err2;
}
obj2.free();
}
} else {
nFuncsA = 1;
if (!(funcsA[0] = Function::parse(&obj1))) {
goto err1;
}
}
obj1.free();
shading = new GfxFunctionShading(x0A, y0A, x1A, y1A, matrixA,
funcsA, nFuncsA);
if (!shading->init(dict)) {
delete shading;
return NULL;
}
return shading;
err2:
obj2.free();
err1:
obj1.free();
return NULL;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void EmulationHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
if (host_ == frame_host)
return;
host_ = frame_host;
if (touch_emulation_enabled_)
UpdateTouchEventEmulationState();
UpdateDeviceEmulationState();
}
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 print_cfs_stats(struct seq_file *m, int cpu)
{
struct cfs_rq *cfs_rq, *pos;
rcu_read_lock();
for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
print_cfs_rq(m, cpu, cfs_rq);
rcu_read_unlock();
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_pocpchg_t *pchg;
int pchgno;
for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs;
++pchgno, ++pchg) {
fprintf(out, "po[%d] = %d; ", pchgno, pchg->prgord);
fprintf(out, "cs[%d] = %d; ce[%d] = %d; ",
pchgno, pchg->compnostart, pchgno, pchg->compnoend);
fprintf(out, "rs[%d] = %d; re[%d] = %d; ",
pchgno, pchg->rlvlnostart, pchgno, pchg->rlvlnoend);
fprintf(out, "le[%d] = %d\n", pchgno, pchg->lyrnoend);
}
return 0;
}
CWE ID: CWE-369
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 testUriHostIpSix2() {
UriParserStateA stateA;
UriUriA uriA;
stateA.uri = &uriA;
const char * const input = "http" "://" "[::1]";
TEST_ASSERT(0 == uriParseUriA(&stateA, input));
TEST_ASSERT(uriA.hostText.first == input + 4 + 3 + 1);
TEST_ASSERT(uriA.hostText.afterLast == input + 4 + 3 + 4);
TEST_ASSERT(uriA.hostData.ip4 == NULL);
TEST_ASSERT(uriA.hostData.ip6 != NULL);
TEST_ASSERT(uriA.hostData.ipFuture.first == NULL);
TEST_ASSERT(uriA.hostData.ipFuture.afterLast == NULL);
uriFreeUriMembersA(&uriA);
}
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: int vrend_create_shader(struct vrend_context *ctx,
uint32_t handle,
const struct pipe_stream_output_info *so_info,
const char *shd_text, uint32_t offlen, uint32_t num_tokens,
uint32_t type, uint32_t pkt_length)
{
struct vrend_shader_selector *sel = NULL;
int ret_handle;
bool new_shader = true, long_shader = false;
bool finished = false;
int ret;
if (type > PIPE_SHADER_GEOMETRY)
return EINVAL;
if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT)
new_shader = false;
else if (((offlen + 3) / 4) > pkt_length)
long_shader = true;
/* if we have an in progress one - don't allow a new shader
of that type or a different handle. */
if (ctx->sub->long_shader_in_progress_handle[type]) {
if (new_shader == true)
return EINVAL;
if (handle != ctx->sub->long_shader_in_progress_handle[type])
return EINVAL;
}
if (new_shader) {
sel = vrend_create_shader_state(ctx, so_info, type);
if (sel == NULL)
return ENOMEM;
if (long_shader) {
sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */
sel->tmp_buf = malloc(sel->buf_len);
if (!sel->tmp_buf) {
ret = ENOMEM;
goto error;
}
memcpy(sel->tmp_buf, shd_text, pkt_length * 4);
sel->buf_offset = pkt_length * 4;
ctx->sub->long_shader_in_progress_handle[type] = handle;
} else
finished = true;
} else {
sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER);
if (!sel) {
fprintf(stderr, "got continuation without original shader %d\n", handle);
ret = EINVAL;
goto error;
}
offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT;
if (offlen != sel->buf_offset) {
fprintf(stderr, "Got mismatched shader continuation %d vs %d\n",
offlen, sel->buf_offset);
ret = EINVAL;
goto error;
}
if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) {
fprintf(stderr, "Got too large shader continuation %d vs %d\n",
pkt_length * 4 + sel->buf_offset, sel->buf_len);
shd_text = sel->tmp_buf;
}
}
if (finished) {
struct tgsi_token *tokens;
tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token));
if (!tokens) {
ret = ENOMEM;
goto error;
}
if (vrend_dump_shaders)
fprintf(stderr,"shader\n%s\n", shd_text);
if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) {
free(tokens);
ret = EINVAL;
goto error;
}
if (vrend_finish_shader(ctx, sel, tokens)) {
free(tokens);
ret = EINVAL;
goto error;
} else {
free(sel->tmp_buf);
sel->tmp_buf = NULL;
}
free(tokens);
ctx->sub->long_shader_in_progress_handle[type] = 0;
}
if (new_shader) {
ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER);
if (ret_handle == 0) {
ret = ENOMEM;
goto error;
}
}
return 0;
error:
if (new_shader)
vrend_destroy_shader_selector(sel);
else
vrend_renderer_object_destroy(ctx, handle);
return ret;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: LIBOPENMPT_MODPLUG_API int ModPlug_GetCurrentPattern(ModPlugFile* file)
{
if(!file) return 0;
return openmpt_module_get_current_pattern(file->mod);
}
CWE ID: CWE-120
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 tipc_nl_compat_link_dump(struct tipc_nl_compat_msg *msg,
struct nlattr **attrs)
{
struct nlattr *link[TIPC_NLA_LINK_MAX + 1];
struct tipc_link_info link_info;
int err;
if (!attrs[TIPC_NLA_LINK])
return -EINVAL;
err = nla_parse_nested(link, TIPC_NLA_LINK_MAX, attrs[TIPC_NLA_LINK],
NULL);
if (err)
return err;
link_info.dest = nla_get_flag(link[TIPC_NLA_LINK_DEST]);
link_info.up = htonl(nla_get_flag(link[TIPC_NLA_LINK_UP]));
strcpy(link_info.str, nla_data(link[TIPC_NLA_LINK_NAME]));
return tipc_add_tlv(msg->rep, TIPC_TLV_LINK_INFO,
&link_info, sizeof(link_info));
}
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: png_write_destroy(png_structp png_ptr)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* Save jump buffer */
#endif
png_error_ptr error_fn;
png_error_ptr warning_fn;
png_voidp error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_free_ptr free_fn;
#endif
png_debug(1, "in png_write_destroy");
/* Free any memory zlib uses */
deflateEnd(&png_ptr->zstream);
/* Free our memory. png_free checks NULL for us. */
png_free(png_ptr, png_ptr->zbuf);
png_free(png_ptr, png_ptr->row_buf);
#ifdef PNG_WRITE_FILTER_SUPPORTED
png_free(png_ptr, png_ptr->prev_row);
png_free(png_ptr, png_ptr->sub_row);
png_free(png_ptr, png_ptr->up_row);
png_free(png_ptr, png_ptr->avg_row);
png_free(png_ptr, png_ptr->paeth_row);
#endif
#ifdef PNG_TIME_RFC1123_SUPPORTED
png_free(png_ptr, png_ptr->time_buffer);
#endif
#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
png_free(png_ptr, png_ptr->prev_filters);
png_free(png_ptr, png_ptr->filter_weights);
png_free(png_ptr, png_ptr->inv_filter_weights);
png_free(png_ptr, png_ptr->filter_costs);
png_free(png_ptr, png_ptr->inv_filter_costs);
#endif
#ifdef PNG_SETJMP_SUPPORTED
/* Reset structure */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf));
#endif
error_fn = png_ptr->error_fn;
warning_fn = png_ptr->warning_fn;
error_ptr = png_ptr->error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
free_fn = png_ptr->free_fn;
#endif
png_memset(png_ptr, 0, png_sizeof(png_struct));
png_ptr->error_fn = error_fn;
png_ptr->warning_fn = warning_fn;
png_ptr->error_ptr = error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_ptr->free_fn = free_fn;
#endif
#ifdef PNG_SETJMP_SUPPORTED
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf));
#endif
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static BOOL update_send_frame_acknowledge(rdpContext* context, UINT32 frameId)
{
rdpRdp* rdp = context->rdp;
if (rdp->settings->ReceivedCapabilities[CAPSET_TYPE_FRAME_ACKNOWLEDGE])
{
wStream* s = rdp_data_pdu_init(rdp);
if (!s)
return FALSE;
Stream_Write_UINT32(s, frameId);
return rdp_send_data_pdu(rdp, s, DATA_PDU_TYPE_FRAME_ACKNOWLEDGE,
rdp->mcs->userId);
}
return TRUE;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Cues::Init() const
{
if (m_cue_points)
return;
assert(m_count == 0);
assert(m_preload_count == 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
const long long stop = m_start + m_size;
long long pos = m_start;
long cue_points_size = 0;
while (pos < stop)
{
const long long idpos = pos;
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); //TODO
assert((pos + len) <= stop);
pos += len; //consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; //consume Size field
assert((pos + size) <= stop);
if (id == 0x3B) //CuePoint ID
PreloadCuePoint(cue_points_size, idpos);
pos += size; //consume payload
assert(pos <= stop);
}
}
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: uint8_t* FAST_FUNC udhcp_get_option32(struct dhcp_packet *packet, int code)
{
uint8_t *r = udhcp_get_option(packet, code);
if (r) {
if (r[-1] != 4)
r = NULL;
}
return r;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: FileSystemDelegate* ChromeExtensionsAPIClient::GetFileSystemDelegate() {
if (!file_system_delegate_)
file_system_delegate_ = base::MakeUnique<ChromeFileSystemDelegate>();
return file_system_delegate_.get();
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static char sctp_tietags_compare(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
/* In this case, the peer may have restarted. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag != new_asoc->c.peer_vtag) &&
(asoc->c.my_vtag == new_asoc->c.my_ttag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_ttag))
return 'A';
/* Collision case B. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
((asoc->c.peer_vtag != new_asoc->c.peer_vtag) ||
(0 == asoc->c.peer_vtag))) {
return 'B';
}
/* Collision case D. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag))
return 'D';
/* Collision case C. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag) &&
(0 == new_asoc->c.my_ttag) &&
(0 == new_asoc->c.peer_ttag))
return 'C';
/* No match to any of the special cases; discard this packet. */
return 'E';
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool InputMethodController::FinishComposingText(
ConfirmCompositionBehavior confirm_behavior) {
if (!HasComposition())
return false;
const bool is_too_long = IsTextTooLongAt(composition_range_->StartPosition());
const String& composing = ComposingText();
if (confirm_behavior == kKeepSelection) {
const bool is_handle_visible = GetFrame().Selection().IsHandleVisible();
const PlainTextRange& old_offsets = GetSelectionOffsets();
Editor::RevealSelectionScope reveal_selection_scope(&GetEditor());
if (is_too_long) {
ReplaceComposition(ComposingText());
} else {
Clear();
DispatchCompositionEndEvent(GetFrame(), composing);
}
GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& old_selection_range =
EphemeralRangeForOffsets(old_offsets);
if (old_selection_range.IsNull())
return false;
const SelectionInDOMTree& selection =
SelectionInDOMTree::Builder()
.SetBaseAndExtent(old_selection_range)
.SetIsHandleVisible(is_handle_visible)
.Build();
GetFrame().Selection().SetSelection(
selection,
SetSelectionData::Builder().SetShouldCloseTyping(true).Build());
return true;
}
Element* root_editable_element =
GetFrame()
.Selection()
.ComputeVisibleSelectionInDOMTreeDeprecated()
.RootEditableElement();
if (!root_editable_element)
return false;
PlainTextRange composition_range =
PlainTextRange::Create(*root_editable_element, *composition_range_);
if (composition_range.IsNull())
return false;
if (is_too_long) {
ReplaceComposition(ComposingText());
} else {
Clear();
}
if (!MoveCaret(composition_range.End()))
return false;
DispatchCompositionEndEvent(GetFrame(), composing);
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int handle_bb_cf_recursive_descent (RAnal *anal, RAnalState *state) {
RAnalBlock *bb = state->current_bb;
ut64 addr = 0;
int result = 0;
if (!bb) {
eprintf ("Error: unable to handle basic block @ 0x%08"PFMT64x"\n", addr);
return R_ANAL_RET_ERROR;
} else if (state->max_depth <= state->current_depth) {
return R_ANAL_RET_ERROR;
}
state->current_depth++;
addr = bb->addr;
IFDBG eprintf ("Handling a control flow change @ 0x%04"PFMT64x".\n", addr);
ut64 control_type = r_anal_ex_map_anal_ex_to_anal_op_type (bb->type2);
switch (control_type) {
case R_ANAL_OP_TYPE_CALL:
IFDBG eprintf (" - Handling a call @ 0x%04"PFMT64x".\n", addr);
r_anal_xrefs_set (anal, bb->addr, bb->jump, R_ANAL_REF_TYPE_CALL);
result = R_ANAL_RET_ERROR;
break;
case R_ANAL_OP_TYPE_JMP:
{
RList * jmp_list;
IFDBG eprintf (" - Handling a jmp @ 0x%04"PFMT64x" to 0x%04"PFMT64x".\n", addr, bb->jump);
if (!r_anal_state_search_bb (state, bb->jump)) {
jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump );
if (jmp_list)
bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0);
if (bb->jumpbb)
bb->jump = bb->jumpbb->addr;
} else {
bb->jumpbb = r_anal_state_search_bb (state, bb->jump);
if (bb->jumpbb)
bb->jump = bb->jumpbb->addr;
}
if (state->done == 1) {
IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr);
}
result = R_ANAL_RET_END;
}
break;
case R_ANAL_OP_TYPE_CJMP:
{
RList *jmp_list;
ut8 encountered_stop = 0;
IFDBG eprintf (" - Handling a cjmp @ 0x%04"PFMT64x" jmp to 0x%04"PFMT64x" and fail to 0x%04"PFMT64x".\n", addr, bb->jump, bb->fail);
IFDBG eprintf (" - Handling jmp to 0x%04"PFMT64x".\n", bb->jump);
if (!r_anal_state_search_bb (state, bb->jump)) {
jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump );
if (jmp_list)
bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0);
if (bb->jumpbb) {
bb->jump = bb->jumpbb->addr;
}
} else {
bb->jumpbb = r_anal_state_search_bb (state, bb->jump);
bb->jump = bb->jumpbb->addr;
}
if (state->done == 1) {
IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr);
state->done = 0;
encountered_stop = 1;
}
if (!r_anal_state_search_bb (state, bb->fail)) {
jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->fail );
if (jmp_list)
bb->failbb = (RAnalBlock *) r_list_get_n (jmp_list, 0);
if (bb->failbb) {
bb->fail = bb->failbb->addr;
}
} else {
bb->failbb = r_anal_state_search_bb (state, bb->fail);
if (bb->failbb) {
bb->fail = bb->failbb->addr;
}
}
IFDBG eprintf (" - Handling an cjmp @ 0x%04"PFMT64x" jmp to 0x%04"PFMT64x" and fail to 0x%04"PFMT64x".\n", addr, bb->jump, bb->fail);
IFDBG eprintf (" - Handling fail to 0x%04"PFMT64x".\n", bb->fail);
if (state->done == 1) {
IFDBG eprintf (" Looks like this fail (bb @ 0x%04"PFMT64x") found a return.\n", addr);
}
result = R_ANAL_RET_END;
if (encountered_stop) state->done = 1;
}
break;
case R_ANAL_OP_TYPE_SWITCH:
{
IFDBG eprintf (" - Handling an switch @ 0x%04"PFMT64x".\n", addr);
if (bb->switch_op) {
RAnalCaseOp *caseop;
RListIter *iter;
RList *jmp_list = NULL;
ut8 encountered_stop = 0;
r_list_foreach (bb->switch_op->cases, iter, caseop) {
if (caseop) {
if (r_anal_state_addr_is_valid (state, caseop->jump) ) {
jmp_list = r_anal_ex_perform_analysis ( anal, state, caseop->jump );
if (jmp_list)
caseop->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0);
if (state->done == 1) {
IFDBG eprintf (" Looks like this jmp (bb @ 0x%04"PFMT64x") found a return.\n", addr);
state->done = 0;
encountered_stop = 1;
}
}
}
}
r_list_free (jmp_list);
if (encountered_stop) state->done = 1;
}
result = R_ANAL_RET_END;
}
break;
case R_ANAL_OP_TYPE_TRAP:
case R_ANAL_OP_TYPE_UJMP:
case R_ANAL_OP_TYPE_IJMP:
case R_ANAL_OP_TYPE_RJMP:
case R_ANAL_OP_TYPE_IRJMP:
case R_ANAL_OP_TYPE_RET:
case R_ANAL_OP_TYPE_ILL:
IFDBG eprintf (" - Handling an ret @ 0x%04"PFMT64x".\n", addr);
state->done = 1;
result = R_ANAL_RET_END;
break;
default: break;
}
state->current_depth--;
return result;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rtecp_reset_retry_counter(sc_card_t *card, unsigned int type,
int ref_qualifier, const u8 *puk, size_t puklen,
const u8 *newref, size_t newlen)
{
sc_apdu_t apdu;
int r;
(void)type, (void)puk, (void)puklen; /* no warning */
assert(card && card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 0x03, ref_qualifier);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Unblock card failed");
if (newref && newlen) {
u8 tmp[2], buf[SC_MAX_APDU_BUFFER_SIZE];
u8 *p = buf;
tmp[0] = (newlen >> 8) & 0xFF;
tmp[1] = newlen & 0xFF;
sc_asn1_put_tag(0x80, tmp, sizeof(tmp), p, sizeof(buf) - (p - buf), &p);
r = sc_asn1_put_tag(0xA5, newref, newlen, p, sizeof(buf) - (p - buf), &p);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Invalid new PIN length");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0x01, ref_qualifier);
apdu.lc = p - buf;
apdu.data = buf;
apdu.datalen = p - buf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Set PIN failed");
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
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 boolean ReadIPTCProfile(j_decompress_ptr jpeg_info)
{
char
magick[MagickPathExtent];
ErrorManager
*error_manager;
ExceptionInfo
*exception;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*iptc_profile,
*profile;
/*
Determine length of binary data stored here.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
/*
Validate that this was written as a Photoshop resource format slug.
*/
for (i=0; i < 10; i++)
magick[i]=(char) GetCharacter(jpeg_info);
magick[10]='\0';
length-=10;
if (length <= 10)
return(TRUE);
if (LocaleCompare(magick,"Photoshop ") != 0)
{
/*
Not a IPTC profile, return.
*/
for (i=0; i < (ssize_t) length; i++)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
/*
Remove the version number.
*/
for (i=0; i < 4; i++)
if (GetCharacter(jpeg_info) == EOF)
break;
if (length <= 11)
return(TRUE);
length-=4;
error_manager=(ErrorManager *) jpeg_info->client_data;
exception=error_manager->exception;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=GetCharacter(jpeg_info);
if (c == EOF)
break;
*p++=(unsigned char) c;
}
error_manager->profile=NULL;
if (i != (ssize_t) length)
{
profile=DestroyStringInfo(profile);
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"InsufficientImageDataInFile","`%s'",
image->filename);
return(FALSE);
}
/* The IPTC profile is actually an 8bim */
iptc_profile=(StringInfo *) GetImageProfile(image,"8bim");
if (iptc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(iptc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: iptc, %.20g bytes",(double) length);
return(TRUE);
}
CWE ID:
Target: 1
Example 2:
Code: static void ipip_tunnel_init(struct net_device *dev)
{
struct ip_tunnel *tunnel = netdev_priv(dev);
tunnel->dev = dev;
strcpy(tunnel->parms.name, dev->name);
memcpy(dev->dev_addr, &tunnel->parms.iph.saddr, 4);
memcpy(dev->broadcast, &tunnel->parms.iph.daddr, 4);
ipip_tunnel_bind_dev(dev);
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int r_flush(apr_vformatter_buff_t *buff)
{
/* callback function passed to ap_vformatter to be called when
* vformatter needs to write into buff and buff.curpos > buff.endpos */
/* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
* "downcast" to an ap_vrprintf_data */
struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
if (vd->r->connection->aborted)
return -1;
/* r_flush is called when vbuff is completely full */
if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
return -1;
}
/* reset the buffer position */
vd->vbuff.curpos = vd->buff;
vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
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: static void rng_egd_request_entropy(RngBackend *b, size_t size,
EntropyReceiveFunc *receive_entropy,
void *opaque)
{
RngEgd *s = RNG_EGD(b);
RngRequest *req;
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
while (size > 0) {
uint8_t header[2];
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
size -= len;
}
s->parent.requests = g_slist_append(s->parent.requests, req);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: lseg_vertical(PG_FUNCTION_ARGS)
{
LSEG *lseg = PG_GETARG_LSEG_P(0);
PG_RETURN_BOOL(FPeq(lseg->p[0].x, lseg->p[1].x));
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int sco_sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int len, err = 0;
struct bt_voice voice;
u32 opt;
BT_DBG("sk %p", sk);
lock_sock(sk);
switch (optname) {
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt)
set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
else
clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
break;
case BT_VOICE:
if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND &&
sk->sk_state != BT_CONNECT2) {
err = -EINVAL;
break;
}
voice.setting = sco_pi(sk)->setting;
len = min_t(unsigned int, sizeof(voice), optlen);
if (copy_from_user((char *)&voice, optval, len)) {
err = -EFAULT;
break;
}
/* Explicitly check for these values */
if (voice.setting != BT_VOICE_TRANSPARENT &&
voice.setting != BT_VOICE_CVSD_16BIT) {
err = -EINVAL;
break;
}
sco_pi(sk)->setting = voice.setting;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
unsigned int copied, rlen;
struct sk_buff *skb, *cskb;
int err = 0;
pr_debug("%p %zu\n", sk, len);
msg->msg_namelen = 0;
lock_sock(sk);
if (sk->sk_state == LLCP_CLOSED &&
skb_queue_empty(&sk->sk_receive_queue)) {
release_sock(sk);
return 0;
}
release_sock(sk);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb) {
pr_err("Recv datagram failed state %d %d %d",
sk->sk_state, err, sock_error(sk));
if (sk->sk_shutdown & RCV_SHUTDOWN)
return 0;
return err;
}
rlen = skb->len; /* real length of skb */
copied = min_t(unsigned int, rlen, len);
cskb = skb;
if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) {
if (!(flags & MSG_PEEK))
skb_queue_head(&sk->sk_receive_queue, skb);
return -EFAULT;
}
sock_recv_timestamp(msg, sk, skb);
if (sk->sk_type == SOCK_DGRAM && msg->msg_name) {
struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb);
struct sockaddr_nfc_llcp *sockaddr =
(struct sockaddr_nfc_llcp *) msg->msg_name;
msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp);
pr_debug("Datagram socket %d %d\n", ui_cb->dsap, ui_cb->ssap);
memset(sockaddr, 0, sizeof(*sockaddr));
sockaddr->sa_family = AF_NFC;
sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP;
sockaddr->dsap = ui_cb->dsap;
sockaddr->ssap = ui_cb->ssap;
}
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
/* SOCK_STREAM: re-queue skb if it contains unreceived data */
if (sk->sk_type == SOCK_STREAM ||
sk->sk_type == SOCK_DGRAM ||
sk->sk_type == SOCK_RAW) {
skb_pull(skb, copied);
if (skb->len) {
skb_queue_head(&sk->sk_receive_queue, skb);
goto done;
}
}
kfree_skb(skb);
}
/* XXX Queue backlogged skbs */
done:
/* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */
if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC))
copied = rlen;
return copied;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int __init sha1_neon_mod_init(void)
{
if (!cpu_has_neon())
return -ENODEV;
return crypto_register_shash(&alg);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FeatureInfo::EnableOESTextureHalfFloatLinear() {
if (!oes_texture_half_float_linear_available_)
return;
AddExtensionString("GL_OES_texture_half_float_linear");
feature_flags_.enable_texture_half_float_linear = true;
feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RGBA_F16);
}
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: eval_js(WebKitWebView * web_view, gchar *script, GString *result) {
WebKitWebFrame *frame;
JSGlobalContextRef context;
JSObjectRef globalobject;
JSStringRef var_name;
JSStringRef js_script;
JSValueRef js_result;
JSStringRef js_result_string;
size_t js_result_size;
js_init();
frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(web_view));
context = webkit_web_frame_get_global_context(frame);
globalobject = JSContextGetGlobalObject(context);
/* uzbl javascript namespace */
var_name = JSStringCreateWithUTF8CString("Uzbl");
JSObjectSetProperty(context, globalobject, var_name,
JSObjectMake(context, uzbl.js.classref, NULL),
kJSClassAttributeNone, NULL);
/* evaluate the script and get return value*/
js_script = JSStringCreateWithUTF8CString(script);
js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL);
if (js_result && !JSValueIsUndefined(context, js_result)) {
js_result_string = JSValueToStringCopy(context, js_result, NULL);
js_result_size = JSStringGetMaximumUTF8CStringSize(js_result_string);
if (js_result_size) {
char js_result_utf8[js_result_size];
JSStringGetUTF8CString(js_result_string, js_result_utf8, js_result_size);
g_string_assign(result, js_result_utf8);
}
JSStringRelease(js_result_string);
}
/* cleanup */
JSObjectDeleteProperty(context, globalobject, var_name, NULL);
JSStringRelease(var_name);
JSStringRelease(js_script);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static struct dentry *nsfs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_pseudo(fs_type, "nsfs:", &nsfs_ops,
&ns_dentry_operations, NSFS_MAGIC);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int countValidCursors(BtShared *pBt, int wrOnly){
BtCursor *pCur;
int r = 0;
for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
&& pCur->eState!=CURSOR_FAULT ) r++;
}
return r;
}
CWE ID: CWE-190
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GLboolean WebGLRenderingContextBase::isShader(WebGLShader* shader) {
if (!shader || isContextLost())
return 0;
return ContextGL()->IsShader(shader->Object());
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Document::DispatchUnloadEvents() {
PluginScriptForbiddenScope forbid_plugin_destructor_scripting;
if (parser_)
parser_->StopParsing();
if (load_event_progress_ == kLoadEventNotRun)
return;
if (load_event_progress_ <= kUnloadEventInProgress) {
Element* current_focused_element = FocusedElement();
if (auto* input = ToHTMLInputElementOrNull(current_focused_element))
input->EndEditing();
if (load_event_progress_ < kPageHideInProgress) {
load_event_progress_ = kPageHideInProgress;
if (LocalDOMWindow* window = domWindow()) {
const TimeTicks pagehide_event_start = CurrentTimeTicks();
window->DispatchEvent(
*PageTransitionEvent::Create(event_type_names::kPagehide, false),
this);
const TimeTicks pagehide_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, pagehide_histogram,
("DocumentEventTiming.PageHideDuration", 0, 10000000, 50));
pagehide_histogram.CountMicroseconds(pagehide_event_end -
pagehide_event_start);
}
if (!frame_)
return;
mojom::PageVisibilityState visibility_state = GetPageVisibilityState();
load_event_progress_ = kUnloadVisibilityChangeInProgress;
if (visibility_state != mojom::PageVisibilityState::kHidden) {
const TimeTicks pagevisibility_hidden_event_start = CurrentTimeTicks();
DispatchEvent(
*Event::CreateBubble(event_type_names::kVisibilitychange));
const TimeTicks pagevisibility_hidden_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(CustomCountHistogram, pagevisibility_histogram,
("DocumentEventTiming.PageVibilityHiddenDuration",
0, 10000000, 50));
pagevisibility_histogram.CountMicroseconds(
pagevisibility_hidden_event_end -
pagevisibility_hidden_event_start);
DispatchEvent(
*Event::CreateBubble(event_type_names::kWebkitvisibilitychange));
}
if (!frame_)
return;
frame_->Loader().SaveScrollAnchor();
DocumentLoader* document_loader =
frame_->Loader().GetProvisionalDocumentLoader();
load_event_progress_ = kUnloadEventInProgress;
Event& unload_event = *Event::Create(event_type_names::kUnload);
if (document_loader &&
document_loader->GetTiming().UnloadEventStart().is_null() &&
document_loader->GetTiming().UnloadEventEnd().is_null()) {
DocumentLoadTiming& timing = document_loader->GetTiming();
DCHECK(!timing.NavigationStart().is_null());
const TimeTicks unload_event_start = CurrentTimeTicks();
timing.MarkUnloadEventStart(unload_event_start);
frame_->DomWindow()->DispatchEvent(unload_event, this);
const TimeTicks unload_event_end = CurrentTimeTicks();
DEFINE_STATIC_LOCAL(
CustomCountHistogram, unload_histogram,
("DocumentEventTiming.UnloadDuration", 0, 10000000, 50));
unload_histogram.CountMicroseconds(unload_event_end -
unload_event_start);
timing.MarkUnloadEventEnd(unload_event_end);
} else {
frame_->DomWindow()->DispatchEvent(unload_event, frame_->GetDocument());
}
}
load_event_progress_ = kUnloadEventHandled;
}
if (!frame_)
return;
bool keep_event_listeners =
frame_->Loader().GetProvisionalDocumentLoader() &&
frame_->ShouldReuseDefaultView(
frame_->Loader().GetProvisionalDocumentLoader()->Url(),
frame_->Loader()
.GetProvisionalDocumentLoader()
->GetContentSecurityPolicy());
if (!keep_event_listeners)
RemoveAllEventListenersRecursively();
}
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 signed short ReadPropertyMSBShort(const unsigned char **p,
size_t *length)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[2];
unsigned short
value;
if (*length < 2)
return((unsigned short) ~0);
for (i=0; i < 2; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned short) (buffer[0] << 8);
value|=buffer[1];
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
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: CreateDataReductionProxyChromeIOData(
Profile* profile,
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(profile);
DCHECK(profile->GetPrefs());
data_reduction_proxy::DataReductionProxySettings*
data_reduction_proxy_settings =
DataReductionProxyChromeSettingsFactory::GetForBrowserContext(
profile);
bool enabled = data_reduction_proxy_settings &&
data_reduction_proxy_settings->IsDataSaverEnabledByUser();
std::unique_ptr<data_reduction_proxy::DataReductionProxyIOData>
data_reduction_proxy_io_data(
new data_reduction_proxy::DataReductionProxyIOData(
DataReductionProxyChromeSettings::GetClient(),
profile->GetPrefs(), content::GetNetworkConnectionTracker(),
io_task_runner, ui_task_runner, enabled, GetUserAgent(),
version_info::GetChannelString(chrome::GetChannel())));
data_reduction_proxy_io_data->set_lofi_decider(
std::make_unique<data_reduction_proxy::ContentLoFiDecider>());
data_reduction_proxy_io_data->set_resource_type_provider(
std::make_unique<data_reduction_proxy::ContentResourceTypeProvider>());
data_reduction_proxy_io_data->set_lofi_ui_service(
std::make_unique<data_reduction_proxy::ContentLoFiUIService>(
ui_task_runner, base::Bind(&OnLoFiResponseReceivedOnUI)));
return data_reduction_proxy_io_data;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeByteSshort(int16 value)
{
if ((value<0)||(value>0xFF))
return(TIFFReadDirEntryErrRange);
else
return(TIFFReadDirEntryErrOk);
}
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: BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s)
{
UINT32 i;
BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE));
if (!bitmapUpdate)
goto fail;
if (Stream_GetRemainingLength(s) < 2)
goto fail;
Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */
WLog_Print(update->log, WLOG_TRACE, "BitmapUpdate: %"PRIu32"", bitmapUpdate->number);
if (bitmapUpdate->number > bitmapUpdate->count)
{
UINT16 count;
BITMAP_DATA* newdata;
count = bitmapUpdate->number * 2;
newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles,
sizeof(BITMAP_DATA) * count);
if (!newdata)
goto fail;
bitmapUpdate->rectangles = newdata;
ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count],
sizeof(BITMAP_DATA) * (count - bitmapUpdate->count));
bitmapUpdate->count = count;
}
/* rectangles */
for (i = 0; i < bitmapUpdate->number; i++)
{
if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i]))
goto fail;
}
return bitmapUpdate;
fail:
free_bitmap_update(update->context, bitmapUpdate);
return NULL;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->AddHandler(std::make_unique<protocol::InspectorHandler>());
session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId()));
session->AddHandler(std::make_unique<protocol::SchemaHandler>());
session->SetRenderer(GetProcess(), nullptr);
if (state_ == WORKER_READY)
session->AttachToAgent(EnsureAgent());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool WebGLRenderingContextBase::ValidateFramebufferTarget(GLenum target) {
if (target == GL_FRAMEBUFFER)
return true;
return false;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: MYSQLND_METHOD(mysqlnd_protocol, get_change_auth_response_packet)(MYSQLND_PROTOCOL * const protocol, zend_bool persistent TSRMLS_DC)
{
struct st_mysqlnd_packet_change_auth_response * packet = mnd_pecalloc(1, packet_methods[PROT_CHANGE_AUTH_RESP_PACKET].struct_size, persistent);
DBG_ENTER("mysqlnd_protocol::get_change_auth_response_packet");
if (packet) {
packet->header.m = &packet_methods[PROT_CHANGE_AUTH_RESP_PACKET];
packet->header.persistent = persistent;
}
DBG_RETURN(packet);
}
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 PrintPreviewDataService::SetDataEntry(
const std::string& preview_ui_addr_str,
int index,
const base::RefCountedBytes* data_bytes) {
PreviewDataStoreMap::iterator it = data_store_map_.find(preview_ui_addr_str);
if (it == data_store_map_.end())
data_store_map_[preview_ui_addr_str] = new PrintPreviewDataStore();
data_store_map_[preview_ui_addr_str]->SetPreviewDataForIndex(index,
data_bytes);
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void CreateFramebufferInfo(GLuint client_id, GLuint service_id) {
return framebuffer_manager()->CreateFramebufferInfo(client_id, service_id);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int SSLErrorInfo::GetErrorsForCertStatus(int cert_id,
net::CertStatus cert_status,
const GURL& url,
std::vector<SSLErrorInfo>* errors) {
const net::CertStatus kErrorFlags[] = {
net::CERT_STATUS_COMMON_NAME_INVALID,
net::CERT_STATUS_DATE_INVALID,
net::CERT_STATUS_AUTHORITY_INVALID,
net::CERT_STATUS_NO_REVOCATION_MECHANISM,
net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
net::CERT_STATUS_REVOKED,
net::CERT_STATUS_INVALID,
net::CERT_STATUS_WEAK_SIGNATURE_ALGORITHM,
net::CERT_STATUS_WEAK_KEY
};
const ErrorType kErrorTypes[] = {
CERT_COMMON_NAME_INVALID,
CERT_DATE_INVALID,
CERT_AUTHORITY_INVALID,
CERT_NO_REVOCATION_MECHANISM,
CERT_UNABLE_TO_CHECK_REVOCATION,
CERT_REVOKED,
CERT_INVALID,
CERT_WEAK_SIGNATURE_ALGORITHM,
CERT_WEAK_KEY
};
DCHECK(arraysize(kErrorFlags) == arraysize(kErrorTypes));
scoped_refptr<net::X509Certificate> cert = NULL;
int count = 0;
for (size_t i = 0; i < arraysize(kErrorFlags); ++i) {
if (cert_status & kErrorFlags[i]) {
count++;
if (!cert.get()) {
bool r = content::CertStore::GetInstance()->RetrieveCert(
cert_id, &cert);
DCHECK(r);
}
if (errors)
errors->push_back(SSLErrorInfo::CreateError(kErrorTypes[i], cert, url));
}
}
return count;
}
CWE ID: CWE-79
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void EBMLHeader::Init()
{
m_version = 1;
m_readVersion = 1;
m_maxIdLength = 4;
m_maxSizeLength = 8;
if (m_docType)
{
delete[] m_docType;
m_docType = NULL;
}
m_docTypeVersion = 1;
m_docTypeReadVersion = 1;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: BOOL IsVolumeClassFilterRegistered ()
{
UNICODE_STRING name;
NTSTATUS status;
BOOL registered = FALSE;
PKEY_VALUE_PARTIAL_INFORMATION data;
RtlInitUnicodeString (&name, L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{71A27CDD-812A-11D0-BEC7-08002BE2092F}");
status = TCReadRegistryKey (&name, L"UpperFilters", &data);
if (NT_SUCCESS (status))
{
if (data->Type == REG_MULTI_SZ && data->DataLength >= 9 * sizeof (wchar_t))
{
ULONG i;
for (i = 0; i <= data->DataLength - 9 * sizeof (wchar_t); ++i)
{
if (memcmp (data->Data + i, L"veracrypt", 9 * sizeof (wchar_t)) == 0)
{
Dump ("Volume class filter active\n");
registered = TRUE;
break;
}
}
}
TCfree (data);
}
return registered;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_FUNCTION(curl_escape)
{
char *str = NULL, *res = NULL;
size_t str_len = 0;
zval *zid;
php_curl *ch;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) {
return;
}
if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) {
RETURN_FALSE;
}
if ((res = curl_easy_escape(ch->cp, str, str_len))) {
RETVAL_STRING(res);
curl_free(res);
} else {
RETURN_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 usage_exit() {
fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n",
exec_name);
exit(EXIT_FAILURE);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void __net_exit nf_ct_frags6_sysctl_unregister(struct net *net)
{
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ExtensionTtsSpeakCompletedFunction::RunImpl() {
int request_id;
std::string error_message;
EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &request_id));
if (args_->GetSize() >= 2)
EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &error_message));
ExtensionTtsController::GetInstance()->OnSpeechFinished(
request_id, error_message);
return true;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: nfsd_dispatch(struct svc_rqst *rqstp, __be32 *statp)
{
struct svc_procedure *proc;
kxdrproc_t xdr;
__be32 nfserr;
__be32 *nfserrp;
dprintk("nfsd_dispatch: vers %d proc %d\n",
rqstp->rq_vers, rqstp->rq_proc);
proc = rqstp->rq_procinfo;
/*
* Give the xdr decoder a chance to change this if it wants
* (necessary in the NFSv4.0 compound case)
*/
rqstp->rq_cachetype = proc->pc_cachetype;
/* Decode arguments */
xdr = proc->pc_decode;
if (xdr && !xdr(rqstp, (__be32*)rqstp->rq_arg.head[0].iov_base,
rqstp->rq_argp)) {
dprintk("nfsd: failed to decode arguments!\n");
*statp = rpc_garbage_args;
return 1;
}
/* Check whether we have this call in the cache. */
switch (nfsd_cache_lookup(rqstp)) {
case RC_DROPIT:
return 0;
case RC_REPLY:
return 1;
case RC_DOIT:;
/* do it */
}
/* need to grab the location to store the status, as
* nfsv4 does some encoding while processing
*/
nfserrp = rqstp->rq_res.head[0].iov_base
+ rqstp->rq_res.head[0].iov_len;
rqstp->rq_res.head[0].iov_len += sizeof(__be32);
/* Now call the procedure handler, and encode NFS status. */
nfserr = proc->pc_func(rqstp, rqstp->rq_argp, rqstp->rq_resp);
nfserr = map_new_errors(rqstp->rq_vers, nfserr);
if (nfserr == nfserr_dropit || test_bit(RQ_DROPME, &rqstp->rq_flags)) {
dprintk("nfsd: Dropping request; may be revisited later\n");
nfsd_cache_update(rqstp, RC_NOCACHE, NULL);
return 0;
}
if (rqstp->rq_proc != 0)
*nfserrp++ = nfserr;
/* Encode result.
* For NFSv2, additional info is never returned in case of an error.
*/
if (!(nfserr && rqstp->rq_vers == 2)) {
xdr = proc->pc_encode;
if (xdr && !xdr(rqstp, nfserrp,
rqstp->rq_resp)) {
/* Failed to encode result. Release cache entry */
dprintk("nfsd: failed to encode result!\n");
nfsd_cache_update(rqstp, RC_NOCACHE, NULL);
*statp = rpc_system_err;
return 1;
}
}
/* Store reply in cache. */
nfsd_cache_update(rqstp, rqstp->rq_cachetype, statp + 1);
return 1;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void sig_winch(int sig) {
unsigned short width,height;
struct mt_packet data;
int plen;
/* terminal height/width has changed, inform server */
if (get_terminal_size(&width, &height) != -1) {
init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
width = htole16(width);
height = htole16(height);
plen = add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2);
plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2);
outcounter += plen;
send_udp(&data, 1);
}
/* reinstate signal handler */
signal(SIGWINCH, sig_winch);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ExtensionResourceRequestPolicy::CanRequestResource(
const GURL& resource_url,
const GURL& frame_url,
const ExtensionSet* loaded_extensions) {
CHECK(resource_url.SchemeIs(chrome::kExtensionScheme));
const Extension* extension =
loaded_extensions->GetExtensionOrAppByURL(ExtensionURLInfo(resource_url));
if (!extension) {
return true;
}
std::string resource_root_relative_path =
resource_url.path().empty() ? "" : resource_url.path().substr(1);
if (extension->is_hosted_app() &&
!extension->icons().ContainsPath(resource_root_relative_path)) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " from "
<< "hosted app.";
return false;
}
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableExtensionsResourceWhitelist) &&
!frame_url.is_empty() &&
!frame_url.SchemeIs(chrome::kExtensionScheme) &&
!extension->IsResourceWebAccessible(resource_url.path())) {
LOG(ERROR) << "Denying load of " << resource_url.spec() << " which "
<< "is not a web accessible resource.";
return false;
}
return true;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) {
DCHECK(CalledOnValidThread());
DCHECK(!is_connected());
DCHECK(!remote_address_.get());
int addr_family = address.GetSockAddrFamily();
int rv = CreateSocket(addr_family);
if (rv < 0)
return rv;
if (bind_type_ == DatagramSocket::RANDOM_BIND) {
size_t addr_size =
addr_family == AF_INET ? kIPv4AddressSize : kIPv6AddressSize;
IPAddressNumber addr_any(addr_size);
rv = RandomBind(addr_any);
}
if (rv < 0) {
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketRandomBindErrorCode", rv);
Close();
return rv;
}
SockaddrStorage storage;
if (!address.ToSockAddr(storage.addr, &storage.addr_len)) {
Close();
return ERR_ADDRESS_INVALID;
}
rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len));
if (rv < 0) {
int result = MapSystemError(errno);
Close();
return result;
}
remote_address_.reset(new IPEndPoint(address));
return rv;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: ecc_point* wc_ecc_new_point_h(void* heap)
{
ecc_point* p;
(void)heap;
p = (ecc_point*)XMALLOC(sizeof(ecc_point), heap, DYNAMIC_TYPE_ECC);
if (p == NULL) {
return NULL;
}
XMEMSET(p, 0, sizeof(ecc_point));
#ifndef ALT_ECC_SIZE
if (mp_init_multi(p->x, p->y, p->z, NULL, NULL, NULL) != MP_OKAY) {
XFREE(p, heap, DYNAMIC_TYPE_ECC);
return NULL;
}
#else
p->x = (mp_int*)&p->xyz[0];
p->y = (mp_int*)&p->xyz[1];
p->z = (mp_int*)&p->xyz[2];
alt_fp_init(p->x);
alt_fp_init(p->y);
alt_fp_init(p->z);
#endif
return p;
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void qeth_core_remove_device(struct ccwgroup_device *gdev)
{
unsigned long flags;
struct qeth_card *card = dev_get_drvdata(&gdev->dev);
QETH_DBF_TEXT(SETUP, 2, "removedv");
if (card->discipline) {
card->discipline->remove(gdev);
qeth_core_free_discipline(card);
}
write_lock_irqsave(&qeth_core_card_list.rwlock, flags);
list_del(&card->list);
write_unlock_irqrestore(&qeth_core_card_list.rwlock, flags);
qeth_core_free_card(card);
dev_set_drvdata(&gdev->dev, NULL);
put_device(&gdev->dev);
return;
}
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: status_t OMXNodeInstance::useBuffer(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_UseBuffer(
mHandle, &header, portIndex, buffer_meta,
allottedSize, static_cast<OMX_U8 *>(params->pointer()));
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER(
portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer()));
return OK;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
{
struct perf_sample_data data;
if (WARN_ON_ONCE(!regs))
return;
perf_sample_data_init(&data, addr, 0);
do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int sysvipc_proc_open(struct inode *inode, struct file *file)
{
int ret;
struct seq_file *seq;
struct ipc_proc_iter *iter;
ret = -ENOMEM;
iter = kmalloc(sizeof(*iter), GFP_KERNEL);
if (!iter)
goto out;
ret = seq_open(file, &sysvipc_proc_seqops);
if (ret)
goto out_kfree;
seq = file->private_data;
seq->private = iter;
iter->iface = PDE(inode)->data;
iter->ns = get_ipc_ns(current->nsproxy->ipc_ns);
out:
return ret;
out_kfree:
kfree(iter);
goto out;
}
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 void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages)
{
unsigned long i;
for (i = 0; i < npages; ++i)
kvm_release_pfn_clean(pfn + i);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNode)
{
if (!RuntimeEnabledFeatures::partialLayoutEnabled() || !ScrollbarTheme::theme()->usesOverlayScrollbars()) {
updateLayoutIgnorePendingStylesheets();
return;
}
TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
recalcStyleForLayoutIgnoringPendingStylesheets();
if (stopLayoutAtNode) {
RenderObject* renderer = stopLayoutAtNode->renderer();
bool canPartialLayout = renderer;
while (renderer) {
if (!renderer->supportsPartialLayout()) {
canPartialLayout = false;
break;
}
renderer = renderer->parent();
}
if (canPartialLayout && view())
view()->partialLayout().setStopAtRenderer(stopLayoutAtNode->renderer());
}
updateLayout();
if (view())
view()->partialLayout().reset();
}
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 AppCacheHost::MarkAsForeignEntry(const GURL& document_url,
int64 cache_document_was_loaded_from) {
storage()->MarkEntryAsForeign(
main_resource_was_namespace_entry_ ? namespace_entry_url_ : document_url,
cache_document_was_loaded_from);
SelectCache(document_url, kAppCacheNoCacheId, GURL());
}
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: vsock_stream_recvmsg(struct kiocb *kiocb,
struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk;
struct vsock_sock *vsk;
int err;
size_t target;
ssize_t copied;
long timeout;
struct vsock_transport_recv_notify_data recv_data;
DEFINE_WAIT(wait);
sk = sock->sk;
vsk = vsock_sk(sk);
err = 0;
msg->msg_namelen = 0;
lock_sock(sk);
if (sk->sk_state != SS_CONNECTED) {
/* Recvmsg is supposed to return 0 if a peer performs an
* orderly shutdown. Differentiate between that case and when a
* peer has not connected or a local shutdown occured with the
* SOCK_DONE flag.
*/
if (sock_flag(sk, SOCK_DONE))
err = 0;
else
err = -ENOTCONN;
goto out;
}
if (flags & MSG_OOB) {
err = -EOPNOTSUPP;
goto out;
}
/* We don't check peer_shutdown flag here since peer may actually shut
* down, but there can be data in the queue that a local socket can
* receive.
*/
if (sk->sk_shutdown & RCV_SHUTDOWN) {
err = 0;
goto out;
}
/* It is valid on Linux to pass in a zero-length receive buffer. This
* is not an error. We may as well bail out now.
*/
if (!len) {
err = 0;
goto out;
}
/* We must not copy less than target bytes into the user's buffer
* before returning successfully, so we wait for the consume queue to
* have that much data to consume before dequeueing. Note that this
* makes it impossible to handle cases where target is greater than the
* queue size.
*/
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
if (target >= transport->stream_rcvhiwat(vsk)) {
err = -ENOMEM;
goto out;
}
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
copied = 0;
err = transport->notify_recv_init(vsk, target, &recv_data);
if (err < 0)
goto out;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
while (1) {
s64 ready = vsock_stream_has_data(vsk);
if (ready < 0) {
/* Invalid queue pair content. XXX This should be
* changed to a connection reset in a later change.
*/
err = -ENOMEM;
goto out_wait;
} else if (ready > 0) {
ssize_t read;
err = transport->notify_recv_pre_dequeue(
vsk, target, &recv_data);
if (err < 0)
break;
read = transport->stream_dequeue(
vsk, msg->msg_iov,
len - copied, flags);
if (read < 0) {
err = -ENOMEM;
break;
}
copied += read;
err = transport->notify_recv_post_dequeue(
vsk, target, read,
!(flags & MSG_PEEK), &recv_data);
if (err < 0)
goto out_wait;
if (read >= target || flags & MSG_PEEK)
break;
target -= read;
} else {
if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN)
|| (vsk->peer_shutdown & SEND_SHUTDOWN)) {
break;
}
/* Don't wait for non-blocking sockets. */
if (timeout == 0) {
err = -EAGAIN;
break;
}
err = transport->notify_recv_pre_block(
vsk, target, &recv_data);
if (err < 0)
break;
release_sock(sk);
timeout = schedule_timeout(timeout);
lock_sock(sk);
if (signal_pending(current)) {
err = sock_intr_errno(timeout);
break;
} else if (timeout == 0) {
err = -EAGAIN;
break;
}
prepare_to_wait(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
}
}
if (sk->sk_err)
err = -sk->sk_err;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
err = 0;
if (copied > 0) {
/* We only do these additional bookkeeping/notification steps
* if we actually copied something out of the queue pair
* instead of just peeking ahead.
*/
if (!(flags & MSG_PEEK)) {
/* If the other side has shutdown for sending and there
* is nothing more to read, then modify the socket
* state.
*/
if (vsk->peer_shutdown & SEND_SHUTDOWN) {
if (vsock_stream_has_data(vsk) <= 0) {
sk->sk_state = SS_UNCONNECTED;
sock_set_flag(sk, SOCK_DONE);
sk->sk_state_change(sk);
}
}
}
err = copied;
}
out_wait:
finish_wait(sk_sleep(sk), &wait);
out:
release_sock(sk);
return err;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: status_t Parcel::writeNoException()
{
return writeInt32(0);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
{
u32 exit_intr_info;
if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
|| vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
return;
vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
exit_intr_info = vmx->exit_intr_info;
/* Handle machine checks before interrupts are enabled */
if (is_machine_check(exit_intr_info))
kvm_machine_check();
/* We need to handle NMIs before interrupts are enabled */
if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR &&
(exit_intr_info & INTR_INFO_VALID_MASK)) {
kvm_before_handle_nmi(&vmx->vcpu);
asm("int $2");
kvm_after_handle_nmi(&vmx->vcpu);
}
}
CWE ID: CWE-388
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: PP_Bool StartPpapiProxy(PP_Instance instance) {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableNaClIPCProxy)) {
ChannelHandleMap& map = g_channel_handle_map.Get();
ChannelHandleMap::iterator it = map.find(instance);
if (it == map.end())
return PP_FALSE;
IPC::ChannelHandle channel_handle = it->second;
map.erase(it);
webkit::ppapi::PluginInstance* plugin_instance =
content::GetHostGlobals()->GetInstance(instance);
if (!plugin_instance)
return PP_FALSE;
WebView* web_view =
plugin_instance->container()->element().document().frame()->view();
RenderView* render_view = content::RenderView::FromWebView(web_view);
webkit::ppapi::PluginModule* plugin_module = plugin_instance->module();
scoped_refptr<SyncMessageStatusReceiver>
status_receiver(new SyncMessageStatusReceiver());
scoped_ptr<OutOfProcessProxy> out_of_process_proxy(new OutOfProcessProxy);
if (out_of_process_proxy->Init(
channel_handle,
plugin_module->pp_module(),
webkit::ppapi::PluginModule::GetLocalGetInterfaceFunc(),
ppapi::Preferences(render_view->GetWebkitPreferences()),
status_receiver.get())) {
plugin_module->InitAsProxiedNaCl(
out_of_process_proxy.PassAs<PluginDelegate::OutOfProcessProxy>(),
instance);
return PP_TRUE;
}
}
return PP_FALSE;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static const char *path_init(struct nameidata *nd, unsigned flags)
{
int retval = 0;
const char *s = nd->name->name;
nd->last_type = LAST_ROOT; /* if there are only slashes... */
nd->flags = flags | LOOKUP_JUMPED | LOOKUP_PARENT;
nd->depth = 0;
nd->total_link_count = 0;
if (flags & LOOKUP_ROOT) {
struct dentry *root = nd->root.dentry;
struct inode *inode = root->d_inode;
if (*s) {
if (!d_can_lookup(root))
return ERR_PTR(-ENOTDIR);
retval = inode_permission(inode, MAY_EXEC);
if (retval)
return ERR_PTR(retval);
}
nd->path = nd->root;
nd->inode = inode;
if (flags & LOOKUP_RCU) {
rcu_read_lock();
nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
nd->root_seq = nd->seq;
nd->m_seq = read_seqbegin(&mount_lock);
} else {
path_get(&nd->path);
}
return s;
}
nd->root.mnt = NULL;
nd->m_seq = read_seqbegin(&mount_lock);
if (*s == '/') {
if (flags & LOOKUP_RCU) {
rcu_read_lock();
set_root_rcu(nd);
nd->seq = nd->root_seq;
} else {
set_root(nd);
path_get(&nd->root);
}
nd->path = nd->root;
} else if (nd->dfd == AT_FDCWD) {
if (flags & LOOKUP_RCU) {
struct fs_struct *fs = current->fs;
unsigned seq;
rcu_read_lock();
do {
seq = read_seqcount_begin(&fs->seq);
nd->path = fs->pwd;
nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq);
} while (read_seqcount_retry(&fs->seq, seq));
} else {
get_fs_pwd(current->fs, &nd->path);
}
} else {
/* Caller must check execute permissions on the starting path component */
struct fd f = fdget_raw(nd->dfd);
struct dentry *dentry;
if (!f.file)
return ERR_PTR(-EBADF);
dentry = f.file->f_path.dentry;
if (*s) {
if (!d_can_lookup(dentry)) {
fdput(f);
return ERR_PTR(-ENOTDIR);
}
}
nd->path = f.file->f_path;
if (flags & LOOKUP_RCU) {
rcu_read_lock();
nd->inode = nd->path.dentry->d_inode;
nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq);
} else {
path_get(&nd->path);
nd->inode = nd->path.dentry->d_inode;
}
fdput(f);
return s;
}
nd->inode = nd->path.dentry->d_inode;
if (!(flags & LOOKUP_RCU))
return s;
if (likely(!read_seqcount_retry(&nd->path.dentry->d_seq, nd->seq)))
return s;
if (!(nd->flags & LOOKUP_ROOT))
nd->root.mnt = NULL;
rcu_read_unlock();
return ERR_PTR(-ECHILD);
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int crypto_rfc4309_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_instance *inst = (void *)tfm->__crt_alg;
struct crypto_aead_spawn *spawn = crypto_instance_ctx(inst);
struct crypto_rfc4309_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_aead *aead;
unsigned long align;
aead = crypto_spawn_aead(spawn);
if (IS_ERR(aead))
return PTR_ERR(aead);
ctx->child = aead;
align = crypto_aead_alignmask(aead);
align &= ~(crypto_tfm_ctx_alignment() - 1);
tfm->crt_aead.reqsize = sizeof(struct aead_request) +
ALIGN(crypto_aead_reqsize(aead),
crypto_tfm_ctx_alignment()) +
align + 16;
return 0;
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
int num_text)
{
int i;
png_debug1(1, "in %s storage function", ((png_ptr == NULL ||
png_ptr->chunk_name[0] == '\0') ?
"text" : (png_const_charp)png_ptr->chunk_name));
if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
return(0);
/* Make sure we have enough space in the "text" array in info_struct
* to hold all of the incoming text_ptr objects.
*/
if (info_ptr->num_text + num_text > info_ptr->max_text)
{
int old_max_text = info_ptr->max_text;
int old_num_text = info_ptr->num_text;
if (info_ptr->text != NULL)
{
png_textp old_text;
info_ptr->max_text = info_ptr->num_text + num_text + 8;
old_text = info_ptr->text;
info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
(png_uint_32)(info_ptr->max_text * png_sizeof(png_text)));
if (info_ptr->text == NULL)
{
/* Restore to previous condition */
info_ptr->max_text = old_max_text;
info_ptr->text = old_text;
return(1);
}
png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max_text *
png_sizeof(png_text)));
png_free(png_ptr, old_text);
}
else
{
info_ptr->max_text = num_text + 8;
info_ptr->num_text = 0;
info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
(png_uint_32)(info_ptr->max_text * png_sizeof(png_text)));
if (info_ptr->text == NULL)
{
/* Restore to previous condition */
info_ptr->num_text = old_num_text;
info_ptr->max_text = old_max_text;
return(1);
}
#ifdef PNG_FREE_ME_SUPPORTED
info_ptr->free_me |= PNG_FREE_TEXT;
#endif
}
png_debug1(3, "allocated %d entries for info_ptr->text",
info_ptr->max_text);
}
for (i = 0; i < num_text; i++)
{
png_size_t text_length, key_len;
png_size_t lang_len, lang_key_len;
png_textp textp = &(info_ptr->text[info_ptr->num_text]);
if (text_ptr[i].key == NULL)
continue;
key_len = png_strlen(text_ptr[i].key);
if (text_ptr[i].compression <= 0)
{
lang_len = 0;
lang_key_len = 0;
}
else
#ifdef PNG_iTXt_SUPPORTED
{
/* Set iTXt data */
if (text_ptr[i].lang != NULL)
lang_len = png_strlen(text_ptr[i].lang);
else
lang_len = 0;
if (text_ptr[i].lang_key != NULL)
lang_key_len = png_strlen(text_ptr[i].lang_key);
else
lang_key_len = 0;
}
#else /* PNG_iTXt_SUPPORTED */
{
png_warning(png_ptr, "iTXt chunk not supported.");
continue;
}
#endif
if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
{
text_length = 0;
#ifdef PNG_iTXt_SUPPORTED
if (text_ptr[i].compression > 0)
textp->compression = PNG_ITXT_COMPRESSION_NONE;
else
#endif
textp->compression = PNG_TEXT_COMPRESSION_NONE;
}
else
{
text_length = png_strlen(text_ptr[i].text);
textp->compression = text_ptr[i].compression;
}
textp->key = (png_charp)png_malloc_warn(png_ptr,
(png_uint_32)
(key_len + text_length + lang_len + lang_key_len + 4));
if (textp->key == NULL)
return(1);
png_debug2(2, "Allocated %lu bytes at %x in png_set_text",
(png_uint_32)
(key_len + lang_len + lang_key_len + text_length + 4),
(int)textp->key);
png_memcpy(textp->key, text_ptr[i].key,(png_size_t)(key_len));
*(textp->key + key_len) = '\0';
#ifdef PNG_iTXt_SUPPORTED
if (text_ptr[i].compression > 0)
{
textp->lang = textp->key + key_len + 1;
png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
*(textp->lang + lang_len) = '\0';
textp->lang_key = textp->lang + lang_len + 1;
png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
*(textp->lang_key + lang_key_len) = '\0';
textp->text = textp->lang_key + lang_key_len + 1;
}
else
#endif
{
#ifdef PNG_iTXt_SUPPORTED
textp->lang=NULL;
textp->lang_key=NULL;
#endif
textp->text = textp->key + key_len + 1;
}
if (text_length)
png_memcpy(textp->text, text_ptr[i].text,
(png_size_t)(text_length));
*(textp->text + text_length) = '\0';
#ifdef PNG_iTXt_SUPPORTED
if (textp->compression > 0)
{
textp->text_length = 0;
textp->itxt_length = text_length;
}
else
#endif
{
textp->text_length = text_length;
#ifdef PNG_iTXt_SUPPORTED
textp->itxt_length = 0;
#endif
}
info_ptr->num_text++;
png_debug1(3, "transferred text chunk %d", info_ptr->num_text);
}
return(0);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void TIFFReadDirEntryCheckedSshort(TIFF* tif, TIFFDirEntry* direntry, int16* value)
{
*value=*(int16*)(&direntry->tdir_offset);
if (tif->tif_flags&TIFF_SWAB)
TIFFSwabShort((uint16*)value);
}
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: make_spnego_token(const char *name)
{
return (spnego_token_t)strdup(name);
}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static PixelChannels **AcquirePixelThreadSet(const Image *images)
{
const Image
*next;
PixelChannels
**pixels;
register ssize_t
i;
size_t
columns,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (PixelChannels **) NULL)
return((PixelChannels **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
columns=images->columns;
for (next=images; next != (Image *) NULL; next=next->next)
columns=MagickMax(next->columns,columns);
for (i=0; i < (ssize_t) number_threads; i++)
{
register ssize_t
j;
pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels));
if (pixels[i] == (PixelChannels *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) columns; j++)
{
register ssize_t
k;
for (k=0; k < MaxPixelChannels; k++)
pixels[i][j].channel[k]=0.0;
}
}
return(pixels);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void perf_output_read(struct perf_output_handle *handle,
struct perf_event *event)
{
u64 enabled = 0, running = 0;
u64 read_format = event->attr.read_format;
/*
* compute total_time_enabled, total_time_running
* based on snapshot values taken when the event
* was last scheduled in.
*
* we cannot simply called update_context_time()
* because of locking issue as we are called in
* NMI context
*/
if (read_format & PERF_FORMAT_TOTAL_TIMES)
calc_timer_values(event, &enabled, &running);
if (event->attr.read_format & PERF_FORMAT_GROUP)
perf_output_read_group(handle, event, enabled, running);
else
perf_output_read_one(handle, event, enabled, running);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void slab_err(struct kmem_cache *s, struct page *page, char *fmt, ...)
{
va_list args;
char buf[100];
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
slab_bug(s, "%s", buf);
print_page_info(page);
dump_stack();
}
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: php_http_url_t *php_http_url_parse(const char *str, size_t len, unsigned flags TSRMLS_DC)
{
size_t maxlen = 3 * len;
struct parse_state *state = ecalloc(1, sizeof(*state) + maxlen);
state->end = str + len;
state->ptr = str;
state->flags = flags;
state->maxlen = maxlen;
TSRMLS_SET_CTX(state->ts);
if (!parse_scheme(state)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL scheme: '%s'", state->ptr);
efree(state);
return NULL;
}
if (!parse_hier(state)) {
efree(state);
return NULL;
}
if (!parse_query(state)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL query: '%s'", state->ptr);
efree(state);
return NULL;
}
if (!parse_fragment(state)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to parse URL fragment: '%s'", state->ptr);
efree(state);
return NULL;
}
return (php_http_url_t *) state;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: GF_Err trak_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackBox *ptr = (GF_TrackBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->Header) {
e = gf_isom_box_write((GF_Box *) ptr->Header, bs);
if (e) return e;
}
if (ptr->References) {
e = gf_isom_box_write((GF_Box *) ptr->References, bs);
if (e) return e;
}
if (ptr->editBox) {
e = gf_isom_box_write((GF_Box *) ptr->editBox, bs);
if (e) return e;
}
if (ptr->Media) {
e = gf_isom_box_write((GF_Box *) ptr->Media, bs);
if (e) return e;
}
if (ptr->meta) {
e = gf_isom_box_write((GF_Box *) ptr->meta, bs);
if (e) return e;
}
if (ptr->groups) {
e = gf_isom_box_write((GF_Box *) ptr->groups, bs);
if (e) return e;
}
if (ptr->udta) {
e = gf_isom_box_write((GF_Box *) ptr->udta, bs);
if (e) return e;
}
return GF_OK;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGLRenderingContextBase::vertexAttrib3fv(
GLuint index,
MaybeShared<const DOMFloat32Array> v) {
if (isContextLost())
return;
if (!v.View() || v.View()->length() < 3) {
SynthesizeGLError(GL_INVALID_VALUE, "vertexAttrib3fv", "invalid array");
return;
}
ContextGL()->VertexAttrib3fv(index, v.View()->DataMaybeShared());
SetVertexAttribType(index, kFloat32ArrayType);
}
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 yam_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct yam_port *yp = netdev_priv(dev);
struct yamdrv_ioctl_cfg yi;
struct yamdrv_ioctl_mcs *ym;
int ioctl_cmd;
if (copy_from_user(&ioctl_cmd, ifr->ifr_data, sizeof(int)))
return -EFAULT;
if (yp->magic != YAM_MAGIC)
return -EINVAL;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd != SIOCDEVPRIVATE)
return -EINVAL;
switch (ioctl_cmd) {
case SIOCYAMRESERVED:
return -EINVAL; /* unused */
case SIOCYAMSMCS:
if (netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((ym = kmalloc(sizeof(struct yamdrv_ioctl_mcs), GFP_KERNEL)) == NULL)
return -ENOBUFS;
if (copy_from_user(ym, ifr->ifr_data, sizeof(struct yamdrv_ioctl_mcs))) {
kfree(ym);
return -EFAULT;
}
if (ym->bitrate > YAM_MAXBITRATE) {
kfree(ym);
return -EINVAL;
}
/* setting predef as 0 for loading userdefined mcs data */
add_mcs(ym->bits, ym->bitrate, 0);
kfree(ym);
break;
case SIOCYAMSCFG:
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (copy_from_user(&yi, ifr->ifr_data, sizeof(struct yamdrv_ioctl_cfg)))
return -EFAULT;
if ((yi.cfg.mask & YAM_IOBASE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_IRQ) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_BITRATE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if ((yi.cfg.mask & YAM_BAUDRATE) && netif_running(dev))
return -EINVAL; /* Cannot change this parameter when up */
if (yi.cfg.mask & YAM_IOBASE) {
yp->iobase = yi.cfg.iobase;
dev->base_addr = yi.cfg.iobase;
}
if (yi.cfg.mask & YAM_IRQ) {
if (yi.cfg.irq > 15)
return -EINVAL;
yp->irq = yi.cfg.irq;
dev->irq = yi.cfg.irq;
}
if (yi.cfg.mask & YAM_BITRATE) {
if (yi.cfg.bitrate > YAM_MAXBITRATE)
return -EINVAL;
yp->bitrate = yi.cfg.bitrate;
}
if (yi.cfg.mask & YAM_BAUDRATE) {
if (yi.cfg.baudrate > YAM_MAXBAUDRATE)
return -EINVAL;
yp->baudrate = yi.cfg.baudrate;
}
if (yi.cfg.mask & YAM_MODE) {
if (yi.cfg.mode > YAM_MAXMODE)
return -EINVAL;
yp->dupmode = yi.cfg.mode;
}
if (yi.cfg.mask & YAM_HOLDDLY) {
if (yi.cfg.holddly > YAM_MAXHOLDDLY)
return -EINVAL;
yp->holdd = yi.cfg.holddly;
}
if (yi.cfg.mask & YAM_TXDELAY) {
if (yi.cfg.txdelay > YAM_MAXTXDELAY)
return -EINVAL;
yp->txd = yi.cfg.txdelay;
}
if (yi.cfg.mask & YAM_TXTAIL) {
if (yi.cfg.txtail > YAM_MAXTXTAIL)
return -EINVAL;
yp->txtail = yi.cfg.txtail;
}
if (yi.cfg.mask & YAM_PERSIST) {
if (yi.cfg.persist > YAM_MAXPERSIST)
return -EINVAL;
yp->pers = yi.cfg.persist;
}
if (yi.cfg.mask & YAM_SLOTTIME) {
if (yi.cfg.slottime > YAM_MAXSLOTTIME)
return -EINVAL;
yp->slot = yi.cfg.slottime;
yp->slotcnt = yp->slot / 10;
}
break;
case SIOCYAMGCFG:
yi.cfg.mask = 0xffffffff;
yi.cfg.iobase = yp->iobase;
yi.cfg.irq = yp->irq;
yi.cfg.bitrate = yp->bitrate;
yi.cfg.baudrate = yp->baudrate;
yi.cfg.mode = yp->dupmode;
yi.cfg.txdelay = yp->txd;
yi.cfg.holddly = yp->holdd;
yi.cfg.txtail = yp->txtail;
yi.cfg.persist = yp->pers;
yi.cfg.slottime = yp->slot;
if (copy_to_user(ifr->ifr_data, &yi, sizeof(struct yamdrv_ioctl_cfg)))
return -EFAULT;
break;
default:
return -EINVAL;
}
return 0;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: virtual ~SystemTrayDelegate() {
AudioHandler* audiohandler = AudioHandler::GetInstance();
if (audiohandler)
audiohandler->RemoveVolumeObserver(this);
DBusThreadManager::Get()->GetPowerManagerClient()->RemoveObserver(this);
NetworkLibrary* crosnet = CrosLibrary::Get()->GetNetworkLibrary();
if (crosnet) {
crosnet->RemoveNetworkManagerObserver(this);
crosnet->RemoveCellularDataPlanObserver(this);
}
input_method::InputMethodManager::GetInstance()->RemoveObserver(this);
system::TimezoneSettings::GetInstance()->RemoveObserver(this);
if (SystemKeyEventListener::GetInstance())
SystemKeyEventListener::GetInstance()->RemoveCapsLockObserver(this);
bluetooth_adapter_->RemoveObserver(this);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool GLES2DecoderImpl::SimulateAttrib0(
const char* function_name, GLuint max_vertex_accessed, bool* simulated) {
DCHECK(simulated);
*simulated = false;
if (gl_version_info().BehavesLikeGLES())
return true;
const VertexAttrib* attrib =
state_.vertex_attrib_manager->GetVertexAttrib(0);
bool attrib_0_used =
state_.current_program->GetAttribInfoByLocation(0) != nullptr;
if (attrib->enabled() && attrib_0_used) {
return true;
}
GLuint num_vertices = max_vertex_accessed + 1;
uint32_t size_needed = 0;
if (num_vertices == 0 ||
!SafeMultiplyUint32(num_vertices, sizeof(Vec4f), &size_needed) ||
size_needed > 0x7FFFFFFFU) {
LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
LOCAL_PERFORMANCE_WARNING(
"Attribute 0 is disabled. This has significant performance penalty");
LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER(function_name);
api()->glBindBufferFn(GL_ARRAY_BUFFER, attrib_0_buffer_id_);
bool new_buffer = static_cast<GLsizei>(size_needed) > attrib_0_size_;
if (new_buffer) {
api()->glBufferDataFn(GL_ARRAY_BUFFER, size_needed, nullptr,
GL_DYNAMIC_DRAW);
GLenum error = api()->glGetErrorFn();
if (error != GL_NO_ERROR) {
LOCAL_SET_GL_ERROR(
GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0");
return false;
}
}
const Vec4& value = state_.attrib_values[0];
if (new_buffer || (attrib_0_used && (!attrib_0_buffer_matches_value_ ||
!value.Equal(attrib_0_value_)))) {
Vec4f fvalue(value);
constexpr GLuint kMaxVerticesPerLoop = 32u << 10;
const GLuint vertices_per_loop =
std::min(num_vertices, kMaxVerticesPerLoop);
std::vector<Vec4f> temp(vertices_per_loop, fvalue);
for (GLuint offset = 0; offset < num_vertices;) {
size_t count = std::min(num_vertices - offset, vertices_per_loop);
api()->glBufferSubDataFn(GL_ARRAY_BUFFER, offset * sizeof(Vec4f),
count * sizeof(Vec4f), temp.data());
offset += count;
}
attrib_0_buffer_matches_value_ = true;
attrib_0_value_ = value;
attrib_0_size_ = size_needed;
}
api()->glVertexAttribPointerFn(0, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
if (feature_info_->feature_flags().angle_instanced_arrays)
api()->glVertexAttribDivisorANGLEFn(0, 0);
*simulated = true;
return true;
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: base::string16 TranslateInfoBarDelegate::GetLanguageDisplayableName(
const std::string& language_code) {
return l10n_util::GetDisplayNameForLocale(
language_code, g_browser_process->GetApplicationLocale(), true);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) {
item_chunk *dch = (item_chunk *) ITEM_schunk(d_it);
/* Advance dch until we find free space */
while (dch->size == dch->used) {
if (dch->next) {
dch = dch->next;
} else {
break;
}
}
if (s_it->it_flags & ITEM_CHUNKED) {
int remain = len;
item_chunk *sch = (item_chunk *) ITEM_schunk(s_it);
int copied = 0;
/* Fills dch's to capacity, not straight copy sch in case data is
* being added or removed (ie append/prepend)
*/
while (sch && dch && remain) {
assert(dch->used <= dch->size);
int todo = (dch->size - dch->used < sch->used - copied)
? dch->size - dch->used : sch->used - copied;
if (remain < todo)
todo = remain;
memcpy(dch->data + dch->used, sch->data + copied, todo);
dch->used += todo;
copied += todo;
remain -= todo;
assert(dch->used <= dch->size);
if (dch->size == dch->used) {
item_chunk *tch = do_item_alloc_chunk(dch, remain);
if (tch) {
dch = tch;
} else {
return -1;
}
}
assert(copied <= sch->used);
if (copied == sch->used) {
copied = 0;
sch = sch->next;
}
}
/* assert that the destination had enough space for the source */
assert(remain == 0);
} else {
int done = 0;
/* Fill dch's via a non-chunked item. */
while (len > done && dch) {
int todo = (dch->size - dch->used < len - done)
? dch->size - dch->used : len - done;
memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo);
done += todo;
dch->used += todo;
assert(dch->used <= dch->size);
if (dch->size == dch->used) {
item_chunk *tch = do_item_alloc_chunk(dch, len - done);
if (tch) {
dch = tch;
} else {
return -1;
}
}
}
assert(len == done);
}
return 0;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
{
unsigned char *sigalgs, *sptr;
int rhash, rsign;
size_t i;
if (salglen & 1)
return 0;
sigalgs = OPENSSL_malloc(salglen);
if (sigalgs == NULL)
return 0;
for (i = 0, sptr = sigalgs; i < salglen; i += 2) {
rhash = tls12_find_id(*psig_nids++, tls12_md, OSSL_NELEM(tls12_md));
rsign = tls12_find_id(*psig_nids++, tls12_sig, OSSL_NELEM(tls12_sig));
if (rhash == -1 || rsign == -1)
goto err;
*sptr++ = rhash;
*sptr++ = rsign;
}
if (client) {
OPENSSL_free(c->client_sigalgs);
c->client_sigalgs = sigalgs;
c->client_sigalgslen = salglen;
} else {
OPENSSL_free(c->conf_sigalgs);
c->conf_sigalgs = sigalgs;
c->conf_sigalgslen = salglen;
}
return 1;
err:
OPENSSL_free(sigalgs);
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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert3(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
c* (toc(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->convert3();
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void RenderViewImpl::GetSelectionBounds(gfx::Rect* start, gfx::Rect* end) {
if (pepper_helper_->IsPluginFocused()) {
gfx::Rect caret = pepper_helper_->GetCaretBounds();
*start = caret;
*end = caret;
return;
}
RenderWidget::GetSelectionBounds(start, end);
}
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: bool Init() {
DCHECK(!initialized_successfully_) << "Already initialized";
if (!CrosLibrary::Get()->EnsureLoaded())
return false;
input_method_status_connection_ = chromeos::MonitorInputMethodStatus(
this,
&InputMethodChangedHandler,
&RegisterPropertiesHandler,
&UpdatePropertyHandler,
&ConnectionChangeHandler);
if (!input_method_status_connection_)
return false;
initialized_successfully_ = true;
return true;
}
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len)
{
unsigned char *pt;
unsigned char l, lg, n = 0;
int fac_national_digis_received = 0;
do {
switch (*p & 0xC0) {
case 0x00:
p += 2;
n += 2;
len -= 2;
break;
case 0x40:
if (*p == FAC_NATIONAL_RAND)
facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF);
p += 3;
n += 3;
len -= 3;
break;
case 0x80:
p += 4;
n += 4;
len -= 4;
break;
case 0xC0:
l = p[1];
if (*p == FAC_NATIONAL_DEST_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN);
facilities->source_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_SRC_DIGI) {
if (!fac_national_digis_received) {
memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN);
facilities->dest_ndigis = 1;
}
}
else if (*p == FAC_NATIONAL_FAIL_CALL) {
memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_FAIL_ADD) {
memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN);
}
else if (*p == FAC_NATIONAL_DIGIS) {
fac_national_digis_received = 1;
facilities->source_ndigis = 0;
facilities->dest_ndigis = 0;
for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) {
if (pt[6] & AX25_HBIT)
memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN);
else
memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN);
}
}
p += l + 2;
n += l + 2;
len -= l + 2;
break;
}
} while (*p != 0x00 && len > 0);
return n;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void nicklist_remove_hash(gpointer key, NICK_REC *nick,
CHANNEL_REC *channel)
{
NICK_REC *next;
while (nick != NULL) {
next = nick->next;
nicklist_destroy(channel, nick);
nick = next;
}
}
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 llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb)
{
struct llc_sock *llc = llc_sk(skb->sk);
if (llc->cmsg_flags & LLC_CMSG_PKTINFO) {
struct llc_pktinfo info;
info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex;
llc_pdu_decode_dsap(skb, &info.lpi_sap);
llc_pdu_decode_da(skb, info.lpi_mac);
put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info);
}
}
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 exit_io_context(void)
{
struct io_context *ioc;
task_lock(current);
ioc = current->io_context;
current->io_context = NULL;
task_unlock(current);
if (atomic_dec_and_test(&ioc->nr_tasks)) {
if (ioc->aic && ioc->aic->exit)
ioc->aic->exit(ioc->aic);
cfq_exit(ioc);
}
put_io_context(ioc);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: struct gendisk *alloc_disk(int minors)
{
return alloc_disk_node(minors, NUMA_NO_NODE);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int hsr_dev_finalize(struct net_device *hsr_dev, struct net_device *slave[2],
unsigned char multicast_spec, u8 protocol_version)
{
struct hsr_priv *hsr;
struct hsr_port *port;
int res;
hsr = netdev_priv(hsr_dev);
INIT_LIST_HEAD(&hsr->ports);
INIT_LIST_HEAD(&hsr->node_db);
INIT_LIST_HEAD(&hsr->self_node_db);
ether_addr_copy(hsr_dev->dev_addr, slave[0]->dev_addr);
/* Make sure we recognize frames from ourselves in hsr_rcv() */
res = hsr_create_self_node(&hsr->self_node_db, hsr_dev->dev_addr,
slave[1]->dev_addr);
if (res < 0)
return res;
spin_lock_init(&hsr->seqnr_lock);
/* Overflow soon to find bugs easier: */
hsr->sequence_nr = HSR_SEQNR_START;
hsr->sup_sequence_nr = HSR_SUP_SEQNR_START;
timer_setup(&hsr->announce_timer, hsr_announce, 0);
timer_setup(&hsr->prune_timer, hsr_prune_nodes, 0);
ether_addr_copy(hsr->sup_multicast_addr, def_multicast_addr);
hsr->sup_multicast_addr[ETH_ALEN - 1] = multicast_spec;
hsr->protVersion = protocol_version;
/* FIXME: should I modify the value of these?
*
* - hsr_dev->flags - i.e.
* IFF_MASTER/SLAVE?
* - hsr_dev->priv_flags - i.e.
* IFF_EBRIDGE?
* IFF_TX_SKB_SHARING?
* IFF_HSR_MASTER/SLAVE?
*/
/* Make sure the 1st call to netif_carrier_on() gets through */
netif_carrier_off(hsr_dev);
res = hsr_add_port(hsr, hsr_dev, HSR_PT_MASTER);
if (res)
return res;
res = register_netdevice(hsr_dev);
if (res)
goto fail;
res = hsr_add_port(hsr, slave[0], HSR_PT_SLAVE_A);
if (res)
goto fail;
res = hsr_add_port(hsr, slave[1], HSR_PT_SLAVE_B);
if (res)
goto fail;
mod_timer(&hsr->prune_timer, jiffies + msecs_to_jiffies(PRUNE_PERIOD));
return 0;
fail:
hsr_for_each_port(hsr, port)
hsr_del_port(port);
return res;
}
CWE ID: CWE-772
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY ||
(policy == POLICY_NOT_SET &&
profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW)) {
return false;
}
}
return true;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: int fscrypt_initialize(unsigned int cop_flags)
{
int i, res = -ENOMEM;
/*
* No need to allocate a bounce page pool if there already is one or
* this FS won't use it.
*/
if (cop_flags & FS_CFLG_OWN_PAGES || fscrypt_bounce_page_pool)
return 0;
mutex_lock(&fscrypt_init_mutex);
if (fscrypt_bounce_page_pool)
goto already_initialized;
for (i = 0; i < num_prealloc_crypto_ctxs; i++) {
struct fscrypt_ctx *ctx;
ctx = kmem_cache_zalloc(fscrypt_ctx_cachep, GFP_NOFS);
if (!ctx)
goto fail;
list_add(&ctx->free_list, &fscrypt_free_ctxs);
}
fscrypt_bounce_page_pool =
mempool_create_page_pool(num_prealloc_crypto_pages, 0);
if (!fscrypt_bounce_page_pool)
goto fail;
already_initialized:
mutex_unlock(&fscrypt_init_mutex);
return 0;
fail:
fscrypt_destroy();
mutex_unlock(&fscrypt_init_mutex);
return res;
}
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 skip_emulated_instruction(struct kvm_vcpu *vcpu)
{
struct vcpu_svm *svm = to_svm(vcpu);
if (svm->vmcb->control.next_rip != 0)
svm->next_rip = svm->vmcb->control.next_rip;
if (!svm->next_rip) {
if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
EMULATE_DONE)
printk(KERN_DEBUG "%s: NOP\n", __func__);
return;
}
if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
__func__, kvm_rip_read(vcpu), svm->next_rip);
kvm_rip_write(vcpu, svm->next_rip);
svm_set_interrupt_shadow(vcpu, 0);
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AudioOutputAuthorizationHandler::GetDeviceParameters(
AuthorizationCompletedCallback cb,
const std::string& raw_device_id) const {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(!raw_device_id.empty());
base::PostTaskAndReplyWithResult(
audio_manager_->GetTaskRunner(), FROM_HERE,
base::Bind(&GetDeviceParametersOnDeviceThread,
base::Unretained(audio_manager_), raw_device_id),
base::Bind(&AudioOutputAuthorizationHandler::DeviceParametersReceived,
weak_factory_.GetWeakPtr(), std::move(cb), false,
raw_device_id));
}
CWE ID:
Target: 1
Example 2:
Code: static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
{
set_compound_page_dtor(page, free_huge_page);
spin_lock(&hugetlb_lock);
h->nr_huge_pages++;
h->nr_huge_pages_node[nid]++;
spin_unlock(&hugetlb_lock);
put_page(page); /* free it into the hugepage allocator */
}
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 inet_set_tos(int fd, const struct sockaddr_storage *from, int tos)
{
#ifdef IP_TOS
if (from->ss_family == AF_INET)
setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
#endif
#ifdef IPV6_TCLASS
if (from->ss_family == AF_INET6) {
if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)from)->sin6_addr))
/* v4-mapped addresses need IP_TOS */
setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
else
setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos));
}
#endif
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ExtensionDevToolsClientHost::AgentHostClosed(
DevToolsAgentHost* agent_host) {
DCHECK(agent_host == agent_host_.get());
SendDetachedEvent();
delete this;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: noname_disable_map(Node** plink, GroupNumRemap* map, int* counter)
{
int r = 0;
Node* node = *plink;
switch (NODE_TYPE(node)) {
case NODE_LIST:
case NODE_ALT:
do {
r = noname_disable_map(&(NODE_CAR(node)), map, counter);
} while (r == 0 && IS_NOT_NULL(node = NODE_CDR(node)));
break;
case NODE_QUANT:
{
Node** ptarget = &(NODE_BODY(node));
Node* old = *ptarget;
r = noname_disable_map(ptarget, map, counter);
if (*ptarget != old && NODE_TYPE(*ptarget) == NODE_QUANT) {
onig_reduce_nested_quantifier(node, *ptarget);
}
}
break;
case NODE_BAG:
{
BagNode* en = BAG_(node);
if (en->type == BAG_MEMORY) {
if (NODE_IS_NAMED_GROUP(node)) {
(*counter)++;
map[en->m.regnum].new_val = *counter;
en->m.regnum = *counter;
r = noname_disable_map(&(NODE_BODY(node)), map, counter);
}
else {
*plink = NODE_BODY(node);
NODE_BODY(node) = NULL_NODE;
onig_node_free(node);
r = noname_disable_map(plink, map, counter);
}
}
else if (en->type == BAG_IF_ELSE) {
r = noname_disable_map(&(NODE_BAG_BODY(en)), map, counter);
if (r != 0) return r;
if (IS_NOT_NULL(en->te.Then)) {
r = noname_disable_map(&(en->te.Then), map, counter);
if (r != 0) return r;
}
if (IS_NOT_NULL(en->te.Else)) {
r = noname_disable_map(&(en->te.Else), map, counter);
if (r != 0) return r;
}
}
else
r = noname_disable_map(&(NODE_BODY(node)), map, counter);
}
break;
case NODE_ANCHOR:
if (IS_NOT_NULL(NODE_BODY(node)))
r = noname_disable_map(&(NODE_BODY(node)), map, counter);
break;
default:
break;
}
return r;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostImpl::Destroy(bool also_delete) {
DCHECK(!destroyed_);
destroyed_ = true;
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, Source<RenderWidgetHost>(this),
NotificationService::NoDetails());
if (view_) {
view_->Destroy();
view_.reset();
}
process_->RemoveRoute(routing_id_);
g_routing_id_widget_map.Get().erase(
RenderWidgetHostID(process_->GetID(), routing_id_));
if (delegate_)
delegate_->RenderWidgetDeleted(this);
if (also_delete)
delete this;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
ALOGV("setNextPlayer");
Mutex::Autolock l(mLock);
sp<Client> c = static_cast<Client*>(player.get());
mNextClient = c;
if (c != NULL) {
if (mAudioOutput != NULL) {
mAudioOutput->setNextOutput(c->mAudioOutput);
} else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
ALOGE("no current audio output");
}
if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
mPlayer->setNextPlayer(mNextClient->getPlayer());
}
}
return OK;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int nfs_post_op_update_inode_locked(struct inode *inode, struct nfs_fattr *fattr)
{
struct nfs_inode *nfsi = NFS_I(inode);
nfsi->cache_validity |= NFS_INO_INVALID_ATTR|NFS_INO_REVAL_PAGECACHE;
if (S_ISDIR(inode->i_mode))
nfsi->cache_validity |= NFS_INO_INVALID_DATA;
if ((fattr->valid & NFS_ATTR_FATTR) == 0)
return 0;
return nfs_refresh_inode_locked(inode, fattr);
}
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: SpeechRecognitionManagerImpl::SpeechRecognitionManagerImpl(
media::AudioSystem* audio_system,
MediaStreamManager* media_stream_manager)
: audio_system_(audio_system),
media_stream_manager_(media_stream_manager),
primary_session_id_(kSessionIDInvalid),
last_session_id_(kSessionIDInvalid),
is_dispatching_event_(false),
delegate_(GetContentClient()
->browser()
->CreateSpeechRecognitionManagerDelegate()),
weak_factory_(this) {
DCHECK(!g_speech_recognition_manager_impl);
g_speech_recognition_manager_impl = this;
frame_deletion_observer_.reset(new FrameDeletionObserver(
base::BindRepeating(&SpeechRecognitionManagerImpl::AbortSessionImpl,
weak_factory_.GetWeakPtr())));
}
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 main(int argc,
char **argv)
{
char *filein, *str, *tempfile, *prestring, *outprotos, *protostr;
const char *spacestr = " ";
char buf[L_BUF_SIZE];
l_uint8 *allheaders;
l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret;
size_t nbytes;
L_BYTEA *ba, *ba2;
SARRAY *sa, *safirst;
static char mainName[] = "xtractprotos";
if (argc == 1) {
fprintf(stderr,
"xtractprotos [-prestring=<string>] [-protos=<where>] "
"[list of C files]\n"
"where the prestring is prepended to each prototype, and \n"
"protos can be either 'inline' or the name of an output "
"prototype file\n");
return 1;
}
/* ---------------------------------------------------------------- */
/* Parse input flags and find prestring and outprotos, if requested */
/* ---------------------------------------------------------------- */
prestring = outprotos = NULL;
in_line = FALSE;
nflags = 0;
maxindex = L_MIN(3, argc);
for (i = 1; i < maxindex; i++) {
if (argv[i][0] == '-') {
if (!strncmp(argv[i], "-prestring", 10)) {
nflags++;
ret = sscanf(argv[i] + 1, "prestring=%s", buf);
if (ret != 1) {
fprintf(stderr, "parse failure for prestring\n");
return 1;
}
if ((len = strlen(buf)) > L_BUF_SIZE - 3) {
L_WARNING("prestring too large; omitting!\n", mainName);
} else {
buf[len] = ' ';
buf[len + 1] = '\0';
prestring = stringNew(buf);
}
} else if (!strncmp(argv[i], "-protos", 7)) {
nflags++;
ret = sscanf(argv[i] + 1, "protos=%s", buf);
if (ret != 1) {
fprintf(stderr, "parse failure for protos\n");
return 1;
}
outprotos = stringNew(buf);
if (!strncmp(outprotos, "inline", 7))
in_line = TRUE;
}
}
}
if (argc - nflags < 2) {
fprintf(stderr, "no files specified!\n");
return 1;
}
/* ---------------------------------------------------------------- */
/* Generate the prototype string */
/* ---------------------------------------------------------------- */
ba = l_byteaCreate(500);
/* First the extern C head */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"/*", L_COPY);
snprintf(buf, L_BUF_SIZE,
" * These prototypes were autogen'd by xtractprotos, v. %s",
version);
sarrayAddString(sa, buf, L_COPY);
sarrayAddString(sa, (char *)" */", L_COPY);
sarrayAddString(sa, (char *)"#ifdef __cplusplus", L_COPY);
sarrayAddString(sa, (char *)"extern \"C\" {", L_COPY);
sarrayAddString(sa, (char *)"#endif /* __cplusplus */\n", L_COPY);
str = sarrayToString(sa, 1);
l_byteaAppendString(ba, str);
lept_free(str);
sarrayDestroy(&sa);
/* Then the prototypes */
firstfile = 1 + nflags;
protos_added = FALSE;
if ((tempfile = l_makeTempFilename()) == NULL) {
fprintf(stderr, "failure to make a writeable temp file\n");
return 1;
}
for (i = firstfile; i < argc; i++) {
filein = argv[i];
len = strlen(filein);
if (filein[len - 1] == 'h') /* skip .h files */
continue;
snprintf(buf, L_BUF_SIZE, "cpp -ansi -DNO_PROTOS %s %s",
filein, tempfile);
ret = system(buf); /* cpp */
if (ret) {
fprintf(stderr, "cpp failure for %s; continuing\n", filein);
continue;
}
if ((str = parseForProtos(tempfile, prestring)) == NULL) {
fprintf(stderr, "parse failure for %s; continuing\n", filein);
continue;
}
if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */
l_byteaAppendString(ba, str);
protos_added = TRUE;
}
lept_free(str);
}
lept_rmfile(tempfile);
lept_free(tempfile);
/* Lastly the extern C tail */
sa = sarrayCreate(0);
sarrayAddString(sa, (char *)"\n#ifdef __cplusplus", L_COPY);
sarrayAddString(sa, (char *)"}", L_COPY);
sarrayAddString(sa, (char *)"#endif /* __cplusplus */", L_COPY);
str = sarrayToString(sa, 1);
l_byteaAppendString(ba, str);
lept_free(str);
sarrayDestroy(&sa);
protostr = (char *)l_byteaCopyData(ba, &nbytes);
l_byteaDestroy(&ba);
/* ---------------------------------------------------------------- */
/* Generate the output */
/* ---------------------------------------------------------------- */
if (!outprotos) { /* just write to stdout */
fprintf(stderr, "%s\n", protostr);
lept_free(protostr);
return 0;
}
/* If no protos were found, do nothing further */
if (!protos_added) {
fprintf(stderr, "No protos found\n");
lept_free(protostr);
return 1;
}
/* Make the output files */
ba = l_byteaInitFromFile("allheaders_top.txt");
if (!in_line) {
snprintf(buf, sizeof(buf), "#include \"%s\"\n", outprotos);
l_byteaAppendString(ba, buf);
l_binaryWrite(outprotos, "w", protostr, nbytes);
} else {
l_byteaAppendString(ba, protostr);
}
ba2 = l_byteaInitFromFile("allheaders_bot.txt");
l_byteaJoin(ba, &ba2);
l_byteaWrite("allheaders.h", ba, 0, 0);
l_byteaDestroy(&ba);
lept_free(protostr);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void CheckAccepted() {
DCHECK(num_accepted_connections_loop_ ||
num_accepted_connections_needed_ == 0);
if (!num_accepted_connections_loop_ ||
num_accepted_connections_needed_ != sockets_.size()) {
return;
}
num_accepted_connections_loop_->Quit();
num_accepted_connections_needed_ = 0;
num_accepted_connections_loop_ = nullptr;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ssize_t driver_override_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
return sprintf(buf, "%s\n", pdev->driver_override);
}
CWE ID: CWE-362
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: restore_page_device(const gs_gstate * pgs_old, const gs_gstate * pgs_new)
{
gx_device *dev_old = gs_currentdevice(pgs_old);
gx_device *dev_new;
gx_device *dev_t1;
gx_device *dev_t2;
bool samepagedevice = obj_eq(dev_old->memory, &gs_int_gstate(pgs_old)->pagedevice,
&gs_int_gstate(pgs_new)->pagedevice);
if ((dev_t1 = (*dev_proc(dev_old, get_page_device)) (dev_old)) == 0)
return false;
/* If we are going to putdeviceparams in a callout, we need to */
/* unlock temporarily. The device will be re-locked as needed */
/* by putdeviceparams from the pgs_old->pagedevice dict state. */
dev_old->LockSafetyParams = false;
dev_new = gs_currentdevice(pgs_new);
dev_new = gs_currentdevice(pgs_new);
if (dev_old != dev_new) {
if ((dev_t2 = (*dev_proc(dev_new, get_page_device)) (dev_new)) == 0)
return false;
if (dev_t1 != dev_t2)
return true;
}
/*
* The current implementation of setpagedevice just sets new
* parameters in the same device object, so we have to check
* whether the page device dictionaries are the same.
*/
return !samepagedevice;
}
CWE ID:
Target: 1
Example 2:
Code: bool DXVAVideoDecodeAccelerator::ProcessOutputSample(IMFSample* sample) {
RETURN_ON_FAILURE(sample, "Decode succeeded with NULL output sample", false);
base::win::ScopedComPtr<IMFSample> output_sample;
output_sample.Attach(sample);
base::win::ScopedComPtr<IMFMediaBuffer> output_buffer;
HRESULT hr = sample->GetBufferByIndex(0, output_buffer.Receive());
RETURN_ON_HR_FAILURE(hr, "Failed to get buffer from output sample", false);
base::win::ScopedComPtr<IDirect3DSurface9> surface;
hr = MFGetService(output_buffer, MR_BUFFER_SERVICE,
IID_PPV_ARGS(surface.Receive()));
RETURN_ON_HR_FAILURE(hr, "Failed to get D3D surface from output sample",
false);
D3DSURFACE_DESC surface_desc;
hr = surface->GetDesc(&surface_desc);
RETURN_ON_HR_FAILURE(hr, "Failed to get surface description", false);
pending_output_samples_.push_back(
PendingSampleInfo(last_input_buffer_id_, surface));
if (output_picture_buffers_.size()) {
ProcessPendingSamples();
return true;
}
if (pictures_requested_) {
DVLOG(1) << "Waiting for picture slots from the client.";
return true;
}
MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
&DXVAVideoDecodeAccelerator::RequestPictureBuffers,
this, surface_desc.Width, surface_desc.Height));
pictures_requested_ = true;
return true;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void MidiManagerUsb::DispatchSendMidiData(MidiManagerClient* client,
uint32_t port_index,
const std::vector<uint8>& data,
double timestamp) {
DCHECK_LT(port_index, output_streams_.size());
output_streams_[port_index]->Send(data);
client->AccumulateMidiBytesSent(data.size());
}
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 scsi_read_data(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
uint32_t n;
if (r->sector_count == (uint32_t)-1) {
DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);
r->sector_count = 0;
scsi_req_data(&r->req, r->iov.iov_len);
return;
}
DPRINTF("Read sector_count=%d\n", r->sector_count);
if (r->sector_count == 0) {
/* This also clears the sense buffer for REQUEST SENSE. */
scsi_req_complete(&r->req, GOOD);
return;
}
/* No data transfer may already be in progress */
assert(r->req.aiocb == NULL);
if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {
DPRINTF("Data transfer direction invalid\n");
scsi_read_complete(r, -EINVAL);
return;
}
n = r->sector_count;
if (n > SCSI_DMA_BUF_SIZE / 512)
n = SCSI_DMA_BUF_SIZE / 512;
if (s->tray_open) {
scsi_read_complete(r, -ENOMEDIUM);
}
r->iov.iov_len = n * 512;
qemu_iovec_init_external(&r->qiov, &r->iov, 1);
bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ);
r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,
scsi_read_complete, r);
if (r->req.aiocb == NULL) {
scsi_read_complete(r, -EIO);
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: circle_distance(PG_FUNCTION_ARGS)
{
CIRCLE *circle1 = PG_GETARG_CIRCLE_P(0);
CIRCLE *circle2 = PG_GETARG_CIRCLE_P(1);
float8 result;
result = point_dt(&circle1->center, &circle2->center)
- (circle1->radius + circle2->radius);
if (result < 0)
result = 0;
PG_RETURN_FLOAT8(result);
}
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: image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_strip_alpha(pp);
this->next->set(this->next, that, pp, pi);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
int noblock = flags & MSG_DONTWAIT;
struct sock *sk = sock->sk;
struct sk_buff *skb;
size_t copied;
int err;
BT_DBG("sock %p sk %p len %zu", sock, sk, len);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb) {
if (sk->sk_shutdown & RCV_SHUTDOWN) {
msg->msg_namelen = 0;
return 0;
}
return err;
}
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(skb);
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err == 0) {
sock_recv_ts_and_drops(msg, sk, skb);
if (bt_sk(sk)->skb_msg_name)
bt_sk(sk)->skb_msg_name(skb, msg->msg_name,
&msg->msg_namelen);
else
msg->msg_namelen = 0;
}
skb_free_datagram(sk, skb);
return err ? : copied;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool Layer::DrawsContent() const {
return is_drawable_;
}
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 ChromeContentUtilityClient::OnMessageReceived(
const IPC::Message& message) {
if (filter_messages_ && !ContainsKey(message_id_whitelist_, message.type()))
return false;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage)
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage,
OnRobustJPEGDecodeImage)
#endif // defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff,
OnPatchFileBsdiff)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette,
OnPatchFileCourgette)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing)
#if defined(FULL_SAFE_BROWSING)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection,
OnAnalyzeZipFileForDownloadProtection)
#endif
#if defined(ENABLE_EXTENSIONS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata,
OnParseMediaMetadata)
#endif
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
for (Handlers::iterator it = handlers_.begin();
!handled && it != handlers_.end(); ++it) {
handled = (*it)->OnMessageReceived(message);
}
return handled;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool DownloadManagerImpl::InterceptDownload(
const download::DownloadCreateInfo& info) {
WebContents* web_contents = WebContentsImpl::FromRenderFrameHostID(
info.render_process_id, info.render_frame_id);
if (info.is_new_download &&
info.result ==
download::DOWNLOAD_INTERRUPT_REASON_SERVER_CROSS_ORIGIN_REDIRECT) {
if (web_contents) {
std::vector<GURL> url_chain(info.url_chain);
GURL url = url_chain.back();
url_chain.pop_back();
NavigationController::LoadURLParams params(url);
params.has_user_gesture = info.has_user_gesture;
params.referrer = Referrer(
info.referrer_url, Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
info.referrer_policy));
params.redirect_chain = url_chain;
web_contents->GetController().LoadURLWithParams(params);
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
if (!delegate_ ||
!delegate_->InterceptDownloadIfApplicable(
info.url(), info.mime_type, info.request_origin, web_contents)) {
return false;
}
if (info.request_handle)
info.request_handle->CancelRequest(false);
return true;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void conditionalAttr2AttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectV8Internal::conditionalAttr2AttributeGetter(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: GF_Box *gitn_New()
{
ISOM_DECL_BOX_ALLOC(GroupIdToNameBox, GF_ISOM_BOX_TYPE_GITN);
return (GF_Box *)tmp;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Splash::blitMask(SplashBitmap *src, int xDest, int yDest,
SplashClipResult clipRes) {
SplashPipe pipe;
Guchar *p;
int w, h, x, y;
w = src->getWidth();
h = src->getHeight();
if (vectorAntialias && clipRes != splashClipAllInside) {
pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL,
(Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse);
drawAAPixelInit();
p = src->getDataPtr();
for (y = 0; y < h; ++y) {
for (x = 0; x < w; ++x) {
pipe.shape = *p++;
pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL,
(Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse);
p = src->getDataPtr();
} else {
pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL,
(Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse);
p = src->getDataPtr();
if (clipRes == splashClipAllInside) {
for (y = 0; y < h; ++y) {
pipeSetXY(&pipe, xDest, yDest + y);
(this->*pipe.run)(&pipe);
} else {
pipeIncX(&pipe);
}
++p;
}
}
updateModX(xDest);
updateModX(xDest + w - 1);
updateModY(yDest);
updateModY(yDest + h - 1);
} else {
for (y = 0; y < h; ++y) {
pipeSetXY(&pipe, xDest, yDest + y);
for (x = 0; x < w; ++x) {
if (*p && state->clip->test(xDest + x, yDest + y)) {
pipe.shape = *p;
(this->*pipe.run)(&pipe);
updateModX(xDest + x);
updateModY(yDest + y);
} else {
pipeIncX(&pipe);
}
++p;
}
}
}
}
}
CWE ID:
Target: 1
Example 2:
Code: static int __init cipso_v4_init(void)
{
int ret_val;
ret_val = cipso_v4_cache_init();
if (ret_val != 0)
panic("Failed to initialize the CIPSO/IPv4 cache (%d)\n",
ret_val);
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: long AudioTrack::Parse(
Segment* pSegment,
const Info& info,
long long element_start,
long long element_size,
AudioTrack*& pResult)
{
if (pResult)
return -1;
if (info.type != Track::kAudio)
return -1;
IMkvReader* const pReader = pSegment->m_pReader;
const Settings& s = info.settings;
assert(s.start >= 0);
assert(s.size >= 0);
long long pos = s.start;
assert(pos >= 0);
const long long stop = pos + s.size;
double rate = 8000.0; // MKV default
long long channels = 1;
long long bit_depth = 0;
while (pos < stop)
{
long long id, size;
long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x35) //Sample Rate
{
status = UnserializeFloat(pReader, pos, size, rate);
if (status < 0)
return status;
if (rate <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x1F) //Channel Count
{
channels = UnserializeUInt(pReader, pos, size);
if (channels <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x2264) //Bit Depth
{
bit_depth = UnserializeUInt(pReader, pos, size);
if (bit_depth <= 0)
return E_FILE_FORMAT_INVALID;
}
pos += size; //consume payload
assert(pos <= stop);
}
assert(pos == stop);
AudioTrack* const pTrack = new (std::nothrow) AudioTrack(pSegment,
element_start,
element_size);
if (pTrack == NULL)
return -1; //generic error
const int status = info.Copy(pTrack->m_info);
if (status)
{
delete pTrack;
return status;
}
pTrack->m_rate = rate;
pTrack->m_channels = channels;
pTrack->m_bitDepth = bit_depth;
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: spnego_gss_inquire_sec_context_by_oid(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
OM_uint32 ret;
ret = gss_inquire_sec_context_by_oid(minor_status,
context_handle,
desired_object,
data_set);
return (ret);
}
CWE ID: CWE-18
Target: 1
Example 2:
Code: add_xml_comment(xmlNode * parent, xmlNode * target, xmlNode * update)
{
CRM_CHECK(update != NULL, return 0);
CRM_CHECK(update->type == XML_COMMENT_NODE, return 0);
if (target == NULL) {
target = find_xml_comment(parent, update);
}
if (target == NULL) {
add_node_copy(parent, update);
/* We wont reach here currently */
} else if (safe_str_neq((const char *)target->content, (const char *)update->content)) {
xmlFree(target->content);
target->content = xmlStrdup(update->content);
}
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: netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket,
int newUid, uid_t callerUid) {
ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__);
const int fd = socket.get();
struct stat info;
if (fstat(fd, &info)) {
return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor");
}
if (info.st_uid != callerUid) {
return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls");
}
if (S_ISSOCK(info.st_mode) == 0) {
return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket");
}
int optval;
socklen_t optlen;
netdutils::Status status =
getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen);
if (status != netdutils::status::ok) {
return status;
}
if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) {
return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set");
}
if (fchown(fd, newUid, -1)) {
return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor");
}
return netdutils::status::ok;
}
CWE ID: CWE-909
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: ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG)));
return NULL;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void perf_mmap_close(struct vm_area_struct *vma)
{
struct perf_event *event = vma->vm_file->private_data;
struct ring_buffer *rb = ring_buffer_get(event);
struct user_struct *mmap_user = rb->mmap_user;
int mmap_locked = rb->mmap_locked;
unsigned long size = perf_data_size(rb);
if (event->pmu->event_unmapped)
event->pmu->event_unmapped(event);
/*
* rb->aux_mmap_count will always drop before rb->mmap_count and
* event->mmap_count, so it is ok to use event->mmap_mutex to
* serialize with perf_mmap here.
*/
if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
/*
* Stop all AUX events that are writing to this buffer,
* so that we can free its AUX pages and corresponding PMU
* data. Note that after rb::aux_mmap_count dropped to zero,
* they won't start any more (see perf_aux_output_begin()).
*/
perf_pmu_output_stop(event);
/* now it's safe to free the pages */
atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
/* this has to be the last one */
rb_free_aux(rb);
WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
mutex_unlock(&event->mmap_mutex);
}
atomic_dec(&rb->mmap_count);
if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
goto out_put;
ring_buffer_attach(event, NULL);
mutex_unlock(&event->mmap_mutex);
/* If there's still other mmap()s of this buffer, we're done. */
if (atomic_read(&rb->mmap_count))
goto out_put;
/*
* No other mmap()s, detach from all other events that might redirect
* into the now unreachable buffer. Somewhat complicated by the
* fact that rb::event_lock otherwise nests inside mmap_mutex.
*/
again:
rcu_read_lock();
list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
if (!atomic_long_inc_not_zero(&event->refcount)) {
/*
* This event is en-route to free_event() which will
* detach it and remove it from the list.
*/
continue;
}
rcu_read_unlock();
mutex_lock(&event->mmap_mutex);
/*
* Check we didn't race with perf_event_set_output() which can
* swizzle the rb from under us while we were waiting to
* acquire mmap_mutex.
*
* If we find a different rb; ignore this event, a next
* iteration will no longer find it on the list. We have to
* still restart the iteration to make sure we're not now
* iterating the wrong list.
*/
if (event->rb == rb)
ring_buffer_attach(event, NULL);
mutex_unlock(&event->mmap_mutex);
put_event(event);
/*
* Restart the iteration; either we're on the wrong list or
* destroyed its integrity by doing a deletion.
*/
goto again;
}
rcu_read_unlock();
/*
* It could be there's still a few 0-ref events on the list; they'll
* get cleaned up by free_event() -- they'll also still have their
* ref on the rb and will free it whenever they are done with it.
*
* Aside from that, this buffer is 'fully' detached and unmapped,
* undo the VM accounting.
*/
atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
vma->vm_mm->pinned_vm -= mmap_locked;
free_uid(mmap_user);
out_put:
ring_buffer_put(rb); /* could be last */
}
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: virtual void Predict(MB_PREDICTION_MODE mode) {
mbptr_->mode_info_context->mbmi.mode = mode;
REGISTER_STATE_CHECK(pred_fn_(mbptr_,
data_ptr_[0] - kStride,
data_ptr_[0] - 1, kStride,
data_ptr_[0], kStride));
}
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: SystemLibrary* CrosLibrary::GetSystemLibrary() {
return system_lib_.GetDefaultImpl(use_stub_impl_);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: AutofillManagerTest() {}
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 NetworkHandler::SetNetworkConditions(
network::mojom::NetworkConditionsPtr conditions) {
if (!process_)
return;
StoragePartition* partition = process_->GetStoragePartition();
network::mojom::NetworkContext* context = partition->GetNetworkContext();
context->SetNetworkConditions(host_id_, std::move(conditions));
}
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 RemoteFrame::ScheduleNavigation(Document& origin_document,
const KURL& url,
WebFrameLoadType frame_load_type,
UserGestureStatus user_gesture_status) {
FrameLoadRequest frame_request(&origin_document, ResourceRequest(url));
frame_request.GetResourceRequest().SetHasUserGesture(
user_gesture_status == UserGestureStatus::kActive);
frame_request.GetResourceRequest().SetFrameType(
IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel
: network::mojom::RequestContextFrameType::kNested);
Navigate(frame_request, frame_load_type);
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
struct vmcs12 *vmcs12)
{
u32 idt_vectoring;
unsigned int nr;
if (vcpu->arch.exception.injected) {
nr = vcpu->arch.exception.nr;
idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
if (kvm_exception_is_soft(nr)) {
vmcs12->vm_exit_instruction_len =
vcpu->arch.event_exit_inst_len;
idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
} else
idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
if (vcpu->arch.exception.has_error_code) {
idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
vmcs12->idt_vectoring_error_code =
vcpu->arch.exception.error_code;
}
vmcs12->idt_vectoring_info_field = idt_vectoring;
} else if (vcpu->arch.nmi_injected) {
vmcs12->idt_vectoring_info_field =
INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
} else if (vcpu->arch.interrupt.pending) {
nr = vcpu->arch.interrupt.nr;
idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
if (vcpu->arch.interrupt.soft) {
idt_vectoring |= INTR_TYPE_SOFT_INTR;
vmcs12->vm_entry_instruction_len =
vcpu->arch.event_exit_inst_len;
} else
idt_vectoring |= INTR_TYPE_EXT_INTR;
vmcs12->idt_vectoring_info_field = idt_vectoring;
}
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __inet_del_ifa(struct in_device *in_dev, struct in_ifaddr **ifap,
int destroy, struct nlmsghdr *nlh, u32 portid)
{
struct in_ifaddr *promote = NULL;
struct in_ifaddr *ifa, *ifa1 = *ifap;
struct in_ifaddr *last_prim = in_dev->ifa_list;
struct in_ifaddr *prev_prom = NULL;
int do_promote = IN_DEV_PROMOTE_SECONDARIES(in_dev);
ASSERT_RTNL();
/* 1. Deleting primary ifaddr forces deletion all secondaries
* unless alias promotion is set
**/
if (!(ifa1->ifa_flags & IFA_F_SECONDARY)) {
struct in_ifaddr **ifap1 = &ifa1->ifa_next;
while ((ifa = *ifap1) != NULL) {
if (!(ifa->ifa_flags & IFA_F_SECONDARY) &&
ifa1->ifa_scope <= ifa->ifa_scope)
last_prim = ifa;
if (!(ifa->ifa_flags & IFA_F_SECONDARY) ||
ifa1->ifa_mask != ifa->ifa_mask ||
!inet_ifa_match(ifa1->ifa_address, ifa)) {
ifap1 = &ifa->ifa_next;
prev_prom = ifa;
continue;
}
if (!do_promote) {
inet_hash_remove(ifa);
*ifap1 = ifa->ifa_next;
rtmsg_ifa(RTM_DELADDR, ifa, nlh, portid);
blocking_notifier_call_chain(&inetaddr_chain,
NETDEV_DOWN, ifa);
inet_free_ifa(ifa);
} else {
promote = ifa;
break;
}
}
}
/* On promotion all secondaries from subnet are changing
* the primary IP, we must remove all their routes silently
* and later to add them back with new prefsrc. Do this
* while all addresses are on the device list.
*/
for (ifa = promote; ifa; ifa = ifa->ifa_next) {
if (ifa1->ifa_mask == ifa->ifa_mask &&
inet_ifa_match(ifa1->ifa_address, ifa))
fib_del_ifaddr(ifa, ifa1);
}
/* 2. Unlink it */
*ifap = ifa1->ifa_next;
inet_hash_remove(ifa1);
/* 3. Announce address deletion */
/* Send message first, then call notifier.
At first sight, FIB update triggered by notifier
will refer to already deleted ifaddr, that could confuse
netlink listeners. It is not true: look, gated sees
that route deleted and if it still thinks that ifaddr
is valid, it will try to restore deleted routes... Grr.
So that, this order is correct.
*/
rtmsg_ifa(RTM_DELADDR, ifa1, nlh, portid);
blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa1);
if (promote) {
struct in_ifaddr *next_sec = promote->ifa_next;
if (prev_prom) {
prev_prom->ifa_next = promote->ifa_next;
promote->ifa_next = last_prim->ifa_next;
last_prim->ifa_next = promote;
}
promote->ifa_flags &= ~IFA_F_SECONDARY;
rtmsg_ifa(RTM_NEWADDR, promote, nlh, portid);
blocking_notifier_call_chain(&inetaddr_chain,
NETDEV_UP, promote);
for (ifa = next_sec; ifa; ifa = ifa->ifa_next) {
if (ifa1->ifa_mask != ifa->ifa_mask ||
!inet_ifa_match(ifa1->ifa_address, ifa))
continue;
fib_add_ifaddr(ifa);
}
}
if (destroy)
inet_free_ifa(ifa1);
}
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: const char *cJSON_GetErrorPtr( void )
{
return ep;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: format_CLEAR_ACTIONS(const struct ofpact_null *a OVS_UNUSED, struct ds *s)
{
ds_put_format(s, "%sclear_actions%s", colors.value, colors.end);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void scsi_read_complete(void * opaque, int ret)
{
SCSIDiskReq *r = (SCSIDiskReq *)opaque;
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
int n;
if (r->req.aiocb != NULL) {
r->req.aiocb = NULL;
bdrv_acct_done(s->bs, &r->acct);
}
if (ret) {
if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) {
return;
}
}
DPRINTF("Data ready tag=0x%x len=%zd\n", r->req.tag, r->iov.iov_len);
n = r->iov.iov_len / 512;
r->sector += n;
r->sector_count -= n;
scsi_req_data(&r->req, r->iov.iov_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: bool ExtensionTtsPlatformImplChromeOs::Speak(
const std::string& utterance,
const std::string& locale,
const std::string& gender,
double rate,
double pitch,
double volume) {
chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get();
if (!cros_library->EnsureLoaded()) {
set_error(kCrosLibraryNotLoadedError);
return false;
}
std::string options;
if (!locale.empty()) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyLocale,
locale,
&options);
}
if (!gender.empty()) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyGender,
gender,
&options);
}
if (rate >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyRate,
DoubleToString(rate * 5),
&options);
}
if (pitch >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyPitch,
DoubleToString(pitch * 2),
&options);
}
if (volume >= 0.0) {
AppendSpeakOption(
chromeos::SpeechSynthesisLibrary::kSpeechPropertyVolume,
DoubleToString(volume * 5),
&options);
}
if (!options.empty()) {
cros_library->GetSpeechSynthesisLibrary()->SetSpeakProperties(
options.c_str());
}
return cros_library->GetSpeechSynthesisLibrary()->Speak(utterance.c_str());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: const char *FLTGetBBOX(FilterEncodingNode *psFilterNode, rectObj *psRect)
{
const char *pszReturn = NULL;
if (!psFilterNode || !psRect)
return NULL;
if (psFilterNode->pszValue && strcasecmp(psFilterNode->pszValue, "BBOX") == 0) {
if (psFilterNode->psRightNode && psFilterNode->psRightNode->pOther) {
rectObj* pRect= (rectObj *)psFilterNode->psRightNode->pOther;
psRect->minx = pRect->minx;
psRect->miny = pRect->miny;
psRect->maxx = pRect->maxx;
psRect->maxy = pRect->maxy;
return psFilterNode->pszSRS;
}
} else {
pszReturn = FLTGetBBOX(psFilterNode->psLeftNode, psRect);
if (pszReturn)
return pszReturn;
else
return FLTGetBBOX(psFilterNode->psRightNode, psRect);
}
return pszReturn;
}
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 verify_vc_allocation(unsigned idx) {
char vcname[sizeof("/dev/vcs") + DECIMAL_STR_MAX(unsigned) - 2];
xsprintf(vcname, "/dev/vcs%u", idx);
if (access(vcname, F_OK) < 0)
return -errno;
return 0;
}
CWE ID: CWE-255
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline key_ref_t __key_update(key_ref_t key_ref,
struct key_preparsed_payload *prep)
{
struct key *key = key_ref_to_ptr(key_ref);
int ret;
/* need write permission on the key to update it */
ret = key_permission(key_ref, KEY_NEED_WRITE);
if (ret < 0)
goto error;
ret = -EEXIST;
if (!key->type->update)
goto error;
down_write(&key->sem);
ret = key->type->update(key, prep);
if (ret == 0)
/* updating a negative key instantiates it */
clear_bit(KEY_FLAG_NEGATIVE, &key->flags);
up_write(&key->sem);
if (ret < 0)
goto error;
out:
return key_ref;
error:
key_put(key);
key_ref = ERR_PTR(ret);
goto out;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: evdns_getaddrinfo(struct evdns_base *dns_base,
const char *nodename, const char *servname,
const struct evutil_addrinfo *hints_in,
evdns_getaddrinfo_cb cb, void *arg)
{
struct evdns_getaddrinfo_request *data;
struct evutil_addrinfo hints;
struct evutil_addrinfo *res = NULL;
int err;
int port = 0;
int want_cname = 0;
if (!dns_base) {
dns_base = current_base;
if (!dns_base) {
log(EVDNS_LOG_WARN,
"Call to getaddrinfo_async with no "
"evdns_base configured.");
cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
return NULL;
}
}
/* If we _must_ answer this immediately, do so. */
if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
res = NULL;
err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
cb(err, res, arg);
return NULL;
}
if (hints_in) {
memcpy(&hints, hints_in, sizeof(hints));
} else {
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
}
evutil_adjust_hints_for_addrconfig_(&hints);
/* Now try to see if we _can_ answer immediately. */
/* (It would be nice to do this by calling getaddrinfo directly, with
* AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
* a reliable way to distinguish the "that wasn't a numeric host!" case
* from any other EAI_NONAME cases.) */
err = evutil_getaddrinfo_common_(nodename, servname, &hints, &res, &port);
if (err != EVUTIL_EAI_NEED_RESOLVE) {
cb(err, res, arg);
return NULL;
}
/* If there is an entry in the hosts file, we should give it now. */
if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
cb(0, res, arg);
return NULL;
}
/* Okay, things are serious now. We're going to need to actually
* launch a request.
*/
data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
if (!data) {
cb(EVUTIL_EAI_MEMORY, NULL, arg);
return NULL;
}
memcpy(&data->hints, &hints, sizeof(data->hints));
data->port = (ev_uint16_t)port;
data->ipv4_request.type = DNS_IPv4_A;
data->ipv6_request.type = DNS_IPv6_AAAA;
data->user_cb = cb;
data->user_data = arg;
data->evdns_base = dns_base;
want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
/* If we are asked for a PF_UNSPEC address, we launch two requests in
* parallel: one for an A address and one for an AAAA address. We
* can't send just one request, since many servers only answer one
* question per DNS request.
*
* Once we have the answer to one request, we allow for a short
* timeout before we report it, to see if the other one arrives. If
* they both show up in time, then we report both the answers.
*
* If too many addresses of one type time out or fail, we should stop
* launching those requests. (XXX we don't do that yet.)
*/
if (hints.ai_family != PF_INET6) {
log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
nodename, &data->ipv4_request);
data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
nodename, 0, evdns_getaddrinfo_gotresolve,
&data->ipv4_request);
if (want_cname && data->ipv4_request.r)
data->ipv4_request.r->current_req->put_cname_in_ptr =
&data->cname_result;
}
if (hints.ai_family != PF_INET) {
log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
nodename, &data->ipv6_request);
data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
nodename, 0, evdns_getaddrinfo_gotresolve,
&data->ipv6_request);
if (want_cname && data->ipv6_request.r)
data->ipv6_request.r->current_req->put_cname_in_ptr =
&data->cname_result;
}
evtimer_assign(&data->timeout, dns_base->event_base,
evdns_getaddrinfo_timeout_cb, data);
if (data->ipv4_request.r || data->ipv6_request.r) {
return data;
} else {
mm_free(data);
cb(EVUTIL_EAI_FAIL, NULL, arg);
return NULL;
}
}
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: reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width,
uint8 *src, uint8 *dst)
{
int i;
uint32 col, bytes_per_pixel, col_offset;
uint8 bytebuff1;
unsigned char swapbuff[32];
if ((src == NULL) || (dst == NULL))
{
TIFFError("reverseSamplesBytes","Invalid input or output buffer");
return (1);
}
bytes_per_pixel = ((bps * spp) + 7) / 8;
switch (bps / 8)
{
case 8: /* Use memcpy for multiple bytes per sample data */
case 4:
case 3:
case 2: for (col = 0; col < (width / 2); col++)
{
col_offset = col * bytes_per_pixel;
_TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel);
_TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel);
_TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel);
}
break;
case 1: /* Use byte copy only for single byte per sample data */
for (col = 0; col < (width / 2); col++)
{
for (i = 0; i < spp; i++)
{
bytebuff1 = *src;
*src++ = *(dst - spp + i);
*(dst - spp + i) = bytebuff1;
}
dst -= spp;
}
break;
default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps);
return (1);
}
return (0);
} /* end reverseSamplesBytes */
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: void PrintMsg_Print_Params::Reset() {
page_size = gfx::Size();
content_size = gfx::Size();
printable_area = gfx::Rect();
margin_top = 0;
margin_left = 0;
dpi = 0;
min_shrink = 0;
max_shrink = 0;
desired_dpi = 0;
document_cookie = 0;
selection_only = false;
supports_alpha_blend = false;
preview_ui_addr = std::string();
preview_request_id = 0;
is_first_request = false;
print_scaling_option = WebKit::WebPrintScalingOptionSourceSize;
print_to_pdf = false;
display_header_footer = false;
date = string16();
title = string16();
url = string16();
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: nvmet_fc_queue_fcp_req(struct nvmet_fc_tgtport *tgtport,
struct nvmet_fc_tgt_queue *queue,
struct nvmefc_tgt_fcp_req *fcpreq)
{
struct nvmet_fc_fcp_iod *fod = fcpreq->nvmet_fc_private;
/*
* put all admin cmds on hw queue id 0. All io commands go to
* the respective hw queue based on a modulo basis
*/
fcpreq->hwqid = queue->qid ?
((queue->qid - 1) % tgtport->ops->max_hw_queues) : 0;
if (tgtport->ops->target_features & NVMET_FCTGTFEAT_CMD_IN_ISR)
queue_work_on(queue->cpu, queue->work_q, &fod->work);
else
nvmet_fc_handle_fcp_rqst(tgtport, fod);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __init gather_bootmem_prealloc(void)
{
struct huge_bootmem_page *m;
list_for_each_entry(m, &huge_boot_pages, list) {
struct page *page = virt_to_page(m);
struct hstate *h = m->hstate;
WARN_ON(page_count(page) != 1);
prep_compound_huge_page(page, h->order);
WARN_ON(PageReserved(page));
prep_new_huge_page(h, page, page_to_nid(page));
put_page(page); /* free it into the hugepage allocator */
/*
* If we had gigantic hugepages allocated at boot time, we need
* to restore the 'stolen' pages to totalram_pages in order to
* fix confusing memory reports from free(1) and another
* side-effects, like CommitLimit going negative.
*/
if (hstate_is_gigantic(h))
adjust_managed_page_count(page, 1 << h->order);
cond_resched();
}
}
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 int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc;
int len;
if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) {
rfcomm_dlc_accept(d);
msg->msg_namelen = 0;
return 0;
}
len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags);
lock_sock(sk);
if (!(flags & MSG_PEEK) && len > 0)
atomic_sub(len, &sk->sk_rmem_alloc);
if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2))
rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc);
release_sock(sk);
return len;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void RenderFrameHostImpl::GetFrameHostTestInterface(
blink::mojom::FrameHostTestInterfaceRequest request) {
class FrameHostTestInterfaceImpl
: public blink::mojom::FrameHostTestInterface {
public:
void Ping(const GURL& url, const std::string& event) override {}
void GetName(GetNameCallback callback) override {
std::move(callback).Run("RenderFrameHostImpl");
}
};
mojo::MakeStrongBinding(std::make_unique<FrameHostTestInterfaceImpl>(),
std::move(request));
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int au1200fb_fb_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
unsigned int len;
unsigned long start=0, off;
struct au1200fb_device *fbdev = info->par;
if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) {
return -EINVAL;
}
start = fbdev->fb_phys & PAGE_MASK;
len = PAGE_ALIGN((start & ~PAGE_MASK) + fbdev->fb_len);
off = vma->vm_pgoff << PAGE_SHIFT;
if ((vma->vm_end - vma->vm_start + off) > len) {
return -EINVAL;
}
off += start;
vma->vm_pgoff = off >> PAGE_SHIFT;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
pgprot_val(vma->vm_page_prot) |= _CACHE_MASK; /* CCA=7 */
return io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
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: opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
opj_cp_t *p_cp,
OPJ_UINT32 p_tile_no)
{
/* loop */
OPJ_UINT32 pino;
OPJ_UINT32 compno, resno;
/* to store w, h, dx and dy fro all components and resolutions */
OPJ_UINT32 * l_tmp_data;
OPJ_UINT32 ** l_tmp_ptr;
/* encoding prameters to set */
OPJ_UINT32 l_max_res;
OPJ_UINT32 l_max_prec;
OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;
OPJ_UINT32 l_dx_min,l_dy_min;
OPJ_UINT32 l_bound;
OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;
OPJ_UINT32 l_data_stride;
/* pointers */
opj_pi_iterator_t *l_pi = 00;
opj_tcp_t *l_tcp = 00;
const opj_tccp_t *l_tccp = 00;
opj_pi_comp_t *l_current_comp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_pi_iterator_t * l_current_pi = 00;
OPJ_UINT32 * l_encoding_value_ptr = 00;
/* preconditions in debug */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tile_no < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps[p_tile_no];
l_bound = l_tcp->numpocs+1;
l_data_stride = 4 * OPJ_J2K_MAXRLVLS;
l_tmp_data = (OPJ_UINT32*)opj_malloc(
l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));
if
(! l_tmp_data)
{
return 00;
}
l_tmp_ptr = (OPJ_UINT32**)opj_malloc(
p_image->numcomps * sizeof(OPJ_UINT32 *));
if
(! l_tmp_ptr)
{
opj_free(l_tmp_data);
return 00;
}
/* memory allocation for pi */
l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
if (!l_pi) {
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
return 00;
}
l_encoding_value_ptr = l_tmp_data;
/* update pointer array */
for
(compno = 0; compno < p_image->numcomps; ++compno)
{
l_tmp_ptr[compno] = l_encoding_value_ptr;
l_encoding_value_ptr += l_data_stride;
}
/* get encoding parameters */
opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);
/* step calculations */
l_step_p = 1;
l_step_c = l_max_prec * l_step_p;
l_step_r = p_image->numcomps * l_step_c;
l_step_l = l_max_res * l_step_r;
/* set values for first packet iterator */
l_current_pi = l_pi;
/* memory allocation for include */
/* prevent an integer overflow issue */
l_current_pi->include = 00;
if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))
{
l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));
}
if
(!l_current_pi->include)
{
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
opj_pi_destroy(l_pi, l_bound);
return 00;
}
/* special treatment for the first packet iterator */
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_img_comp->dx;*/
/*l_current_pi->dy = l_img_comp->dy;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
++l_current_pi;
for (pino = 1 ; pino<l_bound ; ++pino )
{
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_dx_min;*/
/*l_current_pi->dy = l_dy_min;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
/* special treatment*/
l_current_pi->include = (l_current_pi-1)->include;
++l_current_pi;
}
opj_free(l_tmp_data);
l_tmp_data = 00;
opj_free(l_tmp_ptr);
l_tmp_ptr = 00;
if
(l_tcp->POC)
{
opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);
}
else
{
opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);
}
return l_pi;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: armpmu_reserve_hardware(struct arm_pmu *armpmu)
{
int err, irq;
unsigned int i, irqs;
struct platform_device *pmu_device = armpmu->plat_device;
if (!pmu_device) {
pr_err("no PMU device registered\n");
return -ENODEV;
}
irqs = min(pmu_device->num_resources, num_possible_cpus());
if (!irqs) {
pr_err("no irqs for PMUs defined\n");
return -ENODEV;
}
irq = platform_get_irq(pmu_device, 0);
if (irq <= 0) {
pr_err("failed to get valid irq for PMU device\n");
return -ENODEV;
}
if (irq_is_percpu(irq)) {
err = request_percpu_irq(irq, armpmu->handle_irq,
"arm-pmu", &cpu_hw_events);
if (err) {
pr_err("unable to request percpu IRQ%d for ARM PMU counters\n",
irq);
armpmu_release_hardware(armpmu);
return err;
}
on_each_cpu(armpmu_enable_percpu_irq, &irq, 1);
} else {
for (i = 0; i < irqs; ++i) {
err = 0;
irq = platform_get_irq(pmu_device, i);
if (irq <= 0)
continue;
/*
* If we have a single PMU interrupt that we can't shift,
* assume that we're running on a uniprocessor machine and
* continue. Otherwise, continue without this interrupt.
*/
if (irq_set_affinity(irq, cpumask_of(i)) && irqs > 1) {
pr_warning("unable to set irq affinity (irq=%d, cpu=%u)\n",
irq, i);
continue;
}
err = request_irq(irq, armpmu->handle_irq,
IRQF_NOBALANCING,
"arm-pmu", armpmu);
if (err) {
pr_err("unable to request IRQ%d for ARM PMU counters\n",
irq);
armpmu_release_hardware(armpmu);
return err;
}
cpumask_set_cpu(i, &armpmu->active_irqs);
}
}
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: UsbClaimInterfaceFunction::UsbClaimInterfaceFunction() {
}
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 utf16_to_utf8(const char16_t* src, size_t src_len, char* dst)
{
if (src == NULL || src_len == 0 || dst == NULL) {
return;
}
const char16_t* cur_utf16 = src;
const char16_t* const end_utf16 = src + src_len;
char *cur = dst;
while (cur_utf16 < end_utf16) {
char32_t utf32;
if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16
&& (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) {
utf32 = (*cur_utf16++ - 0xD800) << 10;
utf32 |= *cur_utf16++ - 0xDC00;
utf32 += 0x10000;
} else {
utf32 = (char32_t) *cur_utf16++;
}
const size_t len = utf32_codepoint_utf8_length(utf32);
utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len);
cur += len;
}
*cur = '\0';
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: parse_pop_vlan(struct ofpbuf *ofpacts)
{
ofpact_put_STRIP_VLAN(ofpacts)->ofpact.raw = OFPAT_RAW11_POP_VLAN;
return 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: int migrate_huge_page_move_mapping(struct address_space *mapping,
struct page *newpage, struct page *page)
{
int expected_count;
void **pslot;
spin_lock_irq(&mapping->tree_lock);
pslot = radix_tree_lookup_slot(&mapping->page_tree,
page_index(page));
expected_count = 2 + page_has_private(page);
if (page_count(page) != expected_count ||
radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
if (!page_freeze_refs(page, expected_count)) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
set_page_memcg(newpage, page_memcg(page));
newpage->index = page->index;
newpage->mapping = page->mapping;
get_page(newpage);
radix_tree_replace_slot(pslot, newpage);
page_unfreeze_refs(page, expected_count - 1);
spin_unlock_irq(&mapping->tree_lock);
return MIGRATEPAGE_SUCCESS;
}
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int getnum (lua_State *L, const char **fmt, int df) {
if (!isdigit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0')))
luaL_error(L, "integral size overflow");
a = a*10 + *((*fmt)++) - '0';
} while (isdigit(**fmt));
return a;
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: void LoadResource(int idr) {
ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();
scoped_refptr<base::RefCountedMemory> resource =
bundle.LoadDataResourceBytes(idr);
RunTest(GURL(std::string("data:text/html,") +
std::string(resource->front_as<char>(), resource->size())));
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int siocdevprivate_ioctl(struct net *net, unsigned int cmd,
struct compat_ifreq __user *u_ifreq32)
{
struct ifreq __user *u_ifreq64;
char tmp_buf[IFNAMSIZ];
void __user *data64;
u32 data32;
if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]),
IFNAMSIZ))
return -EFAULT;
if (__get_user(data32, &u_ifreq32->ifr_ifru.ifru_data))
return -EFAULT;
data64 = compat_ptr(data32);
u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64));
/* Don't check these user accesses, just let that get trapped
* in the ioctl handler instead.
*/
if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0],
IFNAMSIZ))
return -EFAULT;
if (__put_user(data64, &u_ifreq64->ifr_ifru.ifru_data))
return -EFAULT;
return dev_ioctl(net, cmd, u_ifreq64);
}
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: status_t OMXNodeInstance::useBuffer(
OMX_U32 portIndex, const sp<IMemory> ¶ms,
OMX::buffer_id *buffer, OMX_U32 allottedSize) {
if (params == NULL || buffer == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
if (allottedSize > params->size()) {
return BAD_VALUE;
}
BufferMeta *buffer_meta = new BufferMeta(params, portIndex);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_UseBuffer(
mHandle, &header, portIndex, buffer_meta,
allottedSize, static_cast<OMX_U8 *>(params->pointer()));
if (err != OMX_ErrorNone) {
CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER(
portIndex, (size_t)allottedSize, params->pointer()));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%u(%zu)@%p", allottedSize, params->size(), params->pointer()));
return OK;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static inline void atl2_clear_phy_int(struct atl2_adapter *adapter)
{
u16 phy_data;
spin_lock(&adapter->stats_lock);
atl2_read_phy_reg(&adapter->hw, 19, &phy_data);
spin_unlock(&adapter->stats_lock);
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: format_nid(const u_char *data)
{
static char buf[4][sizeof("01:01:01:01")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%02x:%02x:%02x:%02x",
data[0], data[1], data[2], data[3]);
return buf[i];
}
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: xscale2pmu_handle_irq(int irq_num, void *dev)
{
unsigned long pmnc, of_flags;
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int idx;
/* Disable the PMU. */
pmnc = xscale2pmu_read_pmnc();
xscale2pmu_write_pmnc(pmnc & ~XSCALE_PMU_ENABLE);
/* Check the overflow flag register. */
of_flags = xscale2pmu_read_overflow_flags();
if (!(of_flags & XSCALE2_OVERFLOWED_MASK))
return IRQ_NONE;
/* Clear the overflow bits. */
xscale2pmu_write_overflow_flags(of_flags);
regs = get_irq_regs();
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
for (idx = 0; idx <= armpmu->num_events; ++idx) {
struct perf_event *event = cpuc->events[idx];
struct hw_perf_event *hwc;
if (!test_bit(idx, cpuc->active_mask))
continue;
if (!xscale2_pmnc_counter_has_overflowed(pmnc, idx))
continue;
hwc = &event->hw;
armpmu_event_update(event, hwc, idx, 1);
data.period = event->hw.last_period;
if (!armpmu_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, 0, &data, regs))
armpmu->disable(hwc, idx);
}
irq_work_run();
/*
* Re-enable the PMU.
*/
pmnc = xscale2pmu_read_pmnc() | XSCALE_PMU_ENABLE;
xscale2pmu_write_pmnc(pmnc);
return IRQ_HANDLED;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: Strfgetall(FILE * f)
{
Str s = Strnew();
int c;
while ((c = fgetc(f)) != EOF) {
Strcat_char(s, c);
}
return s;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ShellWindow::ShellWindow(Profile* profile,
const extensions::Extension* extension,
const GURL& url)
: profile_(profile),
extension_(extension),
ALLOW_THIS_IN_INITIALIZER_LIST(
extension_function_dispatcher_(profile, this)) {
web_contents_ = WebContents::Create(
profile, SiteInstance::CreateForURL(profile, url), MSG_ROUTING_NONE, NULL,
NULL);
contents_.reset(new TabContents(web_contents_));
content::WebContentsObserver::Observe(web_contents_);
web_contents_->SetDelegate(this);
chrome::SetViewType(web_contents_, chrome::VIEW_TYPE_APP_SHELL);
web_contents_->GetMutableRendererPrefs()->
browser_handles_all_top_level_requests = true;
web_contents_->GetRenderViewHost()->SyncRendererPrefs();
web_contents_->GetController().LoadURL(
url, content::Referrer(), content::PAGE_TRANSITION_LINK,
std::string());
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
content::Source<Profile>(profile_));
registrar_.Add(this, content::NOTIFICATION_APP_TERMINATING,
content::NotificationService::AllSources());
TabContents* tab_contents = TabContents::FromWebContents(web_contents_);
InfoBarTabHelper* infobar_helper = tab_contents->infobar_tab_helper();
infobar_helper->set_infobars_enabled(false);
browser::StartKeepAlive();
}
CWE ID: CWE-399
Output: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.