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 irqreturn_t armv7pmu_handle_irq(int irq_num, void *dev)
{
unsigned long pmnc;
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int idx;
/*
* Get and reset the IRQ flags
*/
pmnc = armv7_pmnc_getreset_flags();
/*
* Did an overflow occur?
*/
if (!armv7_pmnc_has_overflowed(pmnc))
return IRQ_NONE;
/*
* Handle the counter(s) overflow(s)
*/
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;
/*
* We have a single interrupt for all counters. Check that
* each counter has overflowed before we process it.
*/
if (!armv7_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);
}
/*
* Handle the pending perf events.
*
* Note: this call *must* be run with interrupts disabled. For
* platforms that can have the PMU interrupts raised as an NMI, this
* will not work.
*/
irq_work_run();
return IRQ_HANDLED;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int hash_init(struct ahash_request *req)
{
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
struct hash_req_ctx *req_ctx = ahash_request_ctx(req);
if (!ctx->key)
ctx->keylen = 0;
memset(&req_ctx->state, 0, sizeof(struct hash_state));
req_ctx->updated = 0;
if (hash_mode == HASH_MODE_DMA) {
if (req->nbytes < HASH_DMA_ALIGN_SIZE) {
req_ctx->dma_mode = false; /* Don't use DMA */
pr_debug("%s: DMA mode, but direct to CPU mode for data size < %d\n",
__func__, HASH_DMA_ALIGN_SIZE);
} else {
if (req->nbytes >= HASH_DMA_PERFORMANCE_MIN_SIZE &&
hash_dma_valid_data(req->src, req->nbytes)) {
req_ctx->dma_mode = true;
} else {
req_ctx->dma_mode = false;
pr_debug("%s: DMA mode, but use CPU mode for datalength < %d or non-aligned data, except in last nent\n",
__func__,
HASH_DMA_PERFORMANCE_MIN_SIZE);
}
}
}
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 AllDownloadsCompleteObserver::OnDownloadUpdated(DownloadItem* download) {
if (download->GetState() != DownloadItem::IN_PROGRESS) {
download->RemoveObserver(this);
pending_downloads_.erase(download);
ReplyIfNecessary();
}
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool check_allocations(ASS_Shaper *shaper, size_t new_size)
{
if (new_size > shaper->n_glyphs) {
if (!ASS_REALLOC_ARRAY(shaper->event_text, new_size) ||
!ASS_REALLOC_ARRAY(shaper->ctypes, new_size) ||
!ASS_REALLOC_ARRAY(shaper->emblevels, new_size) ||
!ASS_REALLOC_ARRAY(shaper->cmap, new_size))
return false;
}
return true;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void WaitUntilHostLookedUp(const std::string& host) {
wait_event_ = WaitEvent::kDns;
DCHECK(waiting_on_dns_.empty());
waiting_on_dns_ = host;
Wait();
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_FUNCTION(pathinfo)
{
zval tmp;
char *path, *dirname;
size_t path_len;
int have_basename;
zend_long opt = PHP_PATHINFO_ALL;
zend_string *ret = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|l", &path, &path_len, &opt) == FAILURE) {
return;
}
have_basename = ((opt & PHP_PATHINFO_BASENAME) == PHP_PATHINFO_BASENAME);
array_init(&tmp);
if ((opt & PHP_PATHINFO_DIRNAME) == PHP_PATHINFO_DIRNAME) {
dirname = estrndup(path, path_len);
php_dirname(dirname, path_len);
if (*dirname) {
add_assoc_string(&tmp, "dirname", dirname);
}
efree(dirname);
}
if (have_basename) {
ret = php_basename(path, path_len, NULL, 0);
add_assoc_str(&tmp, "basename", zend_string_copy(ret));
}
if ((opt & PHP_PATHINFO_EXTENSION) == PHP_PATHINFO_EXTENSION) {
const char *p;
ptrdiff_t idx;
if (!have_basename) {
ret = php_basename(path, path_len, NULL, 0);
}
p = zend_memrchr(ZSTR_VAL(ret), '.', ZSTR_LEN(ret));
if (p) {
idx = p - ZSTR_VAL(ret);
add_assoc_stringl(&tmp, "extension", ZSTR_VAL(ret) + idx + 1, ZSTR_LEN(ret) - idx - 1);
}
}
if ((opt & PHP_PATHINFO_FILENAME) == PHP_PATHINFO_FILENAME) {
const char *p;
ptrdiff_t idx;
/* Have we already looked up the basename? */
if (!have_basename && !ret) {
ret = php_basename(path, path_len, NULL, 0);
}
p = zend_memrchr(ZSTR_VAL(ret), '.', ZSTR_LEN(ret));
idx = p ? (p - ZSTR_VAL(ret)) : ZSTR_LEN(ret);
add_assoc_stringl(&tmp, "filename", ZSTR_VAL(ret), idx);
}
if (ret) {
zend_string_release(ret);
}
if (opt == PHP_PATHINFO_ALL) {
ZVAL_COPY_VALUE(return_value, &tmp);
} else {
zval *element;
if ((element = zend_hash_get_current_data(Z_ARRVAL(tmp))) != NULL) {
ZVAL_DEREF(element);
ZVAL_COPY(return_value, element);
} else {
ZVAL_EMPTY_STRING(return_value);
}
zval_ptr_dtor(&tmp);
}
}
CWE ID: CWE-17
Output:
| 0 |
Here are some example code snippets. Analyze the following 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 shash_no_setkey(struct crypto_shash *tfm, const u8 *key,
unsigned int keylen)
{
return -ENOSYS;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: GF_Err stri_Size(GF_Box *s)
{
GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s;
ptr->size += 8 + 4 * ptr->attribute_count;
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: static MagickBooleanType ClonePixelCacheRepository(
CacheInfo *restrict clone_info,CacheInfo *restrict cache_info,
ExceptionInfo *exception)
{
#define MaxCacheThreads 2
#define cache_threads(source,destination,chunk) \
num_threads((chunk) < (16*GetMagickResourceLimit(ThreadResource)) ? 1 : \
GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \
GetMagickResourceLimit(ThreadResource) : MaxCacheThreads)
MagickBooleanType
status;
NexusInfo
**restrict cache_nexus,
**restrict clone_nexus;
size_t
length;
ssize_t
y;
assert(cache_info != (CacheInfo *) NULL);
assert(clone_info != (CacheInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
if (cache_info->type == PingCache)
return(MagickTrue);
if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) &&
((clone_info->type == MemoryCache) || (clone_info->type == MapCache)) &&
(cache_info->columns == clone_info->columns) &&
(cache_info->rows == clone_info->rows) &&
(cache_info->active_index_channel == clone_info->active_index_channel))
{
/*
Identical pixel cache morphology.
*/
CopyPixels(clone_info->pixels,cache_info->pixels,cache_info->columns*
cache_info->rows);
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
(void) memcpy(clone_info->indexes,cache_info->indexes,
cache_info->columns*cache_info->rows*sizeof(*cache_info->indexes));
return(MagickTrue);
}
/*
Mismatched pixel cache morphology.
*/
cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
if ((cache_nexus == (NexusInfo **) NULL) ||
(clone_nexus == (NexusInfo **) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->pixels);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info,cache_info->rows)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue,
cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue,
clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t)
clone_nexus[id]->length);
(void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length);
status=WritePixelCachePixels(clone_info,clone_nexus[id],exception);
}
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
{
/*
Clone indexes.
*/
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->indexes);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info,cache_info->rows)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue,
cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue,
clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length);
status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception);
}
}
cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads);
clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads);
if (cache_info->debug != MagickFalse)
{
char
message[MaxTextExtent];
(void) FormatLocaleString(message,MaxTextExtent,"%s => %s",
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type),
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type));
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
return(status);
}
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 *load_device_tree(const char *filename_path, int *sizep)
{
int dt_size;
int dt_file_load_size;
int ret;
void *fdt = NULL;
*sizep = 0;
dt_size = get_image_size(filename_path);
if (dt_size < 0) {
error_report("Unable to get size of device tree file '%s'",
filename_path);
goto fail;
}
/* Expand to 2x size to give enough room for manipulation. */
dt_size += 10000;
dt_size *= 2;
/* First allocate space in qemu for device tree */
fdt = g_malloc0(dt_size);
dt_file_load_size = load_image(filename_path, fdt);
if (dt_file_load_size < 0) {
error_report("Unable to open device tree file '%s'",
filename_path);
goto fail;
}
ret = fdt_open_into(fdt, fdt, dt_size);
if (ret) {
error_report("Unable to copy device tree in memory");
goto fail;
}
/* Check sanity of device tree */
if (fdt_check_header(fdt)) {
error_report("Device tree file loaded into memory is invalid: %s",
filename_path);
goto fail;
}
*sizep = dt_size;
return fdt;
fail:
g_free(fdt);
return NULL;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static enum print_line_t print_raw_fmt(struct trace_iterator *iter)
{
struct trace_array *tr = iter->tr;
struct trace_seq *s = &iter->seq;
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
if (tr->trace_flags & TRACE_ITER_CONTEXT_INFO)
trace_seq_printf(s, "%d %d %llu ",
entry->pid, iter->cpu, iter->ts);
if (trace_seq_has_overflowed(s))
return TRACE_TYPE_PARTIAL_LINE;
event = ftrace_find_event(entry->type);
if (event)
return event->funcs->raw(iter, 0, event);
trace_seq_printf(s, "%d ?\n", entry->type);
return trace_handle_return(s);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __init ovl_init(void)
{
return register_filesystem(&ovl_fs_type);
}
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 Document::InitSecurityContext(const DocumentInit& initializer) {
DCHECK(!GetSecurityOrigin());
if (!initializer.HasSecurityContext()) {
cookie_url_ = KURL(g_empty_string);
SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque());
InitContentSecurityPolicy();
ApplyFeaturePolicy({});
return;
}
SandboxFlags sandbox_flags = initializer.GetSandboxFlags();
if (fetcher_->Archive()) {
sandbox_flags |=
kSandboxAll &
~(kSandboxPopups | kSandboxPropagatesToAuxiliaryBrowsingContexts);
}
EnforceSandboxFlags(sandbox_flags);
SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());
if (initializer.InsecureNavigationsToUpgrade()) {
for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())
AddInsecureNavigationUpgrade(to_upgrade);
}
ContentSecurityPolicy* policy_to_inherit = nullptr;
if (IsSandboxed(kSandboxOrigin)) {
cookie_url_ = url_;
scoped_refptr<SecurityOrigin> security_origin =
SecurityOrigin::CreateUniqueOpaque();
Document* owner = initializer.OwnerDocument();
if (owner) {
if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy())
security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true);
if (owner->GetSecurityOrigin()->CanLoadLocalResources())
security_origin->GrantLoadLocalResources();
policy_to_inherit = owner->GetContentSecurityPolicy();
}
SetSecurityOrigin(std::move(security_origin));
} else if (Document* owner = initializer.OwnerDocument()) {
cookie_url_ = owner->CookieURL();
SetSecurityOrigin(owner->GetMutableSecurityOrigin());
policy_to_inherit = owner->GetContentSecurityPolicy();
} else {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::Create(url_));
}
if (initializer.IsHostedInReservedIPRange()) {
SetAddressSpace(GetSecurityOrigin()->IsLocalhost()
? mojom::IPAddressSpace::kLocal
: mojom::IPAddressSpace::kPrivate);
} else if (GetSecurityOrigin()->IsLocal()) {
SetAddressSpace(mojom::IPAddressSpace::kLocal);
} else {
SetAddressSpace(mojom::IPAddressSpace::kPublic);
}
if (ImportsController()) {
SetContentSecurityPolicy(
ImportsController()->Master()->GetContentSecurityPolicy());
} else {
InitContentSecurityPolicy(nullptr, policy_to_inherit);
}
if (Settings* settings = initializer.GetSettings()) {
if (!settings->GetWebSecurityEnabled()) {
GetMutableSecurityOrigin()->GrantUniversalAccess();
} else if (GetSecurityOrigin()->IsLocal()) {
if (settings->GetAllowUniversalAccessFromFileURLs()) {
GetMutableSecurityOrigin()->GrantUniversalAccess();
} else if (!settings->GetAllowFileAccessFromFileURLs()) {
GetMutableSecurityOrigin()->BlockLocalAccessFromLocalOrigin();
}
}
}
if (GetSecurityOrigin()->IsOpaque() &&
SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())
GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true);
ApplyFeaturePolicy({});
InitSecureContextState();
}
CWE ID:
Target: 1
Example 2:
Code: static int mailimf_day_name_parse(const char * message, size_t length,
size_t * indx, int * result)
{
size_t cur_token;
int day_of_week;
int guessed_day;
int r;
cur_token = * indx;
guessed_day = guess_day_name(message, length, cur_token);
if (guessed_day == -1)
return MAILIMF_ERROR_PARSE;
r = mailimf_token_case_insensitive_parse(message, length,
&cur_token,
day_names[guessed_day - 1].str);
if (r != MAILIMF_NO_ERROR)
return r;
day_of_week = guessed_day;
* result = day_of_week;
* indx = cur_token;
return MAILIMF_NO_ERROR;
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: INT_PTR CALLBACK NewVersionCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
char cmdline[] = APPLICATION_NAME " -w 150";
static char* filepath = NULL;
static int download_status = 0;
LONG i;
HWND hNotes;
STARTUPINFOA si;
PROCESS_INFORMATION pi;
HFONT hyperlink_font = NULL;
EXT_DECL(dl_ext, NULL, __VA_GROUP__("*.exe"), __VA_GROUP__(lmprintf(MSG_037)));
switch (message) {
case WM_INITDIALOG:
apply_localization(IDD_NEW_VERSION, hDlg);
download_status = 0;
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
update_original_proc = (WNDPROC)SetWindowLongPtr(hDlg, GWLP_WNDPROC, (LONG_PTR)update_subclass_callback);
hNotes = GetDlgItem(hDlg, IDC_RELEASE_NOTES);
SendMessage(hNotes, EM_AUTOURLDETECT, 1, 0);
SendMessageA(hNotes, EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)update.release_notes);
SendMessage(hNotes, EM_SETSEL, -1, -1);
SendMessage(hNotes, EM_SETEVENTMASK, 0, ENM_LINK);
SetWindowTextU(GetDlgItem(hDlg, IDC_YOUR_VERSION), lmprintf(MSG_018,
rufus_version[0], rufus_version[1], rufus_version[2]));
SetWindowTextU(GetDlgItem(hDlg, IDC_LATEST_VERSION), lmprintf(MSG_019,
update.version[0], update.version[1], update.version[2]));
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD_URL), update.download_url);
SendMessage(GetDlgItem(hDlg, IDC_PROGRESS), PBM_SETRANGE, 0, (MAX_PROGRESS<<16) & 0xFFFF0000);
if (update.download_url == NULL)
EnableWindow(GetDlgItem(hDlg, IDC_DOWNLOAD), FALSE);
break;
case WM_CTLCOLORSTATIC:
if ((HWND)lParam != GetDlgItem(hDlg, IDC_WEBSITE))
return FALSE;
SetBkMode((HDC)wParam, TRANSPARENT);
CreateStaticFont((HDC)wParam, &hyperlink_font);
SelectObject((HDC)wParam, hyperlink_font);
SetTextColor((HDC)wParam, RGB(0,0,125)); // DARK_BLUE
return (INT_PTR)CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDCLOSE:
case IDCANCEL:
if (download_status != 1) {
reset_localization(IDD_NEW_VERSION);
safe_free(filepath);
EndDialog(hDlg, LOWORD(wParam));
}
return (INT_PTR)TRUE;
case IDC_WEBSITE:
ShellExecuteA(hDlg, "open", RUFUS_URL, NULL, NULL, SW_SHOWNORMAL);
break;
case IDC_DOWNLOAD: // Also doubles as abort and launch function
switch(download_status) {
case 1: // Abort
FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|ERROR_CANCELLED;
download_status = 0;
break;
case 2: // Launch newer version and close this one
Sleep(1000); // Add a delay on account of antivirus scanners
if (ValidateSignature(hDlg, filepath) != NO_ERROR)
break;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
if (!CreateProcessU(filepath, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
PrintInfo(0, MSG_214);
uprintf("Failed to launch new application: %s\n", WindowsErrorString());
} else {
PrintInfo(0, MSG_213);
PostMessage(hDlg, WM_COMMAND, (WPARAM)IDCLOSE, 0);
PostMessage(hMainDialog, WM_CLOSE, 0, 0);
}
break;
default: // Download
if (update.download_url == NULL) {
uprintf("Could not get download URL\n");
break;
}
for (i=(int)strlen(update.download_url); (i>0)&&(update.download_url[i]!='/'); i--);
dl_ext.filename = &update.download_url[i+1];
filepath = FileDialog(TRUE, app_dir, &dl_ext, OFN_NOCHANGEDIR);
if (filepath == NULL) {
uprintf("Could not get save path\n");
break;
}
SendMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hDlg, IDC_DOWNLOAD), TRUE);
DownloadFileThreaded(update.download_url, filepath, hDlg);
break;
}
return (INT_PTR)TRUE;
}
break;
case UM_PROGRESS_INIT:
EnableWindow(GetDlgItem(hDlg, IDCANCEL), FALSE);
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_038));
FormatStatus = 0;
download_status = 1;
return (INT_PTR)TRUE;
case UM_PROGRESS_EXIT:
EnableWindow(GetDlgItem(hDlg, IDCANCEL), TRUE);
if (wParam) {
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_039));
download_status = 2;
} else {
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_040));
download_status = 0;
}
return (INT_PTR)TRUE;
}
return (INT_PTR)FALSE;
}
CWE ID: CWE-494
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 toggle_utf8(const char *name, int fd, bool utf8) {
int r;
struct termios tc = {};
assert(name);
r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE);
if (r < 0)
return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name);
r = loop_write(fd, utf8 ? "\033%G" : "\033%@", 3, false);
if (r < 0)
return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name);
r = tcgetattr(fd, &tc);
if (r >= 0) {
SET_FLAG(tc.c_iflag, IUTF8, utf8);
r = tcsetattr(fd, TCSANOW, &tc);
}
if (r < 0)
return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name);
log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name);
return 0;
}
CWE ID: CWE-255
Target: 1
Example 2:
Code: struct QBUFFER __iomem *arcmsr_get_iop_rqbuffer(struct AdapterControlBlock *acb)
{
struct QBUFFER __iomem *qbuffer = NULL;
switch (acb->adapter_type) {
case ACB_ADAPTER_TYPE_A: {
struct MessageUnit_A __iomem *reg = acb->pmuA;
qbuffer = (struct QBUFFER __iomem *)®->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_B: {
struct MessageUnit_B *reg = acb->pmuB;
qbuffer = (struct QBUFFER __iomem *)reg->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_C: {
struct MessageUnit_C __iomem *phbcmu = acb->pmuC;
qbuffer = (struct QBUFFER __iomem *)&phbcmu->message_rbuffer;
}
break;
case ACB_ADAPTER_TYPE_D: {
struct MessageUnit_D *reg = acb->pmuD;
qbuffer = (struct QBUFFER __iomem *)reg->message_rbuffer;
}
break;
}
return qbuffer;
}
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: PrintPreviewUIUnitTest() {}
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: int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len)
{
if (!m_debug.outfile) {
int size = 0;
if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.m4v",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H264) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.264",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_HEVC) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%ld_%ld_%p.265",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_H263) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.263",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
} else if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_VP8) {
size = snprintf(m_debug.outfile_name, PROPERTY_VALUE_MAX, "%s/output_enc_%lu_%lu_%p.ivf",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
}
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.outfile_name, size);
}
m_debug.outfile = fopen(m_debug.outfile_name, "ab");
if (!m_debug.outfile) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging errno:%d",
m_debug.outfile_name, errno);
m_debug.outfile_name[0] = '\0';
return -1;
}
}
if (m_debug.outfile && buffer_len) {
DEBUG_PRINT_LOW("%s buffer_len:%d", __func__, buffer_len);
fwrite(buffer_addr, buffer_len, 1, m_debug.outfile);
}
return 0;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: rdma_copy_tail(struct svc_rqst *rqstp, struct svc_rdma_op_ctxt *head,
u32 position, u32 byte_count, u32 page_offset, int page_no)
{
char *srcp, *destp;
srcp = head->arg.head[0].iov_base + position;
byte_count = head->arg.head[0].iov_len - position;
if (byte_count > PAGE_SIZE) {
dprintk("svcrdma: large tail unsupported\n");
return 0;
}
/* Fit as much of the tail on the current page as possible */
if (page_offset != PAGE_SIZE) {
destp = page_address(rqstp->rq_arg.pages[page_no]);
destp += page_offset;
while (byte_count--) {
*destp++ = *srcp++;
page_offset++;
if (page_offset == PAGE_SIZE && byte_count)
goto more;
}
goto done;
}
more:
/* Fit the rest on the next page */
page_no++;
destp = page_address(rqstp->rq_arg.pages[page_no]);
while (byte_count--)
*destp++ = *srcp++;
rqstp->rq_respages = &rqstp->rq_arg.pages[page_no+1];
rqstp->rq_next_page = rqstp->rq_respages + 1;
done:
byte_count = head->arg.head[0].iov_len - position;
head->arg.page_len += byte_count;
head->arg.len += byte_count;
head->arg.buflen += byte_count;
return 1;
}
CWE ID: CWE-404
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: char *path_name(const struct name_path *path, const char *name)
{
const struct name_path *p;
char *n, *m;
int nlen = strlen(name);
int len = nlen + 1;
for (p = path; p; p = p->up) {
if (p->elem_len)
len += p->elem_len + 1;
}
n = xmalloc(len);
m = n + len - (nlen + 1);
strcpy(m, name);
for (p = path; p; p = p->up) {
if (p->elem_len) {
m -= p->elem_len + 1;
memcpy(m, p->elem, p->elem_len);
m[p->elem_len] = '/';
}
}
return n;
}
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 php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
efree(ent1);
} else {
stack->done = 1;
}
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
if (new_str) {
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
} else {
ZVAL_EMPTY_STRING(ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
CWE ID: CWE-476
Target: 1
Example 2:
Code: virtual ~VP9WorkerThreadTest() {}
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 __swiotlb_map_sg_attrs(struct device *dev, struct scatterlist *sgl,
int nelems, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct scatterlist *sg;
int i, ret;
ret = swiotlb_map_sg_attrs(dev, sgl, nelems, dir, attrs);
if (!is_device_dma_coherent(dev))
for_each_sg(sgl, sg, ret, i)
__dma_map_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)),
sg->length, dir);
return ret;
}
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 InputEngine::ProcessText(const std::string& message,
ProcessTextCallback callback) {
NOTIMPLEMENTED(); // Text message not used in the rulebased engine.
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: qtdemux_tag_add_str (GstQTDemux * qtdemux, const char *tag, const char *dummy,
GNode * node)
{
const gchar *env_vars[] = { "GST_QT_TAG_ENCODING", "GST_TAG_ENCODING", NULL };
GNode *data;
char *s;
int len;
int type;
int offset;
data = qtdemux_tree_get_child_by_type (node, FOURCC_data);
if (data) {
len = QT_UINT32 (data->data);
type = QT_UINT32 ((guint8 *) data->data + 8);
if (type == 0x00000001) {
s = gst_tag_freeform_string_to_utf8 ((char *) data->data + 16, len - 16,
env_vars);
if (s) {
GST_DEBUG_OBJECT (qtdemux, "adding tag %s", GST_STR_NULL (s));
gst_tag_list_add (qtdemux->tag_list, GST_TAG_MERGE_REPLACE, tag, s,
NULL);
g_free (s);
} else {
GST_DEBUG_OBJECT (qtdemux, "failed to convert %s tag to UTF-8", tag);
}
}
} else {
len = QT_UINT32 (node->data);
type = QT_UINT32 ((guint8 *) node->data + 4);
if (type & 0xa9000000) {
/* Type starts with the (C) symbol, so the next 32 bits are
* the language code, which we ignore */
offset = 12;
GST_DEBUG_OBJECT (qtdemux, "found international text tag");
} else {
offset = 8;
GST_DEBUG_OBJECT (qtdemux, "found normal text tag");
}
s = gst_tag_freeform_string_to_utf8 ((char *) node->data + offset,
len - offset, env_vars);
if (s) {
GST_DEBUG_OBJECT (qtdemux, "adding tag %s", GST_STR_NULL (s));
gst_tag_list_add (qtdemux->tag_list, GST_TAG_MERGE_REPLACE, tag, s, NULL);
g_free (s);
} else {
GST_DEBUG_OBJECT (qtdemux, "failed to convert %s tag to UTF-8", tag);
}
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline int do_exception(struct pt_regs *regs, int access,
unsigned long trans_exc_code)
{
struct task_struct *tsk;
struct mm_struct *mm;
struct vm_area_struct *vma;
unsigned long address;
unsigned int flags;
int fault;
if (notify_page_fault(regs))
return 0;
tsk = current;
mm = tsk->mm;
/*
* Verify that the fault happened in user space, that
* we are not in an interrupt and that there is a
* user context.
*/
fault = VM_FAULT_BADCONTEXT;
if (unlikely(!user_space_fault(trans_exc_code) || in_atomic() || !mm))
goto out;
address = trans_exc_code & __FAIL_ADDR_MASK;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);
flags = FAULT_FLAG_ALLOW_RETRY;
if (access == VM_WRITE || (trans_exc_code & store_indication) == 0x400)
flags |= FAULT_FLAG_WRITE;
retry:
down_read(&mm->mmap_sem);
fault = VM_FAULT_BADMAP;
vma = find_vma(mm, address);
if (!vma)
goto out_up;
if (unlikely(vma->vm_start > address)) {
if (!(vma->vm_flags & VM_GROWSDOWN))
goto out_up;
if (expand_stack(vma, address))
goto out_up;
}
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
fault = VM_FAULT_BADACCESS;
if (unlikely(!(vma->vm_flags & access)))
goto out_up;
if (is_vm_hugetlb_page(vma))
address &= HPAGE_MASK;
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault.
*/
fault = handle_mm_fault(mm, vma, address, flags);
if (unlikely(fault & VM_FAULT_ERROR))
goto out_up;
/*
* Major/minor page fault accounting is only done on the
* initial attempt. If we go through a retry, it is extremely
* likely that the page will be found in page cache at that point.
*/
if (flags & FAULT_FLAG_ALLOW_RETRY) {
if (fault & VM_FAULT_MAJOR) {
tsk->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0,
regs, address);
} else {
tsk->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0,
regs, address);
}
if (fault & VM_FAULT_RETRY) {
/* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk
* of starvation. */
flags &= ~FAULT_FLAG_ALLOW_RETRY;
goto retry;
}
}
/*
* The instruction that caused the program check will
* be repeated. Don't signal single step via SIGTRAP.
*/
clear_tsk_thread_flag(tsk, TIF_PER_TRAP);
fault = 0;
out_up:
up_read(&mm->mmap_sem);
out:
return fault;
}
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 spl_load_fit_image(struct spl_load_info *info, ulong sector,
void *fit, ulong base_offset, int node,
struct spl_image_info *image_info)
{
int offset;
size_t length;
int len;
ulong size;
ulong load_addr, load_ptr;
void *src;
ulong overhead;
int nr_sectors;
int align_len = ARCH_DMA_MINALIGN - 1;
uint8_t image_comp = -1, type = -1;
const void *data;
bool external_data = false;
if (IS_ENABLED(CONFIG_SPL_FPGA_SUPPORT) ||
(IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP))) {
if (fit_image_get_type(fit, node, &type))
puts("Cannot get image type.\n");
else
debug("%s ", genimg_get_type_name(type));
}
if (IS_ENABLED(CONFIG_SPL_OS_BOOT) && IS_ENABLED(CONFIG_SPL_GZIP)) {
if (fit_image_get_comp(fit, node, &image_comp))
puts("Cannot get image compression format.\n");
else
debug("%s ", genimg_get_comp_name(image_comp));
}
if (fit_image_get_load(fit, node, &load_addr))
load_addr = image_info->load_addr;
if (!fit_image_get_data_position(fit, node, &offset)) {
external_data = true;
} else if (!fit_image_get_data_offset(fit, node, &offset)) {
offset += base_offset;
external_data = true;
}
if (external_data) {
/* External data */
if (fit_image_get_data_size(fit, node, &len))
return -ENOENT;
load_ptr = (load_addr + align_len) & ~align_len;
length = len;
overhead = get_aligned_image_overhead(info, offset);
nr_sectors = get_aligned_image_size(info, length, offset);
if (info->read(info,
sector + get_aligned_image_offset(info, offset),
nr_sectors, (void *)load_ptr) != nr_sectors)
return -EIO;
debug("External data: dst=%lx, offset=%x, size=%lx\n",
load_ptr, offset, (unsigned long)length);
src = (void *)load_ptr + overhead;
} else {
/* Embedded data */
if (fit_image_get_data(fit, node, &data, &length)) {
puts("Cannot get image data/size\n");
return -ENOENT;
}
debug("Embedded data: dst=%lx, size=%lx\n", load_addr,
(unsigned long)length);
src = (void *)data;
}
#ifdef CONFIG_SPL_FIT_SIGNATURE
printf("## Checking hash(es) for Image %s ... ",
fit_get_name(fit, node, NULL));
if (!fit_image_verify_with_data(fit, node,
src, length))
return -EPERM;
puts("OK\n");
#endif
#ifdef CONFIG_SPL_FIT_IMAGE_POST_PROCESS
board_fit_image_post_process(&src, &length);
#endif
if (IS_ENABLED(CONFIG_SPL_GZIP) && image_comp == IH_COMP_GZIP) {
size = length;
if (gunzip((void *)load_addr, CONFIG_SYS_BOOTM_LEN,
src, &size)) {
puts("Uncompressing error\n");
return -EIO;
}
length = size;
} else {
memcpy((void *)load_addr, src, length);
}
if (image_info) {
image_info->load_addr = load_addr;
image_info->size = length;
image_info->entry_point = fdt_getprop_u32(fit, node, "entry");
}
return 0;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void nfs4_reset_write(struct rpc_task *task, struct nfs_write_data *data)
{
dprintk("%s Reset task for i/o through\n", __func__);
put_lseg(data->lseg);
data->lseg = NULL;
data->ds_clp = NULL;
data->write_done_cb = nfs4_write_done_cb;
data->args.fh = NFS_FH(data->inode);
data->args.bitmask = data->res.server->cache_consistency_bitmask;
data->args.offset = data->mds_offset;
data->res.fattr = &data->fattr;
task->tk_ops = data->mds_ops;
rpc_task_reset_client(task, NFS_CLIENT(data->inode));
}
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 wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order)
{
int err;
#ifdef WOLFSSL_SMALL_STACK
byte* buf;
#else
byte buf[ECC_MAXSIZE_GEN];
#endif
#ifdef WOLFSSL_SMALL_STACK
buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (buf == NULL)
return MEMORY_E;
#endif
/*generate 8 extra bytes to mitigate bias from the modulo operation below*/
/*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/
size += 8;
/* make up random string */
err = wc_RNG_GenerateBlock(rng, buf, size);
/* load random buffer data into k */
if (err == 0)
err = mp_read_unsigned_bin(k, (byte*)buf, size);
/* quick sanity check to make sure we're not dealing with a 0 key */
if (err == MP_OKAY) {
if (mp_iszero(k) == MP_YES)
err = MP_ZERO_E;
}
/* the key should be smaller than the order of base point */
if (err == MP_OKAY) {
if (mp_cmp(k, order) != MP_LT) {
err = mp_mod(k, order, k);
}
}
ForceZero(buf, ECC_MAXSIZE);
#ifdef WOLFSSL_SMALL_STACK
XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return err;
}
CWE ID: CWE-200
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void jslTokenAsString(int token, char *str, size_t len) {
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strncpy(str, "EOF", len); return;
case LEX_ID : strncpy(str, "ID", len); return;
case LEX_INT : strncpy(str, "INT", len); return;
case LEX_FLOAT : strncpy(str, "FLOAT", len); return;
case LEX_STR : strncpy(str, "STRING", len); return;
case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return;
case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return;
case LEX_REGEX : strncpy(str, "REGEX", len); return;
case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return;
case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strncpy(str, &tokenNames[p], len);
return;
}
assert(len>=10);
strncpy(str, "?[",len);
itostr(token, &str[2], 10);
strncat(str, "]",len);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: error::Error GLES2DecoderPassthroughImpl::DoUniform1ui(GLint location,
GLuint x) {
api()->glUniform1uiFn(location, x);
return error::kNoError;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) {
scoped_refptr<CaptureData> data;
if (capturing_) {
InvalidRects rects;
helper_.SwapInvalidRects(rects);
VideoFrameBuffer& current_buffer = buffers_[current_buffer_];
current_buffer.Update();
bool flip = true; // GL capturers need flipping.
if (cgl_context_) {
if (pixel_buffer_object_.get() != 0) {
GlBlitFast(current_buffer);
} else {
GlBlitSlow(current_buffer);
}
} else {
CgBlit(current_buffer, rects);
flip = false;
}
DataPlanes planes;
planes.data[0] = current_buffer.ptr();
planes.strides[0] = current_buffer.bytes_per_row();
if (flip) {
planes.strides[0] = -planes.strides[0];
planes.data[0] +=
(current_buffer.size().height() - 1) * current_buffer.bytes_per_row();
}
data = new CaptureData(planes, gfx::Size(current_buffer.size()),
pixel_format());
data->mutable_dirty_rects() = rects;
current_buffer_ = (current_buffer_ + 1) % kNumBuffers;
helper_.set_size_most_recent(data->size());
}
callback->Run(data);
delete callback;
}
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 dgram_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock, int flags,
int *addr_len)
{
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sk_buff *skb;
struct sockaddr_ieee802154 *saddr;
saddr = (struct sockaddr_ieee802154 *)msg->msg_name;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* FIXME: skip headers if necessary ?! */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_ts_and_drops(msg, sk, skb);
if (saddr) {
saddr->family = AF_IEEE802154;
saddr->addr = mac_cb(skb)->sa;
}
if (addr_len)
*addr_len = sizeof(*saddr);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
if (err)
return err;
return copied;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: ofputil_bucket_check_duplicate_id(const struct ovs_list *buckets)
{
struct ofputil_bucket *i, *j;
LIST_FOR_EACH (i, list_node, buckets) {
LIST_FOR_EACH_REVERSE (j, list_node, buckets) {
if (i == j) {
break;
}
if (i->bucket_id == j->bucket_id) {
return true;
}
}
}
return false;
}
CWE ID: CWE-617
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 php_var_serialize_string(smart_str *buf, char *str, size_t len) /* {{{ */
{
smart_str_appendl(buf, "s:", 2);
smart_str_append_unsigned(buf, len);
smart_str_appendl(buf, ":\"", 2);
smart_str_appendl(buf, str, len);
smart_str_appendl(buf, "\";", 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: xfs_attr_shortform_addname(xfs_da_args_t *args)
{
int newsize, forkoff, retval;
trace_xfs_attr_sf_addname(args);
retval = xfs_attr_shortform_lookup(args);
if ((args->flags & ATTR_REPLACE) && (retval == -ENOATTR)) {
return retval;
} else if (retval == -EEXIST) {
if (args->flags & ATTR_CREATE)
return retval;
retval = xfs_attr_shortform_remove(args);
ASSERT(retval == 0);
}
if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX ||
args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX)
return -ENOSPC;
newsize = XFS_ATTR_SF_TOTSIZE(args->dp);
newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen);
forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize);
if (!forkoff)
return -ENOSPC;
xfs_attr_shortform_add(args, forkoff);
return 0;
}
CWE ID: CWE-754
Target: 1
Example 2:
Code: static void Ins_AA( INS_ARG )
{ (void)exc; (void)args;
/* Intentional - no longer supported */
}
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: parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
}
cur = parser->root.cursor;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
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 ExtensionTtsController::SpeakNow(Utterance* utterance) {
std::string extension_id = GetMatchingExtensionId(utterance);
if (!extension_id.empty()) {
current_utterance_ = utterance;
utterance->set_extension_id(extension_id);
ListValue args;
args.Set(0, Value::CreateStringValue(utterance->text()));
DictionaryValue* options = static_cast<DictionaryValue*>(
utterance->options()->DeepCopy());
if (options->HasKey(util::kEnqueueKey))
options->Remove(util::kEnqueueKey, NULL);
args.Set(1, options);
args.Set(2, Value::CreateIntegerValue(utterance->id()));
std::string json_args;
base::JSONWriter::Write(&args, false, &json_args);
utterance->profile()->GetExtensionEventRouter()->DispatchEventToExtension(
extension_id,
events::kOnSpeak,
json_args,
utterance->profile(),
GURL());
return;
}
GetPlatformImpl()->clear_error();
bool success = GetPlatformImpl()->Speak(
utterance->text(),
utterance->locale(),
utterance->gender(),
utterance->rate(),
utterance->pitch(),
utterance->volume());
if (!success) {
utterance->set_error(GetPlatformImpl()->error());
utterance->FinishAndDestroy();
return;
}
current_utterance_ = utterance;
CheckSpeechStatus();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void CalculatePageLayoutFromPrintParams(
const PrintMsg_Print_Params& params,
printing::PageSizeMargins* page_layout_in_points) {
int dpi = GetDPI(¶ms);
int content_width = params.content_size.width();
int content_height = params.content_size.height();
int margin_bottom = params.page_size.height() -
content_height - params.margin_top;
int margin_right = params.page_size.width() -
content_width - params.margin_left;
using printing::ConvertUnit;
using printing::kPointsPerInch;
page_layout_in_points->content_width =
ConvertUnit(content_width, dpi, kPointsPerInch);
page_layout_in_points->content_height =
ConvertUnit(content_height, dpi, kPointsPerInch);
page_layout_in_points->margin_top =
ConvertUnit(params.margin_top, dpi, kPointsPerInch);
page_layout_in_points->margin_right =
ConvertUnit(margin_right, dpi, kPointsPerInch);
page_layout_in_points->margin_bottom =
ConvertUnit(margin_bottom, dpi, kPointsPerInch);
page_layout_in_points->margin_left =
ConvertUnit(params.margin_left, dpi, kPointsPerInch);
}
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: xfs_attr3_rmt_hdr_ok(
struct xfs_mount *mp,
void *ptr,
xfs_ino_t ino,
uint32_t offset,
uint32_t size,
xfs_daddr_t bno)
{
struct xfs_attr3_rmt_hdr *rmt = ptr;
if (bno != be64_to_cpu(rmt->rm_blkno))
return false;
if (offset != be32_to_cpu(rmt->rm_offset))
return false;
if (size != be32_to_cpu(rmt->rm_bytes))
return false;
if (ino != be64_to_cpu(rmt->rm_owner))
return false;
/* ok */
return true;
}
CWE ID: CWE-19
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int read_header_tga(gdIOCtx *ctx, oTga *tga)
{
unsigned char header[18];
if (gdGetBuf(header, sizeof(header), ctx) < 18) {
gd_error("fail to read header");
return -1;
}
tga->identsize = header[0];
tga->colormaptype = header[1];
tga->imagetype = header[2];
tga->colormapstart = header[3] + (header[4] << 8);
tga->colormaplength = header[5] + (header[6] << 8);
tga->colormapbits = header[7];
tga->xstart = header[8] + (header[9] << 8);
tga->ystart = header[10] + (header[11] << 8);
tga->width = header[12] + (header[13] << 8);
tga->height = header[14] + (header[15] << 8);
tga->bits = header[16];
tga->alphabits = header[17] & 0x0f;
tga->fliph = (header[17] & 0x10) ? 1 : 0;
tga->flipv = (header[17] & 0x20) ? 0 : 1;
#if DEBUG
printf("format bps: %i\n", tga->bits);
printf("flip h/v: %i / %i\n", tga->fliph, tga->flipv);
printf("alpha: %i\n", tga->alphabits);
printf("wxh: %i %i\n", tga->width, tga->height);
#endif
switch(tga->bits) {
case 8:
case 16:
case 24:
case 32:
break;
default:
gd_error("bps %i not supported", tga->bits);
return -1;
break;
}
tga->ident = NULL;
if (tga->identsize > 0) {
tga->ident = (char *) gdMalloc(tga->identsize * sizeof(char));
if(tga->ident == NULL) {
return -1;
}
gdGetBuf(tga->ident, tga->identsize, ctx);
}
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static zend_always_inline Bucket *zend_hash_index_find_bucket(const HashTable *ht, zend_ulong h)
{
uint32_t nIndex;
uint32_t idx;
Bucket *p, *arData;
arData = ht->arData;
nIndex = h | ht->nTableMask;
idx = HT_HASH_EX(arData, nIndex);
while (idx != HT_INVALID_IDX) {
ZEND_ASSERT(idx < HT_IDX_TO_HASH(ht->nTableSize));
p = HT_HASH_TO_BUCKET_EX(arData, idx);
if (p->h == h && !p->key) {
return p;
}
idx = Z_NEXT(p->val);
}
return NULL;
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const Cluster* Segment::GetLast() const
{
if ((m_clusters == NULL) || (m_clusterCount <= 0))
return &m_eos;
const long idx = m_clusterCount - 1;
Cluster* const pCluster = m_clusters[idx];
assert(pCluster);
return pCluster;
}
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 read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: ScriptValue Document::registerElement(ScriptState* script_state,
const AtomicString& name,
const ElementRegistrationOptions& options,
ExceptionState& exception_state) {
if (!RegistrationContext()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"No element registration context is available.");
return ScriptValue();
}
if (name == "dom-module")
UseCounter::Count(*this, WebFeature::kPolymerV1Detected);
V0CustomElementConstructorBuilder constructor_builder(script_state, options);
RegistrationContext()->RegisterElement(this, &constructor_builder, name,
exception_state);
return constructor_builder.BindingsReturnValue();
}
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 protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
{
int i;
uint16_t limit;
VncDisplay *vd = vs->vd;
if (data[0] > 3) {
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
}
switch (data[0]) {
case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
if (len == 1)
return 20;
set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
read_u8(data, 6), read_u8(data, 7),
read_u16(data, 8), read_u16(data, 10),
read_u16(data, 12), read_u8(data, 14),
read_u8(data, 15), read_u8(data, 16));
break;
case VNC_MSG_CLIENT_SET_ENCODINGS:
if (len == 1)
return 4;
if (len == 4) {
limit = read_u16(data, 2);
if (limit > 0)
return 4 + (limit * 4);
} else
limit = read_u16(data, 2);
for (i = 0; i < limit; i++) {
int32_t val = read_s32(data, 4 + (i * 4));
memcpy(data + 4 + (i * 4), &val, sizeof(val));
}
set_encodings(vs, (int32_t *)(data + 4), limit);
break;
case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
if (len == 1)
return 10;
framebuffer_update_request(vs,
read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
read_u16(data, 6), read_u16(data, 8));
break;
case VNC_MSG_CLIENT_KEY_EVENT:
if (len == 1)
return 8;
key_event(vs, read_u8(data, 1), read_u32(data, 4));
break;
case VNC_MSG_CLIENT_POINTER_EVENT:
if (len == 1)
return 6;
pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
break;
case VNC_MSG_CLIENT_CUT_TEXT:
if (len == 1) {
return 8;
}
if (len == 8) {
uint32_t dlen = read_u32(data, 4);
if (dlen > (1 << 20)) {
error_report("vnc: client_cut_text msg payload has %u bytes"
" which exceeds our limit of 1MB.", dlen);
vnc_client_error(vs);
break;
}
if (dlen > 0) {
return 8 + dlen;
}
}
client_cut_text(vs, read_u32(data, 4), data + 8);
break;
case VNC_MSG_CLIENT_QEMU:
if (len == 1)
return 2;
switch (read_u8(data, 1)) {
case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
if (len == 2)
return 12;
ext_key_event(vs, read_u16(data, 2),
read_u32(data, 4), read_u32(data, 8));
break;
case VNC_MSG_CLIENT_QEMU_AUDIO:
if (len == 2)
return 4;
switch (read_u16 (data, 2)) {
case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
audio_add(vs);
break;
case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
audio_del(vs);
break;
case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
if (len == 4)
return 10;
switch (read_u8(data, 4)) {
case 0: vs->as.fmt = AUD_FMT_U8; break;
case 1: vs->as.fmt = AUD_FMT_S8; break;
case 2: vs->as.fmt = AUD_FMT_U16; break;
case 3: vs->as.fmt = AUD_FMT_S16; break;
case 4: vs->as.fmt = AUD_FMT_U32; break;
case 5: vs->as.fmt = AUD_FMT_S32; break;
default:
printf("Invalid audio format %d\n", read_u8(data, 4));
vnc_client_error(vs);
break;
}
vs->as.nchannels = read_u8(data, 5);
if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
printf("Invalid audio channel coount %d\n",
read_u8(data, 5));
vnc_client_error(vs);
break;
}
vs->as.freq = read_u32(data, 6);
break;
default:
printf ("Invalid audio message %d\n", read_u8(data, 4));
vnc_client_error(vs);
break;
}
break;
default:
printf("Msg: %d\n", read_u16(data, 0));
vnc_client_error(vs);
break;
}
break;
default:
printf("Msg: %d\n", data[0]);
vnc_client_error(vs);
break;
}
vnc_read_when(vs, protocol_client_msg, 1);
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: void NetworkHandler::SetCookies(
std::unique_ptr<protocol::Array<Network::CookieParam>> cookies,
std::unique_ptr<SetCookiesCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::BindOnce(
&SetCookiesOnIO,
base::Unretained(
process_->GetStoragePartition()->GetURLRequestContext()),
std::move(cookies),
base::BindOnce(&CookiesSetOnIO, std::move(callback))));
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: GfxShading *GfxRadialShading::copy() {
return new GfxRadialShading(this);
}
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: int phar_open_entry_fp(phar_entry_info *entry, char **error, int follow_links TSRMLS_DC) /* {{{ */
{
php_stream_filter *filter;
phar_archive_data *phar = entry->phar;
char *filtername;
off_t loc;
php_stream *ufp;
phar_entry_data dummy;
if (follow_links && entry->link) {
phar_entry_info *link_entry = phar_get_link_source(entry TSRMLS_CC);
if (link_entry && link_entry != entry) {
return phar_open_entry_fp(link_entry, error, 1 TSRMLS_CC);
}
}
if (entry->is_modified) {
return SUCCESS;
}
if (entry->fp_type == PHAR_TMP) {
if (!entry->fp) {
entry->fp = php_stream_open_wrapper(entry->tmp, "rb", STREAM_MUST_SEEK|0, NULL);
}
return SUCCESS;
}
if (entry->fp_type != PHAR_FP) {
/* either newly created or already modified */
return SUCCESS;
}
if (!phar_get_pharfp(phar TSRMLS_CC)) {
if (FAILURE == phar_open_archive_fp(phar TSRMLS_CC)) {
spprintf(error, 4096, "phar error: Cannot open phar archive \"%s\" for reading", phar->fname);
return FAILURE;
}
}
if ((entry->old_flags && !(entry->old_flags & PHAR_ENT_COMPRESSION_MASK)) || !(entry->flags & PHAR_ENT_COMPRESSION_MASK)) {
dummy.internal_file = entry;
dummy.phar = phar;
dummy.zero = entry->offset;
dummy.fp = phar_get_pharfp(phar TSRMLS_CC);
if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 1 TSRMLS_CC)) {
return FAILURE;
}
return SUCCESS;
}
if (!phar_get_entrypufp(entry TSRMLS_CC)) {
phar_set_entrypufp(entry, php_stream_fopen_tmpfile() TSRMLS_CC);
if (!phar_get_entrypufp(entry TSRMLS_CC)) {
spprintf(error, 4096, "phar error: Cannot open temporary file for decompressing phar archive \"%s\" file \"%s\"", phar->fname, entry->filename);
return FAILURE;
}
}
dummy.internal_file = entry;
dummy.phar = phar;
dummy.zero = entry->offset;
dummy.fp = phar_get_pharfp(phar TSRMLS_CC);
if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 1 TSRMLS_CC)) {
return FAILURE;
}
ufp = phar_get_entrypufp(entry TSRMLS_CC);
if ((filtername = phar_decompress_filter(entry, 0)) != NULL) {
filter = php_stream_filter_create(filtername, NULL, 0 TSRMLS_CC);
} else {
filter = NULL;
}
if (!filter) {
spprintf(error, 4096, "phar error: unable to read phar \"%s\" (cannot create %s filter while decompressing file \"%s\")", phar->fname, phar_decompress_filter(entry, 1), entry->filename);
return FAILURE;
}
/* now we can safely use proper decompression */
/* save the new offset location within ufp */
php_stream_seek(ufp, 0, SEEK_END);
loc = php_stream_tell(ufp);
php_stream_filter_append(&ufp->writefilters, filter);
php_stream_seek(phar_get_entrypfp(entry TSRMLS_CC), phar_get_fp_offset(entry TSRMLS_CC), SEEK_SET);
if (entry->uncompressed_filesize) {
if (SUCCESS != phar_stream_copy_to_stream(phar_get_entrypfp(entry TSRMLS_CC), ufp, entry->compressed_filesize, NULL)) {
spprintf(error, 4096, "phar error: internal corruption of phar \"%s\" (actual filesize mismatch on file \"%s\")", phar->fname, entry->filename);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
return FAILURE;
}
}
php_stream_filter_flush(filter, 1);
php_stream_flush(ufp);
php_stream_filter_remove(filter, 1 TSRMLS_CC);
if (php_stream_tell(ufp) - loc != (off_t) entry->uncompressed_filesize) {
spprintf(error, 4096, "phar error: internal corruption of phar \"%s\" (actual filesize mismatch on file \"%s\")", phar->fname, entry->filename);
return FAILURE;
}
entry->old_flags = entry->flags;
/* this is now the new location of the file contents within this fp */
phar_set_fp_type(entry, PHAR_UFP, loc TSRMLS_CC);
dummy.zero = entry->offset;
dummy.fp = ufp;
if (FAILURE == phar_postprocess_file(&dummy, entry->crc32, error, 0 TSRMLS_CC)) {
return FAILURE;
}
return SUCCESS;
}
/* }}} */
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: status_t OMXNodeInstance::allocateBuffer(
OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer,
void **buffer_data) {
Mutex::Autolock autoLock(mLock);
BufferMeta *buffer_meta = new BufferMeta(size);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, size);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
*buffer_data = header->pBuffer;
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateBuffer, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p", size, *buffer_data));
return OK;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: scoped_refptr<gpu::Buffer> CommandBufferProxyImpl::CreateTransferBuffer(
size_t size,
int32_t* id) {
CheckLock();
base::AutoLock lock(last_state_lock_);
*id = -1;
int32_t new_id = channel_->ReserveTransferBufferId();
std::unique_ptr<base::SharedMemory> shared_memory =
AllocateAndMapSharedMemory(size);
if (!shared_memory) {
if (last_state_.error == gpu::error::kNoError)
OnClientError(gpu::error::kOutOfBounds);
return nullptr;
}
if (last_state_.error == gpu::error::kNoError) {
base::SharedMemoryHandle handle =
channel_->ShareToGpuProcess(shared_memory->handle());
if (!base::SharedMemory::IsHandleValid(handle)) {
if (last_state_.error == gpu::error::kNoError)
OnClientError(gpu::error::kLostContext);
return nullptr;
}
Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_, new_id,
handle, size));
}
*id = new_id;
scoped_refptr<gpu::Buffer> buffer(
gpu::MakeBufferFromSharedMemory(std::move(shared_memory), size));
return buffer;
}
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: size_t strnlen32(const char32_t *s, size_t maxlen)
{
const char32_t *ss = s;
while ((maxlen > 0) && *ss) {
ss++;
maxlen--;
}
return ss-s;
}
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: ScriptPromise ImageBitmapFactories::createImageBitmap(EventTarget& eventTarget, HTMLCanvasElement* canvas, int sx, int sy, int sw, int sh, ExceptionState& exceptionState)
{
ASSERT(eventTarget.toDOMWindow());
if (!canvas) {
exceptionState.throwTypeError("The canvas element provided is invalid.");
return ScriptPromise();
}
if (!canvas->originClean()) {
exceptionState.throwSecurityError("The canvas element provided is tainted with cross-origin data.");
return ScriptPromise();
}
if (!sw || !sh) {
exceptionState.throwDOMException(IndexSizeError, String::format("The source %s provided is 0.", sw ? "height" : "width"));
return ScriptPromise();
}
return fulfillImageBitmap(eventTarget.executionContext(), ImageBitmap::create(canvas, IntRect(sx, sy, sw, sh)));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void snd_seq_info_clients_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
int c;
struct snd_seq_client *client;
snd_iprintf(buffer, "Client info\n");
snd_iprintf(buffer, " cur clients : %d\n", client_usage.cur);
snd_iprintf(buffer, " peak clients : %d\n", client_usage.peak);
snd_iprintf(buffer, " max clients : %d\n", SNDRV_SEQ_MAX_CLIENTS);
snd_iprintf(buffer, "\n");
/* list the client table */
for (c = 0; c < SNDRV_SEQ_MAX_CLIENTS; c++) {
client = snd_seq_client_use_ptr(c);
if (client == NULL)
continue;
if (client->type == NO_CLIENT) {
snd_seq_client_unlock(client);
continue;
}
snd_iprintf(buffer, "Client %3d : \"%s\" [%s]\n",
c, client->name,
client->type == USER_CLIENT ? "User" : "Kernel");
snd_seq_info_dump_ports(buffer, client);
if (snd_seq_write_pool_allocated(client)) {
snd_iprintf(buffer, " Output pool :\n");
snd_seq_info_pool(buffer, client->pool, " ");
}
if (client->type == USER_CLIENT && client->data.user.fifo &&
client->data.user.fifo->pool) {
snd_iprintf(buffer, " Input pool :\n");
snd_seq_info_pool(buffer, client->data.user.fifo->pool, " ");
}
snd_seq_client_unlock(client);
}
}
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 cm_alloc_msg(struct cm_id_private *cm_id_priv,
struct ib_mad_send_buf **msg)
{
struct ib_mad_agent *mad_agent;
struct ib_mad_send_buf *m;
struct ib_ah *ah;
mad_agent = cm_id_priv->av.port->mad_agent;
ah = ib_create_ah(mad_agent->qp->pd, &cm_id_priv->av.ah_attr);
if (IS_ERR(ah))
return PTR_ERR(ah);
m = ib_create_send_mad(mad_agent, cm_id_priv->id.remote_cm_qpn,
cm_id_priv->av.pkey_index,
0, IB_MGMT_MAD_HDR, IB_MGMT_MAD_DATA,
GFP_ATOMIC);
if (IS_ERR(m)) {
ib_destroy_ah(ah);
return PTR_ERR(m);
}
/* Timeout set by caller if response is expected. */
m->ah = ah;
m->retries = cm_id_priv->max_cm_retries;
atomic_inc(&cm_id_priv->refcount);
m->context[0] = cm_id_priv;
*msg = m;
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: static int pptp_connect(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr;
struct pppox_sock *po = pppox_sk(sk);
struct pptp_opt *opt = &po->proto.pptp;
struct rtable *rt;
struct flowi4 fl4;
int error = 0;
if (sp->sa_protocol != PX_PROTO_PPTP)
return -EINVAL;
if (lookup_chan_dst(sp->sa_addr.pptp.call_id, sp->sa_addr.pptp.sin_addr.s_addr))
return -EALREADY;
lock_sock(sk);
/* Check for already bound sockets */
if (sk->sk_state & PPPOX_CONNECTED) {
error = -EBUSY;
goto end;
}
/* Check for already disconnected sockets, on attempts to disconnect */
if (sk->sk_state & PPPOX_DEAD) {
error = -EALREADY;
goto end;
}
if (!opt->src_addr.sin_addr.s_addr || !sp->sa_addr.pptp.sin_addr.s_addr) {
error = -EINVAL;
goto end;
}
po->chan.private = sk;
po->chan.ops = &pptp_chan_ops;
rt = ip_route_output_ports(sock_net(sk), &fl4, sk,
opt->dst_addr.sin_addr.s_addr,
opt->src_addr.sin_addr.s_addr,
0, 0,
IPPROTO_GRE, RT_CONN_FLAGS(sk), 0);
if (IS_ERR(rt)) {
error = -EHOSTUNREACH;
goto end;
}
sk_setup_caps(sk, &rt->dst);
po->chan.mtu = dst_mtu(&rt->dst);
if (!po->chan.mtu)
po->chan.mtu = PPP_MRU;
ip_rt_put(rt);
po->chan.mtu -= PPTP_HEADER_OVERHEAD;
po->chan.hdrlen = 2 + sizeof(struct pptp_gre_header);
error = ppp_register_channel(&po->chan);
if (error) {
pr_err("PPTP: failed to register PPP channel (%d)\n", error);
goto end;
}
opt->dst_addr = sp->sa_addr.pptp;
sk->sk_state = PPPOX_CONNECTED;
end:
release_sock(sk);
return error;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void AwContents::SetDipScaleInternal(float dip_scale) {
browser_view_renderer_.SetDipScale(dip_scale);
}
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: AudioSystemImplTest()
: use_audio_thread_(GetParam()), audio_thread_("AudioSystemThread") {
if (use_audio_thread_) {
audio_thread_.StartAndWaitForTesting();
audio_manager_.reset(
new media::MockAudioManager(audio_thread_.task_runner()));
} else {
audio_manager_.reset(new media::MockAudioManager(
base::ThreadTaskRunnerHandle::Get().get()));
}
audio_manager_->SetInputStreamParameters(
media::AudioParameters::UnavailableDeviceParams());
audio_system_ = media::AudioSystemImpl::Create(audio_manager_.get());
EXPECT_EQ(AudioSystem::Get(), audio_system_.get());
}
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: GDataDirectoryService::GDataDirectoryService()
: blocking_task_runner_(NULL),
serialized_size_(0),
largest_changestamp_(0),
origin_(UNINITIALIZED),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
root_.reset(new GDataDirectory(NULL, this));
if (!util::IsDriveV2ApiEnabled())
InitializeRootEntry(kGDataRootDirectoryResourceId);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int cifs_writepage(struct page *page, struct writeback_control *wbc)
{
int rc = cifs_writepage_locked(page, wbc);
unlock_page(page);
return rc;
}
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: evutil_free_sock_err_globals(void)
{
struct cached_sock_errs_entry **errs, *tofree;
for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
; errs; ) {
tofree = *errs;
errs = HT_NEXT_RMV(cached_sock_errs_map,
&windows_socket_errors,
errs);
LocalFree(tofree->msg);
mm_free(tofree);
}
HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
#ifndef EVENT__DISABLE_THREAD_SUPPORT
if (windows_socket_errors_lock_ != NULL) {
EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
windows_socket_errors_lock_ = NULL;
}
#endif
}
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: ikev1_sub_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: V4L2JpegEncodeAccelerator::JpegBufferRecord::~JpegBufferRecord() {}
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: android::SoftOMXComponent *createSoftOMXComponent(
const char *name, const OMX_CALLBACKTYPE *callbacks,
OMX_PTR appData, OMX_COMPONENTTYPE **component) {
return new android::SoftAAC2(name, callbacks, appData, component);
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int udpv6_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_sock *inet = inet_sk(sk);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
int is_udp4;
bool slow;
if (addr_len)
*addr_len = sizeof(struct sockaddr_in6);
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
is_udp4 = (skb->protocol == htons(ETH_P_IP));
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov, copied);
else {
err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udpv6_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS,
is_udplite);
}
goto out_free;
}
if (!peeked) {
if (is_udp4)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
else
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
}
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (msg->msg_name) {
struct sockaddr_in6 *sin6;
sin6 = (struct sockaddr_in6 *) msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = udp_hdr(skb)->source;
sin6->sin6_flowinfo = 0;
if (is_udp4) {
ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,
&sin6->sin6_addr);
sin6->sin6_scope_id = 0;
} else {
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
}
}
if (is_udp4) {
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
} else {
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
}
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
if (is_udp4) {
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
} else {
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_CSUMERRORS, is_udplite);
UDP6_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
}
unlock_sock_fast(sk, slow);
if (noblock)
return -EAGAIN;
/* starting over for a new packet */
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void GpuProcessHost::CreateImageError(
const CreateImageCallback& callback, const gfx::Size size) {
callback.Run(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: hns_ppe_common_get_ioaddr(struct ppe_common_cb *ppe_common)
{
return ppe_common->dsaf_dev->ppe_base + PPE_COMMON_REG_OFFSET;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int xt_check_entry_offsets(const void *base,
unsigned int target_offset,
unsigned int next_offset)
{
const struct xt_entry_target *t;
const char *e = base;
if (target_offset + sizeof(*t) > next_offset)
return -EINVAL;
t = (void *)(e + target_offset);
if (t->u.target_size < sizeof(*t))
return -EINVAL;
if (target_offset + t->u.target_size > next_offset)
return -EINVAL;
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
target_offset + sizeof(struct xt_standard_target) != next_offset)
return -EINVAL;
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool HasEnoughSpaceFor(int64 num_bytes) {
int64 free_space = GetAmountOfFreeDiskSpace();
free_space -= kMinFreeSpace;
return (free_space >= num_bytes);
}
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: xsltValueOfComp(xsltStylesheetPtr style, xmlNodePtr inst) {
#ifdef XSLT_REFACTORED
xsltStyleItemValueOfPtr comp;
#else
xsltStylePreCompPtr comp;
#endif
const xmlChar *prop;
if ((style == NULL) || (inst == NULL) || (inst->type != XML_ELEMENT_NODE))
return;
#ifdef XSLT_REFACTORED
comp = (xsltStyleItemValueOfPtr) xsltNewStylePreComp(style, XSLT_FUNC_VALUEOF);
#else
comp = xsltNewStylePreComp(style, XSLT_FUNC_VALUEOF);
#endif
if (comp == NULL)
return;
inst->psvi = comp;
comp->inst = inst;
prop = xsltGetCNsProp(style, inst,
(const xmlChar *)"disable-output-escaping",
XSLT_NAMESPACE);
if (prop != NULL) {
if (xmlStrEqual(prop, (const xmlChar *)"yes")) {
comp->noescape = 1;
} else if (!xmlStrEqual(prop,
(const xmlChar *)"no")){
xsltTransformError(NULL, style, inst,
"xsl:value-of : disable-output-escaping allows only yes or no\n");
if (style != NULL) style->warnings++;
}
}
comp->select = xsltGetCNsProp(style, inst, (const xmlChar *)"select",
XSLT_NAMESPACE);
if (comp->select == NULL) {
xsltTransformError(NULL, style, inst,
"xsl:value-of : select is missing\n");
if (style != NULL) style->errors++;
return;
}
comp->comp = xsltXPathCompile(style, comp->select);
if (comp->comp == NULL) {
xsltTransformError(NULL, style, inst,
"xsl:value-of : could not compile select expression '%s'\n",
comp->select);
if (style != NULL) style->errors++;
}
}
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 _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG(php_gd_error("Reading gd2 header info"));
for (i = 0; i < 4; i++) {
ch = gdGetC(in);
if (ch == EOF) {
goto fail1;
}
id[i] = ch;
}
id[4] = 0;
GD2_DBG(php_gd_error("Got file code: %s", id));
/* Equiv. of 'magick'. */
if (strcmp(id, GD2_ID) != 0) {
GD2_DBG(php_gd_error("Not a valid gd2 file"));
goto fail1;
}
/* Version */
if (gdGetWord(vers, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("Version: %d", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG(php_gd_error("Bad version: %d", *vers));
goto fail1;
}
/* Image Size */
if (!gdGetWord(sx, in)) {
GD2_DBG(php_gd_error("Could not get x-size"));
goto fail1;
}
if (!gdGetWord(sy, in)) {
GD2_DBG(php_gd_error("Could not get y-size"));
goto fail1;
}
GD2_DBG(php_gd_error("Image is %dx%d", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord(cs, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("ChunkSize: %d", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG(php_gd_error("Bad chunk size: %d", *cs));
goto fail1;
}
/* Data Format */
if (gdGetWord(fmt, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("Format: %d", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG(php_gd_error("Bad data format: %d", *fmt));
goto fail1;
}
/* # of chunks wide */
if (gdGetWord(ncx, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("%d Chunks Wide", *ncx));
/* # of chunks high */
if (gdGetWord(ncy, in) != 1) {
goto fail1;
}
GD2_DBG(php_gd_error("%d Chunks vertically", *ncy));
if (gd2_compressed(*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG(php_gd_error("Reading %d chunk index entries", nc));
sidx = sizeof(t_chunk_info) * nc;
if (sidx <= 0) {
goto fail1;
}
cidx = gdCalloc(sidx, 1);
for (i = 0; i < nc; i++) {
if (gdGetInt(&cidx[i].offset, in) != 1) {
gdFree(cidx);
goto fail1;
}
if (gdGetInt(&cidx[i].size, in) != 1) {
gdFree(cidx);
goto fail1;
}
if (cidx[i].offset < 0 || cidx[i].size < 0) {
gdFree(cidx);
goto fail1;
}
}
*chunkIdx = cidx;
}
GD2_DBG(php_gd_error("gd2 header complete"));
return 1;
fail1:
return 0;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: size_t php_mysqlnd_sha256_pk_request_write(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC)
{
zend_uchar buffer[MYSQLND_HEADER_SIZE + 1];
size_t sent;
DBG_ENTER("php_mysqlnd_sha256_pk_request_write");
int1store(buffer + MYSQLND_HEADER_SIZE, '\1');
sent = conn->net->data->m.send_ex(conn->net, buffer, 1, conn->stats, conn->error_info TSRMLS_CC);
DBG_RETURN(sent);
}
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: GetUsageInfoTask(
QuotaManager* manager,
const GetUsageInfoCallback& callback)
: QuotaTask(manager),
callback_(callback),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
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 DrawingBuffer::ReadBackFramebuffer(unsigned char* pixels,
int width,
int height,
ReadbackOrder readback_order,
WebGLImageConversion::AlphaOp op) {
DCHECK(state_restorer_);
state_restorer_->SetPixelPackAlignmentDirty();
gl_->PixelStorei(GL_PACK_ALIGNMENT, 1);
gl_->ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
size_t buffer_size = 4 * width * height;
if (readback_order == kReadbackSkia) {
#if (SK_R32_SHIFT == 16) && !SK_B32_SHIFT
for (size_t i = 0; i < buffer_size; i += 4) {
std::swap(pixels[i], pixels[i + 2]);
}
#endif
}
if (op == WebGLImageConversion::kAlphaDoPremultiply) {
for (size_t i = 0; i < buffer_size; i += 4) {
pixels[i + 0] = std::min(255, pixels[i + 0] * pixels[i + 3] / 255);
pixels[i + 1] = std::min(255, pixels[i + 1] * pixels[i + 3] / 255);
pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255);
}
} else if (op != WebGLImageConversion::kAlphaDoNothing) {
NOTREACHED();
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
int sockindex, bool *done)
{
return nss_connect_common(conn, sockindex, done);
}
CWE ID: CWE-287
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Gfx::opSetTextRise(Object args[], int numArgs) {
state->setRise(args[0].getNum());
out->updateRise(state);
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
struct sctp_association *assoc,
sctp_socket_type_t type)
{
struct sctp_sock *oldsp = sctp_sk(oldsk);
struct sctp_sock *newsp = sctp_sk(newsk);
struct sctp_bind_bucket *pp; /* hash list port iterator */
struct sctp_endpoint *newep = newsp->ep;
struct sk_buff *skb, *tmp;
struct sctp_ulpevent *event;
int flags = 0;
/* Migrate socket buffer sizes and all the socket level options to the
* new socket.
*/
newsk->sk_sndbuf = oldsk->sk_sndbuf;
newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
/* Brute force copy old sctp opt. */
inet_sk_copy_descendant(newsk, oldsk);
/* Restore the ep value that was overwritten with the above structure
* copy.
*/
newsp->ep = newep;
newsp->hmac = NULL;
/* Hook this new socket in to the bind_hash list. */
pp = sctp_sk(oldsk)->bind_hash;
sk_add_bind_node(newsk, &pp->owner);
sctp_sk(newsk)->bind_hash = pp;
inet_sk(newsk)->num = inet_sk(oldsk)->num;
/* Copy the bind_addr list from the original endpoint to the new
* endpoint so that we can handle restarts properly
*/
if (PF_INET6 == assoc->base.sk->sk_family)
flags = SCTP_ADDR6_ALLOWED;
if (assoc->peer.ipv4_address)
flags |= SCTP_ADDR4_PEERSUPP;
if (assoc->peer.ipv6_address)
flags |= SCTP_ADDR6_PEERSUPP;
sctp_bind_addr_copy(&newsp->ep->base.bind_addr,
&oldsp->ep->base.bind_addr,
SCTP_SCOPE_GLOBAL, GFP_KERNEL, flags);
/* Move any messages in the old socket's receive queue that are for the
* peeled off association to the new socket's receive queue.
*/
sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
sctp_sock_rfree(skb);
__skb_unlink(skb, &oldsk->sk_receive_queue);
__skb_queue_tail(&newsk->sk_receive_queue, skb);
sctp_skb_set_owner_r(skb, newsk);
}
}
/* Clean up any messages pending delivery due to partial
* delivery. Three cases:
* 1) No partial deliver; no work.
* 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
* 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
*/
skb_queue_head_init(&newsp->pd_lobby);
sctp_sk(newsk)->pd_mode = assoc->ulpq.pd_mode;
if (sctp_sk(oldsk)->pd_mode) {
struct sk_buff_head *queue;
/* Decide which queue to move pd_lobby skbs to. */
if (assoc->ulpq.pd_mode) {
queue = &newsp->pd_lobby;
} else
queue = &newsk->sk_receive_queue;
/* Walk through the pd_lobby, looking for skbs that
* need moved to the new socket.
*/
sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == assoc) {
sctp_sock_rfree(skb);
__skb_unlink(skb, &oldsp->pd_lobby);
__skb_queue_tail(queue, skb);
sctp_skb_set_owner_r(skb, newsk);
}
}
/* Clear up any skbs waiting for the partial
* delivery to finish.
*/
if (assoc->ulpq.pd_mode)
sctp_clear_pd(oldsk);
}
/* Set the type of socket to indicate that it is peeled off from the
* original UDP-style socket or created with the accept() call on a
* TCP-style socket..
*/
newsp->type = type;
/* Mark the new socket "in-use" by the user so that any packets
* that may arrive on the association after we've moved it are
* queued to the backlog. This prevents a potential race between
* backlog processing on the old socket and new-packet processing
* on the new socket.
*/
sctp_lock_sock(newsk);
sctp_assoc_migrate(assoc, newsk);
/* If the association on the newsk is already closed before accept()
* is called, set RCV_SHUTDOWN flag.
*/
if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
newsk->sk_shutdown |= RCV_SHUTDOWN;
newsk->sk_state = SCTP_SS_ESTABLISHED;
sctp_release_sock(newsk);
}
CWE ID:
Target: 1
Example 2:
Code: static char *server_create_address_tag(const char *address)
{
const char *start, *end;
g_return_val_if_fail(address != NULL, NULL);
/* try to generate a reasonable server tag */
if (strchr(address, '.') == NULL) {
start = end = NULL;
} else if (g_ascii_strncasecmp(address, "irc", 3) == 0 ||
g_ascii_strncasecmp(address, "chat", 4) == 0) {
/* irc-2.cs.hut.fi -> hut, chat.bt.net -> bt */
end = strrchr(address, '.');
start = end-1;
while (start > address && *start != '.') start--;
} else {
/* efnet.cs.hut.fi -> efnet */
end = strchr(address, '.');
start = end;
}
if (start == end) start = address; else start++;
if (end == NULL) end = address + strlen(address);
return g_strndup(start, (int) (end-start));
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void release_openowner(struct nfs4_openowner *oo)
{
struct nfs4_ol_stateid *stp;
struct nfs4_client *clp = oo->oo_owner.so_client;
struct list_head reaplist;
INIT_LIST_HEAD(&reaplist);
spin_lock(&clp->cl_lock);
unhash_openowner_locked(oo);
while (!list_empty(&oo->oo_owner.so_stateids)) {
stp = list_first_entry(&oo->oo_owner.so_stateids,
struct nfs4_ol_stateid, st_perstateowner);
if (unhash_open_stateid(stp, &reaplist))
put_ol_stateid_locked(stp, &reaplist);
}
spin_unlock(&clp->cl_lock);
free_ol_stateid_reaplist(&reaplist);
release_last_closed_stateid(oo);
nfs4_put_stateowner(&oo->oo_owner);
}
CWE ID: CWE-404
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ModuleExport size_t RegisterXWDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("XWD","XWD","X Windows system window dump (color)");
#if defined(MAGICKCORE_X11_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadXWDImage;
entry->encoder=(EncodeImageHandler *) WriteXWDImage;
#endif
entry->magick=(IsImageFormatHandler *) IsXWD;
entry->flags^=CoderAdjoinFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void PrintRenderFrameHelper::PrintPreviewContext::CalculateIsModifiable() {
is_modifiable_ = !PrintingNodeOrPdfFrame(source_frame(), source_node_);
}
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: logger_adjust_log_filenames ()
{
struct t_infolist *ptr_infolist;
struct t_logger_buffer *ptr_logger_buffer;
struct t_gui_buffer *ptr_buffer;
char *log_filename;
ptr_infolist = weechat_infolist_get ("buffer", NULL, NULL);
if (ptr_infolist)
{
while (weechat_infolist_next (ptr_infolist))
{
ptr_buffer = weechat_infolist_pointer (ptr_infolist, "pointer");
ptr_logger_buffer = logger_buffer_search_buffer (ptr_buffer);
if (ptr_logger_buffer && ptr_logger_buffer->log_filename)
{
log_filename = logger_get_filename (ptr_logger_buffer->buffer);
if (log_filename)
{
if (strcmp (log_filename, ptr_logger_buffer->log_filename) != 0)
{
/*
* log filename has changed (probably due to day
* change),then we'll use new filename
*/
logger_stop (ptr_logger_buffer, 1);
logger_start_buffer (ptr_buffer, 1);
}
free (log_filename);
}
}
}
weechat_infolist_free (ptr_infolist);
}
}
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 a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length)
{
int ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
if (errno == EINTR)
{
/* retry again */
ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
else
{
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
return ret;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: void readpng2_version_info(void)
{
fprintf(stderr, " Compiled with libpng %s; using libpng %s\n",
PNG_LIBPNG_VER_STRING, png_libpng_ver);
fprintf(stderr, " and with zlib %s; using zlib %s.\n",
ZLIB_VERSION, zlib_version);
}
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 close_uinput (void)
{
BTIF_TRACE_DEBUG("%s", __FUNCTION__);
if (uinput_fd > 0) {
ioctl(uinput_fd, UI_DEV_DESTROY);
close(uinput_fd);
uinput_fd = -1;
}
}
CWE ID: CWE-284
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb,
int tlen, int offset)
{
__wsum csum = skb->csum;
if (skb->ip_summed != CHECKSUM_COMPLETE)
return;
if (offset != 0)
csum = csum_sub(csum,
csum_partial(skb_transport_header(skb) + tlen,
offset, 0));
put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void RetrieveAllCookiesOnIO(
net::URLRequestContextGetter* context_getter) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
callback_count_ = 1;
net::URLRequestContext* request_context =
context_getter->GetURLRequestContext();
request_context->cookie_store()->GetAllCookiesAsync(
base::BindOnce(&CookieRetriever::GotCookies, this));
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PlatformSensorAccelerometerMac::PlatformSensorAccelerometerMac(
mojo::ScopedSharedBufferMapping mapping,
PlatformSensorProvider* provider)
: PlatformSensor(SensorType::ACCELEROMETER, std::move(mapping), provider),
sudden_motion_sensor_(SuddenMotionSensor::Create()) {}
CWE ID: CWE-732
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: chunk_type_valid(png_uint_32 c)
/* Bit whacking approach to chunk name validation that is intended to avoid
* branches. The cost is that it uses a lot of 32-bit constants, which might
* be bad on some architectures.
*/
{
png_uint_32 t;
/* Remove bit 5 from all but the reserved byte; this means every
* 8-bit unit must be in the range 65-90 to be valid. So bit 5
* must be zero, bit 6 must be set and bit 7 zero.
*/
c &= ~PNG_U32(32,32,0,32);
t = (c & ~0x1f1f1f1f) ^ 0x40404040;
/* Subtract 65 for each 8 bit quantity, this must not overflow
* and each byte must then be in the range 0-25.
*/
c -= PNG_U32(65,65,65,65);
t |=c ;
/* Subtract 26, handling the overflow which should set the top
* three bits of each byte.
*/
c -= PNG_U32(25,25,25,26);
t |= ~c;
return (t & 0xe0e0e0e0) == 0;
}
CWE ID:
Target: 1
Example 2:
Code: static int nfs4_xdr_dec_open_confirm(struct rpc_rqst *rqstp,
struct xdr_stream *xdr,
struct nfs_open_confirmres *res)
{
struct compound_hdr hdr;
int status;
status = decode_compound_hdr(xdr, &hdr);
if (status)
goto out;
status = decode_putfh(xdr);
if (status)
goto out;
status = decode_open_confirm(xdr, res);
out:
return status;
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void sock_release(struct socket *sock)
{
if (sock->ops) {
struct module *owner = sock->ops->owner;
sock->ops->release(sock);
sock->ops = NULL;
module_put(owner);
}
if (rcu_dereference_protected(sock->wq, 1)->fasync_list)
pr_err("%s: fasync list not empty!\n", __func__);
if (!sock->file) {
iput(SOCK_INODE(sock));
return;
}
sock->file = NULL;
}
CWE ID: CWE-362
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static struct mount *next_mnt(struct mount *p, struct mount *root)
{
struct list_head *next = p->mnt_mounts.next;
if (next == &p->mnt_mounts) {
while (1) {
if (p == root)
return NULL;
next = p->mnt_child.next;
if (next != &p->mnt_parent->mnt_mounts)
break;
p = p->mnt_parent;
}
}
return list_entry(next, struct mount, mnt_child);
}
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: zsetcmykcolor(i_ctx_t * i_ctx_p)
{
os_ptr op = osp; /* required by "push" macro */
int code, i;
float values[4];
/* Gather numeric operand value(s) (also checks type) */
code = float_params(op, 4, (float *)&values);
if (code < 0)
return code;
/* Clamp numeric operand range(s) */
for (i = 0;i < 4; i++) {
if (values[i] < 0)
values[i] = 0;
else if (values[i] > 1)
values[i] = 1;
}
code = make_floats(&op[-3], (const float *)&values, 4);
if (code < 0)
return code;
/* Set up for the continuation procedure which will do the work */
/* Make sure the exec stack has enough space */
check_estack(5);
push_mark_estack(es_other, colour_cleanup);
esp++;
/* variable to hold base type (2 = CMYK) */
make_int(esp, 2);
esp++;
/* Store the 'stage' of processing (initially 0) */
make_int(esp, 0);
/* Finally, the actual continuation routine */
push_op_estack(setdevicecolor_cont);
return o_push_estack;
}
CWE ID: CWE-704
Output:
| 0 |
Here are some example code snippets. Analyze the following 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 SetupMockGroup() {
std::unique_ptr<net::HttpResponseInfo> info(MakeMockResponseInfo());
const int kMockInfoSize = GetResponseInfoSize(info.get());
scoped_refptr<AppCacheGroup> group(
new AppCacheGroup(service_->storage(), kManifestUrl, kMockGroupId));
scoped_refptr<AppCache> cache(
new AppCache(service_->storage(), kMockCacheId));
cache->AddEntry(
kManifestUrl,
AppCacheEntry(AppCacheEntry::MANIFEST, kMockResponseId,
kMockInfoSize + kMockBodySize));
cache->set_complete(true);
group->AddCache(cache.get());
mock_storage()->AddStoredGroup(group.get());
mock_storage()->AddStoredCache(cache.get());
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
const unsigned char *in, int inl)
{
if (ctx->encrypt)
return EVP_EncryptUpdate(ctx, out, outl, in, inl);
else
return EVP_DecryptUpdate(ctx, out, outl, in, inl);
}
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: MediaElementAudioSourceHandler::MediaElementAudioSourceHandler(
AudioNode& node,
HTMLMediaElement& media_element)
: AudioHandler(kNodeTypeMediaElementAudioSource,
node,
node.context()->sampleRate()),
media_element_(media_element),
source_number_of_channels_(0),
source_sample_rate_(0),
passes_current_src_cors_access_check_(
PassesCurrentSrcCORSAccessCheck(media_element.currentSrc())),
maybe_print_cors_message_(!passes_current_src_cors_access_check_),
current_src_string_(media_element.currentSrc().GetString()) {
DCHECK(IsMainThread());
AddOutput(2);
if (Context()->GetExecutionContext()) {
task_runner_ = Context()->GetExecutionContext()->GetTaskRunner(
TaskType::kMediaElementEvent);
}
Initialize();
}
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: xps_select_best_font_encoding(xps_font_t *font)
{
static struct { int pid, eid; } xps_cmap_list[] =
{
{ 3, 10 }, /* Unicode with surrogates */
{ 3, 1 }, /* Unicode without surrogates */
{ 3, 5 }, /* Wansung */
{ 3, 4 }, /* Big5 */
{ 3, 3 }, /* Prc */
{ 3, 2 }, /* ShiftJis */
{ 3, 0 }, /* Symbol */
{ 1, 0 },
{ -1, -1 },
};
int i, k, n, pid, eid;
n = xps_count_font_encodings(font);
for (k = 0; xps_cmap_list[k].pid != -1; k++)
{
for (i = 0; i < n; i++)
{
xps_identify_font_encoding(font, i, &pid, &eid);
if (pid == xps_cmap_list[k].pid && eid == xps_cmap_list[k].eid)
{
xps_select_font_encoding(font, i);
return;
}
}
}
gs_warn("could not find a suitable cmap");
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: scheme_leading_string (enum url_scheme scheme)
{
return supported_schemes[scheme].leading_string;
}
CWE ID: CWE-93
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void CastConfigDelegateChromeos::StopCasting(const std::string& activity_id) {
ExecuteJavaScript("backgroundSetup.stopCastMirroring('user-stop');");
}
CWE ID: CWE-79
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: sctp_disposition_t sctp_sf_do_5_2_4_dupcook(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
int error = 0;
char action;
struct sctp_chunk *err_chk_p;
/* Make sure that the chunk has a valid length from the protocol
* perspective. In this case check to make sure we have at least
* enough for the chunk header. Cookie length verification is
* done later.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(net, ep, asoc, type, arg,
commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie
* of a duplicate COOKIE ECHO match the Verification Tags of the
* current association, consider the State Cookie valid even if
* the lifespan is exceeded.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Compare the tie_tag in cookie with the verification tag of
* current association.
*/
action = sctp_tietags_compare(new_asoc, asoc);
switch (action) {
case 'A': /* Association restart. */
retval = sctp_sf_do_dupcook_a(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'B': /* Collision case B. */
retval = sctp_sf_do_dupcook_b(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'C': /* Collision case C. */
retval = sctp_sf_do_dupcook_c(net, ep, asoc, chunk, commands,
new_asoc);
break;
case 'D': /* Collision case D. */
retval = sctp_sf_do_dupcook_d(net, ep, asoc, chunk, commands,
new_asoc);
break;
default: /* Discard packet for all others. */
retval = sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
break;
}
/* Delete the tempory new association. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
/* Restore association pointer to provide SCTP command interpeter
* with a valid context in case it needs to manipulate
* the queues */
sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC,
SCTP_ASOC((struct sctp_association *)asoc));
return retval;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
CWE ID:
Target: 1
Example 2:
Code: bool RenderFrameHostImpl::SchemeShouldBypassCSP(
const base::StringPiece& scheme) {
const auto& bypassing_schemes = url::GetCSPBypassingSchemes();
return std::find(bypassing_schemes.begin(), bypassing_schemes.end(),
scheme) != bypassing_schemes.end();
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color)
{
int lastBorder;
/* Seek left */
int leftLimit = -1, rightLimit;
int i, restoreAlphaBlending = 0;
if (border < 0) {
/* Refuse to fill to a non-solid border */
return;
}
restoreAlphaBlending = im->alphaBlendingFlag;
im->alphaBlendingFlag = 0;
if (x >= im->sx) {
x = im->sx - 1;
} else if (x < 0) {
x = 0;
}
if (y >= im->sy) {
y = im->sy - 1;
} else if (y < 0) {
y = 0;
}
for (i = x; i >= 0; i--) {
if (gdImageGetPixel(im, i, y) == border) {
break;
}
gdImageSetPixel(im, i, y, color);
leftLimit = i;
}
if (leftLimit == -1) {
im->alphaBlendingFlag = restoreAlphaBlending;
return;
}
/* Seek right */
rightLimit = x;
for (i = (x + 1); i < im->sx; i++) {
if (gdImageGetPixel(im, i, y) == border) {
break;
}
gdImageSetPixel(im, i, y, color);
rightLimit = i;
}
/* Look at lines above and below and start paints */
/* Above */
if (y > 0) {
lastBorder = 1;
for (i = leftLimit; i <= rightLimit; i++) {
int c = gdImageGetPixel(im, i, y - 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder(im, i, y - 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
/* Below */
if (y < ((im->sy) - 1)) {
lastBorder = 1;
for (i = leftLimit; i <= rightLimit; i++) {
int c = gdImageGetPixel(im, i, y + 1);
if (lastBorder) {
if ((c != border) && (c != color)) {
gdImageFillToBorder(im, i, y + 1, border, color);
lastBorder = 0;
}
} else if ((c == border) || (c == color)) {
lastBorder = 1;
}
}
}
im->alphaBlendingFlag = restoreAlphaBlending;
}
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: bool DownloadItemImpl::CanOpenDownload() {
const bool is_complete = GetState() == DownloadItem::COMPLETE;
return (!IsDone() || is_complete) && !IsTemporary() &&
!file_externally_removed_;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
int delta)
{
int nr_nodes, node;
VM_BUG_ON(delta != -1 && delta != 1);
if (delta < 0) {
for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
if (h->surplus_huge_pages_node[node])
goto found;
}
} else {
for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
if (h->surplus_huge_pages_node[node] <
h->nr_huge_pages_node[node])
goto found;
}
}
return 0;
found:
h->surplus_huge_pages += delta;
h->surplus_huge_pages_node[node] += delta;
return 1;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int connected(struct usb_dev_state *ps)
{
return (!list_empty(&ps->list) &&
ps->dev->state != USB_STATE_NOTATTACHED);
}
CWE ID: CWE-200
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHref(cppValue);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: handle_queue_stats_dump_cb(uint32_t queue_id,
struct netdev_queue_stats *stats,
void *cbdata_)
{
struct queue_stats_cbdata *cbdata = cbdata_;
put_queue_stats(cbdata, queue_id, stats);
}
CWE ID: CWE-617
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 perf_event_disable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Disable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_disable, event);
return;
}
retry:
if (!task_function_call(task, __perf_event_disable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the event is still active, we need to retry the cross-call.
*/
if (event->state == PERF_EVENT_STATE_ACTIVE) {
raw_spin_unlock_irq(&ctx->lock);
/*
* Reload the task pointer, it might have been changed by
* a concurrent perf_event_context_sched_out().
*/
task = ctx->task;
goto retry;
}
/*
* Since we have the lock this context can't be scheduled
* in, so we can change the state safely.
*/
if (event->state == PERF_EVENT_STATE_INACTIVE) {
update_group_times(event);
event->state = PERF_EVENT_STATE_OFF;
}
raw_spin_unlock_irq(&ctx->lock);
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void TabStripModelObserver::TabDetachedAt(TabContents* contents,
int index) {
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
loff_t end, int sync_mode)
{
int ret;
struct writeback_control wbc = {
.sync_mode = sync_mode,
.nr_to_write = mapping->nrpages * 2,
.range_start = start,
.range_end = end,
};
if (!mapping_cap_writeback_dirty(mapping))
return 0;
ret = do_writepages(mapping, &wbc);
return ret;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void performInternal(WebPagePrivate* webPagePrivate)
{
webPagePrivate->m_webPage->popupListClosed(webPagePrivate->m_cachedPopupListSelectedIndex);
}
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: validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
{
/*
** Check if screen exists.
*/
if (screen >= screenInfo.numScreens) {
client->errorValue = screen;
*err = BadValue;
return FALSE;
}
*pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
return TRUE;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: SYSCALL_DEFINE2(osf_settimeofday, struct timeval32 __user *, tv,
struct timezone __user *, tz)
{
struct timespec kts;
struct timezone ktz;
if (tv) {
if (get_tv32((struct timeval *)&kts, tv))
return -EFAULT;
}
if (tz) {
if (copy_from_user(&ktz, tz, sizeof(*tz)))
return -EFAULT;
}
kts.tv_nsec *= 1000;
return do_sys_settimeofday(tv ? &kts : NULL, tz ? &ktz : NULL);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct sk_buff **gre_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct sk_buff *p;
const struct gre_base_hdr *greh;
unsigned int hlen, grehlen;
unsigned int off;
int flush = 1;
struct packet_offload *ptype;
__be16 type;
off = skb_gro_offset(skb);
hlen = off + sizeof(*greh);
greh = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out;
}
/* Only support version 0 and K (key), C (csum) flags. Note that
* although the support for the S (seq#) flag can be added easily
* for GRO, this is problematic for GSO hence can not be enabled
* here because a GRO pkt may end up in the forwarding path, thus
* requiring GSO support to break it up correctly.
*/
if ((greh->flags & ~(GRE_KEY|GRE_CSUM)) != 0)
goto out;
type = greh->protocol;
rcu_read_lock();
ptype = gro_find_receive_by_type(type);
if (!ptype)
goto out_unlock;
grehlen = GRE_HEADER_SECTION;
if (greh->flags & GRE_KEY)
grehlen += GRE_HEADER_SECTION;
if (greh->flags & GRE_CSUM)
grehlen += GRE_HEADER_SECTION;
hlen = off + grehlen;
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out_unlock;
}
/* Don't bother verifying checksum if we're going to flush anyway. */
if ((greh->flags & GRE_CSUM) && !NAPI_GRO_CB(skb)->flush) {
if (skb_gro_checksum_simple_validate(skb))
goto out_unlock;
skb_gro_checksum_try_convert(skb, IPPROTO_GRE, 0,
null_compute_pseudo);
}
for (p = *head; p; p = p->next) {
const struct gre_base_hdr *greh2;
if (!NAPI_GRO_CB(p)->same_flow)
continue;
/* The following checks are needed to ensure only pkts
* from the same tunnel are considered for aggregation.
* The criteria for "the same tunnel" includes:
* 1) same version (we only support version 0 here)
* 2) same protocol (we only support ETH_P_IP for now)
* 3) same set of flags
* 4) same key if the key field is present.
*/
greh2 = (struct gre_base_hdr *)(p->data + off);
if (greh2->flags != greh->flags ||
greh2->protocol != greh->protocol) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
if (greh->flags & GRE_KEY) {
/* compare keys */
if (*(__be32 *)(greh2+1) != *(__be32 *)(greh+1)) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
}
}
skb_gro_pull(skb, grehlen);
/* Adjusted NAPI_GRO_CB(skb)->csum after skb_gro_pull()*/
skb_gro_postpull_rcsum(skb, greh, grehlen);
pp = ptype->callbacks.gro_receive(head, skb);
flush = 0;
out_unlock:
rcu_read_unlock();
out:
NAPI_GRO_CB(skb)->flush |= flush;
return pp;
}
CWE ID: CWE-400
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AppResult::AppResult(Profile* profile,
const std::string& app_id,
AppListControllerDelegate* controller,
bool is_recommendation)
: profile_(profile),
app_id_(app_id),
controller_(controller),
extension_registry_(NULL) {
set_id(extensions::Extension::GetBaseURLFromExtensionId(app_id_).spec());
if (app_list::switches::IsExperimentalAppListEnabled())
set_display_type(is_recommendation ? DISPLAY_RECOMMENDATION : DISPLAY_TILE);
const extensions::Extension* extension =
extensions::ExtensionSystem::Get(profile_)->extension_service()
->GetInstalledExtension(app_id_);
DCHECK(extension);
is_platform_app_ = extension->is_platform_app();
icon_.reset(
new extensions::IconImage(profile_,
extension,
extensions::IconsInfo::GetIcons(extension),
GetPreferredIconDimension(),
extensions::util::GetDefaultAppIcon(),
this));
UpdateIcon();
StartObservingExtensionRegistry();
}
CWE ID:
Target: 1
Example 2:
Code: NodeIntersectionObserverData& Document::ensureIntersectionObserverData()
{
if (!m_intersectionObserverData)
m_intersectionObserverData = new NodeIntersectionObserverData();
return *m_intersectionObserverData;
}
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 ext4_orphan_del(handle_t *handle, struct inode *inode)
{
struct list_head *prev;
struct ext4_inode_info *ei = EXT4_I(inode);
struct ext4_sb_info *sbi;
__u32 ino_next;
struct ext4_iloc iloc;
int err = 0;
/* ext4_handle_valid() assumes a valid handle_t pointer */
if (handle && !ext4_handle_valid(handle))
return 0;
mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
if (list_empty(&ei->i_orphan))
goto out;
ino_next = NEXT_ORPHAN(inode);
prev = ei->i_orphan.prev;
sbi = EXT4_SB(inode->i_sb);
jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino);
list_del_init(&ei->i_orphan);
/* If we're on an error path, we may not have a valid
* transaction handle with which to update the orphan list on
* disk, but we still need to remove the inode from the linked
* list in memory. */
if (sbi->s_journal && !handle)
goto out;
err = ext4_reserve_inode_write(handle, inode, &iloc);
if (err)
goto out_err;
if (prev == &sbi->s_orphan) {
jbd_debug(4, "superblock will point to %u\n", ino_next);
BUFFER_TRACE(sbi->s_sbh, "get_write_access");
err = ext4_journal_get_write_access(handle, sbi->s_sbh);
if (err)
goto out_brelse;
sbi->s_es->s_last_orphan = cpu_to_le32(ino_next);
err = ext4_handle_dirty_super(handle, inode->i_sb);
} else {
struct ext4_iloc iloc2;
struct inode *i_prev =
&list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode;
jbd_debug(4, "orphan inode %lu will point to %u\n",
i_prev->i_ino, ino_next);
err = ext4_reserve_inode_write(handle, i_prev, &iloc2);
if (err)
goto out_brelse;
NEXT_ORPHAN(i_prev) = ino_next;
err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2);
}
if (err)
goto out_brelse;
NEXT_ORPHAN(inode) = 0;
err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out_err:
ext4_std_error(inode->i_sb, err);
out:
mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock);
return err;
out_brelse:
brelse(iloc.bh);
goto out_err;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void Sp_split_regexp(js_State *J)
{
js_Regexp *re;
const char *text;
int limit, len, k;
const char *p, *a, *b, *c, *e;
Resub m;
text = checkstring(J, 0);
re = js_toregexp(J, 1);
limit = js_isdefined(J, 2) ? js_tointeger(J, 2) : 1 << 30;
js_newarray(J);
len = 0;
e = text + strlen(text);
/* splitting the empty string */
if (e == text) {
if (js_regexec(re->prog, text, &m, 0)) {
if (len == limit) return;
js_pushliteral(J, "");
js_setindex(J, -2, 0);
}
return;
}
p = a = text;
while (a < e) {
if (js_regexec(re->prog, a, &m, a > text ? REG_NOTBOL : 0))
break; /* no match */
b = m.sub[0].sp;
c = m.sub[0].ep;
/* empty string at end of last match */
if (b == p) {
++a;
continue;
}
if (len == limit) return;
js_pushlstring(J, p, b - p);
js_setindex(J, -2, len++);
for (k = 1; k < m.nsub; ++k) {
if (len == limit) return;
js_pushlstring(J, m.sub[k].sp, m.sub[k].ep - m.sub[k].sp);
js_setindex(J, -2, len++);
}
a = p = c;
}
if (len == limit) return;
js_pushstring(J, p);
js_setindex(J, -2, len);
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: static void lsi_stop_script(LSIState *s)
{
s->istat1 &= ~LSI_ISTAT1_SRUN;
}
CWE ID: CWE-835
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int __fpu__restore_sig(void __user *buf, void __user *buf_fx, int size)
{
int ia32_fxstate = (buf != buf_fx);
struct task_struct *tsk = current;
struct fpu *fpu = &tsk->thread.fpu;
int state_size = fpu_kernel_xstate_size;
u64 xfeatures = 0;
int fx_only = 0;
ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) ||
IS_ENABLED(CONFIG_IA32_EMULATION));
if (!buf) {
fpu__clear(fpu);
return 0;
}
if (!access_ok(VERIFY_READ, buf, size))
return -EACCES;
fpu__activate_curr(fpu);
if (!static_cpu_has(X86_FEATURE_FPU))
return fpregs_soft_set(current, NULL,
0, sizeof(struct user_i387_ia32_struct),
NULL, buf) != 0;
if (use_xsave()) {
struct _fpx_sw_bytes fx_sw_user;
if (unlikely(check_for_xstate(buf_fx, buf_fx, &fx_sw_user))) {
/*
* Couldn't find the extended state information in the
* memory layout. Restore just the FP/SSE and init all
* the other extended state.
*/
state_size = sizeof(struct fxregs_state);
fx_only = 1;
trace_x86_fpu_xstate_check_failed(fpu);
} else {
state_size = fx_sw_user.xstate_size;
xfeatures = fx_sw_user.xfeatures;
}
}
if (ia32_fxstate) {
/*
* For 32-bit frames with fxstate, copy the user state to the
* thread's fpu state, reconstruct fxstate from the fsave
* header. Sanitize the copied state etc.
*/
struct fpu *fpu = &tsk->thread.fpu;
struct user_i387_ia32_struct env;
int err = 0;
/*
* Drop the current fpu which clears fpu->fpstate_active. This ensures
* that any context-switch during the copy of the new state,
* avoids the intermediate state from getting restored/saved.
* Thus avoiding the new restored state from getting corrupted.
* We will be ready to restore/save the state only after
* fpu->fpstate_active is again set.
*/
fpu__drop(fpu);
if (using_compacted_format())
err = copy_user_to_xstate(&fpu->state.xsave, buf_fx);
else
err = __copy_from_user(&fpu->state.xsave, buf_fx, state_size);
if (err || __copy_from_user(&env, buf, sizeof(env))) {
fpstate_init(&fpu->state);
trace_x86_fpu_init_state(fpu);
err = -1;
} else {
sanitize_restored_xstate(tsk, &env, xfeatures, fx_only);
}
fpu->fpstate_active = 1;
preempt_disable();
fpu__restore(fpu);
preempt_enable();
return err;
} else {
/*
* For 64-bit frames and 32-bit fsave frames, restore the user
* state to the registers directly (with exceptions handled).
*/
user_fpu_begin();
if (copy_user_to_fpregs_zeroing(buf_fx, xfeatures, fx_only)) {
fpu__clear(fpu);
return -1;
}
}
return 0;
}
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 InspectorNetworkAgent::WillSendRequest(
ExecutionContext* execution_context,
unsigned long identifier,
DocumentLoader* loader,
ResourceRequest& request,
const ResourceResponse& redirect_response,
const FetchInitiatorInfo& initiator_info) {
if (initiator_info.name == FetchInitiatorTypeNames::internal)
return;
if (initiator_info.name == FetchInitiatorTypeNames::document &&
loader->GetSubstituteData().IsValid())
return;
protocol::DictionaryValue* headers =
state_->getObject(NetworkAgentState::kExtraRequestHeaders);
if (headers) {
for (size_t i = 0; i < headers->size(); ++i) {
auto header = headers->at(i);
String value;
if (header.second->asString(&value))
request.SetHTTPHeaderField(AtomicString(header.first),
AtomicString(value));
}
}
request.SetReportRawHeaders(true);
if (state_->booleanProperty(NetworkAgentState::kCacheDisabled, false)) {
if (LoadsFromCacheOnly(request) &&
request.GetRequestContext() != WebURLRequest::kRequestContextInternal) {
request.SetCachePolicy(WebCachePolicy::kBypassCacheLoadOnlyFromCache);
} else {
request.SetCachePolicy(WebCachePolicy::kBypassingCache);
}
request.SetShouldResetAppCache(true);
}
if (state_->booleanProperty(NetworkAgentState::kBypassServiceWorker, false))
request.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kNone);
WillSendRequestInternal(execution_context, identifier, loader, request,
redirect_response, initiator_info);
if (!host_id_.IsEmpty()) {
request.AddHTTPHeaderField(
HTTPNames::X_DevTools_Emulate_Network_Conditions_Client_Id,
AtomicString(host_id_));
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: fz_catch(ctx)
{
pdf_drop_obj(ctx, encrypt);
pdf_drop_obj(ctx, id);
pdf_drop_obj(ctx, obj);
pdf_drop_obj(ctx, info);
fz_free(ctx, list);
fz_rethrow(ctx);
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void TaskService::RunTask(InstanceId instance_id,
RunnerId runner_id,
base::OnceClosure task) {
base::subtle::AutoReadLock task_lock(task_lock_);
{
base::AutoLock lock(lock_);
if (instance_id != bound_instance_id_)
return;
}
std::move(task).Run();
}
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 sum_init(int csum_type, int seed)
{
char s[4];
if (csum_type < 0)
csum_type = parse_csum_name(NULL, 0);
cursum_type = csum_type;
switch (csum_type) {
case CSUM_MD5:
md5_begin(&md);
break;
case CSUM_MD4:
mdfour_begin(&md);
sumresidue = 0;
break;
case CSUM_MD4_OLD:
break;
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
mdfour_begin(&md);
sumresidue = 0;
SIVAL(s, 0, seed);
break;
}
}
CWE ID: CWE-354
Target: 1
Example 2:
Code: static inline bool got_nohz_idle_kick(void)
{
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: UNCURL_EXPORT int32_t uncurl_ws_connect(struct uncurl_conn *ucc, char *path, char *origin)
{
int32_t e;
int32_t r = UNCURL_ERR_DEFAULT;
char *sec_key = ws_create_key(&ucc->seed);
uncurl_set_header_str(ucc, "Upgrade", "websocket");
uncurl_set_header_str(ucc, "Connection", "Upgrade");
uncurl_set_header_str(ucc, "Sec-WebSocket-Key", sec_key);
uncurl_set_header_str(ucc, "Sec-WebSocket-Version", "13");
if (origin)
uncurl_set_header_str(ucc, "Origin", origin);
e = uncurl_write_header(ucc, "GET", path, UNCURL_REQUEST);
if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;}
e = uncurl_read_header(ucc);
if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;}
int32_t status_code = 0;
e = uncurl_get_status_code(ucc, &status_code);
if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;}
if (status_code != 101) {r = UNCURL_WS_ERR_STATUS; goto uncurl_ws_connect_end;}
char *server_sec_key = NULL;
e = uncurl_get_header_str(ucc, "Sec-WebSocket-Accept", &server_sec_key);
if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;}
if (!ws_validate_key(sec_key, server_sec_key)) {r = UNCURL_WS_ERR_KEY; goto uncurl_ws_connect_end;}
ucc->ws_mask = 1;
r = UNCURL_OK;
uncurl_ws_connect_end:
free(sec_key);
return r;
}
CWE ID: CWE-352
Output:
| 0 |
Here are some example code snippets. Analyze the following 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 jslTokenAsString(int token, char *str, size_t len) {
if (token>32 && token<128) {
assert(len>=4);
str[0] = '\'';
str[1] = (char)token;
str[2] = '\'';
str[3] = 0;
return;
}
switch (token) {
case LEX_EOF : strncpy(str, "EOF", len); return;
case LEX_ID : strncpy(str, "ID", len); return;
case LEX_INT : strncpy(str, "INT", len); return;
case LEX_FLOAT : strncpy(str, "FLOAT", len); return;
case LEX_STR : strncpy(str, "STRING", len); return;
case LEX_UNFINISHED_STR : strncpy(str, "UNFINISHED STRING", len); return;
case LEX_TEMPLATE_LITERAL : strncpy(str, "TEMPLATE LITERAL", len); return;
case LEX_UNFINISHED_TEMPLATE_LITERAL : strncpy(str, "UNFINISHED TEMPLATE LITERAL", len); return;
case LEX_REGEX : strncpy(str, "REGEX", len); return;
case LEX_UNFINISHED_REGEX : strncpy(str, "UNFINISHED REGEX", len); return;
case LEX_UNFINISHED_COMMENT : strncpy(str, "UNFINISHED COMMENT", len); return;
}
if (token>=_LEX_OPERATOR_START && token<_LEX_R_LIST_END) {
const char tokenNames[] =
/* LEX_EQUAL : */ "==\0"
/* LEX_TYPEEQUAL : */ "===\0"
/* LEX_NEQUAL : */ "!=\0"
/* LEX_NTYPEEQUAL : */ "!==\0"
/* LEX_LEQUAL : */ "<=\0"
/* LEX_LSHIFT : */ "<<\0"
/* LEX_LSHIFTEQUAL : */ "<<=\0"
/* LEX_GEQUAL : */ ">=\0"
/* LEX_RSHIFT : */ ">>\0"
/* LEX_RSHIFTUNSIGNED */ ">>>\0"
/* LEX_RSHIFTEQUAL : */ ">>=\0"
/* LEX_RSHIFTUNSIGNEDEQUAL */ ">>>=\0"
/* LEX_PLUSEQUAL : */ "+=\0"
/* LEX_MINUSEQUAL : */ "-=\0"
/* LEX_PLUSPLUS : */ "++\0"
/* LEX_MINUSMINUS */ "--\0"
/* LEX_MULEQUAL : */ "*=\0"
/* LEX_DIVEQUAL : */ "/=\0"
/* LEX_MODEQUAL : */ "%=\0"
/* LEX_ANDEQUAL : */ "&=\0"
/* LEX_ANDAND : */ "&&\0"
/* LEX_OREQUAL : */ "|=\0"
/* LEX_OROR : */ "||\0"
/* LEX_XOREQUAL : */ "^=\0"
/* LEX_ARROW_FUNCTION */ "=>\0"
/*LEX_R_IF : */ "if\0"
/*LEX_R_ELSE : */ "else\0"
/*LEX_R_DO : */ "do\0"
/*LEX_R_WHILE : */ "while\0"
/*LEX_R_FOR : */ "for\0"
/*LEX_R_BREAK : */ "return\0"
/*LEX_R_CONTINUE */ "continue\0"
/*LEX_R_FUNCTION */ "function\0"
/*LEX_R_RETURN */ "return\0"
/*LEX_R_VAR : */ "var\0"
/*LEX_R_LET : */ "let\0"
/*LEX_R_CONST : */ "const\0"
/*LEX_R_THIS : */ "this\0"
/*LEX_R_THROW : */ "throw\0"
/*LEX_R_TRY : */ "try\0"
/*LEX_R_CATCH : */ "catch\0"
/*LEX_R_FINALLY : */ "finally\0"
/*LEX_R_TRUE : */ "true\0"
/*LEX_R_FALSE : */ "false\0"
/*LEX_R_NULL : */ "null\0"
/*LEX_R_UNDEFINED */ "undefined\0"
/*LEX_R_NEW : */ "new\0"
/*LEX_R_IN : */ "in\0"
/*LEX_R_INSTANCEOF */ "instanceof\0"
/*LEX_R_SWITCH */ "switch\0"
/*LEX_R_CASE */ "case\0"
/*LEX_R_DEFAULT */ "default\0"
/*LEX_R_DELETE */ "delete\0"
/*LEX_R_TYPEOF : */ "typeof\0"
/*LEX_R_VOID : */ "void\0"
/*LEX_R_DEBUGGER : */ "debugger\0"
/*LEX_R_CLASS : */ "class\0"
/*LEX_R_EXTENDS : */ "extends\0"
/*LEX_R_SUPER : */ "super\0"
/*LEX_R_STATIC : */ "static\0"
;
unsigned int p = 0;
int n = token-_LEX_OPERATOR_START;
while (n>0 && p<sizeof(tokenNames)) {
while (tokenNames[p] && p<sizeof(tokenNames)) p++;
p++; // skip the zero
n--; // next token
}
assert(n==0);
strncpy(str, &tokenNames[p], len);
return;
}
assert(len>=10);
espruino_snprintf(str, len, "?[%d]", token);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: static void vma_gap_update(struct vm_area_struct *vma)
{
/*
* As it turns out, RB_DECLARE_CALLBACKS() already created a callback
* function that does exactly what we want.
*/
vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
}
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 Document::setXMLVersion(const String& version, ExceptionState& es)
{
if (!implementation()->hasFeature("XML", String())) {
es.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
if (!XMLDocumentParser::supportsXMLVersion(version)) {
es.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
m_xmlVersion = version;
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __vcpu_run(struct kvm_vcpu *vcpu)
{
int r;
struct kvm *kvm = vcpu->kvm;
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
r = vapic_enter(vcpu);
if (r) {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
return r;
}
r = 1;
while (r > 0) {
if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
!vcpu->arch.apf.halted)
r = vcpu_enter_guest(vcpu);
else {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
kvm_vcpu_block(vcpu);
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
kvm_apic_accept_events(vcpu);
switch(vcpu->arch.mp_state) {
case KVM_MP_STATE_HALTED:
vcpu->arch.pv.pv_unhalted = false;
vcpu->arch.mp_state =
KVM_MP_STATE_RUNNABLE;
case KVM_MP_STATE_RUNNABLE:
vcpu->arch.apf.halted = false;
break;
case KVM_MP_STATE_INIT_RECEIVED:
break;
default:
r = -EINTR;
break;
}
}
}
if (r <= 0)
break;
clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
if (kvm_cpu_has_pending_timer(vcpu))
kvm_inject_pending_timer_irqs(vcpu);
if (dm_request_for_irq_injection(vcpu)) {
r = -EINTR;
vcpu->run->exit_reason = KVM_EXIT_INTR;
++vcpu->stat.request_irq_exits;
}
kvm_check_async_pf_completion(vcpu);
if (signal_pending(current)) {
r = -EINTR;
vcpu->run->exit_reason = KVM_EXIT_INTR;
++vcpu->stat.signal_exits;
}
if (need_resched()) {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
kvm_resched(vcpu);
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
}
}
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
vapic_exit(vcpu);
return r;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void read_pathspec_from_stdin(struct rev_info *revs, struct strbuf *sb,
struct cmdline_pathspec *prune)
{
while (strbuf_getline(sb, stdin) != EOF) {
ALLOC_GROW(prune->path, prune->nr + 1, prune->alloc);
prune->path[prune->nr++] = xstrdup(sb->buf);
}
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ext4_dax_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
{
return dax_mkwrite(vma, vmf, ext4_get_block_dax,
ext4_end_io_unwritten);
}
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: std::string SerializeDefaultPaddingKey() {
return (*GetPaddingKey())->key();
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void FetchSources() {
for (mojom::SensorType type : fusion_algorithm_->source_types()) {
scoped_refptr<PlatformSensor> sensor = provider_->GetSensor(type);
if (sensor) {
SensorCreated(std::move(sensor));
} else {
provider_->CreateSensor(type,
base::Bind(&Factory::SensorCreated, this));
}
}
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool UnprivilegedProcessDelegate::CreateConnectedIpcChannel(
const std::string& channel_name,
IPC::Listener* delegate,
ScopedHandle* client_out,
scoped_ptr<IPC::ChannelProxy>* server_out) {
scoped_ptr<IPC::ChannelProxy> server;
if (!CreateIpcChannel(channel_name, kDaemonIpcSecurityDescriptor,
io_task_runner_, delegate, &server)) {
return false;
}
std::string pipe_name(kChromePipeNamePrefix);
pipe_name.append(channel_name);
SECURITY_ATTRIBUTES security_attributes;
security_attributes.nLength = sizeof(security_attributes);
security_attributes.lpSecurityDescriptor = NULL;
security_attributes.bInheritHandle = TRUE;
ScopedHandle client;
client.Set(CreateFile(UTF8ToUTF16(pipe_name).c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
&security_attributes,
OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION |
FILE_FLAG_OVERLAPPED,
NULL));
if (!client.IsValid())
return false;
*client_out = client.Pass();
*server_out = server.Pass();
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 void ip6_append_data_mtu(int *mtu,
int *maxfraglen,
unsigned int fragheaderlen,
struct sk_buff *skb,
struct rt6_info *rt)
{
if (!(rt->dst.flags & DST_XFRM_TUNNEL)) {
if (skb == NULL) {
/* first fragment, reserve header_len */
*mtu = *mtu - rt->dst.header_len;
} else {
/*
* this fragment is not first, the headers
* space is regarded as data space.
*/
*mtu = dst_mtu(rt->dst.path);
}
*maxfraglen = ((*mtu - fragheaderlen) & ~7)
+ fragheaderlen - sizeof(struct frag_hdr);
}
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: void account_idle_ticks(unsigned long ticks)
{
if (sched_clock_irqtime) {
irqtime_account_idle_ticks(ticks);
return;
}
account_idle_time(jiffies_to_cputime(ticks));
}
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: grub_fshelp_read_file (grub_disk_t disk, grub_fshelp_node_t node,
void (*read_hook) (grub_disk_addr_t sector,
unsigned offset,
unsigned length,
void *closure),
void *closure, int flags,
grub_off_t pos, grub_size_t len, char *buf,
grub_disk_addr_t (*get_block) (grub_fshelp_node_t node,
grub_disk_addr_t block),
grub_off_t filesize, int log2blocksize)
{
grub_disk_addr_t i, blockcnt;
int blocksize = 1 << (log2blocksize + GRUB_DISK_SECTOR_BITS);
/* Adjust LEN so it we can't read past the end of the file. */
if (pos + len > filesize)
len = filesize - pos;
blockcnt = ((len + pos) + blocksize - 1) >>
(log2blocksize + GRUB_DISK_SECTOR_BITS);
for (i = pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS); i < blockcnt; i++)
{
grub_disk_addr_t blknr;
int blockoff = pos & (blocksize - 1);
int blockend = blocksize;
int skipfirst = 0;
blknr = get_block (node, i);
if (grub_errno)
return -1;
blknr = blknr << log2blocksize;
/* Last block. */
if (i == blockcnt - 1)
{
blockend = (len + pos) & (blocksize - 1);
/* The last portion is exactly blocksize. */
if (! blockend)
blockend = blocksize;
}
/* First block. */
if (i == (pos >> (log2blocksize + GRUB_DISK_SECTOR_BITS)))
{
skipfirst = blockoff;
blockend -= skipfirst;
}
/* If the block number is 0 this block is not stored on disk but
is zero filled instead. */
if (blknr)
{
disk->read_hook = read_hook;
disk->closure = closure;
grub_hack_lastoff = blknr * 512;
grub_disk_read_ex (disk, blknr, skipfirst, blockend, buf, flags);
disk->read_hook = 0;
if (grub_errno)
return -1;
}
else if (buf)
grub_memset (buf, 0, blockend);
if (buf)
buf += blocksize - skipfirst;
}
return len;
}
CWE ID: CWE-787
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void *Sys_LoadDll(const char *name, qboolean useSystemLib)
{
void *dllhandle;
if(useSystemLib)
Com_Printf("Trying to load \"%s\"...\n", name);
if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name)))
{
const char *topDir;
char libPath[MAX_OSPATH];
topDir = Sys_BinaryPath();
if(!*topDir)
topDir = ".";
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name);
if(!(dllhandle = Sys_LoadLibrary(libPath)))
{
const char *basePath = Cvar_VariableString("fs_basepath");
if(!basePath || !*basePath)
basePath = ".";
if(FS_FilenameCompare(topDir, basePath))
{
Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath);
Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name);
dllhandle = Sys_LoadLibrary(libPath);
}
if(!dllhandle)
Com_Printf("Loading \"%s\" failed\n", name);
}
}
return dllhandle;
}
CWE ID: CWE-269
Target: 1
Example 2:
Code: CSSStyleDeclaration *Element::style()
{
return 0;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int x509_verify(const CA_CERT_CTX *ca_cert_ctx, const X509_CTX *cert,
int *pathLenConstraint)
{
int ret = X509_OK, i = 0;
bigint *cert_sig;
X509_CTX *next_cert = NULL;
BI_CTX *ctx = NULL;
bigint *mod = NULL, *expn = NULL;
int match_ca_cert = 0;
struct timeval tv;
uint8_t is_self_signed = 0;
if (cert == NULL)
{
ret = X509_VFY_ERROR_NO_TRUSTED_CERT;
goto end_verify;
}
/* a self-signed certificate that is not in the CA store - use this
to check the signature */
if (asn1_compare_dn(cert->ca_cert_dn, cert->cert_dn) == 0)
{
is_self_signed = 1;
ctx = cert->rsa_ctx->bi_ctx;
mod = cert->rsa_ctx->m;
expn = cert->rsa_ctx->e;
}
gettimeofday(&tv, NULL);
/* check the not before date */
if (tv.tv_sec < cert->not_before)
{
ret = X509_VFY_ERROR_NOT_YET_VALID;
goto end_verify;
}
/* check the not after date */
if (tv.tv_sec > cert->not_after)
{
ret = X509_VFY_ERROR_EXPIRED;
goto end_verify;
}
if (cert->basic_constraint_present)
{
/* If the cA boolean is not asserted,
then the keyCertSign bit in the key usage extension MUST NOT be
asserted. */
if (!cert->basic_constraint_cA &&
IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_CERT_SIGN))
{
ret = X509_VFY_ERROR_BASIC_CONSTRAINT;
goto end_verify;
}
/* The pathLenConstraint field is meaningful only if the cA boolean is
asserted and the key usage extension, if present, asserts the
keyCertSign bit. In this case, it gives the maximum number of
non-self-issued intermediate certificates that may follow this
certificate in a valid certification path. */
if (cert->basic_constraint_cA &&
(!cert->key_usage_present ||
IS_SET_KEY_USAGE_FLAG(cert, KEY_USAGE_KEY_CERT_SIGN)) &&
(cert->basic_constraint_pathLenConstraint+1) < *pathLenConstraint)
{
ret = X509_VFY_ERROR_BASIC_CONSTRAINT;
goto end_verify;
}
}
next_cert = cert->next;
/* last cert in the chain - look for a trusted cert */
if (next_cert == NULL)
{
if (ca_cert_ctx != NULL)
{
/* go thru the CA store */
while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i])
{
/* the extension is present but the cA boolean is not
asserted, then the certified public key MUST NOT be used
to verify certificate signatures. */
if (cert->basic_constraint_present &&
!ca_cert_ctx->cert[i]->basic_constraint_cA)
continue;
if (asn1_compare_dn(cert->ca_cert_dn,
ca_cert_ctx->cert[i]->cert_dn) == 0)
{
/* use this CA certificate for signature verification */
match_ca_cert = true;
ctx = ca_cert_ctx->cert[i]->rsa_ctx->bi_ctx;
mod = ca_cert_ctx->cert[i]->rsa_ctx->m;
expn = ca_cert_ctx->cert[i]->rsa_ctx->e;
break;
}
i++;
}
}
/* couldn't find a trusted cert (& let self-signed errors
be returned) */
if (!match_ca_cert && !is_self_signed)
{
ret = X509_VFY_ERROR_NO_TRUSTED_CERT;
goto end_verify;
}
}
else if (asn1_compare_dn(cert->ca_cert_dn, next_cert->cert_dn) != 0)
{
/* check the chain */
ret = X509_VFY_ERROR_INVALID_CHAIN;
goto end_verify;
}
else /* use the next certificate in the chain for signature verify */
{
ctx = next_cert->rsa_ctx->bi_ctx;
mod = next_cert->rsa_ctx->m;
expn = next_cert->rsa_ctx->e;
}
/* cert is self signed */
if (!match_ca_cert && is_self_signed)
{
ret = X509_VFY_ERROR_SELF_SIGNED;
goto end_verify;
}
/* check the signature */
cert_sig = sig_verify(ctx, cert->signature, cert->sig_len,
bi_clone(ctx, mod), bi_clone(ctx, expn));
if (cert_sig && cert->digest)
{
if (bi_compare(cert_sig, cert->digest) != 0)
ret = X509_VFY_ERROR_BAD_SIGNATURE;
bi_free(ctx, cert_sig);
}
else
{
ret = X509_VFY_ERROR_BAD_SIGNATURE;
}
bi_clear_cache(ctx);
if (ret)
goto end_verify;
/* go down the certificate chain using recursion. */
if (next_cert != NULL)
{
(*pathLenConstraint)++; /* don't include last certificate */
ret = x509_verify(ca_cert_ctx, next_cert, pathLenConstraint);
}
end_verify:
return ret;
}
CWE ID: CWE-347
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: sec_decrypt(uint8 * data, int length)
{
if (g_sec_decrypt_use_count == 4096)
{
sec_update(g_sec_decrypt_key, g_sec_decrypt_update_key);
rdssl_rc4_set_key(&g_rc4_decrypt_key, g_sec_decrypt_key, g_rc4_key_len);
g_sec_decrypt_use_count = 0;
}
rdssl_rc4_crypt(&g_rc4_decrypt_key, data, data, length);
g_sec_decrypt_use_count++;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
struct net_device *upper_dev,
struct list_head *up_list,
struct list_head *down_list)
{
__netdev_adjacent_dev_remove(dev, upper_dev, up_list);
__netdev_adjacent_dev_remove(upper_dev, dev, down_list);
}
CWE ID: CWE-400
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t Parcel::setDataCapacity(size_t size)
{
if (size > mDataCapacity) return continueWrite(size);
return NO_ERROR;
}
CWE ID: CWE-264
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: EncodedJSValue JSC_HOST_CALL jsTestMediaQueryListListenerPrototypeFunctionMethod(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestMediaQueryListListener::s_info))
return throwVMTypeError(exec);
JSTestMediaQueryListListener* castedThis = jsCast<JSTestMediaQueryListListener*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestMediaQueryListListener::s_info);
TestMediaQueryListListener* impl = static_cast<TestMediaQueryListListener*>(castedThis->impl());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
RefPtr<MediaQueryListListener> listener(MediaQueryListListener::create(ScriptValue(exec->globalData(), MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))));
if (exec->hadException())
return JSValue::encode(jsUndefined());
impl->method(listener);
return JSValue::encode(jsUndefined());
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void VerifyFormInteractionUkm(const ukm::TestAutoSetUkmRecorder& ukm_recorder,
const FormData& form,
const char* event_name,
const ExpectedUkmMetrics& expected_metrics) {
auto entries = ukm_recorder.GetEntriesByName(event_name);
EXPECT_LE(entries.size(), expected_metrics.size());
for (size_t i = 0; i < expected_metrics.size() && i < entries.size(); i++) {
ukm_recorder.ExpectEntrySourceHasUrl(entries[i],
GURL(form.main_frame_origin.GetURL()));
EXPECT_THAT(
entries[i]->metrics,
UnorderedPointwise(CompareMetricsIgnoringMillisecondsSinceFormParsed(),
expected_metrics[i]));
}
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: std::unique_ptr<FakeMediaStreamUIProxy> CreateMockUI(bool expect_started) {
std::unique_ptr<MockMediaStreamUIProxy> fake_ui =
std::make_unique<MockMediaStreamUIProxy>();
if (expect_started)
EXPECT_CALL(*fake_ui, MockOnStarted(_));
return fake_ui;
}
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 UserSelectionScreen::FillMultiProfileUserPrefs(
user_manager::User* user,
base::DictionaryValue* user_dict,
bool is_signin_to_add) {
if (!is_signin_to_add) {
user_dict->SetBoolean(kKeyMultiProfilesAllowed, true);
return;
}
bool is_user_allowed;
ash::mojom::MultiProfileUserBehavior policy;
GetMultiProfilePolicy(user, &is_user_allowed, &policy);
user_dict->SetBoolean(kKeyMultiProfilesAllowed, is_user_allowed);
user_dict->SetInteger(kKeyMultiProfilesPolicy, static_cast<int>(policy));
}
CWE ID:
Target: 1
Example 2:
Code: bool GLES2Implementation::GetProgramInterfaceivHelper(GLuint program,
GLenum program_interface,
GLenum pname,
GLint* params) {
bool success = share_group_->program_info_manager()->GetProgramInterfaceiv(
this, program, program_interface, pname, params);
GPU_CLIENT_LOG_CODE_BLOCK({
if (success) {
GPU_CLIENT_LOG(" 0: " << *params);
}
});
return success;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AppCacheUpdateJob::HandleUrlFetchCompleted(URLFetcher* fetcher,
int net_error) {
DCHECK(internal_state_ == DOWNLOADING);
UpdateURLLoaderRequest* request = fetcher->request();
const GURL& url = request->GetURL();
pending_url_fetches_.erase(url);
NotifyAllProgress(url);
++url_fetches_completed_;
int response_code = net_error == net::OK ? request->GetResponseCode()
: fetcher->redirect_response_code();
AppCacheEntry& entry = url_file_list_.find(url)->second;
if (response_code / 100 == 2) {
DCHECK(fetcher->response_writer());
entry.set_response_id(fetcher->response_writer()->response_id());
entry.set_response_size(fetcher->response_writer()->amount_written());
if (!inprogress_cache_->AddOrModifyEntry(url, entry))
duplicate_response_ids_.push_back(entry.response_id());
} else {
VLOG(1) << "Request error: " << net_error
<< " response code: " << response_code;
if (entry.IsExplicit() || entry.IsFallback() || entry.IsIntercept()) {
if (response_code == 304 && fetcher->existing_entry().has_response_id()) {
entry.set_response_id(fetcher->existing_entry().response_id());
entry.set_response_size(fetcher->existing_entry().response_size());
inprogress_cache_->AddOrModifyEntry(url, entry);
} else {
const char kFormatString[] = "Resource fetch failed (%d) %s";
std::string message = FormatUrlErrorMessage(
kFormatString, url, fetcher->result(), response_code);
ResultType result = fetcher->result();
bool is_cross_origin = url.GetOrigin() != manifest_url_.GetOrigin();
switch (result) {
case DISKCACHE_ERROR:
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
message,
blink::mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR,
GURL(), 0, is_cross_origin),
result, url);
break;
case NETWORK_ERROR:
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
message,
blink::mojom::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR,
url, 0, is_cross_origin),
result, url);
break;
default:
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
message,
blink::mojom::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR,
url, response_code, is_cross_origin),
result, url);
break;
}
return;
}
} else if (response_code == 404 || response_code == 410) {
} else if (update_type_ == UPGRADE_ATTEMPT &&
fetcher->existing_entry().has_response_id()) {
entry.set_response_id(fetcher->existing_entry().response_id());
entry.set_response_size(fetcher->existing_entry().response_size());
inprogress_cache_->AddOrModifyEntry(url, entry);
}
}
DCHECK(internal_state_ != CACHE_FAILURE);
FetchUrls();
MaybeCompleteUpdate();
}
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: spnego_gss_export_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 ret;
ret = gss_export_sec_context(minor_status,
context_handle,
interprocess_token);
return (ret);
}
CWE ID: CWE-18
Target: 1
Example 2:
Code: static void raisesExceptionVoidMethodOptionalLongArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "raisesExceptionVoidMethodOptionalLongArg", "TestObjectPython", info.Holder(), info.GetIsolate());
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
if (UNLIKELY(info.Length() <= 0)) {
imp->raisesExceptionVoidMethodOptionalLongArg(exceptionState);
if (exceptionState.throwIfNeeded())
return;
return;
}
V8TRYCATCH_EXCEPTION_VOID(int, optionalLongArg, toInt32(info[0], exceptionState), exceptionState);
imp->raisesExceptionVoidMethodOptionalLongArg(optionalLongArg, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
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 long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct perf_event *event = file->private_data;
void (*func)(struct perf_event *);
u32 flags = arg;
switch (cmd) {
case PERF_EVENT_IOC_ENABLE:
func = perf_event_enable;
break;
case PERF_EVENT_IOC_DISABLE:
func = perf_event_disable;
break;
case PERF_EVENT_IOC_RESET:
func = perf_event_reset;
break;
case PERF_EVENT_IOC_REFRESH:
return perf_event_refresh(event, arg);
case PERF_EVENT_IOC_PERIOD:
return perf_event_period(event, (u64 __user *)arg);
case PERF_EVENT_IOC_ID:
{
u64 id = primary_event_id(event);
if (copy_to_user((void __user *)arg, &id, sizeof(id)))
return -EFAULT;
return 0;
}
case PERF_EVENT_IOC_SET_OUTPUT:
{
int ret;
if (arg != -1) {
struct perf_event *output_event;
struct fd output;
ret = perf_fget_light(arg, &output);
if (ret)
return ret;
output_event = output.file->private_data;
ret = perf_event_set_output(event, output_event);
fdput(output);
} else {
ret = perf_event_set_output(event, NULL);
}
return ret;
}
case PERF_EVENT_IOC_SET_FILTER:
return perf_event_set_filter(event, (void __user *)arg);
default:
return -ENOTTY;
}
if (flags & PERF_IOC_FLAG_GROUP)
perf_event_for_each(event, func);
else
perf_event_for_each_child(event, func);
return 0;
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: chrand_principal3_2_svc(chrand3_arg *arg, struct svc_req *rqstp)
{
static chrand_ret ret;
krb5_keyblock *k;
int nkeys;
char *prime_arg, *funcname;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_chrand_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
funcname = "kadm5_randkey_principal";
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 = randkey_principal_wrapper_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
&k, &nkeys);
} else if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_CHANGEPW, arg->princ, NULL)) {
ret.code = kadm5_randkey_principal_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
&k, &nkeys);
} else {
log_unauth(funcname, prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_CHANGEPW;
}
if(ret.code == KADM5_OK) {
ret.keys = k;
ret.n_keys = nkeys;
}
if(ret.code != KADM5_AUTH_CHANGEPW) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done(funcname, prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
nsecs_t currentTime) {
if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
return currentTime - mInputTargetWaitStartTime;
}
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: gfx::Size LockScreenMediaControlsView::CalculatePreferredSize() const {
return gfx::Size(kMediaControlsTotalWidthDp, kMediaControlsTotalHeightDp);
}
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 LockContentsView::OnUsersChanged(
const std::vector<mojom::LoginUserInfoPtr>& users) {
main_view_->RemoveAllChildViews(true /*delete_children*/);
opt_secondary_big_view_ = nullptr;
users_list_ = nullptr;
rotation_actions_.clear();
users_.clear();
if (users.empty()) {
LOG_IF(FATAL, screen_type_ != LockScreen::ScreenType::kLogin)
<< "Empty user list received";
Shell::Get()->login_screen_controller()->ShowGaiaSignin(
false /*can_close*/, base::nullopt /*prefilled_account*/);
return;
}
for (const mojom::LoginUserInfoPtr& user : users) {
UserState state(user->basic_user_info->account_id);
state.fingerprint_state = user->allow_fingerprint_unlock
? mojom::FingerprintUnlockState::AVAILABLE
: mojom::FingerprintUnlockState::UNAVAILABLE;
users_.push_back(std::move(state));
}
auto box_layout =
std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal);
main_layout_ = box_layout.get();
main_layout_->set_main_axis_alignment(
views::BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER);
main_layout_->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER);
main_view_->SetLayoutManager(std::move(box_layout));
primary_big_view_ = AllocateLoginBigUserView(users[0], true /*is_primary*/);
main_view_->AddChildView(primary_big_view_);
if (users.size() == 2)
CreateLowDensityLayout(users);
else if (users.size() >= 3 && users.size() <= 6)
CreateMediumDensityLayout(users);
else if (users.size() >= 7)
CreateHighDensityLayout(users);
LayoutAuth(primary_big_view_, opt_secondary_big_view_, false /*animate*/);
OnBigUserChanged();
PreferredSizeChanged();
Layout();
}
CWE ID:
Target: 1
Example 2:
Code: static void TerminateWorkerOnIOThread(scoped_refptr<WorkerData> worker_data) {
if (WorkerService::GetInstance()->TerminateWorker(
worker_data->worker_process_id, worker_data->worker_route_id)) {
WorkerService::GetInstance()->AddObserver(
new WorkerTerminationObserver(worker_data.get()));
return;
}
FAIL() << "Failed to terminate worker.\n";
}
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 RenderFrameImpl::didChangeThemeColor() {
if (frame_->parent())
return;
Send(new FrameHostMsg_DidChangeThemeColor(
routing_id_, frame_->document().themeColor()));
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void testTimeout(void* self)
{
CCLayerTreeHostTest* test = static_cast<CCLayerTreeHostTest*>(self);
if (!test->m_running)
return;
test->m_timedOut = true;
test->endTest();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: build_auth_pack(krb5_context context,
unsigned nonce,
krb5_pk_init_ctx ctx,
const KDC_REQ_BODY *body,
AuthPack *a)
{
size_t buf_size, len = 0;
krb5_error_code ret;
void *buf;
krb5_timestamp sec;
int32_t usec;
Checksum checksum;
krb5_clear_error_message(context);
memset(&checksum, 0, sizeof(checksum));
krb5_us_timeofday(context, &sec, &usec);
a->pkAuthenticator.ctime = sec;
a->pkAuthenticator.nonce = nonce;
ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, body, &len, ret);
if (ret)
return ret;
if (buf_size != len)
krb5_abortx(context, "internal error in ASN.1 encoder");
ret = krb5_create_checksum(context,
NULL,
0,
CKSUMTYPE_SHA1,
buf,
len,
&checksum);
free(buf);
if (ret)
return ret;
ALLOC(a->pkAuthenticator.paChecksum, 1);
if (a->pkAuthenticator.paChecksum == NULL) {
return krb5_enomem(context);
}
ret = krb5_data_copy(a->pkAuthenticator.paChecksum,
checksum.checksum.data, checksum.checksum.length);
free_Checksum(&checksum);
if (ret)
return ret;
if (ctx->keyex == USE_DH || ctx->keyex == USE_ECDH) {
const char *moduli_file;
unsigned long dh_min_bits;
krb5_data dhbuf;
size_t size = 0;
krb5_data_zero(&dhbuf);
moduli_file = krb5_config_get_string(context, NULL,
"libdefaults",
"moduli",
NULL);
dh_min_bits =
krb5_config_get_int_default(context, NULL, 0,
"libdefaults",
"pkinit_dh_min_bits",
NULL);
ret = _krb5_parse_moduli(context, moduli_file, &ctx->m);
if (ret)
return ret;
ctx->u.dh = DH_new();
if (ctx->u.dh == NULL)
return krb5_enomem(context);
ret = select_dh_group(context, ctx->u.dh, dh_min_bits, ctx->m);
if (ret)
return ret;
if (DH_generate_key(ctx->u.dh) != 1) {
krb5_set_error_message(context, ENOMEM,
N_("pkinit: failed to generate DH key", ""));
return ENOMEM;
}
if (1 /* support_cached_dh */) {
ALLOC(a->clientDHNonce, 1);
if (a->clientDHNonce == NULL) {
krb5_clear_error_message(context);
return ENOMEM;
}
ret = krb5_data_alloc(a->clientDHNonce, 40);
if (a->clientDHNonce == NULL) {
krb5_clear_error_message(context);
return ret;
}
RAND_bytes(a->clientDHNonce->data, a->clientDHNonce->length);
ret = krb5_copy_data(context, a->clientDHNonce,
&ctx->clientDHNonce);
if (ret)
return ret;
}
ALLOC(a->clientPublicValue, 1);
if (a->clientPublicValue == NULL)
return ENOMEM;
if (ctx->keyex == USE_DH) {
DH *dh = ctx->u.dh;
DomainParameters dp;
heim_integer dh_pub_key;
ret = der_copy_oid(&asn1_oid_id_dhpublicnumber,
&a->clientPublicValue->algorithm.algorithm);
if (ret)
return ret;
memset(&dp, 0, sizeof(dp));
ret = BN_to_integer(context, dh->p, &dp.p);
if (ret) {
free_DomainParameters(&dp);
return ret;
}
ret = BN_to_integer(context, dh->g, &dp.g);
if (ret) {
free_DomainParameters(&dp);
return ret;
}
dp.q = calloc(1, sizeof(*dp.q));
if (dp.q == NULL) {
free_DomainParameters(&dp);
return ENOMEM;
}
ret = BN_to_integer(context, dh->q, dp.q);
if (ret) {
free_DomainParameters(&dp);
return ret;
}
dp.j = NULL;
dp.validationParms = NULL;
a->clientPublicValue->algorithm.parameters =
malloc(sizeof(*a->clientPublicValue->algorithm.parameters));
if (a->clientPublicValue->algorithm.parameters == NULL) {
free_DomainParameters(&dp);
return ret;
}
ASN1_MALLOC_ENCODE(DomainParameters,
a->clientPublicValue->algorithm.parameters->data,
a->clientPublicValue->algorithm.parameters->length,
&dp, &size, ret);
free_DomainParameters(&dp);
if (ret)
return ret;
if (size != a->clientPublicValue->algorithm.parameters->length)
krb5_abortx(context, "Internal ASN1 encoder error");
ret = BN_to_integer(context, dh->pub_key, &dh_pub_key);
if (ret)
return ret;
ASN1_MALLOC_ENCODE(DHPublicKey, dhbuf.data, dhbuf.length,
&dh_pub_key, &size, ret);
der_free_heim_integer(&dh_pub_key);
if (ret)
return ret;
if (size != dhbuf.length)
krb5_abortx(context, "asn1 internal error");
a->clientPublicValue->subjectPublicKey.length = dhbuf.length * 8;
a->clientPublicValue->subjectPublicKey.data = dhbuf.data;
} else if (ctx->keyex == USE_ECDH) {
ret = _krb5_build_authpack_subjectPK_EC(context, ctx, a);
if (ret)
return ret;
} else
krb5_abortx(context, "internal error");
}
{
a->supportedCMSTypes = calloc(1, sizeof(*a->supportedCMSTypes));
if (a->supportedCMSTypes == NULL)
return ENOMEM;
ret = hx509_crypto_available(context->hx509ctx, HX509_SELECT_ALL,
ctx->id->cert,
&a->supportedCMSTypes->val,
&a->supportedCMSTypes->len);
if (ret)
return ret;
}
return ret;
}
CWE ID: CWE-320
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: fbCombineConjointAtopReverseC (CARD32 *dest, CARD32 *src, CARD32 *mask, int width)
{
fbCombineConjointGeneralC (dest, src, mask, width, CombineBAtop);
}
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: void DownloadCoreServiceImpl::SetDownloadManagerDelegateForTesting(
std::unique_ptr<ChromeDownloadManagerDelegate> new_delegate) {
manager_delegate_.swap(new_delegate);
DownloadManager* dm = BrowserContext::GetDownloadManager(profile_);
dm->SetDelegate(manager_delegate_.get());
manager_delegate_->SetDownloadManager(dm);
if (new_delegate)
new_delegate->Shutdown();
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: int32_t AXTree::GetSetSize(const AXNode& node, const AXNode* ordered_set) {
if (ordered_set_info_map_.find(node.id()) == ordered_set_info_map_.end())
ComputeSetSizePosInSetAndCache(node, ordered_set);
return ordered_set_info_map_[node.id()].set_size;
}
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: mrb_vm_define_class(mrb_state *mrb, mrb_value outer, mrb_value super, mrb_sym id)
{
struct RClass *s;
struct RClass *c;
if (!mrb_nil_p(super)) {
if (mrb_type(super) != MRB_TT_CLASS) {
mrb_raisef(mrb, E_TYPE_ERROR, "superclass must be a Class (%S given)",
mrb_inspect(mrb, super));
}
s = mrb_class_ptr(super);
}
else {
s = 0;
}
check_if_class_or_module(mrb, outer);
if (mrb_const_defined_at(mrb, outer, id)) {
mrb_value old = mrb_const_get(mrb, outer, id);
if (mrb_type(old) != MRB_TT_CLASS) {
mrb_raisef(mrb, E_TYPE_ERROR, "%S is not a class", mrb_inspect(mrb, old));
}
c = mrb_class_ptr(old);
if (s) {
/* check super class */
if (mrb_class_real(c->super) != s) {
mrb_raisef(mrb, E_TYPE_ERROR, "superclass mismatch for class %S", old);
}
}
return c;
}
c = define_class(mrb, id, s, mrb_class_ptr(outer));
mrb_class_inherited(mrb, mrb_class_real(c->super), c);
return c;
}
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: GDataFile::GDataFile(GDataDirectory* parent,
GDataDirectoryService* directory_service)
: GDataEntry(parent, directory_service),
kind_(DocumentEntry::UNKNOWN),
is_hosted_document_(false) {
file_info_.is_directory = false;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void HighEntropyAttributeWithMeasureAsAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.Holder();
TestObject* impl = V8TestObject::ToImpl(holder);
V8SetReturnValueString(info, impl->highEntropyAttributeWithMeasureAs(), info.GetIsolate());
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cliprdr_process(STREAM s)
{
uint16 type, status;
uint32 length, format;
uint8 *data;
in_uint16_le(s, type);
in_uint16_le(s, status);
in_uint32_le(s, length);
data = s->p;
logger(Clipboard, Debug, "cliprdr_process(), type=%d, status=%d, length=%d", type, status,
length);
if (status == CLIPRDR_ERROR)
{
switch (type)
{
case CLIPRDR_FORMAT_ACK:
/* FIXME: We seem to get this when we send an announce while the server is
still processing a paste. Try sending another announce. */
cliprdr_send_native_format_announce(last_formats,
last_formats_length);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_request_failed();
break;
default:
logger(Clipboard, Warning,
"cliprdr_process(), unhandled error (type=%d)", type);
}
return;
}
switch (type)
{
case CLIPRDR_CONNECT:
ui_clip_sync();
break;
case CLIPRDR_FORMAT_ANNOUNCE:
ui_clip_format_announce(data, length);
cliprdr_send_packet(CLIPRDR_FORMAT_ACK, CLIPRDR_RESPONSE, NULL, 0);
return;
case CLIPRDR_FORMAT_ACK:
break;
case CLIPRDR_DATA_REQUEST:
in_uint32_le(s, format);
ui_clip_request_data(format);
break;
case CLIPRDR_DATA_RESPONSE:
ui_clip_handle_data(data, length);
break;
case 7: /* TODO: W2K3 SP1 sends this on connect with a value of 1 */
break;
default:
logger(Clipboard, Warning, "cliprdr_process(), unhandled packet type %d",
type);
}
}
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 void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
tx_type_ = GET_PARAM(2);
pitch_ = 4;
fwd_txfm_ref = fht4x4_ref;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void ExecuteScriptAndCheckNavigation(
RenderFrameHost* rfh,
const std::string& javascript,
ExpectedNavigationStatus expected_navigation_status) {
const GURL original_url(shell()->web_contents()->GetLastCommittedURL());
const std::string expected_message;
DataURLWarningConsoleObserverDelegate console_delegate(
shell()->web_contents(), expected_navigation_status);
shell()->web_contents()->SetDelegate(&console_delegate);
TestNavigationObserver navigation_observer(shell()->web_contents());
EXPECT_TRUE(ExecuteScript(rfh, javascript));
console_delegate.Wait();
EXPECT_FALSE(console_delegate.saw_failure_message());
shell()->web_contents()->SetDelegate(nullptr);
switch (expected_navigation_status) {
case NAVIGATION_ALLOWED:
navigation_observer.Wait();
EXPECT_TRUE(shell()->web_contents()->GetLastCommittedURL().SchemeIs(
url::kDataScheme));
EXPECT_TRUE(navigation_observer.last_navigation_url().SchemeIs(
url::kDataScheme));
EXPECT_TRUE(navigation_observer.last_navigation_succeeded());
break;
case NAVIGATION_BLOCKED:
EXPECT_EQ(original_url, shell()->web_contents()->GetLastCommittedURL());
EXPECT_FALSE(navigation_observer.last_navigation_succeeded());
break;
default:
NOTREACHED();
}
}
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: validate_as_request(kdc_realm_t *kdc_active_realm,
register krb5_kdc_req *request, krb5_db_entry client,
krb5_db_entry server, krb5_timestamp kdc_time,
const char **status, krb5_pa_data ***e_data)
{
int errcode;
krb5_error_code ret;
/*
* If an option is set that is only allowed in TGS requests, complain.
*/
if (request->kdc_options & AS_INVALID_OPTIONS) {
*status = "INVALID AS OPTIONS";
return KDC_ERR_BADOPTION;
}
/* The client must not be expired */
if (client.expiration && client.expiration < kdc_time) {
*status = "CLIENT EXPIRED";
if (vague_errors)
return(KRB_ERR_GENERIC);
else
return(KDC_ERR_NAME_EXP);
}
/* The client's password must not be expired, unless the server is
a KRB5_KDC_PWCHANGE_SERVICE. */
if (client.pw_expiration && client.pw_expiration < kdc_time &&
!isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {
*status = "CLIENT KEY EXPIRED";
if (vague_errors)
return(KRB_ERR_GENERIC);
else
return(KDC_ERR_KEY_EXP);
}
/* The server must not be expired */
if (server.expiration && server.expiration < kdc_time) {
*status = "SERVICE EXPIRED";
return(KDC_ERR_SERVICE_EXP);
}
/*
* If the client requires password changing, then only allow the
* pwchange service.
*/
if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) &&
!isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {
*status = "REQUIRED PWCHANGE";
return(KDC_ERR_KEY_EXP);
}
/* Client and server must allow postdating tickets */
if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) ||
isflagset(request->kdc_options, KDC_OPT_POSTDATED)) &&
(isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) ||
isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) {
*status = "POSTDATE NOT ALLOWED";
return(KDC_ERR_CANNOT_POSTDATE);
}
/*
* A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of
* KDC_ERR_POLICY in the following case:
*
* - KDC_OPT_FORWARDABLE is set in KDCOptions but local
* policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the
* client, and;
* - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but
* preauthentication data is absent in the request.
*
* Hence, this check most be done after the check for preauth
* data, and is now performed by validate_forwardable() (the
* contents of which were previously below).
*/
/* Client and server must allow proxiable tickets */
if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) &&
(isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) ||
isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) {
*status = "PROXIABLE NOT ALLOWED";
return(KDC_ERR_POLICY);
}
/* Check to see if client is locked out */
if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {
*status = "CLIENT LOCKED OUT";
return(KDC_ERR_CLIENT_REVOKED);
}
/* Check to see if server is locked out */
if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {
*status = "SERVICE LOCKED OUT";
return(KDC_ERR_S_PRINCIPAL_UNKNOWN);
}
/* Check to see if server is allowed to be a service */
if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) {
*status = "SERVICE NOT ALLOWED";
return(KDC_ERR_MUST_USE_USER2USER);
}
if (check_anon(kdc_active_realm, request->client, request->server) != 0) {
*status = "ANONYMOUS NOT ALLOWED";
return(KDC_ERR_POLICY);
}
/* Perform KDB module policy checks. */
ret = krb5_db_check_policy_as(kdc_context, request, &client, &server,
kdc_time, status, e_data);
if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP)
return errcode_to_protocol(ret);
/* Check against local policy. */
errcode = against_local_policy_as(request, client, server,
kdc_time, status, e_data);
if (errcode)
return errcode;
return 0;
}
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: TestPaintArtifact& TestPaintArtifact::ScrollHitTest(
scoped_refptr<const TransformPaintPropertyNode> scroll_offset) {
return ScrollHitTest(NewClient(), scroll_offset);
}
CWE ID:
Target: 1
Example 2:
Code: static int cancel_discovery(void)
{
/* sanity check */
if (interface_ready() == FALSE)
return BT_STATUS_NOT_READY;
return btif_dm_cancel_discovery();
}
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: forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
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: CSSStyleRule* InspectorCSSOMWrappers::getWrapperForRuleInSheets(StyleRule* rule, StyleEngine* styleSheetCollection)
{
if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::simpleDefaultStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::defaultStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::quirksStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::svgStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::mediaControlsStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::fullscreenStyleSheet);
collectFromStyleEngine(styleSheetCollection);
}
return m_styleRuleToCSSOMWrapperMap.get(rule);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int FAST_FUNC read_str(const char *line, void *arg)
{
char **dest = arg;
free(*dest);
*dest = xstrdup(line);
return 1;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void jmp_rel(struct x86_emulate_ctxt *ctxt, int rel)
{
assign_eip_near(ctxt, ctxt->_eip + rel);
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void WillDispatchTabUpdatedEvent(WebContents* contents,
Profile* profile,
const Extension* extension,
ListValue* event_args) {
DictionaryValue* tab_value = ExtensionTabUtil::CreateTabValue(
contents, extension);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
unsigned long nr_pages,
const void __user * __user *pages,
const int __user *nodes,
int __user *status, int flags)
{
struct page_to_node *pm;
unsigned long chunk_nr_pages;
unsigned long chunk_start;
int err;
err = -ENOMEM;
pm = (struct page_to_node *)__get_free_page(GFP_KERNEL);
if (!pm)
goto out;
migrate_prep();
/*
* Store a chunk of page_to_node array in a page,
* but keep the last one as a marker
*/
chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1;
for (chunk_start = 0;
chunk_start < nr_pages;
chunk_start += chunk_nr_pages) {
int j;
if (chunk_start + chunk_nr_pages > nr_pages)
chunk_nr_pages = nr_pages - chunk_start;
/* fill the chunk pm with addrs and nodes from user-space */
for (j = 0; j < chunk_nr_pages; j++) {
const void __user *p;
int node;
err = -EFAULT;
if (get_user(p, pages + j + chunk_start))
goto out_pm;
pm[j].addr = (unsigned long) p;
if (get_user(node, nodes + j + chunk_start))
goto out_pm;
err = -ENODEV;
if (node < 0 || node >= MAX_NUMNODES)
goto out_pm;
if (!node_state(node, N_MEMORY))
goto out_pm;
err = -EACCES;
if (!node_isset(node, task_nodes))
goto out_pm;
pm[j].node = node;
}
/* End marker for this chunk */
pm[chunk_nr_pages].node = MAX_NUMNODES;
/* Migrate this chunk */
err = do_move_page_to_node_array(mm, pm,
flags & MPOL_MF_MOVE_ALL);
if (err < 0)
goto out_pm;
/* Return status information */
for (j = 0; j < chunk_nr_pages; j++)
if (put_user(pm[j].status, status + j + chunk_start)) {
err = -EFAULT;
goto out_pm;
}
}
err = 0;
out_pm:
free_page((unsigned long)pm);
out:
return err;
}
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: bool EditorClientBlackBerry::shouldChangeSelectedRange(Range* fromRange, Range* toRange, EAffinity affinity, bool stillSelecting)
{
if (m_webPagePrivate->m_dumpRenderTree)
return m_webPagePrivate->m_dumpRenderTree->shouldChangeSelectedDOMRangeToDOMRangeAffinityStillSelecting(fromRange, toRange, static_cast<int>(affinity), stillSelecting);
Frame* frame = m_webPagePrivate->focusedOrMainFrame();
if (frame && frame->document()) {
if (frame->document()->focusedNode() && frame->document()->focusedNode()->hasTagName(HTMLNames::selectTag))
return false;
if (m_webPagePrivate->m_inputHandler->isInputMode() && fromRange && toRange && (fromRange->startContainer() == toRange->startContainer()))
m_webPagePrivate->m_inputHandler->notifyClientOfKeyboardVisibilityChange(true);
}
return true;
}
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 ExtensionsGuestViewMessageFilter::ResumeAttachOrDestroy(
int32_t element_instance_id,
int32_t plugin_frame_routing_id) {
auto it = frame_navigation_helpers_.find(element_instance_id);
if (it == frame_navigation_helpers_.end()) {
return;
}
auto* plugin_rfh = content::RenderFrameHost::FromID(render_process_id_,
plugin_frame_routing_id);
auto* helper = it->second.get();
auto* guest_view = helper->GetGuestView();
if (!guest_view)
return;
if (plugin_rfh) {
DCHECK(
guest_view->web_contents()->CanAttachToOuterContentsFrame(plugin_rfh));
guest_view->AttachToOuterWebContentsFrame(plugin_rfh, element_instance_id,
helper->is_full_page_plugin());
} else {
guest_view->GetEmbedderFrame()->Send(
new ExtensionsGuestViewMsg_DestroyFrameContainer(element_instance_id));
guest_view->Destroy(true);
}
frame_navigation_helpers_.erase(element_instance_id);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: void reference2_16x16_idct_2d(double *input, double *output) {
double x;
for (int l = 0; l < 16; ++l) {
for (int k = 0; k < 16; ++k) {
double s = 0;
for (int i = 0; i < 16; ++i) {
for (int j = 0; j < 16; ++j) {
x = cos(PI * j * (l + 0.5) / 16.0) *
cos(PI * i * (k + 0.5) / 16.0) *
input[i * 16 + j] / 256;
if (i != 0)
x *= sqrt(2.0);
if (j != 0)
x *= sqrt(2.0);
s += x;
}
}
output[k*16+l] = 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: void AutofillDialogViews::SuggestedButton::OnPaint(gfx::Canvas* canvas) {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
const gfx::Insets insets = GetInsets();
canvas->DrawImageInt(*rb.GetImageSkiaNamed(ResourceIDForState()),
insets.left(), insets.top());
views::Painter::PaintFocusPainter(this, canvas, focus_painter());
}
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: cJSON *cJSON_CreateInt( int64_t num )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_Number;
item->valuefloat = num;
item->valueint = num;
}
return item;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static jpc_dec_importopts_t *jpc_dec_opts_create(const char *optstr)
{
jpc_dec_importopts_t *opts;
jas_tvparser_t *tvp;
opts = 0;
if (!(opts = jas_malloc(sizeof(jpc_dec_importopts_t)))) {
goto error;
}
opts->debug = 0;
opts->maxlyrs = JPC_MAXLYRS;
opts->maxpkts = -1;
opts->max_samples = JAS_DEC_DEFAULT_MAX_SAMPLES;
if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
goto error;
}
while (!jas_tvparser_next(tvp)) {
switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts,
jas_tvparser_gettag(tvp)))->id) {
case OPT_MAXLYRS:
opts->maxlyrs = atoi(jas_tvparser_getval(tvp));
break;
case OPT_DEBUG:
opts->debug = atoi(jas_tvparser_getval(tvp));
break;
case OPT_MAXPKTS:
opts->maxpkts = atoi(jas_tvparser_getval(tvp));
break;
case OPT_MAXSAMPLES:
opts->max_samples = strtoull(jas_tvparser_getval(tvp), 0, 10);
break;
default:
jas_eprintf("warning: ignoring invalid option %s\n",
jas_tvparser_gettag(tvp));
break;
}
}
jas_tvparser_destroy(tvp);
return opts;
error:
if (opts) {
jpc_dec_opts_destroy(opts);
}
return 0;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BaseShadow::emailRemoveEvent( const char* reason )
{
Email mailer;
mailer.sendRemove( jobAd, reason );
}
CWE ID: CWE-134
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long vhost_dev_ioctl(struct vhost_dev *d, unsigned int ioctl, void __user *argp)
{
struct file *eventfp, *filep = NULL;
struct eventfd_ctx *ctx = NULL;
u64 p;
long r;
int i, fd;
/* If you are not the owner, you can become one */
if (ioctl == VHOST_SET_OWNER) {
r = vhost_dev_set_owner(d);
goto done;
}
/* You must be the owner to do anything else */
r = vhost_dev_check_owner(d);
if (r)
goto done;
switch (ioctl) {
case VHOST_SET_MEM_TABLE:
r = vhost_set_memory(d, argp);
break;
case VHOST_SET_LOG_BASE:
if (copy_from_user(&p, argp, sizeof p)) {
r = -EFAULT;
break;
}
if ((u64)(unsigned long)p != p) {
r = -EFAULT;
break;
}
for (i = 0; i < d->nvqs; ++i) {
struct vhost_virtqueue *vq;
void __user *base = (void __user *)(unsigned long)p;
vq = d->vqs[i];
mutex_lock(&vq->mutex);
/* If ring is inactive, will check when it's enabled. */
if (vq->private_data && !vq_log_access_ok(vq, base))
r = -EFAULT;
else
vq->log_base = base;
mutex_unlock(&vq->mutex);
}
break;
case VHOST_SET_LOG_FD:
r = get_user(fd, (int __user *)argp);
if (r < 0)
break;
eventfp = fd == -1 ? NULL : eventfd_fget(fd);
if (IS_ERR(eventfp)) {
r = PTR_ERR(eventfp);
break;
}
if (eventfp != d->log_file) {
filep = d->log_file;
ctx = d->log_ctx;
d->log_ctx = eventfp ?
eventfd_ctx_fileget(eventfp) : NULL;
} else
filep = eventfp;
for (i = 0; i < d->nvqs; ++i) {
mutex_lock(&d->vqs[i]->mutex);
d->vqs[i]->log_ctx = d->log_ctx;
mutex_unlock(&d->vqs[i]->mutex);
}
if (ctx)
eventfd_ctx_put(ctx);
if (filep)
fput(filep);
break;
default:
r = -ENOIOCTLCMD;
break;
}
done:
return r;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void codeDistinct(
Parse *pParse, /* Parsing and code generating context */
int iTab, /* A sorting index used to test for distinctness */
int addrRepeat, /* Jump to here if not distinct */
int N, /* Number of elements */
int iMem /* First element */
){
Vdbe *v;
int r1;
v = pParse->pVdbe;
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
sqlite3ReleaseTempReg(pParse, r1);
}
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: ImportSingleTIFF_SByte ( const TIFF_Manager::TagInfo & tagInfo,
SXMPMeta * xmp, const char * xmpNS, const char * xmpProp )
{
try { // Don't let errors with one stop the others.
XMP_Int8 binValue = *((XMP_Int8*)tagInfo.dataPtr);
char strValue[20];
snprintf ( strValue, sizeof(strValue), "%hd", (short)binValue ); // AUDIT: Using sizeof(strValue) is safe.
xmp->SetProperty ( xmpNS, xmpProp, strValue );
} catch ( ... ) {
}
} // ImportSingleTIFF_SByte
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: Chapters::Atom::Atom()
{
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int FS_Seek( fileHandle_t f, long offset, int origin ) {
int _origin;
if ( !fs_searchpaths ) {
Com_Error( ERR_FATAL, "Filesystem call made without initialization" );
return -1;
}
if ( fsh[f].streamed ) {
int r;
fsh[f].streamed = qfalse;
r = FS_Seek( f, offset, origin );
fsh[f].streamed = qtrue;
return r;
}
if ( fsh[f].zipFile == qtrue ) {
byte buffer[PK3_SEEK_BUFFER_SIZE];
int remainder;
int currentPosition = FS_FTell( f );
if ( offset < 0 ) {
switch( origin ) {
case FS_SEEK_END:
remainder = fsh[f].zipFileLen + offset;
break;
case FS_SEEK_CUR:
remainder = currentPosition + offset;
break;
case FS_SEEK_SET:
default:
remainder = 0;
break;
}
if ( remainder < 0 ) {
remainder = 0;
}
origin = FS_SEEK_SET;
} else {
if ( origin == FS_SEEK_END ) {
remainder = fsh[f].zipFileLen - currentPosition + offset;
} else {
remainder = offset;
}
}
switch( origin ) {
case FS_SEEK_SET:
if ( remainder == currentPosition ) {
return offset;
}
unzSetOffset(fsh[f].handleFiles.file.z, fsh[f].zipFilePos);
unzOpenCurrentFile(fsh[f].handleFiles.file.z);
case FS_SEEK_END:
case FS_SEEK_CUR:
while( remainder > PK3_SEEK_BUFFER_SIZE ) {
FS_Read( buffer, PK3_SEEK_BUFFER_SIZE, f );
remainder -= PK3_SEEK_BUFFER_SIZE;
}
FS_Read( buffer, remainder, f );
return offset;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
return -1;
}
} else {
FILE *file;
file = FS_FileForHandle( f );
switch ( origin ) {
case FS_SEEK_CUR:
_origin = SEEK_CUR;
break;
case FS_SEEK_END:
_origin = SEEK_END;
break;
case FS_SEEK_SET:
_origin = SEEK_SET;
break;
default:
Com_Error( ERR_FATAL, "Bad origin in FS_Seek" );
break;
}
return fseek( file, offset, _origin );
}
}
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 int __hw_perf_event_init(struct perf_event *event)
{
struct perf_event_attr *attr = &event->attr;
struct hw_perf_event *hwc = &event->hw;
struct perf_event *evts[MAX_HWEVENTS];
unsigned long evtypes[MAX_HWEVENTS];
int idx_rubbish_bin[MAX_HWEVENTS];
int ev;
int n;
/* We only support a limited range of HARDWARE event types with one
* only programmable via a RAW event type.
*/
if (attr->type == PERF_TYPE_HARDWARE) {
if (attr->config >= alpha_pmu->max_events)
return -EINVAL;
ev = alpha_pmu->event_map[attr->config];
} else if (attr->type == PERF_TYPE_HW_CACHE) {
return -EOPNOTSUPP;
} else if (attr->type == PERF_TYPE_RAW) {
ev = attr->config & 0xff;
} else {
return -EOPNOTSUPP;
}
if (ev < 0) {
return ev;
}
/* The EV67 does not support mode exclusion */
if (attr->exclude_kernel || attr->exclude_user
|| attr->exclude_hv || attr->exclude_idle) {
return -EPERM;
}
/*
* We place the event type in event_base here and leave calculation
* of the codes to programme the PMU for alpha_pmu_enable() because
* it is only then we will know what HW events are actually
* scheduled on to the PMU. At that point the code to programme the
* PMU is put into config_base and the PMC to use is placed into
* idx. We initialise idx (below) to PMC_NO_INDEX to indicate that
* it is yet to be determined.
*/
hwc->event_base = ev;
/* Collect events in a group together suitable for calling
* alpha_check_constraints() to verify that the group as a whole can
* be scheduled on to the PMU.
*/
n = 0;
if (event->group_leader != event) {
n = collect_events(event->group_leader,
alpha_pmu->num_pmcs - 1,
evts, evtypes, idx_rubbish_bin);
if (n < 0)
return -EINVAL;
}
evtypes[n] = hwc->event_base;
evts[n] = event;
if (alpha_check_constraints(evts, evtypes, n + 1))
return -EINVAL;
/* Indicate that PMU config and idx are yet to be determined. */
hwc->config_base = 0;
hwc->idx = PMC_NO_INDEX;
event->destroy = hw_perf_event_destroy;
/*
* Most architectures reserve the PMU for their use at this point.
* As there is no existing mechanism to arbitrate usage and there
* appears to be no other user of the Alpha PMU we just assume
* that we can just use it, hence a NO-OP here.
*
* Maybe an alpha_reserve_pmu() routine should be implemented but is
* anything else ever going to use it?
*/
if (!hwc->sample_period) {
hwc->sample_period = alpha_pmu->pmc_max_period[0];
hwc->last_period = hwc->sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
}
return 0;
}
CWE ID: CWE-399
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void * CAPSTONE_API cs_winkernel_malloc(size_t size)
{
NT_ASSERT(size);
#pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory
CS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag(
NonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG);
if (!block) {
return NULL;
}
block->size = size;
return block->data;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static void nfs4_init_opendata_res(struct nfs4_opendata *p)
{
p->o_res.f_attr = &p->f_attr;
p->o_res.dir_attr = &p->dir_attr;
p->o_res.seqid = p->o_arg.seqid;
p->c_res.seqid = p->c_arg.seqid;
p->o_res.server = p->o_arg.server;
nfs_fattr_init(&p->f_attr);
nfs_fattr_init(&p->dir_attr);
}
CWE ID: CWE-189
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool ChromeDownloadManagerDelegate::IsDangerousFile(
const DownloadItem& download,
const FilePath& suggested_path,
bool visited_referrer_before) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (download.GetTransitionType() & content::PAGE_TRANSITION_FROM_ADDRESS_BAR)
return false;
if (extensions::FeatureSwitch::easy_off_store_install()->IsEnabled() &&
download_crx_util::IsExtensionDownload(download) &&
!extensions::WebstoreInstaller::GetAssociatedApproval(download)) {
return true;
}
if (ShouldOpenFileBasedOnExtension(suggested_path) &&
download.HasUserGesture())
return false;
download_util::DownloadDangerLevel danger_level =
download_util::GetFileDangerLevel(suggested_path.BaseName());
if (danger_level == download_util::AllowOnUserGesture)
return !download.HasUserGesture() || !visited_referrer_before;
return danger_level == download_util::Dangerous;
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static const ut8 *r_bin_dwarf_parse_attr_value(const ut8 *obuf, int obuf_len,
RBinDwarfAttrSpec *spec, RBinDwarfAttrValue *value,
const RBinDwarfCompUnitHdr *hdr,
const ut8 *debug_str, size_t debug_str_len) {
const ut8 *buf = obuf;
const ut8 *buf_end = obuf + obuf_len;
size_t j;
if (!spec || !value || !hdr || !obuf || obuf_len < 0) {
return NULL;
}
value->form = spec->attr_form;
value->name = spec->attr_name;
value->encoding.block.data = NULL;
value->encoding.str_struct.string = NULL;
value->encoding.str_struct.offset = 0;
switch (spec->attr_form) {
case DW_FORM_addr:
switch (hdr->pointer_size) {
case 1:
value->encoding.address = READ (buf, ut8);
break;
case 2:
value->encoding.address = READ (buf, ut16);
break;
case 4:
value->encoding.address = READ (buf, ut32);
break;
case 8:
value->encoding.address = READ (buf, ut64);
break;
default:
eprintf("DWARF: Unexpected pointer size: %u\n", (unsigned)hdr->pointer_size);
return NULL;
}
break;
case DW_FORM_block2:
value->encoding.block.length = READ (buf, ut16);
if (value->encoding.block.length > 0) {
value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
}
break;
case DW_FORM_block4:
value->encoding.block.length = READ (buf, ut32);
if (value->encoding.block.length > 0) {
ut8 *data = calloc (sizeof (ut8), value->encoding.block.length);
if (data) {
for (j = 0; j < value->encoding.block.length; j++) {
data[j] = READ (buf, ut8);
}
}
value->encoding.block.data = data;
}
break;
//// This causes segfaults to happen
case DW_FORM_data2:
value->encoding.data = READ (buf, ut16);
break;
case DW_FORM_data4:
value->encoding.data = READ (buf, ut32);
break;
case DW_FORM_data8:
value->encoding.data = READ (buf, ut64);
break;
case DW_FORM_string:
value->encoding.str_struct.string = *buf? strdup ((const char*)buf) : NULL;
buf += (strlen ((const char*)buf) + 1);
break;
case DW_FORM_block:
buf = r_uleb128 (buf, buf_end - buf, &value->encoding.block.length);
if (!buf) {
return NULL;
}
value->encoding.block.data = calloc (sizeof(ut8), value->encoding.block.length);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
break;
case DW_FORM_block1:
value->encoding.block.length = READ (buf, ut8);
value->encoding.block.data = calloc (sizeof (ut8), value->encoding.block.length + 1);
for (j = 0; j < value->encoding.block.length; j++) {
value->encoding.block.data[j] = READ (buf, ut8);
}
break;
case DW_FORM_flag:
value->encoding.flag = READ (buf, ut8);
break;
case DW_FORM_sdata:
buf = r_leb128 (buf, &value->encoding.sdata);
break;
case DW_FORM_strp:
value->encoding.str_struct.offset = READ (buf, ut32);
if (debug_str && value->encoding.str_struct.offset < debug_str_len) {
value->encoding.str_struct.string = strdup (
(const char *)(debug_str +
value->encoding.str_struct.offset));
} else {
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_udata:
{
ut64 ndata = 0;
const ut8 *data = (const ut8*)&ndata;
buf = r_uleb128 (buf, R_MIN (sizeof (data), (size_t)(buf_end - buf)), &ndata);
memcpy (&value->encoding.data, data, sizeof (value->encoding.data));
value->encoding.str_struct.string = NULL;
}
break;
case DW_FORM_ref_addr:
value->encoding.reference = READ (buf, ut64); // addr size of machine
break;
case DW_FORM_ref1:
value->encoding.reference = READ (buf, ut8);
break;
case DW_FORM_ref2:
value->encoding.reference = READ (buf, ut16);
break;
case DW_FORM_ref4:
value->encoding.reference = READ (buf, ut32);
break;
case DW_FORM_ref8:
value->encoding.reference = READ (buf, ut64);
break;
case DW_FORM_data1:
value->encoding.data = READ (buf, ut8);
break;
default:
eprintf ("Unknown DW_FORM 0x%02"PFMT64x"\n", spec->attr_form);
value->encoding.data = 0;
return NULL;
}
return buf;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void Chapters::Display::Init() {
m_string = NULL;
m_language = NULL;
m_country = NULL;
}
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 Notification::show()
{
ASSERT(m_state == NotificationStateIdle);
if (Notification::checkPermission(executionContext()) != WebNotificationPermissionAllowed) {
dispatchErrorEvent();
return;
}
SecurityOrigin* origin = executionContext()->securityOrigin();
ASSERT(origin);
notificationManager()->show(WebSecurityOrigin(origin), m_data, this);
m_state = NotificationStateShowing;
}
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: int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *run)
{
int ret;
sigset_t sigsaved;
/* Make sure they initialize the vcpu with KVM_ARM_VCPU_INIT */
if (unlikely(vcpu->arch.target < 0))
return -ENOEXEC;
ret = kvm_vcpu_first_run_init(vcpu);
if (ret)
return ret;
if (run->exit_reason == KVM_EXIT_MMIO) {
ret = kvm_handle_mmio_return(vcpu, vcpu->run);
if (ret)
return ret;
}
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
ret = 1;
run->exit_reason = KVM_EXIT_UNKNOWN;
while (ret > 0) {
/*
* Check conditions before entering the guest
*/
cond_resched();
update_vttbr(vcpu->kvm);
if (vcpu->arch.pause)
vcpu_pause(vcpu);
kvm_vgic_flush_hwstate(vcpu);
kvm_timer_flush_hwstate(vcpu);
local_irq_disable();
/*
* Re-check atomic conditions
*/
if (signal_pending(current)) {
ret = -EINTR;
run->exit_reason = KVM_EXIT_INTR;
}
if (ret <= 0 || need_new_vmid_gen(vcpu->kvm)) {
local_irq_enable();
kvm_timer_sync_hwstate(vcpu);
kvm_vgic_sync_hwstate(vcpu);
continue;
}
/**************************************************************
* Enter the guest
*/
trace_kvm_entry(*vcpu_pc(vcpu));
kvm_guest_enter();
vcpu->mode = IN_GUEST_MODE;
ret = kvm_call_hyp(__kvm_vcpu_run, vcpu);
vcpu->mode = OUTSIDE_GUEST_MODE;
vcpu->arch.last_pcpu = smp_processor_id();
kvm_guest_exit();
trace_kvm_exit(*vcpu_pc(vcpu));
/*
* We may have taken a host interrupt in HYP mode (ie
* while executing the guest). This interrupt is still
* pending, as we haven't serviced it yet!
*
* We're now back in SVC mode, with interrupts
* disabled. Enabling the interrupts now will have
* the effect of taking the interrupt again, in SVC
* mode this time.
*/
local_irq_enable();
/*
* Back from guest
*************************************************************/
kvm_timer_sync_hwstate(vcpu);
kvm_vgic_sync_hwstate(vcpu);
ret = handle_exit(vcpu, run, ret);
}
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
return ret;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool ExtensionService::IsDownloadFromMiniGallery(const GURL& download_url) {
return StartsWithASCII(download_url.spec(),
extension_urls::kMiniGalleryDownloadPrefix,
false); // case_sensitive
}
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 x25_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
struct x25_sock *x25 = x25_sk(sk);
struct sockaddr_x25 *sx25 = (struct sockaddr_x25 *)msg->msg_name;
size_t copied;
int qbit, header_len;
struct sk_buff *skb;
unsigned char *asmptr;
int rc = -ENOTCONN;
lock_sock(sk);
if (x25->neighbour == NULL)
goto out;
header_len = x25->neighbour->extended ?
X25_EXT_MIN_LEN : X25_STD_MIN_LEN;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
if (flags & MSG_OOB) {
rc = -EINVAL;
if (sock_flag(sk, SOCK_URGINLINE) ||
!skb_peek(&x25->interrupt_in_queue))
goto out;
skb = skb_dequeue(&x25->interrupt_in_queue);
if (!pskb_may_pull(skb, X25_STD_MIN_LEN))
goto out_free_dgram;
skb_pull(skb, X25_STD_MIN_LEN);
/*
* No Q bit information on Interrupt data.
*/
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = 0x00;
}
msg->msg_flags |= MSG_OOB;
} else {
/* Now we can treat all alike */
release_sock(sk);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &rc);
lock_sock(sk);
if (!skb)
goto out;
if (!pskb_may_pull(skb, header_len))
goto out_free_dgram;
qbit = (skb->data[0] & X25_Q_BIT) == X25_Q_BIT;
skb_pull(skb, header_len);
if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) {
asmptr = skb_push(skb, 1);
*asmptr = qbit;
}
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
/* Currently, each datagram always contains a complete record */
msg->msg_flags |= MSG_EOR;
rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (rc)
goto out_free_dgram;
if (sx25) {
sx25->sx25_family = AF_X25;
sx25->sx25_addr = x25->dest_addr;
}
msg->msg_namelen = sizeof(struct sockaddr_x25);
x25_check_rbuf(sk);
rc = copied;
out_free_dgram:
skb_free_datagram(sk, skb);
out:
release_sock(sk);
return rc;
}
CWE ID: CWE-20
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void tun_net_init(struct net_device *dev)
{
struct tun_struct *tun = netdev_priv(dev);
switch (tun->flags & TUN_TYPE_MASK) {
case TUN_TUN_DEV:
dev->netdev_ops = &tun_netdev_ops;
/* Point-to-Point TUN Device */
dev->hard_header_len = 0;
dev->addr_len = 0;
dev->mtu = 1500;
/* Zero header length */
dev->type = ARPHRD_NONE;
dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
break;
case TUN_TAP_DEV:
dev->netdev_ops = &tap_netdev_ops;
/* Ethernet TAP Device */
ether_setup(dev);
random_ether_addr(dev->dev_addr);
dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */
break;
}
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void conditionalAndLongAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
TestObjectPythonV8Internal::conditionalAndLongAttributeAttributeSetter(jsValue, 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: int drm_mode_addfb(struct drm_device *dev,
void *data, struct drm_file *file_priv)
{
struct drm_mode_fb_cmd *r = data;
struct drm_mode_config *config = &dev->mode_config;
struct drm_framebuffer *fb;
int ret = 0;
if (!drm_core_check_feature(dev, DRIVER_MODESET))
return -EINVAL;
if ((config->min_width > r->width) || (r->width > config->max_width)) {
DRM_ERROR("mode new framebuffer width not within limits\n");
return -EINVAL;
}
if ((config->min_height > r->height) || (r->height > config->max_height)) {
DRM_ERROR("mode new framebuffer height not within limits\n");
return -EINVAL;
}
mutex_lock(&dev->mode_config.mutex);
/* TODO check buffer is sufficiently large */
/* TODO setup destructor callback */
fb = dev->mode_config.funcs->fb_create(dev, file_priv, r);
if (IS_ERR(fb)) {
DRM_ERROR("could not create framebuffer\n");
ret = PTR_ERR(fb);
goto out;
}
r->fb_id = fb->base.id;
list_add(&fb->filp_head, &file_priv->fbs);
DRM_DEBUG_KMS("[FB:%d]\n", fb->base.id);
out:
mutex_unlock(&dev->mode_config.mutex);
return ret;
}
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: transform_name(int t)
/* The name, if 't' has multiple bits set the name of the lowest set bit is
* returned.
*/
{
unsigned int i;
t &= -t; /* first set bit */
for (i=0; i<TTABLE_SIZE; ++i)
{
if ((transform_info[i].transform & t) != 0)
return transform_info[i].name;
}
return "invalid transform";
}
CWE ID:
Target: 1
Example 2:
Code: int FLTApplyFilterToLayer(FilterEncodingNode *psNode, mapObj *map, int iLayerIndex)
{
layerObj *layer = GET_LAYER(map, iLayerIndex);
if ( ! layer->vtable) {
int rv = msInitializeVirtualTable(layer);
if (rv != MS_SUCCESS)
return rv;
}
return layer->vtable->LayerApplyFilterToLayer(psNode, map, iLayerIndex);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ehci_process_itd(EHCIState *ehci,
EHCIitd *itd,
uint32_t addr)
{
USBDevice *dev;
USBEndpoint *ep;
uint32_t i, len, pid, dir, devaddr, endp;
uint32_t pg, off, ptr1, ptr2, max, mult;
ehci->periodic_sched_active = PERIODIC_ACTIVE;
dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION);
devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR);
endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP);
max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT);
mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT);
for(i = 0; i < 8; i++) {
if (itd->transact[i] & ITD_XACT_ACTIVE) {
pg = get_field(itd->transact[i], ITD_XACT_PGSEL);
off = itd->transact[i] & ITD_XACT_OFFSET_MASK;
ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK);
ptr2 = (itd->bufptr[pg+1] & ITD_BUFPTR_MASK);
len = get_field(itd->transact[i], ITD_XACT_LENGTH);
if (len > max * mult) {
len = max * mult;
}
if (len > BUFF_SIZE) {
return -1;
}
qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as);
if (off + len > 4096) {
/* transfer crosses page border */
uint32_t len2 = off + len - 4096;
uint32_t len1 = len - len2;
qemu_sglist_add(&ehci->isgl, ptr1 + off, len1);
qemu_sglist_add(&ehci->isgl, ptr2, len2);
} else {
qemu_sglist_add(&ehci->isgl, ptr1 + off, len);
}
pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT;
dev = ehci_find_device(ehci, devaddr);
ep = usb_ep_get(dev, pid, endp);
if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) {
usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false,
(itd->transact[i] & ITD_XACT_IOC) != 0);
usb_packet_map(&ehci->ipacket, &ehci->isgl);
usb_handle_packet(dev, &ehci->ipacket);
usb_packet_unmap(&ehci->ipacket, &ehci->isgl);
} else {
DPRINTF("ISOCH: attempt to addess non-iso endpoint\n");
ehci->ipacket.status = USB_RET_NAK;
ehci->ipacket.actual_length = 0;
}
qemu_sglist_destroy(&ehci->isgl);
switch (ehci->ipacket.status) {
case USB_RET_SUCCESS:
break;
default:
fprintf(stderr, "Unexpected iso usb result: %d\n",
ehci->ipacket.status);
/* Fall through */
case USB_RET_IOERROR:
case USB_RET_NODEV:
/* 3.3.2: XACTERR is only allowed on IN transactions */
if (dir) {
itd->transact[i] |= ITD_XACT_XACTERR;
ehci_raise_irq(ehci, USBSTS_ERRINT);
}
break;
case USB_RET_BABBLE:
itd->transact[i] |= ITD_XACT_BABBLE;
ehci_raise_irq(ehci, USBSTS_ERRINT);
break;
case USB_RET_NAK:
/* no data for us, so do a zero-length transfer */
ehci->ipacket.actual_length = 0;
break;
}
if (!dir) {
set_field(&itd->transact[i], len - ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* OUT */
} else {
set_field(&itd->transact[i], ehci->ipacket.actual_length,
ITD_XACT_LENGTH); /* IN */
}
if (itd->transact[i] & ITD_XACT_IOC) {
ehci_raise_irq(ehci, USBSTS_INT);
}
itd->transact[i] &= ~ITD_XACT_ACTIVE;
}
}
return 0;
}
CWE ID: CWE-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 test_base64_lengths(void)
{
const char *in = "FuseMuse";
char out1[32];
char out2[32];
size_t enclen;
int declen;
/* Encoding a zero-length string should fail */
enclen = mutt_b64_encode(out1, in, 0, 32);
if (!TEST_CHECK(enclen == 0))
{
TEST_MSG("Expected: %zu", 0);
TEST_MSG("Actual : %zu", enclen);
}
/* Decoding a zero-length string should fail, too */
out1[0] = '\0';
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == -1))
{
TEST_MSG("Expected: %zu", -1);
TEST_MSG("Actual : %zu", declen);
}
/* Encode one to eight bytes, check the lengths of the returned string */
for (size_t i = 1; i <= 8; ++i)
{
enclen = mutt_b64_encode(out1, in, i, 32);
size_t exp = ((i + 2) / 3) << 2;
if (!TEST_CHECK(enclen == exp))
{
TEST_MSG("Expected: %zu", exp);
TEST_MSG("Actual : %zu", enclen);
}
declen = mutt_b64_decode(out2, out1);
if (!TEST_CHECK(declen == i))
{
TEST_MSG("Expected: %zu", i);
TEST_MSG("Actual : %zu", declen);
}
out2[declen] = '\0';
if (!TEST_CHECK(strncmp(out2, in, i) == 0))
{
TEST_MSG("Expected: %s", in);
TEST_MSG("Actual : %s", out2);
}
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
{
if (!request.httpOrigin().isEmpty())
return; // Request already has an Origin header.
if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
return;
if (origin.isEmpty()) {
request.setHTTPOrigin(SecurityOrigin::createUnique()->toString());
return;
}
request.setHTTPOrigin(origin);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_FUNCTION(gmmktime)
{
php_mktime(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
}
CWE ID:
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int gdTransformAffineCopy(gdImagePtr dst,
int dst_x, int dst_y,
const gdImagePtr src,
gdRectPtr src_region,
const double affine[6])
{
int c1x,c1y,c2x,c2y;
int backclip = 0;
int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2;
register int x, y, src_offset_x, src_offset_y;
double inv[6];
int *dst_p;
gdPointF pt, src_pt;
gdRect bbox;
int end_x, end_y;
gdInterpolationMethod interpolation_id_bak = GD_DEFAULT;
interpolation_method interpolation_bak;
/* These methods use special implementations */
if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) {
interpolation_id_bak = src->interpolation_id;
interpolation_bak = src->interpolation;
gdImageSetInterpolationMethod(src, GD_BICUBIC);
}
gdImageClipRectangle(src, src_region);
if (src_region->x > 0 || src_region->y > 0
|| src_region->width < gdImageSX(src)
|| src_region->height < gdImageSY(src)) {
backclip = 1;
gdImageGetClip(src, &backup_clipx1, &backup_clipy1,
&backup_clipx2, &backup_clipy2);
gdImageSetClip(src, src_region->x, src_region->y,
src_region->x + src_region->width - 1,
src_region->y + src_region->height - 1);
}
if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) {
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_FALSE;
}
gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y);
end_x = bbox.width + (int) fabs(bbox.x);
end_y = bbox.height + (int) fabs(bbox.y);
/* Get inverse affine to let us work with destination -> source */
gdAffineInvert(inv, affine);
src_offset_x = src_region->x;
src_offset_y = src_region->y;
if (dst->alphaBlendingFlag) {
for (y = bbox.y; y <= end_y; y++) {
pt.y = y + 0.5;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5;
gdAffineApplyToPointF(&src_pt, &pt, inv);
gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0));
}
}
} else {
for (y = 0; y <= end_y; y++) {
pt.y = y + 0.5 + bbox.y;
if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) {
continue;
}
dst_p = dst->tpixels[dst_y + y] + dst_x;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5 + bbox.x;
gdAffineApplyToPointF(&src_pt, &pt, inv);
if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) {
break;
}
*(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1);
}
}
}
/* Restore clip if required */
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_TRUE;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: int run_lxc_hooks(const char *name, char *hook, struct lxc_conf *conf,
const char *lxcpath, char *argv[])
{
int which = -1;
struct lxc_list *it;
if (strcmp(hook, "pre-start") == 0)
which = LXCHOOK_PRESTART;
else if (strcmp(hook, "pre-mount") == 0)
which = LXCHOOK_PREMOUNT;
else if (strcmp(hook, "mount") == 0)
which = LXCHOOK_MOUNT;
else if (strcmp(hook, "autodev") == 0)
which = LXCHOOK_AUTODEV;
else if (strcmp(hook, "start") == 0)
which = LXCHOOK_START;
else if (strcmp(hook, "post-stop") == 0)
which = LXCHOOK_POSTSTOP;
else if (strcmp(hook, "clone") == 0)
which = LXCHOOK_CLONE;
else if (strcmp(hook, "destroy") == 0)
which = LXCHOOK_DESTROY;
else
return -1;
lxc_list_for_each(it, &conf->hooks[which]) {
int ret;
char *hookname = it->elem;
ret = run_script_argv(name, "lxc", hookname, hook, lxcpath, argv);
if (ret)
return ret;
}
return 0;
}
CWE ID: CWE-59
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: kadm5_randkey_principal_3(void *server_handle,
krb5_principal principal,
krb5_boolean keepold,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
krb5_keyblock **keyblocks,
int *n_keys)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
krb5_int32 now;
kadm5_policy_ent_rec pol;
int ret, last_pwd;
krb5_boolean have_pol = FALSE;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
if (keyblocks)
*keyblocks = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
if (principal == NULL)
return EINVAL;
if ((ret = kdb_get_entry(handle, principal, &kdb, &adb)))
return(ret);
ret = apply_keysalt_policy(handle, adb.policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto done;
if (krb5_principal_compare(handle->context, principal, hist_princ)) {
/* If changing the history entry, the new entry must have exactly one
* key. */
if (keepold)
return KADM5_PROTECT_PRINCIPAL;
new_n_ks_tuple = 1;
}
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto done;
ret = krb5_dbe_crk(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple,
keepold, kdb);
if (ret)
goto done;
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto done;
kdb->attributes &= ~KRB5_KDB_REQUIRES_PWCHANGE;
ret = krb5_timeofday(handle->context, &now);
if (ret)
goto done;
if ((adb.aux_attributes & KADM5_POLICY)) {
ret = get_policy(handle, adb.policy, &pol, &have_pol);
if (ret)
goto done;
}
if (have_pol) {
ret = krb5_dbe_lookup_last_pwd_change(handle->context, kdb, &last_pwd);
if (ret)
goto done;
#if 0
/*
* The spec says this check is overridden if the caller has
* modify privilege. The admin server therefore makes this
* check itself (in chpass_principal_wrapper, misc.c). A
* local caller implicitly has all authorization bits.
*/
if((now - last_pwd) < pol.pw_min_life &&
!(kdb->attributes & KRB5_KDB_REQUIRES_PWCHANGE)) {
ret = KADM5_PASS_TOOSOON;
goto done;
}
#endif
if (pol.pw_max_life)
kdb->pw_expiration = now + pol.pw_max_life;
else
kdb->pw_expiration = 0;
} else {
kdb->pw_expiration = 0;
}
ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now);
if (ret)
goto done;
/* unlock principal on this KDC */
kdb->fail_auth_count = 0;
if (keyblocks) {
ret = decrypt_key_data(handle->context,
kdb->n_key_data, kdb->key_data,
keyblocks, n_keys);
if (ret)
goto done;
}
/* key data changed, let the database provider know */
kdb->mask = KADM5_KEY_DATA | KADM5_FAIL_AUTH_COUNT;
/* | KADM5_RANDKEY_USED */;
ret = k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, principal, keepold,
new_n_ks_tuple, new_ks_tuple, NULL);
if (ret)
goto done;
if ((ret = kdb_put_entry(handle, kdb, &adb)))
goto done;
(void) k5_kadm5_hook_chpass(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, principal,
keepold, new_n_ks_tuple, new_ks_tuple, NULL);
ret = KADM5_OK;
done:
free(new_ks_tuple);
kdb_free_entry(handle, kdb, &adb);
if (have_pol)
kadm5_free_policy_ent(handle->lhandle, &pol);
return ret;
}
CWE ID: CWE-255
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 mount_entry(const char *fsname, const char *target,
const char *fstype, unsigned long mountflags,
const char *data, int optional)
{
#ifdef HAVE_STATVFS
struct statvfs sb;
#endif
if (mount(fsname, target, fstype, mountflags & ~MS_REMOUNT, data)) {
if (optional) {
INFO("failed to mount '%s' on '%s' (optional): %s", fsname,
target, strerror(errno));
return 0;
}
else {
SYSERROR("failed to mount '%s' on '%s'", fsname, target);
return -1;
}
}
if ((mountflags & MS_REMOUNT) || (mountflags & MS_BIND)) {
DEBUG("remounting %s on %s to respect bind or remount options",
fsname ? fsname : "(none)", target ? target : "(none)");
unsigned long rqd_flags = 0;
if (mountflags & MS_RDONLY)
rqd_flags |= MS_RDONLY;
#ifdef HAVE_STATVFS
if (statvfs(fsname, &sb) == 0) {
unsigned long required_flags = rqd_flags;
if (sb.f_flag & MS_NOSUID)
required_flags |= MS_NOSUID;
if (sb.f_flag & MS_NODEV)
required_flags |= MS_NODEV;
if (sb.f_flag & MS_RDONLY)
required_flags |= MS_RDONLY;
if (sb.f_flag & MS_NOEXEC)
required_flags |= MS_NOEXEC;
DEBUG("(at remount) flags for %s was %lu, required extra flags are %lu", fsname, sb.f_flag, required_flags);
/*
* If this was a bind mount request, and required_flags
* does not have any flags which are not already in
* mountflags, then skip the remount
*/
if (!(mountflags & MS_REMOUNT)) {
if (!(required_flags & ~mountflags) && rqd_flags == 0) {
DEBUG("mountflags already was %lu, skipping remount",
mountflags);
goto skipremount;
}
}
mountflags |= required_flags;
}
#endif
if (mount(fsname, target, fstype,
mountflags | MS_REMOUNT, data)) {
if (optional) {
INFO("failed to mount '%s' on '%s' (optional): %s",
fsname, target, strerror(errno));
return 0;
}
else {
SYSERROR("failed to mount '%s' on '%s'",
fsname, target);
return -1;
}
}
}
#ifdef HAVE_STATVFS
skipremount:
#endif
DEBUG("mounted '%s' on '%s', type '%s'", fsname, target, fstype);
return 0;
}
CWE ID: CWE-59
Target: 1
Example 2:
Code: copy_from_user_nmi(void *to, const void __user *from, unsigned long n)
{
unsigned long offset, addr = (unsigned long)from;
unsigned long size, len = 0;
struct page *page;
void *map;
int ret;
do {
ret = __get_user_pages_fast(addr, 1, 0, &page);
if (!ret)
break;
offset = addr & (PAGE_SIZE - 1);
size = min(PAGE_SIZE - offset, n - len);
map = kmap_atomic(page);
memcpy(to, map+offset, size);
kunmap_atomic(map);
put_page(page);
len += size;
to += size;
addr += size;
} while (len < n);
return len;
}
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: image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
/* NOTE: we can actually pend the tRNS processing at this point because we
* can correctly recognize the original pixel value even though we have
* mapped the one gray channel to the three RGB ones, but in fact libpng
* doesn't do this, so we don't either.
*/
if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
image_pixel_add_alpha(that, &display->this);
/* Simply expand the bit depth and alter the colour type as required. */
if (that->colour_type == PNG_COLOR_TYPE_GRAY)
{
/* RGB images have a bit depth at least equal to '8' */
if (that->bit_depth < 8)
that->sample_depth = that->bit_depth = 8;
/* And just changing the colour type works here because the green and blue
* channels are being maintained in lock-step with the red/gray:
*/
that->colour_type = PNG_COLOR_TYPE_RGB;
}
else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
this->next->mod(this->next, that, pp, display);
}
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 rds_rdma_extra_size(struct rds_rdma_args *args)
{
struct rds_iovec vec;
struct rds_iovec __user *local_vec;
int tot_pages = 0;
unsigned int nr_pages;
unsigned int i;
local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;
/* figure out the number of pages in the vector */
for (i = 0; i < args->nr_local; i++) {
if (copy_from_user(&vec, &local_vec[i],
sizeof(struct rds_iovec)))
return -EFAULT;
nr_pages = rds_pages_in_vec(&vec);
if (nr_pages == 0)
return -EINVAL;
tot_pages += nr_pages;
/*
* nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,
* so tot_pages cannot overflow without first going negative.
*/
if (tot_pages < 0)
return -EINVAL;
}
return tot_pages * sizeof(struct scatterlist);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void WebGL2RenderingContextBase::uniform4fv(
const WebGLUniformLocation* location,
const FlexibleFloat32ArrayView& v) {
WebGLRenderingContextBase::uniform4fv(location, v);
}
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 sas_smp_get_phy_events(struct sas_phy *phy)
{
int res;
u8 *req;
u8 *resp;
struct sas_rphy *rphy = dev_to_rphy(phy->dev.parent);
struct domain_device *dev = sas_find_dev_by_rphy(rphy);
req = alloc_smp_req(RPEL_REQ_SIZE);
if (!req)
return -ENOMEM;
resp = alloc_smp_resp(RPEL_RESP_SIZE);
if (!resp) {
kfree(req);
return -ENOMEM;
}
req[1] = SMP_REPORT_PHY_ERR_LOG;
req[9] = phy->number;
res = smp_execute_task(dev, req, RPEL_REQ_SIZE,
resp, RPEL_RESP_SIZE);
if (!res)
goto out;
phy->invalid_dword_count = scsi_to_u32(&resp[12]);
phy->running_disparity_error_count = scsi_to_u32(&resp[16]);
phy->loss_of_dword_sync_count = scsi_to_u32(&resp[20]);
phy->phy_reset_problem_count = scsi_to_u32(&resp[24]);
out:
kfree(resp);
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: void file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum)
{
struct map_struct *buf;
OFF_T i, len = st_p->st_size;
md_context m;
int32 remainder;
int fd;
memset(sum, 0, MAX_DIGEST_LEN);
fd = do_open(fname, O_RDONLY, 0);
if (fd == -1)
return;
buf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK);
switch (checksum_type) {
case CSUM_MD5:
md5_begin(&m);
for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) {
md5_update(&m, (uchar *)map_ptr(buf, i, CSUM_CHUNK),
CSUM_CHUNK);
}
remainder = (int32)(len - i);
if (remainder > 0)
md5_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);
md5_result(&m, (uchar *)sum);
break;
case CSUM_MD4:
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
mdfour_begin(&m);
for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) {
}
/* Prior to version 27 an incorrect MD4 checksum was computed
* by failing to call mdfour_tail() for block sizes that
* are multiples of 64. This is fixed by calling mdfour_update()
* even when there are no more bytes. */
* are multiples of 64. This is fixed by calling mdfour_update()
* even when there are no more bytes. */
remainder = (int32)(len - i);
if (remainder > 0 || checksum_type != CSUM_MD4_BUSTED)
mdfour_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);
mdfour_result(&m, (uchar *)sum);
rprintf(FERROR, "invalid checksum-choice for the --checksum option (%d)\n", checksum_type);
exit_cleanup(RERR_UNSUPPORTED);
}
close(fd);
unmap_file(buf);
}
CWE ID: CWE-354
Target: 1
Example 2:
Code: kvm_irqfd_deassign(struct kvm *kvm, struct kvm_irqfd *args)
{
struct kvm_kernel_irqfd *irqfd, *tmp;
struct eventfd_ctx *eventfd;
eventfd = eventfd_ctx_fdget(args->fd);
if (IS_ERR(eventfd))
return PTR_ERR(eventfd);
spin_lock_irq(&kvm->irqfds.lock);
list_for_each_entry_safe(irqfd, tmp, &kvm->irqfds.items, list) {
if (irqfd->eventfd == eventfd && irqfd->gsi == args->gsi) {
/*
* This clearing of irq_entry.type is needed for when
* another thread calls kvm_irq_routing_update before
* we flush workqueue below (we synchronize with
* kvm_irq_routing_update using irqfds.lock).
*/
write_seqcount_begin(&irqfd->irq_entry_sc);
irqfd->irq_entry.type = 0;
write_seqcount_end(&irqfd->irq_entry_sc);
irqfd_deactivate(irqfd);
}
}
spin_unlock_irq(&kvm->irqfds.lock);
eventfd_ctx_put(eventfd);
/*
* Block until we know all outstanding shutdown jobs have completed
* so that we guarantee there will not be any more interrupts on this
* gsi once this deassign function returns.
*/
flush_workqueue(irqfd_cleanup_wq);
return 0;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: uint8* ptr() const { return ptr_.get(); }
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: RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host,
bool is_guest_view_hack)
: host_(RenderWidgetHostImpl::From(host)),
window_(nullptr),
in_shutdown_(false),
in_bounds_changed_(false),
popup_parent_host_view_(nullptr),
popup_child_host_view_(nullptr),
is_loading_(false),
has_composition_text_(false),
background_color_(SK_ColorWHITE),
needs_begin_frames_(false),
needs_flush_input_(false),
added_frame_observer_(false),
cursor_visibility_state_in_renderer_(UNKNOWN),
#if defined(OS_WIN)
legacy_render_widget_host_HWND_(nullptr),
legacy_window_destroyed_(false),
virtual_keyboard_requested_(false),
#endif
has_snapped_to_boundary_(false),
is_guest_view_hack_(is_guest_view_hack),
device_scale_factor_(0.0f),
event_handler_(new RenderWidgetHostViewEventHandler(host_, this, this)),
weak_ptr_factory_(this) {
if (!is_guest_view_hack_)
host_->SetView(this);
if (GetTextInputManager())
GetTextInputManager()->AddObserver(this);
bool overscroll_enabled = base::CommandLine::ForCurrentProcess()->
GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0";
SetOverscrollControllerEnabled(overscroll_enabled);
selection_controller_client_.reset(
new TouchSelectionControllerClientAura(this));
CreateSelectionController();
RenderViewHost* rvh = RenderViewHost::From(host_);
if (rvh) {
ignore_result(rvh->GetWebkitPreferences());
}
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
{
int rc;
struct cifs_ses *ses = sess_data->ses;
struct smb2_sess_setup_req *req;
struct TCP_Server_Info *server = ses->server;
unsigned int total_len;
rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, (void **) &req,
&total_len);
if (rc)
return rc;
/* First session, not a reauthenticate */
req->sync_hdr.SessionId = 0;
/* if reconnect, we need to send previous sess id, otherwise it is 0 */
req->PreviousSessionId = sess_data->previous_session;
req->Flags = 0; /* MBZ */
/* enough to enable echos and oplocks and one max size write */
req->sync_hdr.CreditRequest = cpu_to_le16(130);
/* only one of SMB2 signing flags may be set in SMB2 request */
if (server->sign)
req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
else
req->SecurityMode = 0;
req->Capabilities = 0;
req->Channel = 0; /* MBZ */
sess_data->iov[0].iov_base = (char *)req;
/* 1 for pad */
sess_data->iov[0].iov_len = total_len - 1;
/*
* This variable will be used to clear the buffer
* allocated above in case of any error in the calling function.
*/
sess_data->buf0_type = CIFS_SMALL_BUFFER;
return 0;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: session_by_tty(char *tty)
{
int i;
for (i = 0; i < sessions_nalloc; i++) {
Session *s = &sessions[i];
if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
debug("session_by_tty: session %d tty %s", i, tty);
return s;
}
}
debug("session_by_tty: unknown tty %.100s", tty);
session_dump();
return NULL;
}
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 InspectorNetworkAgent::DidBlockRequest(
ExecutionContext* execution_context,
const ResourceRequest& request,
DocumentLoader* loader,
const FetchInitiatorInfo& initiator_info,
ResourceRequestBlockedReason reason) {
unsigned long identifier = CreateUniqueIdentifier();
WillSendRequestInternal(execution_context, identifier, loader, request,
ResourceResponse(), initiator_info);
String request_id = IdentifiersFactory::RequestId(identifier);
String protocol_reason = BuildBlockedReason(reason);
GetFrontend()->loadingFailed(
request_id, MonotonicallyIncreasingTime(),
InspectorPageAgent::ResourceTypeJson(
resources_data_->GetResourceType(request_id)),
String(), false, protocol_reason);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: SVGDocumentExtensions& Document::AccessSVGExtensions() {
if (!svg_extensions_)
svg_extensions_ = new SVGDocumentExtensions(this);
return *svg_extensions_;
}
CWE ID: CWE-732
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ssize_t lbs_debugfs_write(struct file *f, const char __user *buf,
size_t cnt, loff_t *ppos)
{
int r, i;
char *pdata;
char *p;
char *p0;
char *p1;
char *p2;
struct debug_data *d = f->private_data;
pdata = kmalloc(cnt, GFP_KERNEL);
if (pdata == NULL)
return 0;
if (copy_from_user(pdata, buf, cnt)) {
lbs_deb_debugfs("Copy from user failed\n");
kfree(pdata);
return 0;
}
p0 = pdata;
for (i = 0; i < num_of_items; i++) {
do {
p = strstr(p0, d[i].name);
if (p == NULL)
break;
p1 = strchr(p, '\n');
if (p1 == NULL)
break;
p0 = p1++;
p2 = strchr(p, '=');
if (!p2)
break;
p2++;
r = simple_strtoul(p2, NULL, 0);
if (d[i].size == 1)
*((u8 *) d[i].addr) = (u8) r;
else if (d[i].size == 2)
*((u16 *) d[i].addr) = (u16) r;
else if (d[i].size == 4)
*((u32 *) d[i].addr) = (u32) r;
else if (d[i].size == 8)
*((u64 *) d[i].addr) = (u64) r;
break;
} while (1);
}
kfree(pdata);
return (ssize_t)cnt;
}
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 RunInvTxfm(int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int hugetlb_report_node_meminfo(int nid, char *buf)
{
struct hstate *h = &default_hstate;
if (!hugepages_supported())
return 0;
return sprintf(buf,
"Node %d HugePages_Total: %5u\n"
"Node %d HugePages_Free: %5u\n"
"Node %d HugePages_Surp: %5u\n",
nid, h->nr_huge_pages_node[nid],
nid, h->free_huge_pages_node[nid],
nid, h->surplus_huge_pages_node[nid]);
}
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 DestroySkImageOnOriginalThread(
sk_sp<SkImage> image,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
std::unique_ptr<gpu::SyncToken> sync_token) {
if (context_provider_wrapper &&
image->isValid(
context_provider_wrapper->ContextProvider()->GetGrContext())) {
if (sync_token->HasData()) {
context_provider_wrapper->ContextProvider()
->ContextGL()
->WaitSyncTokenCHROMIUM(sync_token->GetData());
}
image->getTexture()->textureParamsModified();
}
}
CWE ID: CWE-119
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *raw_data)
{
struct super_block *s;
struct ecryptfs_sb_info *sbi;
struct ecryptfs_dentry_info *root_info;
const char *err = "Getting sb failed";
struct inode *inode;
struct path path;
uid_t check_ruid;
int rc;
sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL);
if (!sbi) {
rc = -ENOMEM;
goto out;
}
rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid);
if (rc) {
err = "Error parsing options";
goto out;
}
s = sget(fs_type, NULL, set_anon_super, flags, NULL);
if (IS_ERR(s)) {
rc = PTR_ERR(s);
goto out;
}
rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY);
if (rc)
goto out1;
ecryptfs_set_superblock_private(s, sbi);
s->s_bdi = &sbi->bdi;
/* ->kill_sb() will take care of sbi after that point */
sbi = NULL;
s->s_op = &ecryptfs_sops;
s->s_d_op = &ecryptfs_dops;
err = "Reading sb failed";
rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path);
if (rc) {
ecryptfs_printk(KERN_WARNING, "kern_path() failed\n");
goto out1;
}
if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) {
rc = -EINVAL;
printk(KERN_ERR "Mount on filesystem of type "
"eCryptfs explicitly disallowed due to "
"known incompatibilities\n");
goto out_free;
}
if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) {
rc = -EPERM;
printk(KERN_ERR "Mount of device (uid: %d) not owned by "
"requested user (uid: %d)\n",
i_uid_read(path.dentry->d_inode),
from_kuid(&init_user_ns, current_uid()));
goto out_free;
}
ecryptfs_set_superblock_lower(s, path.dentry->d_sb);
/**
* Set the POSIX ACL flag based on whether they're enabled in the lower
* mount. Force a read-only eCryptfs mount if the lower mount is ro.
* Allow a ro eCryptfs mount even when the lower mount is rw.
*/
s->s_flags = flags & ~MS_POSIXACL;
s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL);
s->s_maxbytes = path.dentry->d_sb->s_maxbytes;
s->s_blocksize = path.dentry->d_sb->s_blocksize;
s->s_magic = ECRYPTFS_SUPER_MAGIC;
inode = ecryptfs_get_inode(path.dentry->d_inode, s);
rc = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_free;
s->s_root = d_make_root(inode);
if (!s->s_root) {
rc = -ENOMEM;
goto out_free;
}
rc = -ENOMEM;
root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL);
if (!root_info)
goto out_free;
/* ->kill_sb() will take care of root_info */
ecryptfs_set_dentry_private(s->s_root, root_info);
root_info->lower_path = path;
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
out_free:
path_put(&path);
out1:
deactivate_locked_super(s);
out:
if (sbi) {
ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat);
kmem_cache_free(ecryptfs_sb_info_cache, sbi);
}
printk(KERN_ERR "%s; rc = [%d]\n", err, rc);
return ERR_PTR(rc);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: RemoteFrame::~RemoteFrame() {
DCHECK(!view_);
}
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: process_plane(uint8 * in, int width, int height, uint8 * out, int size)
{
UNUSED(size);
int indexw;
int indexh;
int code;
int collen;
int replen;
int color;
int x;
int revcode;
uint8 * last_line;
uint8 * this_line;
uint8 * org_in;
uint8 * org_out;
org_in = in;
org_out = out;
last_line = 0;
indexh = 0;
while (indexh < height)
{
out = (org_out + width * height * 4) - ((indexh + 1) * width * 4);
color = 0;
this_line = out;
indexw = 0;
if (last_line == 0)
{
while (indexw < width)
{
code = CVAL(in);
replen = code & 0xf;
collen = (code >> 4) & 0xf;
revcode = (replen << 4) | collen;
if ((revcode <= 47) && (revcode >= 16))
{
replen = revcode;
collen = 0;
}
while (collen > 0)
{
color = CVAL(in);
*out = color;
out += 4;
indexw++;
collen--;
}
while (replen > 0)
{
*out = color;
out += 4;
indexw++;
replen--;
}
}
}
else
{
while (indexw < width)
{
code = CVAL(in);
replen = code & 0xf;
collen = (code >> 4) & 0xf;
revcode = (replen << 4) | collen;
if ((revcode <= 47) && (revcode >= 16))
{
replen = revcode;
collen = 0;
}
while (collen > 0)
{
x = CVAL(in);
if (x & 1)
{
x = x >> 1;
x = x + 1;
color = -x;
}
else
{
x = x >> 1;
color = x;
}
x = last_line[indexw * 4] + color;
*out = x;
out += 4;
indexw++;
collen--;
}
while (replen > 0)
{
x = last_line[indexw * 4] + color;
*out = x;
out += 4;
indexw++;
replen--;
}
}
}
indexh++;
last_line = this_line;
}
return (int) (in - org_in);
}
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 SendTabToSelfInfoBarDelegate::OpenTab() {
NOTIMPLEMENTED();
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: TabRecordingIndicatorAnimation(const gfx::MultiAnimation::Parts& parts,
const base::TimeDelta interval)
: MultiAnimation(parts, interval) {}
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 catc_disconnect(struct usb_interface *intf)
{
struct catc *catc = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
if (catc) {
unregister_netdev(catc->netdev);
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(catc->netdev);
}
}
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 ThreadableBlobRegistry::registerStreamURL(const KURL& url, const String& type)
{
if (isMainThread()) {
blobRegistry().registerStreamURL(url, type);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, type));
callOnMainThread(®isterStreamURLTask, context.leakPtr());
}
}
CWE ID:
Target: 1
Example 2:
Code: const Extension* extension() const { return extension_.get(); }
CWE ID: CWE-79
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static jint Bitmap_getGenerationId(JNIEnv* env, jobject, jlong bitmapHandle) {
SkBitmap* bitmap = reinterpret_cast<SkBitmap*>(bitmapHandle);
return static_cast<jint>(bitmap->getGenerationID());
}
CWE ID: CWE-189
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int netlbl_cipsov4_add_common(struct genl_info *info,
struct cipso_v4_doi *doi_def)
{
struct nlattr *nla;
int nla_rem;
u32 iter = 0;
doi_def->doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);
if (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_TAGLST],
NLBL_CIPSOV4_A_MAX,
netlbl_cipsov4_genl_policy) != 0)
return -EINVAL;
nla_for_each_nested(nla, info->attrs[NLBL_CIPSOV4_A_TAGLST], nla_rem)
if (nla->nla_type == NLBL_CIPSOV4_A_TAG) {
if (iter > CIPSO_V4_TAG_MAXCNT)
return -EINVAL;
doi_def->tags[iter++] = nla_get_u8(nla);
}
if (iter < CIPSO_V4_TAG_MAXCNT)
doi_def->tags[iter] = CIPSO_V4_TAG_INVALID;
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int compat_ip_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
int err;
if (optname == MCAST_MSFILTER)
return compat_mc_getsockopt(sk, level, optname, optval, optlen,
ip_getsockopt);
err = do_ip_getsockopt(sk, level, optname, optval, optlen,
MSG_CMSG_COMPAT);
#ifdef CONFIG_NETFILTER
/* we need to exclude all possible ENOPROTOOPTs except default case */
if (err == -ENOPROTOOPT && optname != IP_PKTOPTIONS &&
!ip_mroute_opt(optname)) {
int len;
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
err = compat_nf_getsockopt(sk, PF_INET, optname, optval, &len);
release_sock(sk);
if (err >= 0)
err = put_user(len, optlen);
return err;
}
#endif
return err;
}
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 comps_mrtree_set(COMPS_MRTree * rt, char * key, void * data)
{
__comps_mrtree_set(rt, key, strlen(key), data);
}
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: GF_Err cat_multiple_files(GF_ISOFile *dest, char *fileName, u32 import_flags, Double force_fps, u32 frames_per_sample, char *tmp_dir, Bool force_cat, Bool align_timelines, Bool allow_add_in_command)
{
CATEnum cat_enum;
char *sep;
cat_enum.dest = dest;
cat_enum.import_flags = import_flags;
cat_enum.force_fps = force_fps;
cat_enum.frames_per_sample = frames_per_sample;
cat_enum.tmp_dir = tmp_dir;
cat_enum.force_cat = force_cat;
cat_enum.align_timelines = align_timelines;
cat_enum.allow_add_in_command = allow_add_in_command;
strcpy(cat_enum.szPath, fileName);
sep = strrchr(cat_enum.szPath, GF_PATH_SEPARATOR);
if (!sep) sep = strrchr(cat_enum.szPath, '/');
if (!sep) {
strcpy(cat_enum.szPath, ".");
strcpy(cat_enum.szRad1, fileName);
} else {
strcpy(cat_enum.szRad1, sep+1);
sep[0] = 0;
}
sep = strchr(cat_enum.szRad1, '*');
strcpy(cat_enum.szRad2, sep+1);
sep[0] = 0;
sep = strchr(cat_enum.szRad2, '%');
if (!sep) sep = strchr(cat_enum.szRad2, '#');
if (!sep) sep = strchr(cat_enum.szRad2, ':');
strcpy(cat_enum.szOpt, "");
if (sep) {
strcpy(cat_enum.szOpt, sep);
sep[0] = 0;
}
return gf_enum_directory(cat_enum.szPath, 0, cat_enumerate, &cat_enum, NULL);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool ChromeMockRenderThread::OnMessageReceived(const IPC::Message& msg) {
if (content::MockRenderThread::OnMessageReceived(msg))
return true;
bool handled = true;
bool msg_is_ok = true;
IPC_BEGIN_MESSAGE_MAP_EX(ChromeMockRenderThread, msg, msg_is_ok)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension,
OnMsgOpenChannelToExtension)
IPC_MESSAGE_HANDLER(PrintHostMsg_GetDefaultPrintSettings,
OnGetDefaultPrintSettings)
IPC_MESSAGE_HANDLER(PrintHostMsg_ScriptedPrint, OnScriptedPrint)
IPC_MESSAGE_HANDLER(PrintHostMsg_UpdatePrintSettings, OnUpdatePrintSettings)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPrintedPagesCount,
OnDidGetPrintedPagesCount)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidPrintPage, OnDidPrintPage)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPreviewPageCount,
OnDidGetPreviewPageCount)
IPC_MESSAGE_HANDLER(PrintHostMsg_DidPreviewPage, OnDidPreviewPage)
IPC_MESSAGE_HANDLER(PrintHostMsg_CheckForCancel, OnCheckForCancel)
#if defined(OS_WIN)
IPC_MESSAGE_HANDLER(PrintHostMsg_DuplicateSection, OnDuplicateSection)
#endif
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(PrintHostMsg_AllocateTempFileForPrinting,
OnAllocateTempFileForPrinting)
IPC_MESSAGE_HANDLER(PrintHostMsg_TempFileForPrintingWritten,
OnTempFileForPrintingWritten)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP_EX()
return handled;
}
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: add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many);
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
CWE ID: CWE-416
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __init ipip_init(void)
{
int err;
printk(banner);
if (xfrm4_tunnel_register(&ipip_handler, AF_INET)) {
printk(KERN_INFO "ipip init: can't register tunnel\n");
return -EAGAIN;
}
err = register_pernet_device(&ipip_net_ops);
if (err)
xfrm4_tunnel_deregister(&ipip_handler, AF_INET);
return err;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: int index() const { return index_; }
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip, cs;
u16 old_cs;
int cpl = ctxt->ops->cpl(ctxt);
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_cs, &old_desc, NULL,
VCPU_SREG_CS);
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, cpl,
X86_TRANSFER_RET,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, eip, &new_desc);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
}
return rc;
}
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: coolkey_find_attribute(sc_card_t *card, sc_cardctl_coolkey_attribute_t *attribute)
{
u8 object_record_type;
CK_ATTRIBUTE_TYPE attr_type = attribute->attribute_type;
const u8 *obj = attribute->object->data;
const u8 *attr = NULL;
size_t buf_len = attribute->object->length;
coolkey_object_header_t *object_head;
int attribute_count,i;
attribute->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING;
attribute->attribute_length = 0;
attribute->attribute_value = NULL;
if (obj == NULL) {
/* cast away const so we can cache the data value */
int r = coolkey_fill_object(card, (sc_cardctl_coolkey_object_t *)attribute->object);
if (r < 0) {
return r;
}
obj = attribute->object->data;
}
/* should be a static assert so we catch this at compile time */
assert(sizeof(coolkey_object_header_t) >= sizeof(coolkey_v0_object_header_t));
/* make sure we have enough of the object to read the record_type */
if (buf_len <= sizeof(coolkey_v0_object_header_t)) {
return SC_ERROR_CORRUPTED_DATA;
}
object_head = (coolkey_object_header_t *)obj;
object_record_type = object_head->record_type;
/* make sure it's a type we recognize */
if ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) {
return SC_ERROR_CORRUPTED_DATA;
}
/*
* now loop through all the attributes in the list. first find the start of the list
*/
attr = coolkey_attribute_start(obj, object_record_type, buf_len);
if (attr == NULL) {
return SC_ERROR_CORRUPTED_DATA;
}
buf_len -= (attr-obj);
/* now get the count */
attribute_count = coolkey_get_attribute_count(obj, object_record_type, buf_len);
for (i=0; i < attribute_count; i++) {
size_t record_len = coolkey_get_attribute_record_len(attr, object_record_type, buf_len);
/* make sure we have the complete record */
if (buf_len < record_len) {
return SC_ERROR_CORRUPTED_DATA;
}
/* does the attribute match the one we are looking for */
if (attr_type == coolkey_get_attribute_type(attr, object_record_type, record_len)) {
/* yup, return it */
return coolkey_get_attribute_data(attr, object_record_type, record_len, attribute);
}
/* go to the next attribute on the list */
buf_len -= record_len;
attr += record_len;
}
/* not find in attribute list, check the fixed attribute record */
if (object_record_type == COOLKEY_V1_OBJECT) {
unsigned long fixed_attributes = bebytes2ulong(object_head->fixed_attributes_values);
return coolkey_get_attribute_data_fixed(attr_type, fixed_attributes, attribute);
}
return SC_ERROR_DATA_OBJECT_NOT_FOUND;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void GLES2DecoderImpl::BeginDecoding() {
gpu_tracer_->BeginDecoding();
gpu_trace_commands_ = gpu_tracer_->IsTracing() && *gpu_decoder_category_;
gpu_debug_commands_ = log_commands() || debug() || gpu_trace_commands_;
query_manager_->ProcessFrameBeginUpdates();
query_manager_->BeginProcessingCommands();
}
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: CheckClientDownloadRequest::~CheckClientDownloadRequest() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
item_->RemoveObserver(this);
}
CWE ID: CWE-20
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void Ins_MDRP( INS_ARG )
{
Int point;
TT_F26Dot6 distance,
org_dist;
point = (Int)args[0];
if ( BOUNDS( args[0], CUR.zp1.n_points ) )
{
/* Current version of FreeType silently ignores this out of bounds error
* and drops the instruction, see bug #691121
return;
}
/* XXX: Is there some undocumented feature while in the */
/* twilight zone? */
org_dist = CUR_Func_dualproj( CUR.zp1.org_x[point] -
CUR.zp0.org_x[CUR.GS.rp0],
CUR.zp1.org_y[point] -
CUR.zp0.org_y[CUR.GS.rp0] );
/* single width cutin test */
if ( ABS(org_dist) < CUR.GS.single_width_cutin )
{
if ( org_dist >= 0 )
org_dist = CUR.GS.single_width_value;
else
org_dist = -CUR.GS.single_width_value;
}
/* round flag */
if ( (CUR.opcode & 4) != 0 )
distance = CUR_Func_round( org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
else
distance = Round_None( EXEC_ARGS
org_dist,
CUR.metrics.compensations[CUR.opcode & 3] );
/* minimum distance flag */
if ( (CUR.opcode & 8) != 0 )
{
if ( org_dist >= 0 )
{
if ( distance < CUR.GS.minimum_distance )
distance = CUR.GS.minimum_distance;
}
else
{
if ( distance > -CUR.GS.minimum_distance )
distance = -CUR.GS.minimum_distance;
}
}
/* now move the point */
org_dist = CUR_Func_project( CUR.zp1.cur_x[point] -
CUR.zp0.cur_x[CUR.GS.rp0],
CUR.zp1.cur_y[point] -
CUR.zp0.cur_y[CUR.GS.rp0] );
CUR_Func_move( &CUR.zp1, point, distance - org_dist );
CUR.GS.rp1 = CUR.GS.rp0;
CUR.GS.rp2 = point;
if ( (CUR.opcode & 16) != 0 )
CUR.GS.rp0 = point;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
const void *data, int offset, int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva_memslot(memslot, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = __copy_to_user((void __user *)addr + offset, data, len);
if (r)
return -EFAULT;
mark_page_dirty_in_slot(memslot, gfn);
return 0;
}
CWE ID: CWE-416
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline struct sem_array *sem_lock_check(struct ipc_namespace *ns,
int id)
{
struct kern_ipc_perm *ipcp = ipc_lock_check(&sem_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct sem_array, sem_perm);
}
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 LayoutSVGContainer::layout()
{
ASSERT(needsLayout());
LayoutAnalyzer::Scope analyzer(*this);
calcViewport();
bool updatedTransform = calculateLocalTransform();
m_didScreenScaleFactorChange = updatedTransform || SVGLayoutSupport::screenScaleFactorChanged(parent());
determineIfLayoutSizeChanged();
bool layoutSizeChanged = element()->hasRelativeLengths()
&& SVGLayoutSupport::layoutSizeOfNearestViewportChanged(this);
SVGLayoutSupport::layoutChildren(firstChild(), false, m_didScreenScaleFactorChange, layoutSizeChanged);
if (everHadLayout() && needsLayout())
SVGResourcesCache::clientLayoutChanged(this);
if (m_needsBoundariesUpdate || updatedTransform) {
updateCachedBoundaries();
m_needsBoundariesUpdate = false;
LayoutSVGModelObject::setNeedsBoundariesUpdate();
}
ASSERT(!m_needsBoundariesUpdate);
clearNeedsLayout();
}
CWE ID:
Target: 1
Example 2:
Code: unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s)
{
return s->compress_meth;
}
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 ChromeClientImpl::AttachRootLayer(WebLayer* root_layer,
LocalFrame* local_frame) {
WebLocalFrameImpl* web_frame =
WebLocalFrameImpl::FromFrame(local_frame)->LocalRoot();
DCHECK(web_frame->FrameWidget() || !root_layer);
if (web_frame->FrameWidget())
web_frame->FrameWidget()->SetRootLayer(root_layer);
}
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 ChromeOSCancelHandwriting(InputMethodStatusConnection* connection,
int n_strokes) {
g_return_if_fail(connection);
connection->CancelHandwriting(n_strokes);
}
CWE ID: CWE-399
Target: 1
Example 2:
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
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
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-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 SVGDocumentExtensions::addPendingResource(const AtomicString& id, Element* element)
{
ASSERT(element);
ASSERT(element->inDocument());
if (id.isEmpty())
return;
HashMap<AtomicString, OwnPtr<SVGPendingElements> >::AddResult result = m_pendingResources.add(id, nullptr);
if (result.isNewEntry)
result.storedValue->value = adoptPtr(new SVGPendingElements);
result.storedValue->value->add(element);
element->setHasPendingResources();
}
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 SoftAVC::setDecodeArgs(
ivd_video_decode_ip_t *ps_dec_ip,
ivd_video_decode_op_t *ps_dec_op,
OMX_BUFFERHEADERTYPE *inHeader,
OMX_BUFFERHEADERTYPE *outHeader,
size_t timeStampIx) {
size_t sizeY = outputBufferWidth() * outputBufferHeight();
size_t sizeUV;
uint8_t *pBuf;
ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t);
ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t);
ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE;
/* When in flush and after EOS with zero byte input,
* inHeader is set to zero. Hence check for non-null */
if (inHeader) {
ps_dec_ip->u4_ts = timeStampIx;
ps_dec_ip->pv_stream_buffer =
inHeader->pBuffer + inHeader->nOffset;
ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen;
} else {
ps_dec_ip->u4_ts = 0;
ps_dec_ip->pv_stream_buffer = NULL;
ps_dec_ip->u4_num_Bytes = 0;
}
if (outHeader) {
pBuf = outHeader->pBuffer;
} else {
pBuf = mFlushOutBuffer;
}
sizeUV = sizeY / 4;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV;
ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV;
ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf;
ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY;
ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV;
ps_dec_ip->s_out_buffer.u4_num_bufs = 3;
return;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void n_tty_receive_char(struct tty_struct *tty, unsigned char c)
{
n_tty_receive_char_inline(tty, c);
}
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 HB_Error Load_ChainPosClassSet(
HB_ChainContextPosFormat2* ccpf2,
HB_ChainPosClassSet* cpcs,
HB_Stream stream )
{
HB_Error error;
HB_UShort n, m, count;
HB_UInt cur_offset, new_offset, base_offset;
HB_ChainPosClassRule* cpcr;
base_offset = FILE_Pos();
if ( ACCESS_Frame( 2L ) )
return error;
count = cpcs->ChainPosClassRuleCount = GET_UShort();
FORGET_Frame();
cpcs->ChainPosClassRule = NULL;
if ( ALLOC_ARRAY( cpcs->ChainPosClassRule, count,
HB_ChainPosClassRule ) )
return error;
cpcr = cpcs->ChainPosClassRule;
for ( n = 0; n < count; n++ )
{
if ( ACCESS_Frame( 2L ) )
goto Fail;
new_offset = GET_UShort() + base_offset;
FORGET_Frame();
cur_offset = FILE_Pos();
if ( FILE_Seek( new_offset ) ||
( error = Load_ChainPosClassRule( ccpf2, &cpcr[n],
stream ) ) != HB_Err_Ok )
goto Fail;
(void)FILE_Seek( cur_offset );
}
return HB_Err_Ok;
Fail:
for ( m = 0; m < n; m++ )
Free_ChainPosClassRule( &cpcr[m] );
FREE( cpcr );
return error;
}
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 long mem_seek(jas_stream_obj_t *obj, long offset, int origin)
{
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
long newpos;
JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin));
switch (origin) {
case SEEK_SET:
newpos = offset;
break;
case SEEK_END:
newpos = m->len_ - offset;
break;
case SEEK_CUR:
newpos = m->pos_ + offset;
break;
default:
abort();
break;
}
if (newpos < 0) {
return -1;
}
m->pos_ = newpos;
return m->pos_;
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
journal->j_commit_interval = sbi->s_commit_interval;
journal->j_min_batch_time = sbi->s_min_batch_time;
journal->j_max_batch_time = sbi->s_max_batch_time;
write_lock(&journal->j_state_lock);
if (test_opt(sb, BARRIER))
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
if (test_opt(sb, DATA_ERR_ABORT))
journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
else
journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
write_unlock(&journal->j_state_lock);
}
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 hidp_process_data(struct hidp_session *session, struct sk_buff *skb,
unsigned char param)
{
int done_with_skb = 1;
BT_DBG("session %p skb %p len %d param 0x%02x", session, skb, skb->len, param);
switch (param) {
case HIDP_DATA_RTYPE_INPUT:
hidp_set_timer(session);
if (session->input)
hidp_input_report(session, skb);
if (session->hid)
hid_input_report(session->hid, HID_INPUT_REPORT, skb->data, skb->len, 0);
break;
case HIDP_DATA_RTYPE_OTHER:
case HIDP_DATA_RTYPE_OUPUT:
case HIDP_DATA_RTYPE_FEATURE:
break;
default:
__hidp_send_ctrl_message(session,
HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_INVALID_PARAMETER, NULL, 0);
}
if (test_bit(HIDP_WAITING_FOR_RETURN, &session->flags) &&
param == session->waiting_report_type) {
if (session->waiting_report_number < 0 ||
session->waiting_report_number == skb->data[0]) {
/* hidp_get_raw_report() is waiting on this report. */
session->report_return = skb;
done_with_skb = 0;
clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags);
wake_up_interruptible(&session->report_queue);
}
}
return done_with_skb;
}
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 SSLManager::OnSSLCertificateError(
base::WeakPtr<SSLErrorHandler::Delegate> delegate,
const content::GlobalRequestID& id,
const ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id,
const net::SSLInfo& ssl_info,
bool fatal) {
DCHECK(delegate);
DVLOG(1) << "OnSSLCertificateError() cert_error: "
<< net::MapCertStatusToNetError(ssl_info.cert_status)
<< " id: " << id.child_id << "," << id.request_id
<< " resource_type: " << resource_type
<< " url: " << url.spec()
<< " render_process_id: " << render_process_id
<< " render_view_id: " << render_view_id
<< " cert_status: " << std::hex << ssl_info.cert_status;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&SSLCertErrorHandler::Dispatch,
new SSLCertErrorHandler(delegate,
id,
resource_type,
url,
render_process_id,
render_view_id,
ssl_info,
fatal)));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image,
const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception)
{
CacheInfo
*restrict cache_info;
const int
id = GetOpenMPThreadId();
PixelPacket
*restrict pixels;
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickSignature);
*pixel=image->background_color;
assert(id < (int) cache_info->number_threads);
pixels=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,
cache_info->nexus_info[id],exception);
if (pixels == (PixelPacket *) NULL)
return(MagickFalse);
*pixel=(*pixels);
return(MagickTrue);
}
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 nfs_read_req(struct file_priv *priv, uint64_t offset,
uint32_t readlen)
{
uint32_t data[1024];
uint32_t *p;
int len;
struct packet *nfs_packet;
uint32_t rlen, eof;
/*
* struct READ3args {
* nfs_fh3 file;
* offset3 offset;
* count3 count;
* };
*
* struct READ3resok {
* post_op_attr file_attributes;
* count3 count;
* bool eof;
* opaque data<>;
* };
*
* struct READ3resfail {
* post_op_attr file_attributes;
* };
*
* union READ3res switch (nfsstat3 status) {
* case NFS3_OK:
* READ3resok resok;
* default:
* READ3resfail resfail;
* };
*/
p = &(data[0]);
p = rpc_add_credentials(p);
p = nfs_add_fh3(p, &priv->fh);
p = nfs_add_uint64(p, offset);
p = nfs_add_uint32(p, readlen);
len = p - &(data[0]);
nfs_packet = rpc_req(priv->npriv, PROG_NFS, NFSPROC3_READ, data, len);
if (IS_ERR(nfs_packet))
return PTR_ERR(nfs_packet);
p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4;
p = nfs_read_post_op_attr(p, NULL);
rlen = ntoh32(net_read_uint32(p));
/* skip over count */
p += 1;
eof = ntoh32(net_read_uint32(p));
/*
* skip over eof and count embedded in the representation of data
* assuming it equals rlen above.
*/
p += 2;
if (readlen && !rlen && !eof) {
free(nfs_packet);
return -EIO;
}
kfifo_put(priv->fifo, (char *)p, rlen);
free(nfs_packet);
return 0;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct pipe_inode_info *pipe;
long ret;
pipe = get_pipe_info(file);
if (!pipe)
return -EBADF;
__pipe_lock(pipe);
switch (cmd) {
case F_SETPIPE_SZ: {
unsigned int size, nr_pages;
size = round_pipe_size(arg);
nr_pages = size >> PAGE_SHIFT;
ret = -EINVAL;
if (!nr_pages)
goto out;
if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) {
ret = -EPERM;
goto out;
}
ret = pipe_set_size(pipe, nr_pages);
break;
}
case F_GETPIPE_SZ:
ret = pipe->buffers * PAGE_SIZE;
break;
default:
ret = -EINVAL;
break;
}
out:
__pipe_unlock(pipe);
return ret;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int pit_ioport_write(struct kvm_io_device *this,
gpa_t addr, int len, const void *data)
{
struct kvm_pit *pit = dev_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
int channel, access;
struct kvm_kpit_channel_state *s;
u32 val = *(u32 *) data;
if (!pit_in_range(addr))
return -EOPNOTSUPP;
val &= 0xff;
addr &= KVM_PIT_CHANNEL_MASK;
mutex_lock(&pit_state->lock);
if (val != 0)
pr_debug("write addr is 0x%x, len is %d, val is 0x%x\n",
(unsigned int)addr, len, val);
if (addr == 3) {
channel = val >> 6;
if (channel == 3) {
/* Read-Back Command. */
for (channel = 0; channel < 3; channel++) {
s = &pit_state->channels[channel];
if (val & (2 << channel)) {
if (!(val & 0x20))
pit_latch_count(kvm, channel);
if (!(val & 0x10))
pit_latch_status(kvm, channel);
}
}
} else {
/* Select Counter <channel>. */
s = &pit_state->channels[channel];
access = (val >> 4) & KVM_PIT_CHANNEL_MASK;
if (access == 0) {
pit_latch_count(kvm, channel);
} else {
s->rw_mode = access;
s->read_state = access;
s->write_state = access;
s->mode = (val >> 1) & 7;
if (s->mode > 5)
s->mode -= 4;
s->bcd = val & 1;
}
}
} else {
/* Write Count. */
s = &pit_state->channels[addr];
switch (s->write_state) {
default:
case RW_STATE_LSB:
pit_load_count(kvm, addr, val);
break;
case RW_STATE_MSB:
pit_load_count(kvm, addr, val << 8);
break;
case RW_STATE_WORD0:
s->write_latch = val;
s->write_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
pit_load_count(kvm, addr, s->write_latch | (val << 8));
s->write_state = RW_STATE_WORD0;
break;
}
}
mutex_unlock(&pit_state->lock);
return 0;
}
CWE ID: CWE-362
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int __usb_get_extra_descriptor(char *buffer, unsigned size,
unsigned char type, void **ptr)
{
struct usb_descriptor_header *header;
while (size >= sizeof(struct usb_descriptor_header)) {
header = (struct usb_descriptor_header *)buffer;
if (header->bLength < 2) {
printk(KERN_ERR
"%s: bogus descriptor, type %d length %d\n",
usbcore_name,
header->bDescriptorType,
header->bLength);
return -1;
}
if (header->bDescriptorType == type) {
*ptr = header;
return 0;
}
buffer += header->bLength;
size -= header->bLength;
}
return -1;
}
CWE ID: CWE-400
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx,
Flow *f,
uint8_t *buf, uint32_t buflen,
uint8_t ipproto, uint8_t direction)
{
SCEnter();
SCLogDebug("buflen %u for %s direction", buflen,
(direction & STREAM_TOSERVER) ? "toserver" : "toclient");
AppProto alproto = ALPROTO_UNKNOWN;
if (!FLOW_IS_PM_DONE(f, direction)) {
AppProto pm_results[ALPROTO_MAX];
uint16_t pm_matches = AppLayerProtoDetectPMGetProto(tctx, f,
buf, buflen,
direction,
ipproto,
pm_results);
if (pm_matches > 0) {
alproto = pm_results[0];
goto end;
}
}
if (!FLOW_IS_PP_DONE(f, direction)) {
alproto = AppLayerProtoDetectPPGetProto(f, buf, buflen,
ipproto, direction);
if (alproto != ALPROTO_UNKNOWN)
goto end;
}
/* Look if flow can be found in expectation list */
if (!FLOW_IS_PE_DONE(f, direction)) {
alproto = AppLayerProtoDetectPEGetProto(f, ipproto, direction);
}
end:
SCReturnUInt(alproto);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int ext4_ext_search_left(struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t *logical, ext4_fsblk_t *phys)
{
struct ext4_extent_idx *ix;
struct ext4_extent *ex;
int depth, ee_len;
if (unlikely(path == NULL)) {
EXT4_ERROR_INODE(inode, "path == NULL *logical %d!", *logical);
return -EIO;
}
depth = path->p_depth;
*phys = 0;
if (depth == 0 && path->p_ext == NULL)
return 0;
/* usually extent in the path covers blocks smaller
* then *logical, but it can be that extent is the
* first one in the file */
ex = path[depth].p_ext;
ee_len = ext4_ext_get_actual_len(ex);
if (*logical < le32_to_cpu(ex->ee_block)) {
if (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {
EXT4_ERROR_INODE(inode,
"EXT_FIRST_EXTENT != ex *logical %d ee_block %d!",
*logical, le32_to_cpu(ex->ee_block));
return -EIO;
}
while (--depth >= 0) {
ix = path[depth].p_idx;
if (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {
EXT4_ERROR_INODE(inode,
"ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!",
ix != NULL ? ix->ei_block : 0,
EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?
EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block : 0,
depth);
return -EIO;
}
}
return 0;
}
if (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {
EXT4_ERROR_INODE(inode,
"logical %d < ee_block %d + ee_len %d!",
*logical, le32_to_cpu(ex->ee_block), ee_len);
return -EIO;
}
*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;
*phys = ext4_ext_pblock(ex) + ee_len - 1;
return 0;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FileSystemManagerImpl::ChooseEntry(
blink::mojom::ChooseFileSystemEntryType type,
std::vector<blink::mojom::ChooseFileSystemEntryAcceptsOptionPtr> accepts,
bool include_accepts_all,
ChooseEntryCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (!base::FeatureList::IsEnabled(blink::features::kWritableFilesAPI)) {
bindings_.ReportBadMessage("FSMI_WRITABLE_FILES_DISABLED");
return;
}
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(
&FileSystemChooser::CreateAndShow, process_id_, frame_id_, type,
std::move(accepts), include_accepts_all, std::move(callback),
base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})));
}
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_FUNCTION(mcrypt_generic_init)
{
char *key, *iv;
int key_len, iv_len;
zval *mcryptind;
unsigned char *key_s, *iv_s;
int max_key_size, key_size, iv_size;
php_mcrypt *pm;
int result = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt);
max_key_size = mcrypt_enc_get_key_size(pm->td);
iv_size = mcrypt_enc_get_iv_size(pm->td);
if (key_len == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0");
}
key_s = emalloc(key_len);
memset(key_s, 0, key_len);
iv_s = emalloc(iv_size + 1);
memset(iv_s, 0, iv_size + 1);
if (key_len > max_key_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size);
key_size = max_key_size;
} else {
key_size = key_len;
}
memcpy(key_s, key, key_len);
if (iv_len != iv_size) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size);
if (iv_len > iv_size) {
iv_len = iv_size;
}
}
memcpy(iv_s, iv, iv_len);
mcrypt_generic_deinit(pm->td);
result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s);
/* If this function fails, close the mcrypt module to prevent crashes
* when further functions want to access this resource */
if (result < 0) {
zend_list_delete(Z_LVAL_P(mcryptind));
switch (result) {
case -3:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect");
break;
case -4:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error");
break;
case -1:
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error");
break;
}
} else {
pm->init = 1;
}
RETVAL_LONG(result);
efree(iv_s);
efree(key_s);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg)
{
struct btrfs_fs_info *fs_info = btrfs_sb(fdentry(file)->d_sb);
struct btrfs_device *device;
struct request_queue *q;
struct fstrim_range range;
u64 minlen = ULLONG_MAX;
u64 num_devices = 0;
u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
int ret;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
rcu_read_lock();
list_for_each_entry_rcu(device, &fs_info->fs_devices->devices,
dev_list) {
if (!device->bdev)
continue;
q = bdev_get_queue(device->bdev);
if (blk_queue_discard(q)) {
num_devices++;
minlen = min((u64)q->limits.discard_granularity,
minlen);
}
}
rcu_read_unlock();
if (!num_devices)
return -EOPNOTSUPP;
if (copy_from_user(&range, arg, sizeof(range)))
return -EFAULT;
if (range.start > total_bytes ||
range.len < fs_info->sb->s_blocksize)
return -EINVAL;
range.len = min(range.len, total_bytes - range.start);
range.minlen = max(range.minlen, minlen);
ret = btrfs_trim_fs(fs_info->tree_root, &range);
if (ret < 0)
return ret;
if (copy_to_user(arg, &range, sizeof(range)))
return -EFAULT;
return 0;
}
CWE ID: CWE-310
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int32_t SoftAVCEncoder::allocOutputBuffers(
unsigned int sizeInMbs, unsigned int numBuffers) {
CHECK(mOutputBuffers.isEmpty());
size_t frameSize = (sizeInMbs << 7) * 3;
for (unsigned int i = 0; i < numBuffers; ++i) {
MediaBuffer *buffer = new MediaBuffer(frameSize);
buffer->setObserver(this);
mOutputBuffers.push(buffer);
}
return 1;
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: GetStartupData(HANDLE pipe, STARTUP_DATA *sud)
{
size_t size, len;
BOOL ret = FALSE;
WCHAR *data = NULL;
DWORD bytes, read;
bytes = PeekNamedPipeAsync(pipe, 1, &exit_event);
if (bytes == 0)
{
MsgToEventLog(M_SYSERR, TEXT("PeekNamedPipeAsync failed"));
ReturnLastError(pipe, L"PeekNamedPipeAsync");
goto out;
}
size = bytes / sizeof(*data);
if (size == 0)
{
MsgToEventLog(M_SYSERR, TEXT("malformed startup data: 1 byte received"));
ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
goto out;
}
data = malloc(bytes);
if (data == NULL)
{
MsgToEventLog(M_SYSERR, TEXT("malloc failed"));
ReturnLastError(pipe, L"malloc");
goto out;
}
read = ReadPipeAsync(pipe, data, bytes, 1, &exit_event);
if (bytes != read)
{
MsgToEventLog(M_SYSERR, TEXT("ReadPipeAsync failed"));
ReturnLastError(pipe, L"ReadPipeAsync");
goto out;
}
if (data[size - 1] != 0)
{
MsgToEventLog(M_ERR, TEXT("Startup data is not NULL terminated"));
ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
goto out;
}
sud->directory = data;
len = wcslen(sud->directory) + 1;
size -= len;
if (size <= 0)
{
MsgToEventLog(M_ERR, TEXT("Startup data ends at working directory"));
ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
goto out;
}
sud->options = sud->directory + len;
len = wcslen(sud->options) + 1;
size -= len;
if (size <= 0)
{
MsgToEventLog(M_ERR, TEXT("Startup data ends at command line options"));
ReturnError(pipe, ERROR_STARTUP_DATA, L"GetStartupData", 1, &exit_event);
goto out;
}
sud->std_input = sud->options + len;
data = NULL; /* don't free data */
ret = TRUE;
out:
free(data);
return ret;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: void AwContents::SetJsOnlineProperty(JNIEnv* env,
jobject obj,
jboolean network_up) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
render_view_host_ext_->SetJsOnlineProperty(network_up);
}
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 V8Window::namedPropertyGetterCustom(v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
if (!name->IsString())
return;
auto nameString = name.As<v8::String>();
LocalDOMWindow* window = toLocalDOMWindow(V8Window::toImpl(info.Holder()));
if (!window)
return;
LocalFrame* frame = window->frame();
if (!frame)
return;
AtomicString propName = toCoreAtomicString(nameString);
Frame* child = frame->tree().scopedChild(propName);
if (child) {
v8SetReturnValueFast(info, child->domWindow(), window);
return;
}
if (!info.Holder()->GetRealNamedProperty(nameString).IsEmpty())
return;
Document* doc = frame->document();
if (doc && doc->isHTMLDocument()) {
if (toHTMLDocument(doc)->hasNamedItem(propName) || doc->hasElementWithId(propName)) {
RefPtrWillBeRawPtr<HTMLCollection> items = doc->windowNamedItems(propName);
if (!items->isEmpty()) {
if (items->hasExactlyOneItem()) {
v8SetReturnValueFast(info, items->item(0), window);
return;
}
v8SetReturnValueFast(info, items.release(), window);
return;
}
}
}
}
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: tChecksumCheckResult ParaNdis_CheckRxChecksum(
PARANDIS_ADAPTER *pContext,
ULONG virtioFlags,
tCompletePhysicalAddress *pPacketPages,
ULONG ulPacketLength,
ULONG ulDataOffset)
{
tOffloadSettingsFlags f = pContext->Offload.flags;
tChecksumCheckResult res, resIp;
tTcpIpPacketParsingResult ppr;
ULONG flagsToCalculate = 0;
res.value = 0;
resIp.value = 0;
if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only
if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID))
{
if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
{
flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum;
}
else
{
if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum;
if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum;
if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum;
if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum;
}
}
ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__);
if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)
{
pContext->extraStatistics.framesRxCSHwOK++;
ppr.xxpCheckSum = ppresCSOK;
}
if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment)
{
if (f.fRxIPChecksum)
{
res.flags.IpOK = ppr.ipCheckSum == ppresCSOK;
res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad;
}
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPChecksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPChecksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
else if (ppr.ipStatus == ppresIPV6)
{
if(ppr.xxpStatus == ppresXxpKnown)
{
if(ppr.TcpUdp == ppresIsTCP) /* TCP */
{
if (f.fRxTCPv6Checksum)
{
res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.TcpFailed = !res.flags.TcpOK;
}
}
else /* UDP */
{
if (f.fRxUDPv6Checksum)
{
res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS;
res.flags.UdpFailed = !res.flags.UdpOK;
}
}
}
}
return res;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int web_server_set_alias(const char *alias_name,
const char *alias_content, size_t alias_content_length,
time_t last_modified)
{
int ret_code;
struct xml_alias_t alias;
alias_release(&gAliasDoc);
if (alias_name == NULL) {
/* don't serve aliased doc anymore */
return 0;
}
assert(alias_content != NULL);
membuffer_init(&alias.doc);
membuffer_init(&alias.name);
alias.ct = NULL;
do {
/* insert leading /, if missing */
if (*alias_name != '/')
if (membuffer_assign_str(&alias.name, "/") != 0)
break; /* error; out of mem */
ret_code = membuffer_append_str(&alias.name, alias_name);
if (ret_code != 0)
break; /* error */
if ((alias.ct = (int *)malloc(sizeof(int))) == NULL)
break; /* error */
*alias.ct = 1;
membuffer_attach(&alias.doc, (char *)alias_content,
alias_content_length);
alias.last_modified = last_modified;
/* save in module var */
ithread_mutex_lock(&gWebMutex);
gAliasDoc = alias;
ithread_mutex_unlock(&gWebMutex);
return 0;
} while (FALSE);
/* error handler */
/* free temp alias */
membuffer_destroy(&alias.name);
membuffer_destroy(&alias.doc);
free(alias.ct);
return UPNP_E_OUTOF_MEMORY;
}
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: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip_checkentry(&e->ip))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e,
e->target_offset, e->next_offset);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
CWE ID: CWE-264
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int g2m_init_buffers(G2MContext *c)
{
int aligned_height;
if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
c->framebuf_stride = FFALIGN(c->width * 3, 16);
aligned_height = FFALIGN(c->height, 16);
av_free(c->framebuf);
c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
if (!c->framebuf)
return AVERROR(ENOMEM);
}
if (!c->synth_tile || !c->jpeg_tile ||
c->old_tile_w < c->tile_width ||
c->old_tile_h < c->tile_height) {
c->tile_stride = FFALIGN(c->tile_width, 16) * 3;
aligned_height = FFALIGN(c->tile_height, 16);
av_free(c->synth_tile);
av_free(c->jpeg_tile);
av_free(c->kempf_buf);
av_free(c->kempf_flags);
c->synth_tile = av_mallocz(c->tile_stride * aligned_height);
c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);
c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height
+ FF_INPUT_BUFFER_PADDING_SIZE);
c->kempf_flags = av_mallocz( c->tile_width * aligned_height);
if (!c->synth_tile || !c->jpeg_tile ||
!c->kempf_buf || !c->kempf_flags)
return AVERROR(ENOMEM);
}
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: brcmf_update_pmklist(struct brcmf_cfg80211_info *cfg, struct brcmf_if *ifp)
{
struct brcmf_pmk_list_le *pmk_list;
int i;
u32 npmk;
s32 err;
pmk_list = &cfg->pmk_list;
npmk = le32_to_cpu(pmk_list->npmk);
brcmf_dbg(CONN, "No of elements %d\n", npmk);
for (i = 0; i < npmk; i++)
brcmf_dbg(CONN, "PMK[%d]: %pM\n", i, &pmk_list->pmk[i].bssid);
err = brcmf_fil_iovar_data_set(ifp, "pmkid_info", pmk_list,
sizeof(*pmk_list));
return err;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void GLES2DecoderImpl::DoUniform1i(GLint fake_location, GLint v0) {
GLenum type = 0;
GLsizei count = 1;
GLint real_location = -1;
if (!PrepForSetUniformByLocation(
fake_location, "glUniform1iv", &real_location, &type, &count)) {
return;
}
current_program_->SetSamplers(fake_location, 1, &v0);
glUniform1i(real_location, v0);
}
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: explicit SyncInternal(const std::string& name)
: name_(name),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
enable_sync_tabs_for_other_clients_(false),
registrar_(NULL),
change_delegate_(NULL),
initialized_(false),
testing_mode_(NON_TEST),
observing_ip_address_changes_(false),
traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord),
encryptor_(NULL),
unrecoverable_error_handler_(NULL),
report_unrecoverable_error_function_(NULL),
created_on_loop_(MessageLoop::current()),
nigori_overwrite_count_(0) {
for (int i = syncable::FIRST_REAL_MODEL_TYPE;
i < syncable::MODEL_TYPE_COUNT; ++i) {
notification_info_map_.insert(
std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo()));
}
BindJsMessageHandler(
"getNotificationState",
&SyncManager::SyncInternal::GetNotificationState);
BindJsMessageHandler(
"getNotificationInfo",
&SyncManager::SyncInternal::GetNotificationInfo);
BindJsMessageHandler(
"getRootNodeDetails",
&SyncManager::SyncInternal::GetRootNodeDetails);
BindJsMessageHandler(
"getNodeSummariesById",
&SyncManager::SyncInternal::GetNodeSummariesById);
BindJsMessageHandler(
"getNodeDetailsById",
&SyncManager::SyncInternal::GetNodeDetailsById);
BindJsMessageHandler(
"getAllNodes",
&SyncManager::SyncInternal::GetAllNodes);
BindJsMessageHandler(
"getChildNodeIds",
&SyncManager::SyncInternal::GetChildNodeIds);
BindJsMessageHandler(
"getClientServerTraffic",
&SyncManager::SyncInternal::GetClientServerTraffic);
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int anon_pipe_buf_steal(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
struct page *page = buf->page;
if (page_count(page) == 1) {
if (memcg_kmem_enabled())
memcg_kmem_uncharge(page, 0);
__SetPageLocked(page);
return 0;
}
return 1;
}
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: PHP_FUNCTION(openssl_error_string)
{
char buf[512];
unsigned long val;
if (zend_parse_parameters_none() == FAILURE) {
return;
}
val = ERR_get_error();
if (val) {
RETURN_STRING(ERR_error_string(val, buf), 1);
} else {
RETURN_FALSE;
}
}
CWE ID: CWE-119
Output:
| 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool ExtensionApiTest::InitializeEmbeddedTestServer() {
if (!embedded_test_server()->InitializeAndListen())
return false;
test_config_->SetInteger(kEmbeddedTestServerPort,
embedded_test_server()->port());
return true;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void nfs_clear_inode(struct inode *inode)
{
/*
* The following should never happen...
*/
BUG_ON(nfs_have_writebacks(inode));
BUG_ON(!list_empty(&NFS_I(inode)->open_files));
nfs_zap_acl_cache(inode);
nfs_access_zap_cache(inode);
}
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 char* lookup_loc_range(const char* loc_range, HashTable* hash_arr, int canonicalize TSRMLS_DC)
{
int i = 0;
int cur_arr_len = 0;
int result = 0;
char* lang_tag = NULL;
zval** ele_value = NULL;
char** cur_arr = NULL;
char* cur_loc_range = NULL;
char* can_loc_range = NULL;
int saved_pos = 0;
char* return_value = NULL;
cur_arr = ecalloc(zend_hash_num_elements(hash_arr)*2, sizeof(char *));
/* convert the array to lowercase , also replace hyphens with the underscore and store it in cur_arr */
for(zend_hash_internal_pointer_reset(hash_arr);
zend_hash_has_more_elements(hash_arr) == SUCCESS;
zend_hash_move_forward(hash_arr)) {
if (zend_hash_get_current_data(hash_arr, (void**)&ele_value) == FAILURE) {
/* Should never actually fail since the key is known to exist.*/
continue;
}
if(Z_TYPE_PP(ele_value)!= IS_STRING) {
/* element value is not a string */
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: locale array element is not a string", 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
cur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_PP(ele_value), Z_STRLEN_PP(ele_value));
result = strToMatch(Z_STRVAL_PP(ele_value), cur_arr[cur_arr_len*2]);
if(result == 0) {
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag", 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
cur_arr[cur_arr_len*2+1] = Z_STRVAL_PP(ele_value);
cur_arr_len++ ;
} /* end of for */
/* Canonicalize array elements */
if(canonicalize) {
for(i=0; i<cur_arr_len; i++) {
lang_tag = get_icu_value_internal(cur_arr[i*2], LOC_CANONICALIZE_TAG, &result, 0);
if(result != 1 || lang_tag == NULL || !lang_tag[0]) {
if(lang_tag) {
efree(lang_tag);
}
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
cur_arr[i*2] = erealloc(cur_arr[i*2], strlen(lang_tag)+1);
result = strToMatch(lang_tag, cur_arr[i*2]);
efree(lang_tag);
if(result == 0) {
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
}
}
if(canonicalize) {
/* Canonicalize the loc_range */
can_loc_range = get_icu_value_internal(loc_range, LOC_CANONICALIZE_TAG, &result , 0);
if( result != 1 || can_loc_range == NULL || !can_loc_range[0]) {
/* Error */
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize loc_range" , 0 TSRMLS_CC );
if(can_loc_range) {
efree(can_loc_range);
}
LOOKUP_CLEAN_RETURN(NULL);
} else {
loc_range = can_loc_range;
}
}
cur_loc_range = ecalloc(1, strlen(loc_range)+1);
/* convert to lower and replace hyphens */
result = strToMatch(loc_range, cur_loc_range);
if(can_loc_range) {
efree(can_loc_range);
}
if(result == 0) {
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
/* Lookup for the lang_tag match */
saved_pos = strlen(cur_loc_range);
while(saved_pos > 0) {
for(i=0; i< cur_arr_len; i++){
if(cur_arr[i*2] != NULL && strlen(cur_arr[i*2]) == saved_pos && strncmp(cur_loc_range, cur_arr[i*2], saved_pos) == 0) {
/* Match found */
return_value = estrdup(canonicalize?cur_arr[i*2]:cur_arr[i*2+1]);
efree(cur_loc_range);
LOOKUP_CLEAN_RETURN(return_value);
}
}
saved_pos = getStrrtokenPos(cur_loc_range, saved_pos);
}
/* Match not found */
efree(cur_loc_range);
LOOKUP_CLEAN_RETURN(NULL);
}
CWE ID: CWE-125
Output:
| 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ff_jpeg2000_cleanup(Jpeg2000Component *comp, Jpeg2000CodingStyle *codsty)
{
int reslevelno, bandno, precno;
for (reslevelno = 0;
comp->reslevel && reslevelno < codsty->nreslevels;
reslevelno++) {
Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
for (bandno = 0; bandno < reslevel->nbands; bandno++) {
Jpeg2000Band *band = reslevel->band + bandno;
for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++) {
Jpeg2000Prec *prec = band->prec + precno;
av_freep(&prec->zerobits);
av_freep(&prec->cblkincl);
av_freep(&prec->cblk);
}
av_freep(&band->prec);
}
av_freep(&reslevel->band);
}
ff_dwt_destroy(&comp->dwt);
av_freep(&comp->reslevel);
av_freep(&comp->i_data);
av_freep(&comp->f_data);
}
CWE ID:
Target: 1
Example 2:
Code: static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
{
return (vmcs12->cpu_based_vm_exec_control &
CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
(vmcs12->secondary_vm_exec_control & bit);
}
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: virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name) {
if (name->Equals(v8::String::New("GetExtensionAPIDefinition"))) {
return v8::FunctionTemplate::New(GetExtensionAPIDefinition);
} else if (name->Equals(v8::String::New("GetExtensionViews"))) {
return v8::FunctionTemplate::New(GetExtensionViews,
v8::External::New(this));
} else if (name->Equals(v8::String::New("GetNextRequestId"))) {
return v8::FunctionTemplate::New(GetNextRequestId);
} else if (name->Equals(v8::String::New("OpenChannelToTab"))) {
return v8::FunctionTemplate::New(OpenChannelToTab);
} else if (name->Equals(v8::String::New("GetNextContextMenuId"))) {
return v8::FunctionTemplate::New(GetNextContextMenuId);
} else if (name->Equals(v8::String::New("GetCurrentPageActions"))) {
return v8::FunctionTemplate::New(GetCurrentPageActions,
v8::External::New(this));
} else if (name->Equals(v8::String::New("StartRequest"))) {
return v8::FunctionTemplate::New(StartRequest,
v8::External::New(this));
} else if (name->Equals(v8::String::New("GetRenderViewId"))) {
return v8::FunctionTemplate::New(GetRenderViewId);
} else if (name->Equals(v8::String::New("SetIconCommon"))) {
return v8::FunctionTemplate::New(SetIconCommon,
v8::External::New(this));
} else if (name->Equals(v8::String::New("IsExtensionProcess"))) {
return v8::FunctionTemplate::New(IsExtensionProcess,
v8::External::New(this));
} else if (name->Equals(v8::String::New("IsIncognitoProcess"))) {
return v8::FunctionTemplate::New(IsIncognitoProcess);
} else if (name->Equals(v8::String::New("GetUniqueSubEventName"))) {
return v8::FunctionTemplate::New(GetUniqueSubEventName);
} else if (name->Equals(v8::String::New("GetLocalFileSystem"))) {
return v8::FunctionTemplate::New(GetLocalFileSystem);
} else if (name->Equals(v8::String::New("DecodeJPEG"))) {
return v8::FunctionTemplate::New(DecodeJPEG, v8::External::New(this));
}
return ExtensionBase::GetNativeFunction(name);
}
CWE ID: CWE-20
Output:
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.