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: OMX_ERRORTYPE omx_video::allocate_output_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header
unsigned i= 0; // Temporary counter
#ifdef _MSM8974_
int align_size;
#endif
DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes);
if (!m_out_mem_ptr) {
int nBufHdrSize = 0;
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual);
nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE);
/*
* Memory for output side involves the following:
* 1. Array of Buffer Headers
* 2. Bitmask array to hold the buffer allocation details
* In order to minimize the memory management entire allocation
* is done in one step.
*/
m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1);
#ifdef USE_ION
m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem");
return OMX_ErrorInsufficientResources;
}
if (m_out_mem_ptr && m_pOutput_pmem) {
bufHdr = m_out_mem_ptr;
for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) {
bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
bufHdr->nVersion.nVersion = OMX_SPEC_VERSION;
bufHdr->nAllocLen = bytes;
bufHdr->nFilledLen = 0;
bufHdr->pAppPrivate = appData;
bufHdr->nOutputPortIndex = PORT_INDEX_OUT;
bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i];
bufHdr->pBuffer = NULL;
bufHdr++;
m_pOutput_pmem[i].fd = -1;
#ifdef USE_ION
m_pOutput_ion[i].ion_device_fd =-1;
m_pOutput_ion[i].fd_ion_data.fd=-1;
m_pOutput_ion[i].ion_alloc_data.handle = 0;
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem");
eRet = OMX_ErrorInsufficientResources;
}
}
DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual);
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_out_bm_count,i)) {
DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i);
break;
}
}
if (eRet == OMX_ErrorNone) {
if (i < m_sOutPortDef.nBufferCountActual) {
#ifdef USE_ION
#ifdef _MSM8974_
align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096;
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED);
#else
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pOutput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd;
#else
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pOutput_pmem[i].fd == 0) {
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pOutput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].offset = 0;
m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
#ifdef _MSM8974_
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
align_size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#else
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#endif
if (m_pOutput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer");
close (m_pOutput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pOutput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
}
else {
m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
(*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*);
native_handle_t *handle = native_handle_create(1, 0);
handle->data[0] = m_pOutput_pmem[i].fd;
char *data = (char*) m_pOutput_pmem[i].buffer;
OMX_U32 type = 1;
memcpy(data, &type, sizeof(OMX_U32));
memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*));
}
*bufferHdr = (m_out_mem_ptr + i );
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer;
(*bufferHdr)->pAppPrivate = appData;
BITMASK_SET(&m_out_bm_count,i);
if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call"
"for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual);
}
}
return eRet;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void local_flush_tlb_all(void)
{
/* Invalidate all, including shared pages, excluding fixed TLBs */
unsigned long flags, tlb;
local_irq_save(flags);
/* Flush each ITLB entry */
for_each_itlb_entry(tlb)
__flush_tlb_slot(tlb);
/* Flush each DTLB entry */
for_each_dtlb_entry(tlb)
__flush_tlb_slot(tlb);
local_irq_restore(flags);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: update_info_in_idle_cb (gpointer user_data)
{
UpdateInfoInIdleData *data = user_data;
/* this indirectly calls update_info and also removes the device
* if it wants to be removed (e.g. if update_info() returns FALSE)
*/
daemon_local_synthesize_changed (data->device->priv->daemon, data->device);
return FALSE; /* remove source */
}
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 InspectorClientImpl::clearBrowserCache()
{
if (WebDevToolsAgentImpl* agent = devToolsAgent())
agent->clearBrowserCache();
}
CWE ID:
Target: 1
Example 2:
Code: ExtensionTtsPlatformImplChromeOs() {}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)
{
switch (mem->type) {
case RXE_MEM_TYPE_DMA:
return 0;
case RXE_MEM_TYPE_MR:
case RXE_MEM_TYPE_FMR:
return ((iova < mem->iova) ||
((iova + length) > (mem->iova + mem->length))) ?
-EFAULT : 0;
default:
return -EFAULT;
}
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_byte = data[0];
ut64 offset = addr - java_get_method_start ();
ut8 pos = (offset+1)%4 ? 1 + 4 - (offset+1)%4 : 1;
if (op_byte == 0xaa) {
if (pos + 8 > len) {
return op->size;
}
int min_val = (ut32)(UINT (data, pos + 4)),
max_val = (ut32)(UINT (data, pos + 8));
ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0;
op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);
RAnalCaseOp *caseop = NULL;
pos += 12;
if (max_val > min_val && ((max_val - min_val)<(UT16_MAX/4))) {
for (cur_case = 0; cur_case <= max_val - min_val; pos += 4, cur_case++) {
if (pos + 4 >= len) {
break;
}
int offset = (int)(ut32)(R_BIN_JAVA_UINT (data, pos));
caseop = r_anal_switch_op_add_case (op->switch_op,
addr + pos, cur_case + min_val, addr + offset);
if (caseop) {
caseop->bb_ref_to = addr+offset;
caseop->bb_ref_from = addr; // TODO figure this one out
}
}
} else {
eprintf ("Invalid switch boundaries at 0x%"PFMT64x"\n", addr);
}
}
op->size = pos;
return op->size;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: SProcRenderQueryPictIndexValues (ClientPtr client)
{
register int n;
REQUEST(xRenderQueryPictIndexValuesReq);
swaps(&stuff->length, n);
swapl(&stuff->format, n);
return (*ProcRenderVector[stuff->renderReqType]) (client);
}
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 FrameImpl::GoBack() {
NOTIMPLEMENTED();
}
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: load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity,
char immediate_load)
{
static const int intoffset[] = { 0, 4, 2, 1 };
static const int intjump[] = { 8, 8, 4, 2 };
int rc;
DATA32 *ptr;
GifFileType *gif;
GifRowType *rows;
GifRecordType rec;
ColorMapObject *cmap;
int i, j, done, bg, r, g, b, w = 0, h = 0;
float per = 0.0, per_inc;
int last_per = 0, last_y = 0;
int transp;
int fd;
done = 0;
rows = NULL;
transp = -1;
/* if immediate_load is 1, then dont delay image laoding as below, or */
/* already data in this image - dont load it again */
if (im->data)
return 0;
fd = open(im->real_file, O_RDONLY);
if (fd < 0)
return 0;
#if GIFLIB_MAJOR >= 5
gif = DGifOpenFileHandle(fd, NULL);
#else
gif = DGifOpenFileHandle(fd);
#endif
if (!gif)
{
close(fd);
return 0;
}
rc = 0; /* Failure */
do
{
if (DGifGetRecordType(gif, &rec) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done))
{
if (DGifGetImageDesc(gif) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
w = gif->Image.Width;
h = gif->Image.Height;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit2;
rows = calloc(h, sizeof(GifRowType *));
if (!rows)
goto quit2;
for (i = 0; i < h; i++)
{
rows[i] = malloc(w * sizeof(GifPixelType));
if (!rows[i])
goto quit;
}
if (gif->Image.Interlace)
{
for (i = 0; i < 4; i++)
{
for (j = intoffset[i]; j < h; j += intjump[i])
{
DGifGetLine(gif, rows[j], w);
}
}
}
else
{
for (i = 0; i < h; i++)
{
DGifGetLine(gif, rows[i], w);
}
}
done = 1;
}
else if (rec == EXTENSION_RECORD_TYPE)
{
int ext_code;
GifByteType *ext;
ext = NULL;
DGifGetExtension(gif, &ext_code, &ext);
while (ext)
{
if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0))
{
transp = (int)ext[4];
}
ext = NULL;
DGifGetExtensionNext(gif, &ext);
}
}
}
while (rec != TERMINATE_RECORD_TYPE);
if (transp >= 0)
{
SET_FLAG(im->flags, F_HAS_ALPHA);
}
else
{
UNSET_FLAG(im->flags, F_HAS_ALPHA);
}
/* set the format string member to the lower-case full extension */
/* name for the format - so example names would be: */
/* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */
im->w = w;
im->h = h;
if (!im->format)
im->format = strdup("gif");
if (im->loader || immediate_load || progress)
{
bg = gif->SBackGroundColor;
cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap);
im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h);
if (!im->data)
goto quit;
ptr = im->data;
per_inc = 100.0 / (((float)w) * h);
for (i = 0; i < h; i++)
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
}
per += per_inc;
if (progress && (((int)per) != last_per)
&& (((int)per) % progress_granularity == 0))
{
last_per = (int)per;
if (!(progress(im, (int)per, 0, last_y, w, i)))
{
rc = 2;
goto quit;
}
last_y = i;
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int init_rmode_tss(struct kvm *kvm)
{
gfn_t fn;
u16 data = 0;
int r, idx, ret = 0;
idx = srcu_read_lock(&kvm->srcu);
fn = kvm->arch.tss_addr >> PAGE_SHIFT;
r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
if (r < 0)
goto out;
data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
r = kvm_write_guest_page(kvm, fn++, &data,
TSS_IOPB_BASE_OFFSET, sizeof(u16));
if (r < 0)
goto out;
r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
if (r < 0)
goto out;
r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
if (r < 0)
goto out;
data = ~0;
r = kvm_write_guest_page(kvm, fn, &data,
RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
sizeof(u8));
if (r < 0)
goto out;
ret = 1;
out:
srcu_read_unlock(&kvm->srcu, idx);
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: ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
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: bool NormalPageArena::expandObject(HeapObjectHeader* header, size_t newSize) {
ASSERT(header->checkHeader());
if (header->payloadSize() >= newSize)
return true;
size_t allocationSize = ThreadHeap::allocationSizeFromSize(newSize);
ASSERT(allocationSize > header->size());
size_t expandSize = allocationSize - header->size();
if (isObjectAllocatedAtAllocationPoint(header) &&
expandSize <= m_remainingAllocationSize) {
m_currentAllocationPoint += expandSize;
ASSERT(m_remainingAllocationSize >= expandSize);
setRemainingAllocationSize(m_remainingAllocationSize - expandSize);
SET_MEMORY_ACCESSIBLE(header->payloadEnd(), expandSize);
header->setSize(allocationSize);
ASSERT(findPageFromAddress(header->payloadEnd() - 1));
return true;
}
return false;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: int libevt_record_values_free(
libevt_record_values_t **record_values,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_free";
int result = 1;
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( *record_values != NULL )
{
if( ( *record_values )->source_name != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->source_name ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free source name value.",
function );
result = -1;
}
}
if( ( *record_values )->computer_name != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->computer_name ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free computer name value.",
function );
result = -1;
}
}
if( ( *record_values )->user_security_identifier != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->user_security_identifier ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free user security identifier (SID).",
function );
result = -1;
}
}
if( ( *record_values )->strings != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->strings ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free strings.",
function );
result = -1;
}
}
if( ( *record_values )->data != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->data ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free data.",
function );
result = -1;
}
}
memory_free(
*record_values );
*record_values = NULL;
}
return( result );
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static JSValue setDataViewMember(ExecState* exec, DataView* imp, DataViewAccessType type)
{
if (exec->argumentCount() < 2)
return throwError(exec, createTypeError(exec, "Not enough arguments"));
ExceptionCode ec = 0;
unsigned byteOffset = exec->argument(0).toUInt32(exec);
if (exec->hadException())
return jsUndefined();
int value = exec->argument(1).toInt32(exec);
if (exec->hadException())
return jsUndefined();
switch (type) {
case AccessDataViewMemberAsInt8:
imp->setInt8(byteOffset, static_cast<int8_t>(value), ec);
break;
case AccessDataViewMemberAsUint8:
imp->setUint8(byteOffset, static_cast<uint8_t>(value), ec);
break;
default:
ASSERT_NOT_REACHED();
break;
}
setDOMException(exec, ec);
return jsUndefined();
}
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: GpuProcessHost::~GpuProcessHost() {
DCHECK(CalledOnValidThread());
SendOutstandingReplies();
if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) {
if (software_rendering_) {
if (++g_gpu_software_crash_count >= kGpuMaxCrashCount) {
gpu_enabled_ = false;
}
} else {
if (++g_gpu_crash_count >= kGpuMaxCrashCount) {
#if !defined(OS_CHROMEOS)
hardware_gpu_enabled_ = false;
GpuDataManagerImpl::GetInstance()->BlacklistCard();
#endif
}
}
}
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents",
DIED_FIRST_TIME + g_gpu_crash_count,
GPU_PROCESS_LIFETIME_EVENT_MAX);
int exit_code;
base::TerminationStatus status = process_->GetTerminationStatus(&exit_code);
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus",
status,
base::TERMINATION_STATUS_MAX_ENUM);
if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION ||
status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) {
UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode",
exit_code,
content::RESULT_CODE_LAST_CODE);
}
#if defined(OS_WIN)
if (gpu_process_)
CloseHandle(gpu_process_);
#endif
while (!queued_messages_.empty()) {
delete queued_messages_.front();
queued_messages_.pop();
}
if (g_gpu_process_hosts[kind_] == this)
g_gpu_process_hosts[kind_] = NULL;
BrowserThread::PostTask(BrowserThread::UI,
FROM_HERE,
base::Bind(&GpuProcessHostUIShim::Destroy, host_id_));
}
CWE ID:
Target: 1
Example 2:
Code: str_replace (const char* search, const char* replace, const char* string) {
gchar **buf;
char *ret;
if(!string)
return NULL;
buf = g_strsplit (string, search, -1);
ret = g_strjoinv (replace, buf);
g_strfreev(buf);
return ret;
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int comp_t1_glyphs(const void *pa, const void *pb, void *p)
{
return strcmp(*((const char * const *) pa), *((const char * const *) pb));
}
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: hstore_from_record(PG_FUNCTION_ARGS)
{
HeapTupleHeader rec;
int32 buflen;
HStore *out;
Pairs *pairs;
Oid tupType;
int32 tupTypmod;
TupleDesc tupdesc;
HeapTupleData tuple;
RecordIOData *my_extra;
int ncolumns;
int i,
j;
Datum *values;
bool *nulls;
if (PG_ARGISNULL(0))
{
Oid argtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
/*
* have no tuple to look at, so the only source of type info is the
* argtype. The lookup_rowtype_tupdesc call below will error out if we
* don't have a known composite type oid here.
*/
tupType = argtype;
tupTypmod = -1;
rec = NULL;
}
else
{
rec = PG_GETARG_HEAPTUPLEHEADER(0);
/* Extract type info from the tuple itself */
tupType = HeapTupleHeaderGetTypeId(rec);
tupTypmod = HeapTupleHeaderGetTypMod(rec);
}
tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
ncolumns = tupdesc->natts;
/*
* We arrange to look up the needed I/O info just once per series of
* calls, assuming the record type doesn't change underneath us.
*/
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
if (my_extra == NULL ||
my_extra->ncolumns != ncolumns)
{
fcinfo->flinfo->fn_extra =
MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
my_extra->record_type = InvalidOid;
my_extra->record_typmod = 0;
}
if (my_extra->record_type != tupType ||
my_extra->record_typmod != tupTypmod)
{
MemSet(my_extra, 0,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra->record_type = tupType;
my_extra->record_typmod = tupTypmod;
my_extra->ncolumns = ncolumns;
}
pairs = palloc(ncolumns * sizeof(Pairs));
if (rec)
{
/* Build a temporary HeapTuple control structure */
tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
ItemPointerSetInvalid(&(tuple.t_self));
tuple.t_tableOid = InvalidOid;
tuple.t_data = rec;
values = (Datum *) palloc(ncolumns * sizeof(Datum));
nulls = (bool *) palloc(ncolumns * sizeof(bool));
/* Break down the tuple into fields */
heap_deform_tuple(&tuple, tupdesc, values, nulls);
}
else
{
values = NULL;
nulls = NULL;
}
for (i = 0, j = 0; i < ncolumns; ++i)
{
ColumnIOData *column_info = &my_extra->columns[i];
Oid column_type = tupdesc->attrs[i]->atttypid;
char *value;
/* Ignore dropped columns in datatype */
if (tupdesc->attrs[i]->attisdropped)
continue;
pairs[j].key = NameStr(tupdesc->attrs[i]->attname);
pairs[j].keylen = hstoreCheckKeyLen(strlen(NameStr(tupdesc->attrs[i]->attname)));
if (!nulls || nulls[i])
{
pairs[j].val = NULL;
pairs[j].vallen = 4;
pairs[j].isnull = true;
pairs[j].needfree = false;
++j;
continue;
}
/*
* Convert the column value to text
*/
if (column_info->column_type != column_type)
{
bool typIsVarlena;
getTypeOutputInfo(column_type,
&column_info->typiofunc,
&typIsVarlena);
fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
fcinfo->flinfo->fn_mcxt);
column_info->column_type = column_type;
}
value = OutputFunctionCall(&column_info->proc, values[i]);
pairs[j].val = value;
pairs[j].vallen = hstoreCheckValLen(strlen(value));
pairs[j].isnull = false;
pairs[j].needfree = false;
++j;
}
ncolumns = hstoreUniquePairs(pairs, j, &buflen);
out = hstorePairs(pairs, ncolumns, buflen);
ReleaseTupleDesc(tupdesc);
PG_RETURN_POINTER(out);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void follow_mount(struct path *path)
{
while (d_mountpoint(path->dentry)) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
}
}
CWE ID: CWE-254
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int bluebird_fx2_identify_state(struct usb_device *udev,
struct dvb_usb_device_properties *props,
struct dvb_usb_device_description **desc,
int *cold)
{
int wascold = *cold;
*cold = udev->descriptor.bDeviceClass == 0xff &&
udev->descriptor.bDeviceSubClass == 0xff &&
udev->descriptor.bDeviceProtocol == 0xff;
if (*cold && !wascold)
*desc = NULL;
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: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: tracing_buffers_splice_read(struct file *file, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct ftrace_buffer_info *info = file->private_data;
struct trace_iterator *iter = &info->iter;
struct partial_page partial_def[PIPE_DEF_BUFFERS];
struct page *pages_def[PIPE_DEF_BUFFERS];
struct splice_pipe_desc spd = {
.pages = pages_def,
.partial = partial_def,
.nr_pages_max = PIPE_DEF_BUFFERS,
.ops = &buffer_pipe_buf_ops,
.spd_release = buffer_spd_release,
};
struct buffer_ref *ref;
int entries, i;
ssize_t ret = 0;
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->tr->current_trace->use_max_tr)
return -EBUSY;
#endif
if (*ppos & (PAGE_SIZE - 1))
return -EINVAL;
if (len & (PAGE_SIZE - 1)) {
if (len < PAGE_SIZE)
return -EINVAL;
len &= PAGE_MASK;
}
if (splice_grow_spd(pipe, &spd))
return -ENOMEM;
again:
trace_access_lock(iter->cpu_file);
entries = ring_buffer_entries_cpu(iter->trace_buffer->buffer, iter->cpu_file);
for (i = 0; i < spd.nr_pages_max && len && entries; i++, len -= PAGE_SIZE) {
struct page *page;
int r;
ref = kzalloc(sizeof(*ref), GFP_KERNEL);
if (!ref) {
ret = -ENOMEM;
break;
}
ref->ref = 1;
ref->buffer = iter->trace_buffer->buffer;
ref->page = ring_buffer_alloc_read_page(ref->buffer, iter->cpu_file);
if (IS_ERR(ref->page)) {
ret = PTR_ERR(ref->page);
ref->page = NULL;
kfree(ref);
break;
}
ref->cpu = iter->cpu_file;
r = ring_buffer_read_page(ref->buffer, &ref->page,
len, iter->cpu_file, 1);
if (r < 0) {
ring_buffer_free_read_page(ref->buffer, ref->cpu,
ref->page);
kfree(ref);
break;
}
page = virt_to_page(ref->page);
spd.pages[i] = page;
spd.partial[i].len = PAGE_SIZE;
spd.partial[i].offset = 0;
spd.partial[i].private = (unsigned long)ref;
spd.nr_pages++;
*ppos += PAGE_SIZE;
entries = ring_buffer_entries_cpu(iter->trace_buffer->buffer, iter->cpu_file);
}
trace_access_unlock(iter->cpu_file);
spd.nr_pages = i;
/* did we read anything? */
if (!spd.nr_pages) {
if (ret)
goto out;
ret = -EAGAIN;
if ((file->f_flags & O_NONBLOCK) || (flags & SPLICE_F_NONBLOCK))
goto out;
ret = wait_on_pipe(iter, true);
if (ret)
goto out;
goto again;
}
ret = splice_to_pipe(pipe, &spd);
out:
splice_shrink_spd(&spd);
return ret;
}
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: PHP_METHOD(Phar, delete)
{
char *fname;
size_t fname_len;
char *error;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write out phar archive, phar is read-only");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
RETURN_FALSE;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) {
if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) {
if (entry->is_deleted) {
/* entry is deleted, but has not been flushed to disk yet */
RETURN_TRUE;
} else {
entry->is_deleted = 1;
entry->is_modified = 1;
phar_obj->archive->is_modified = 1;
}
}
} else {
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname);
RETURN_FALSE;
}
phar_flush(phar_obj->archive, NULL, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
RETURN_TRUE;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void WallpaperManager::SetDefaultWallpaperPathsFromCommandLine(
base::CommandLine* command_line) {
default_small_wallpaper_file_ = command_line->GetSwitchValuePath(
chromeos::switches::kDefaultWallpaperSmall);
default_large_wallpaper_file_ = command_line->GetSwitchValuePath(
chromeos::switches::kDefaultWallpaperLarge);
guest_small_wallpaper_file_ = command_line->GetSwitchValuePath(
chromeos::switches::kGuestWallpaperSmall);
guest_large_wallpaper_file_ = command_line->GetSwitchValuePath(
chromeos::switches::kGuestWallpaperLarge);
child_small_wallpaper_file_ = command_line->GetSwitchValuePath(
chromeos::switches::kChildWallpaperSmall);
child_large_wallpaper_file_ = command_line->GetSwitchValuePath(
chromeos::switches::kChildWallpaperLarge);
default_wallpaper_image_.reset();
}
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: SessionStartupPref StartupBrowserCreator::GetSessionStartupPref(
const base::CommandLine& command_line,
Profile* profile) {
DCHECK(profile);
PrefService* prefs = profile->GetPrefs();
SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs);
#if defined(OS_CHROMEOS)
const bool is_first_run =
user_manager::UserManager::Get()->IsCurrentUserNew();
const bool did_restart = false;
StartupBrowserCreator::WasRestarted();
#else
const bool is_first_run = first_run::IsChromeFirstRun();
const bool did_restart = StartupBrowserCreator::WasRestarted();
#endif
if (is_first_run && SessionStartupPref::TypeIsDefault(prefs))
pref.type = SessionStartupPref::DEFAULT;
if ((command_line.HasSwitch(switches::kRestoreLastSession) || did_restart) &&
!profile->IsNewProfile()) {
pref.type = SessionStartupPref::LAST;
}
if (!profile->IsGuestSession()) {
ProfileAttributesEntry* entry = nullptr;
bool has_entry =
g_browser_process->profile_manager()
->GetProfileAttributesStorage()
.GetProfileAttributesWithPath(profile->GetPath(), &entry);
if (has_entry && entry->IsSigninRequired())
pref.type = SessionStartupPref::LAST;
}
if (pref.type == SessionStartupPref::LAST &&
IncognitoModePrefs::ShouldLaunchIncognito(command_line, prefs)) {
pref.type = SessionStartupPref::DEFAULT;
}
return pref;
}
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: static void TearDownTestCase() {
vpx_free(source_data_);
source_data_ = NULL;
vpx_free(reference_data_);
reference_data_ = NULL;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static TEE_Result check_ta_store(void)
{
const struct user_ta_store_ops *op = NULL;
SCATTERED_ARRAY_FOREACH(op, ta_stores, struct user_ta_store_ops)
DMSG("TA store: \"%s\"", op->description);
return TEE_SUCCESS;
}
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 ssl_write_record( ssl_context *ssl )
{
int ret, done = 0;
size_t len = ssl->out_msglen;
SSL_DEBUG_MSG( 2, ( "=> write record" ) );
if( ssl->out_msgtype == SSL_MSG_HANDSHAKE )
{
ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 );
ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 );
ssl->out_msg[3] = (unsigned char)( ( len - 4 ) );
ssl->handshake->update_checksum( ssl, ssl->out_msg, len );
}
#if defined(POLARSSL_ZLIB_SUPPORT)
if( ssl->transform_out != NULL &&
ssl->session_out->compression == SSL_COMPRESS_DEFLATE )
{
if( ( ret = ssl_compress_buf( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_compress_buf", ret );
return( ret );
}
len = ssl->out_msglen;
}
#endif /*POLARSSL_ZLIB_SUPPORT */
#if defined(POLARSSL_SSL_HW_RECORD_ACCEL)
if( ssl_hw_record_write != NULL)
{
SSL_DEBUG_MSG( 2, ( "going for ssl_hw_record_write()" ) );
ret = ssl_hw_record_write( ssl );
if( ret != 0 && ret != POLARSSL_ERR_SSL_HW_ACCEL_FALLTHROUGH )
{
SSL_DEBUG_RET( 1, "ssl_hw_record_write", ret );
return POLARSSL_ERR_SSL_HW_ACCEL_FAILED;
}
done = 1;
}
#endif
if( !done )
{
ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype;
ssl->out_hdr[1] = (unsigned char) ssl->major_ver;
ssl->out_hdr[2] = (unsigned char) ssl->minor_ver;
ssl->out_hdr[3] = (unsigned char)( len >> 8 );
ssl->out_hdr[4] = (unsigned char)( len );
if( ssl->transform_out != NULL )
{
if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret );
return( ret );
}
len = ssl->out_msglen;
ssl->out_hdr[3] = (unsigned char)( len >> 8 );
ssl->out_hdr[4] = (unsigned char)( len );
}
ssl->out_left = 5 + ssl->out_msglen;
SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, "
"version = [%d:%d], msglen = %d",
ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2],
( ssl->out_hdr[3] << 8 ) | ssl->out_hdr[4] ) );
SSL_DEBUG_BUF( 4, "output record header sent to network",
ssl->out_hdr, 5 );
SSL_DEBUG_BUF( 4, "output record sent to network",
ssl->out_hdr + 32, ssl->out_msglen );
}
if( ( ret = ssl_flush_output( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_flush_output", ret );
return( ret );
}
SSL_DEBUG_MSG( 2, ( "<= write record" ) );
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 dccp_error(struct net *net, struct nf_conn *tmpl,
struct sk_buff *skb, unsigned int dataoff,
enum ip_conntrack_info *ctinfo,
u_int8_t pf, unsigned int hooknum)
{
struct dccp_hdr _dh, *dh;
unsigned int dccp_len = skb->len - dataoff;
unsigned int cscov;
const char *msg;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
if (dh == NULL) {
msg = "nf_ct_dccp: short packet ";
goto out_invalid;
}
if (dh->dccph_doff * 4 < sizeof(struct dccp_hdr) ||
dh->dccph_doff * 4 > dccp_len) {
msg = "nf_ct_dccp: truncated/malformed packet ";
goto out_invalid;
}
cscov = dccp_len;
if (dh->dccph_cscov) {
cscov = (dh->dccph_cscov - 1) * 4;
if (cscov > dccp_len) {
msg = "nf_ct_dccp: bad checksum coverage ";
goto out_invalid;
}
}
if (net->ct.sysctl_checksum && hooknum == NF_INET_PRE_ROUTING &&
nf_checksum_partial(skb, hooknum, dataoff, cscov, IPPROTO_DCCP,
pf)) {
msg = "nf_ct_dccp: bad checksum ";
goto out_invalid;
}
if (dh->dccph_type >= DCCP_PKT_INVALID) {
msg = "nf_ct_dccp: reserved packet type ";
goto out_invalid;
}
return NF_ACCEPT;
out_invalid:
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, "%s", msg);
return -NF_ACCEPT;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: GraphicsContext3D::GraphicsContext3D(GraphicsContext3D::Attributes attrs, HostWindow* hostWindow, GraphicsContext3D::RenderStyle renderStyle)
: m_currentWidth(0)
, m_currentHeight(0)
, m_compiler(isGLES2Compliant() ? SH_ESSL_OUTPUT : SH_GLSL_OUTPUT)
, m_attrs(attrs)
, m_renderStyle(renderStyle)
, m_texture(0)
, m_compositorTexture(0)
, m_fbo(0)
#if USE(OPENGL_ES_2)
, m_depthBuffer(0)
, m_stencilBuffer(0)
#endif
, m_depthStencilBuffer(0)
, m_layerComposited(false)
, m_internalColorFormat(0)
, m_boundFBO(0)
, m_activeTexture(GL_TEXTURE0)
, m_boundTexture0(0)
, m_multisampleFBO(0)
, m_multisampleDepthStencilBuffer(0)
, m_multisampleColorBuffer(0)
, m_private(adoptPtr(new GraphicsContext3DPrivate(this, hostWindow, renderStyle)))
{
validateAttributes();
if (!m_private->m_surface) {
LOG_ERROR("GraphicsContext3D: QGLWidget initialization failed.");
m_private = nullptr;
return;
}
static bool initialized = false;
static bool success = true;
if (!initialized) {
success = initializeOpenGLShims();
initialized = true;
}
if (!success) {
m_private = nullptr;
return;
}
if (renderStyle == RenderOffscreen)
m_private->createOffscreenBuffers();
m_private->initializeANGLE();
#if !USE(OPENGL_ES_2)
glEnable(GL_POINT_SPRITE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
#endif
if (renderStyle != RenderToCurrentGLContext)
glClearColor(0.0, 0.0, 0.0, 0.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 SyncBackendHost::NotifyUpdatedToken(const std::string& token) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
TokenAvailableDetails details(GaiaConstants::kSyncService, token);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TOKEN_UPDATED,
content::Source<Profile>(profile_),
content::Details<const TokenAvailableDetails>(&details));
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: krb5_gss_process_context_token(minor_status, context_handle,
token_buffer)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_buffer_t token_buffer;
{
krb5_gss_ctx_id_rec *ctx;
OM_uint32 majerr;
ctx = (krb5_gss_ctx_id_t) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
/* "unseal" the token */
if (GSS_ERROR(majerr = kg_unseal(minor_status, context_handle,
token_buffer,
GSS_C_NO_BUFFER, NULL, NULL,
KG_TOK_DEL_CTX)))
return(majerr);
/* that's it. delete the context */
return(krb5_gss_delete_sec_context(minor_status, &context_handle,
GSS_C_NO_BUFFER));
}
CWE ID:
Target: 1
Example 2:
Code: SYSCALL_DEFINE2(sigaltstack,const stack_t __user *,uss, stack_t __user *,uoss)
{
stack_t new, old;
int err;
if (uss && copy_from_user(&new, uss, sizeof(stack_t)))
return -EFAULT;
err = do_sigaltstack(uss ? &new : NULL, uoss ? &old : NULL,
current_user_stack_pointer());
if (!err && uoss && copy_to_user(uoss, &old, sizeof(stack_t)))
err = -EFAULT;
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: ut64 MACH0_(get_baddr)(struct MACH0_(obj_t)* bin) {
int i;
if (bin->hdr.filetype != MH_EXECUTE && bin->hdr.filetype != MH_DYLINKER)
return 0;
for (i = 0; i < bin->nsegs; ++i)
if (bin->segs[i].fileoff == 0 && bin->segs[i].filesize != 0)
return bin->segs[i].vmaddr;
return 0;
}
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int sctp_rcv(struct sk_buff *skb)
{
struct sock *sk;
struct sctp_association *asoc;
struct sctp_endpoint *ep = NULL;
struct sctp_ep_common *rcvr;
struct sctp_transport *transport = NULL;
struct sctp_chunk *chunk;
struct sctphdr *sh;
union sctp_addr src;
union sctp_addr dest;
int family;
struct sctp_af *af;
if (skb->pkt_type!=PACKET_HOST)
goto discard_it;
SCTP_INC_STATS_BH(SCTP_MIB_INSCTPPACKS);
if (skb_linearize(skb))
goto discard_it;
sh = sctp_hdr(skb);
/* Pull up the IP and SCTP headers. */
__skb_pull(skb, skb_transport_offset(skb));
if (skb->len < sizeof(struct sctphdr))
goto discard_it;
if (!skb_csum_unnecessary(skb) && sctp_rcv_checksum(skb) < 0)
goto discard_it;
skb_pull(skb, sizeof(struct sctphdr));
/* Make sure we at least have chunk headers worth of data left. */
if (skb->len < sizeof(struct sctp_chunkhdr))
goto discard_it;
family = ipver2af(ip_hdr(skb)->version);
af = sctp_get_af_specific(family);
if (unlikely(!af))
goto discard_it;
/* Initialize local addresses for lookups. */
af->from_skb(&src, skb, 1);
af->from_skb(&dest, skb, 0);
/* If the packet is to or from a non-unicast address,
* silently discard the packet.
*
* This is not clearly defined in the RFC except in section
* 8.4 - OOTB handling. However, based on the book "Stream Control
* Transmission Protocol" 2.1, "It is important to note that the
* IP address of an SCTP transport address must be a routable
* unicast address. In other words, IP multicast addresses and
* IP broadcast addresses cannot be used in an SCTP transport
* address."
*/
if (!af->addr_valid(&src, NULL, skb) ||
!af->addr_valid(&dest, NULL, skb))
goto discard_it;
asoc = __sctp_rcv_lookup(skb, &src, &dest, &transport);
if (!asoc)
ep = __sctp_rcv_lookup_endpoint(&dest);
/* Retrieve the common input handling substructure. */
rcvr = asoc ? &asoc->base : &ep->base;
sk = rcvr->sk;
/*
* If a frame arrives on an interface and the receiving socket is
* bound to another interface, via SO_BINDTODEVICE, treat it as OOTB
*/
if (sk->sk_bound_dev_if && (sk->sk_bound_dev_if != af->skb_iif(skb)))
{
if (asoc) {
sctp_association_put(asoc);
asoc = NULL;
} else {
sctp_endpoint_put(ep);
ep = NULL;
}
sk = sctp_get_ctl_sock();
ep = sctp_sk(sk)->ep;
sctp_endpoint_hold(ep);
rcvr = &ep->base;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets.
* An SCTP packet is called an "out of the blue" (OOTB)
* packet if it is correctly formed, i.e., passed the
* receiver's checksum check, but the receiver is not
* able to identify the association to which this
* packet belongs.
*/
if (!asoc) {
if (sctp_rcv_ootb(skb)) {
SCTP_INC_STATS_BH(SCTP_MIB_OUTOFBLUES);
goto discard_release;
}
}
if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family))
goto discard_release;
nf_reset(skb);
if (sk_filter(sk, skb))
goto discard_release;
/* Create an SCTP packet structure. */
chunk = sctp_chunkify(skb, asoc, sk);
if (!chunk)
goto discard_release;
SCTP_INPUT_CB(skb)->chunk = chunk;
/* Remember what endpoint is to handle this packet. */
chunk->rcvr = rcvr;
/* Remember the SCTP header. */
chunk->sctp_hdr = sh;
/* Set the source and destination addresses of the incoming chunk. */
sctp_init_addrs(chunk, &src, &dest);
/* Remember where we came from. */
chunk->transport = transport;
/* Acquire access to the sock lock. Note: We are safe from other
* bottom halves on this lock, but a user may be in the lock too,
* so check if it is busy.
*/
sctp_bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_BACKLOG);
sctp_add_backlog(sk, skb);
} else {
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_SOFTIRQ);
sctp_inq_push(&chunk->rcvr->inqueue, chunk);
}
sctp_bh_unlock_sock(sk);
/* Release the asoc/ep ref we took in the lookup calls. */
if (asoc)
sctp_association_put(asoc);
else
sctp_endpoint_put(ep);
return 0;
discard_it:
SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_DISCARDS);
kfree_skb(skb);
return 0;
discard_release:
/* Release the asoc/ep ref we took in the lookup calls. */
if (asoc)
sctp_association_put(asoc);
else
sctp_endpoint_put(ep);
goto discard_it;
}
CWE ID: CWE-362
Target: 1
Example 2:
Code: void PushMessagingServiceImpl::DidUnsubscribe(
const std::string& app_id_when_instance_id,
bool was_subscribed) {
if (!app_id_when_instance_id.empty())
GetInstanceIDDriver()->RemoveInstanceID(app_id_when_instance_id);
if (was_subscribed)
DecreasePushSubscriptionCount(1, false /* was_pending */);
if (!unsubscribe_callback_for_testing_.is_null())
unsubscribe_callback_for_testing_.Run();
}
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 mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)
{
AVStream *st;
MOVStreamContext *sc;
int entries, i, j;
if (c->fc->nb_streams < 1)
return 0;
st = c->fc->streams[c->fc->nb_streams-1];
sc = st->priv_data;
avio_rb32(pb); // version + flags
entries = avio_rb32(pb);
if (entries >= UINT_MAX / sizeof(*sc->drefs))
return AVERROR_INVALIDDATA;
av_free(sc->drefs);
sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));
if (!sc->drefs)
return AVERROR(ENOMEM);
sc->drefs_count = entries;
for (i = 0; i < sc->drefs_count; i++) {
MOVDref *dref = &sc->drefs[i];
uint32_t size = avio_rb32(pb);
int64_t next = avio_tell(pb) + size - 4;
if (size < 12)
return AVERROR_INVALIDDATA;
dref->type = avio_rl32(pb);
avio_rb32(pb); // version + flags
av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);
if (dref->type == MKTAG('a','l','i','s') && size > 150) {
/* macintosh alias record */
uint16_t volume_len, len;
int16_t type;
avio_skip(pb, 10);
volume_len = avio_r8(pb);
volume_len = FFMIN(volume_len, 27);
avio_read(pb, dref->volume, 27);
dref->volume[volume_len] = 0;
av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);
avio_skip(pb, 12);
len = avio_r8(pb);
len = FFMIN(len, 63);
avio_read(pb, dref->filename, 63);
dref->filename[len] = 0;
av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);
avio_skip(pb, 16);
/* read next level up_from_alias/down_to_target */
dref->nlvl_from = avio_rb16(pb);
dref->nlvl_to = avio_rb16(pb);
av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",
dref->nlvl_from, dref->nlvl_to);
avio_skip(pb, 16);
for (type = 0; type != -1 && avio_tell(pb) < next; ) {
if(url_feof(pb))
return AVERROR_EOF;
type = avio_rb16(pb);
len = avio_rb16(pb);
av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);
if (len&1)
len += 1;
if (type == 2) { // absolute path
av_free(dref->path);
dref->path = av_mallocz(len+1);
if (!dref->path)
return AVERROR(ENOMEM);
avio_read(pb, dref->path, len);
if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {
len -= volume_len;
memmove(dref->path, dref->path+volume_len, len);
dref->path[len] = 0;
}
for (j = 0; j < len; j++)
if (dref->path[j] == ':')
dref->path[j] = '/';
av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);
} else if (type == 0) { // directory name
av_free(dref->dir);
dref->dir = av_malloc(len+1);
if (!dref->dir)
return AVERROR(ENOMEM);
avio_read(pb, dref->dir, len);
dref->dir[len] = 0;
for (j = 0; j < len; j++)
if (dref->dir[j] == ':')
dref->dir[j] = '/';
av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);
} else
avio_skip(pb, len);
}
}
avio_seek(pb, next, SEEK_SET);
}
return 0;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct posix_acl *jffs2_get_acl(struct inode *inode, int type)
{
struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode);
struct posix_acl *acl;
char *value = NULL;
int rc, xprefix;
switch (type) {
case ACL_TYPE_ACCESS:
acl = jffs2_iget_acl(inode, &f->i_acl_access);
if (acl != JFFS2_ACL_NOT_CACHED)
return acl;
xprefix = JFFS2_XPREFIX_ACL_ACCESS;
break;
case ACL_TYPE_DEFAULT:
acl = jffs2_iget_acl(inode, &f->i_acl_default);
if (acl != JFFS2_ACL_NOT_CACHED)
return acl;
xprefix = JFFS2_XPREFIX_ACL_DEFAULT;
break;
default:
return ERR_PTR(-EINVAL);
}
rc = do_jffs2_getxattr(inode, xprefix, "", NULL, 0);
if (rc > 0) {
value = kmalloc(rc, GFP_KERNEL);
if (!value)
return ERR_PTR(-ENOMEM);
rc = do_jffs2_getxattr(inode, xprefix, "", value, rc);
}
if (rc > 0) {
acl = jffs2_acl_from_medium(value, rc);
} else if (rc == -ENODATA || rc == -ENOSYS) {
acl = NULL;
} else {
acl = ERR_PTR(rc);
}
if (value)
kfree(value);
if (!IS_ERR(acl)) {
switch (type) {
case ACL_TYPE_ACCESS:
jffs2_iset_acl(inode, &f->i_acl_access, acl);
break;
case ACL_TYPE_DEFAULT:
jffs2_iset_acl(inode, &f->i_acl_default, acl);
break;
}
}
return acl;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int do_move_mount(struct path *path, const char *old_name)
{
struct path old_path, parent_path;
struct mount *p;
struct mount *old;
int err;
if (!old_name || !*old_name)
return -EINVAL;
err = kern_path(old_name, LOOKUP_FOLLOW, &old_path);
if (err)
return err;
err = lock_mount(path);
if (err < 0)
goto out;
old = real_mount(old_path.mnt);
p = real_mount(path->mnt);
err = -EINVAL;
if (!check_mnt(p) || !check_mnt(old))
goto out1;
if (d_unlinked(path->dentry))
goto out1;
err = -EINVAL;
if (old_path.dentry != old_path.mnt->mnt_root)
goto out1;
if (!mnt_has_parent(old))
goto out1;
if (S_ISDIR(path->dentry->d_inode->i_mode) !=
S_ISDIR(old_path.dentry->d_inode->i_mode))
goto out1;
/*
* Don't move a mount residing in a shared parent.
*/
if (IS_MNT_SHARED(old->mnt_parent))
goto out1;
/*
* Don't move a mount tree containing unbindable mounts to a destination
* mount which is shared.
*/
if (IS_MNT_SHARED(p) && tree_contains_unbindable(old))
goto out1;
err = -ELOOP;
for (; mnt_has_parent(p); p = p->mnt_parent)
if (p == old)
goto out1;
err = attach_recursive_mnt(old, path, &parent_path);
if (err)
goto out1;
/* if the mount is moved, it should no longer be expire
* automatically */
list_del_init(&old->mnt_expire);
out1:
unlock_mount(path);
out:
if (!err)
path_put(&parent_path);
path_put(&old_path);
return err;
}
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 br_multicast_ipv6_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct sk_buff *skb2;
struct ipv6hdr *ip6h;
struct icmp6hdr *icmp6h;
u8 nexthdr;
unsigned len;
int offset;
int err;
if (!pskb_may_pull(skb, sizeof(*ip6h)))
return -EINVAL;
ip6h = ipv6_hdr(skb);
/*
* We're interested in MLD messages only.
* - Version is 6
* - MLD has always Router Alert hop-by-hop option
* - But we do not support jumbrograms.
*/
if (ip6h->version != 6 ||
ip6h->nexthdr != IPPROTO_HOPOPTS ||
ip6h->payload_len == 0)
return 0;
len = ntohs(ip6h->payload_len);
if (skb->len < len)
return -EINVAL;
nexthdr = ip6h->nexthdr;
offset = ipv6_skip_exthdr(skb, sizeof(*ip6h), &nexthdr);
if (offset < 0 || nexthdr != IPPROTO_ICMPV6)
return 0;
/* Okay, we found ICMPv6 header */
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
return -ENOMEM;
err = -EINVAL;
if (!pskb_may_pull(skb2, offset + sizeof(struct icmp6hdr)))
goto out;
len -= offset - skb_network_offset(skb2);
__skb_pull(skb2, offset);
skb_reset_transport_header(skb2);
icmp6h = icmp6_hdr(skb2);
switch (icmp6h->icmp6_type) {
case ICMPV6_MGM_QUERY:
case ICMPV6_MGM_REPORT:
case ICMPV6_MGM_REDUCTION:
case ICMPV6_MLD2_REPORT:
break;
default:
err = 0;
goto out;
}
/* Okay, we found MLD message. Check further. */
if (skb2->len > len) {
err = pskb_trim_rcsum(skb2, len);
if (err)
goto out;
}
switch (skb2->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_fold(skb2->csum))
break;
/*FALLTHROUGH*/
case CHECKSUM_NONE:
skb2->csum = 0;
if (skb_checksum_complete(skb2))
goto out;
}
err = 0;
BR_INPUT_SKB_CB(skb)->igmp = 1;
switch (icmp6h->icmp6_type) {
case ICMPV6_MGM_REPORT:
{
struct mld_msg *mld;
if (!pskb_may_pull(skb2, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *)skb_transport_header(skb2);
BR_INPUT_SKB_CB(skb2)->mrouters_only = 1;
err = br_ip6_multicast_add_group(br, port, &mld->mld_mca);
break;
}
case ICMPV6_MLD2_REPORT:
err = br_ip6_multicast_mld2_report(br, port, skb2);
break;
case ICMPV6_MGM_QUERY:
err = br_ip6_multicast_query(br, port, skb2);
break;
case ICMPV6_MGM_REDUCTION:
{
struct mld_msg *mld;
if (!pskb_may_pull(skb2, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *)skb_transport_header(skb2);
br_ip6_multicast_leave_group(br, port, &mld->mld_mca);
}
}
out:
kfree_skb(skb2);
return err;
}
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: long long Segment::GetDuration() const
{
assert(m_pInfo);
return m_pInfo->GetDuration();
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static tAVRC_STS bta_av_chk_notif_evt_id(tAVRC_MSG_VENDOR* p_vendor) {
tAVRC_STS status = BTA_AV_STS_NO_RSP;
uint8_t xx;
uint16_t u16;
uint8_t* p = p_vendor->p_vendor_data + 2;
BE_STREAM_TO_UINT16(u16, p);
/* double check the fixed length */
if ((u16 != 5) || (p_vendor->vendor_len != 9)) {
status = AVRC_STS_INTERNAL_ERR;
} else {
/* make sure the player_id is valid */
for (xx = 0; xx < p_bta_av_cfg->num_evt_ids; xx++) {
if (*p == p_bta_av_cfg->p_meta_evt_ids[xx]) {
break;
}
}
if (xx == p_bta_av_cfg->num_evt_ids) {
status = AVRC_STS_BAD_PARAM;
}
}
return status;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int verify_vc_kbmode(int fd) {
int curr_mode;
/*
* Make sure we only adjust consoles in K_XLATE or K_UNICODE mode.
* Otherwise we would (likely) interfere with X11's processing of the
* key events.
*
* http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html
*/
if (ioctl(fd, KDGKBMODE, &curr_mode) < 0)
return -errno;
return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY;
}
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: RTCVoidRequestTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCVoidRequest& request, bool succeeded)
: MethodTask<MockWebRTCPeerConnectionHandler>(object)
, m_request(request)
, m_succeeded(succeeded)
{
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int shmem_removexattr(struct dentry *dentry, const char *name)
{
struct shmem_inode_info *info = SHMEM_I(dentry->d_inode);
int err;
/*
* If this is a request for a synthetic attribute in the system.*
* namespace use the generic infrastructure to resolve a handler
* for it via sb->s_xattr.
*/
if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
return generic_removexattr(dentry, name);
err = shmem_xattr_validate(name);
if (err)
return err;
return simple_xattr_remove(&info->xattrs, name);
}
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 InspectorAccessibilityAgent::addAncestors(
AXObject& firstAncestor,
AXObject* inspectedAXObject,
std::unique_ptr<protocol::Array<AXNode>>& nodes,
AXObjectCacheImpl& cache) const {
AXObject* ancestor = &firstAncestor;
while (ancestor) {
nodes->addItem(buildProtocolAXObject(*ancestor, inspectedAXObject, true,
nodes, cache));
ancestor = ancestor->parentObjectUnignored();
}
}
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const AXObject* AXObject::disabledAncestor() const {
const AtomicString& disabled = getAttribute(aria_disabledAttr);
if (equalIgnoringCase(disabled, "true"))
return this;
if (equalIgnoringCase(disabled, "false"))
return 0;
if (AXObject* parent = parentObject())
return parent->disabledAncestor();
return 0;
}
CWE ID: CWE-254
Target: 1
Example 2:
Code: Response CreateInvalidVersionIdErrorResponse() {
return Response::InvalidParams("Invalid version ID");
}
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 opj_bool pi_next_cprl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
pi->first = 0;
}
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int resno;
comp = &pi->comps[pi->compno];
pi->dx = 0;
pi->dy = 0;
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static v8::Handle<v8::Value> methodWithNonOptionalArgAndOptionalArgCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.methodWithNonOptionalArgAndOptionalArg");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(int, nonOpt, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)));
if (args.Length() <= 1) {
imp->methodWithNonOptionalArgAndOptionalArg(nonOpt);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(int, opt, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)));
imp->methodWithNonOptionalArgAndOptionalArg(nonOpt, opt);
return v8::Handle<v8::Value>();
}
CWE ID:
Target: 1
Example 2:
Code: void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl* rwh) {
if (browser_plugin_embedder_)
browser_plugin_embedder_->DidSendScreenRects();
}
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: GLboolean WebGLRenderingContextBase::isFramebuffer(
WebGLFramebuffer* framebuffer) {
if (!framebuffer || isContextLost())
return 0;
if (!framebuffer->HasEverBeenBound())
return 0;
if (framebuffer->IsDeleted())
return 0;
return ContextGL()->IsFramebuffer(framebuffer->Object());
}
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: shared_memory_handle(const gfx::GpuMemoryBufferHandle& handle) {
if (handle.type != gfx::SHARED_MEMORY_BUFFER &&
handle.type != gfx::DXGI_SHARED_HANDLE &&
handle.type != gfx::ANDROID_HARDWARE_BUFFER)
return mojo::ScopedSharedBufferHandle();
return mojo::WrapSharedMemoryHandle(handle.handle, handle.handle.GetSize(),
false);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void RunTest(const FilePath& url, GpuResultFlags expectations) {
using trace_analyzer::Query;
using trace_analyzer::TraceAnalyzer;
ASSERT_TRUE(tracing::BeginTracing("test_gpu"));
RunTest(url, NULL, true);
std::string json_events;
ASSERT_TRUE(tracing::EndTracing(&json_events));
scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
analyzer->AssociateBeginEndEvents();
trace_analyzer::TraceEventVector events;
if (expectations & EXPECT_NO_GPU_PROCESS) {
EXPECT_EQ(0u, analyzer->FindEvents(
Query::MatchBeginName("OnGraphicsInfoCollected"), &events));
}
if (expectations & EXPECT_GPU_SWAP_BUFFERS) {
EXPECT_GT(analyzer->FindEvents(Query::EventName() ==
Query::String("SwapBuffers"), &events),
size_t(0));
}
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ndp_sock_recv(struct ndp *ndp)
{
struct ndp_msg *msg;
enum ndp_msg_type msg_type;
size_t len;
int err;
msg = ndp_msg_alloc();
if (!msg)
return -ENOMEM;
len = ndp_msg_payload_maxlen(msg);
err = myrecvfrom6(ndp->sock, msg->buf, &len, 0,
&msg->addrto, &msg->ifindex);
if (err) {
err(ndp, "Failed to receive message");
goto free_msg;
}
dbg(ndp, "rcvd from: %s, ifindex: %u",
str_in6_addr(&msg->addrto), msg->ifindex);
if (len < sizeof(*msg->icmp6_hdr)) {
warn(ndp, "rcvd icmp6 packet too short (%luB)", len);
err = 0;
goto free_msg;
}
err = ndp_msg_type_by_raw_type(&msg_type, msg->icmp6_hdr->icmp6_type);
if (err) {
err = 0;
goto free_msg;
}
ndp_msg_init(msg, msg_type);
ndp_msg_payload_len_set(msg, len);
if (!ndp_msg_check_valid(msg)) {
warn(ndp, "rcvd invalid ND message");
err = 0;
goto free_msg;
}
dbg(ndp, "rcvd %s, len: %zuB",
ndp_msg_type_info(msg_type)->strabbr, len);
if (!ndp_msg_check_opts(msg)) {
err = 0;
goto free_msg;
}
err = ndp_call_handlers(ndp, msg);;
free_msg:
ndp_msg_destroy(msg);
return err;
}
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: ZEND_METHOD(CURLFile, __wakeup)
{
zend_update_property_string(curl_CURLFile_class, getThis(), "name", sizeof("name")-1, "" TSRMLS_CC);
zend_throw_exception(NULL, "Unserialization of CURLFile instances is not allowed", 0 TSRMLS_CC);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void ResourceTracker::ClearSingletonOverride() {
DCHECK(singleton_override_);
singleton_override_ = NULL;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: mojo::ScopedSharedBufferHandle GamepadProvider::GetSharedBufferHandle() {
base::SharedMemoryHandle handle = base::SharedMemory::DuplicateHandle(
gamepad_shared_buffer_->shared_memory()->handle());
return mojo::WrapSharedMemoryHandle(handle, sizeof(GamepadHardwareBuffer),
true /* read_only */);
}
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline void sem_getref(struct sem_array *sma)
{
spin_lock(&(sma)->sem_perm.lock);
ipc_rcu_getref(sma);
ipc_unlock(&(sma)->sem_perm);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void attach_one_task(struct rq *rq, struct task_struct *p)
{
struct rq_flags rf;
rq_lock(rq, &rf);
update_rq_clock(rq);
attach_task(rq, p);
rq_unlock(rq, &rf);
}
CWE ID: CWE-400
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int orinoco_ioctl_set_auth(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct orinoco_private *priv = ndev_priv(dev);
hermes_t *hw = &priv->hw;
struct iw_param *param = &wrqu->param;
unsigned long flags;
int ret = -EINPROGRESS;
if (orinoco_lock(priv, &flags) != 0)
return -EBUSY;
switch (param->flags & IW_AUTH_INDEX) {
case IW_AUTH_WPA_VERSION:
case IW_AUTH_CIPHER_PAIRWISE:
case IW_AUTH_CIPHER_GROUP:
case IW_AUTH_RX_UNENCRYPTED_EAPOL:
case IW_AUTH_PRIVACY_INVOKED:
case IW_AUTH_DROP_UNENCRYPTED:
/*
* orinoco does not use these parameters
*/
break;
case IW_AUTH_KEY_MGMT:
/* wl_lkm implies value 2 == PSK for Hermes I
* which ties in with WEXT
* no other hints tho :(
*/
priv->key_mgmt = param->value;
break;
case IW_AUTH_TKIP_COUNTERMEASURES:
/* When countermeasures are enabled, shut down the
* card; when disabled, re-enable the card. This must
* take effect immediately.
*
* TODO: Make sure that the EAPOL message is getting
* out before card disabled
*/
if (param->value) {
priv->tkip_cm_active = 1;
ret = hermes_enable_port(hw, 0);
} else {
priv->tkip_cm_active = 0;
ret = hermes_disable_port(hw, 0);
}
break;
case IW_AUTH_80211_AUTH_ALG:
if (param->value & IW_AUTH_ALG_SHARED_KEY)
priv->wep_restrict = 1;
else if (param->value & IW_AUTH_ALG_OPEN_SYSTEM)
priv->wep_restrict = 0;
else
ret = -EINVAL;
break;
case IW_AUTH_WPA_ENABLED:
if (priv->has_wpa) {
priv->wpa_enabled = param->value ? 1 : 0;
} else {
if (param->value)
ret = -EOPNOTSUPP;
/* else silently accept disable of WPA */
priv->wpa_enabled = 0;
}
break;
default:
ret = -EOPNOTSUPP;
}
orinoco_unlock(priv, &flags);
return ret;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int propagate_one(struct mount *m)
{
struct mount *child;
int type;
/* skip ones added by this propagate_mnt() */
if (IS_MNT_NEW(m))
return 0;
/* skip if mountpoint isn't covered by it */
if (!is_subdir(mp->m_dentry, m->mnt.mnt_root))
return 0;
if (peers(m, last_dest)) {
type = CL_MAKE_SHARED;
} else {
struct mount *n, *p;
bool done;
for (n = m; ; n = p) {
p = n->mnt_master;
if (p == dest_master || IS_MNT_MARKED(p))
break;
}
do {
struct mount *parent = last_source->mnt_parent;
if (last_source == first_source)
break;
done = parent->mnt_master == p;
if (done && peers(n, parent))
break;
last_source = last_source->mnt_master;
} while (!done);
type = CL_SLAVE;
/* beginning of peer group among the slaves? */
if (IS_MNT_SHARED(m))
type |= CL_MAKE_SHARED;
}
/* Notice when we are propagating across user namespaces */
if (m->mnt_ns->user_ns != user_ns)
type |= CL_UNPRIVILEGED;
child = copy_tree(last_source, last_source->mnt.mnt_root, type);
if (IS_ERR(child))
return PTR_ERR(child);
child->mnt.mnt_flags &= ~MNT_LOCKED;
mnt_set_mountpoint(m, mp, child);
last_dest = m;
last_source = child;
if (m->mnt_master != dest_master) {
read_seqlock_excl(&mount_lock);
SET_MNT_MARK(m->mnt_master);
read_sequnlock_excl(&mount_lock);
}
hlist_add_head(&child->mnt_hash, list);
return 0;
}
CWE ID: CWE-400
Target: 1
Example 2:
Code: static int cp2112_raw_event(struct hid_device *hdev, struct hid_report *report,
u8 *data, int size)
{
struct cp2112_device *dev = hid_get_drvdata(hdev);
struct cp2112_xfer_status_report *xfer = (void *)data;
switch (data[0]) {
case CP2112_TRANSFER_STATUS_RESPONSE:
hid_dbg(hdev, "xfer status: %02x %02x %04x %04x\n",
xfer->status0, xfer->status1,
be16_to_cpu(xfer->retries), be16_to_cpu(xfer->length));
switch (xfer->status0) {
case STATUS0_IDLE:
dev->xfer_status = -EAGAIN;
break;
case STATUS0_BUSY:
dev->xfer_status = -EBUSY;
break;
case STATUS0_COMPLETE:
dev->xfer_status = be16_to_cpu(xfer->length);
break;
case STATUS0_ERROR:
switch (xfer->status1) {
case STATUS1_TIMEOUT_NACK:
case STATUS1_TIMEOUT_BUS:
dev->xfer_status = -ETIMEDOUT;
break;
default:
dev->xfer_status = -EIO;
break;
}
break;
default:
dev->xfer_status = -EINVAL;
break;
}
atomic_set(&dev->xfer_avail, 1);
break;
case CP2112_DATA_READ_RESPONSE:
hid_dbg(hdev, "read response: %02x %02x\n", data[1], data[2]);
dev->read_length = data[2];
if (dev->read_length > sizeof(dev->read_data))
dev->read_length = sizeof(dev->read_data);
memcpy(dev->read_data, &data[3], dev->read_length);
atomic_set(&dev->read_avail, 1);
break;
default:
hid_err(hdev, "unknown report\n");
return 0;
}
wake_up_interruptible(&dev->wait);
return 1;
}
CWE ID: CWE-388
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ide_sector_write(IDEState *s)
{
int64_t sector_num;
int n;
s->status = READY_STAT | SEEK_STAT | BUSY_STAT;
sector_num = ide_get_sector(s);
#if defined(DEBUG_IDE)
printf("sector=%" PRId64 "\n", sector_num);
#endif
n = s->nsector;
if (n > s->req_nb_sectors) {
n = s->req_nb_sectors;
}
if (!ide_sect_range_ok(s, sector_num, n)) {
ide_rw_error(s);
return;
}
s->iov.iov_base = s->io_buffer;
s->iov.iov_len = n * BDRV_SECTOR_SIZE;
qemu_iovec_init_external(&s->qiov, &s->iov, 1);
block_acct_start(blk_get_stats(s->blk), &s->acct,
n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);
s->pio_aiocb = blk_aio_writev(s->blk, sector_num, &s->qiov, n,
ide_sector_write_cb, s);
}
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: PHYSICALPATH_FUNC(mod_alias_physical_handler) {
plugin_data *p = p_d;
int uri_len, basedir_len;
char *uri_ptr;
size_t k;
if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON;
mod_alias_patch_connection(srv, con, p);
/* not to include the tailing slash */
basedir_len = buffer_string_length(con->physical.basedir);
if ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len;
uri_len = buffer_string_length(con->physical.path) - basedir_len;
uri_ptr = con->physical.path->ptr + basedir_len;
for (k = 0; k < p->conf.alias->used; k++) {
data_string *ds = (data_string *)p->conf.alias->data[k];
int alias_len = buffer_string_length(ds->key);
if (alias_len > uri_len) continue;
if (buffer_is_empty(ds->key)) continue;
if (0 == (con->conf.force_lowercase_filenames ?
strncasecmp(uri_ptr, ds->key->ptr, alias_len) :
strncmp(uri_ptr, ds->key->ptr, alias_len))) {
/* matched */
buffer_copy_buffer(con->physical.basedir, ds->value);
buffer_copy_buffer(srv->tmp_buf, ds->value);
buffer_append_string(srv->tmp_buf, uri_ptr + alias_len);
buffer_copy_buffer(con->physical.path, srv->tmp_buf);
return HANDLER_GO_ON;
}
}
/* not found */
return HANDLER_GO_ON;
}
CWE ID:
Target: 1
Example 2:
Code: void red_channel_pipes_new_add_tail(RedChannel *channel, new_pipe_item_t creator, void *data)
{
red_channel_pipes_create_batch(channel, creator, data,
red_channel_client_pipe_add_tail_no_push);
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int colorCmp (const void *x, const void *y)
{
int a = *(int const *)x;
int b = *(int const *)y;
return (a > b) - (a < b);
}
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: PreconnectRequest::PreconnectRequest(
const GURL& origin,
int num_sockets,
const net::NetworkIsolationKey& network_isolation_key)
: origin(origin),
num_sockets(num_sockets),
network_isolation_key(network_isolation_key) {
DCHECK_GE(num_sockets, 0);
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: dissect_dch_ul_node_synchronisation(proto_tree *tree, packet_info *pinfo, tvbuff_t *tvb, int offset)
{
return dissect_common_ul_node_synchronisation(pinfo, tree, tvb, offset);
}
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: struct r_bin_pe_addr_t *PE_(check_mingw) (struct PE_(r_bin_pe_obj_t) *bin) {
struct r_bin_pe_addr_t* entry;
int sw = 0;
ut8 b[1024];
int n = 0;
if (!bin || !bin->b) {
return 0LL;
}
entry = PE_(r_bin_pe_get_entrypoint) (bin);
ZERO_FILL (b);
if (r_buf_read_at (bin->b, entry->paddr, b, sizeof (b)) < 0) {
bprintf ("Warning: Cannot read entry at 0x%08"PFMT64x "\n", entry->paddr);
free (entry);
return NULL;
}
if (b[0] == 0x55 && b[1] == 0x89 && b[3] == 0x83 && b[6] == 0xc7 && b[13] == 0xff && b[19] == 0xe8) {
const st32 jmp_dst = (st32) r_read_le32 (&b[20]);
entry->paddr += (5 + 19 + jmp_dst);
entry->vaddr += (5 + 19 + jmp_dst);
sw = 1;
}
if (b[0] == 0x83 && b[3] == 0xc7 && b[10] == 0xff && b[16] == 0xe8) {
const st32 jmp_dst = (st32) r_read_le32 (&b[17]);
entry->paddr += (5 + 16 + jmp_dst);
entry->vaddr += (5 + 16 + jmp_dst);
sw = 1;
}
if (b[0] == 0x83 && b[3] == 0xc7 && b[13] == 0xe8 && b[18] == 0x83 && b[21] == 0xe9) {
const st32 jmp_dst = (st32) r_read_le32 (&b[22]);
entry->paddr += (5 + 21 + jmp_dst);
entry->vaddr += (5 + 21 + jmp_dst);
sw = 1;
}
if (sw) {
if (r_buf_read_at (bin->b, entry->paddr, b, sizeof (b)) > 0) {
for (n = 0; n < sizeof (b) - 12; n++) {
if (b[n] == 0xa1 && b[n + 5] == 0x89 && b[n + 8] == 0xe8) {
const st32 call_dst = (st32) r_read_le32 (&b[n + 9]);
entry->paddr += (n + 5 + 8 + call_dst);
entry->vaddr += (n + 5 + 8 + call_dst);
return entry;
}
}
}
}
free (entry);
return NULL;
}
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: vhost_scsi_send_evt(struct vhost_scsi *vs,
struct vhost_scsi_tpg *tpg,
struct se_lun *lun,
u32 event,
u32 reason)
{
struct vhost_scsi_evt *evt;
evt = vhost_scsi_allocate_evt(vs, event, reason);
if (!evt)
return;
if (tpg && lun) {
/* TODO: share lun setup code with virtio-scsi.ko */
/*
* Note: evt->event is zeroed when we allocate it and
* lun[4-7] need to be zero according to virtio-scsi spec.
*/
evt->event.lun[0] = 0x01;
evt->event.lun[1] = tpg->tport_tpgt & 0xFF;
if (lun->unpacked_lun >= 256)
evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
evt->event.lun[3] = lun->unpacked_lun & 0xFF;
}
llist_add(&evt->list, &vs->vs_event_list);
vhost_work_queue(&vs->dev, &vs->vs_event_work);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
{
struct kvm_memory_slot *memslot;
memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
mark_page_dirty_in_slot(memslot, gfn);
}
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 FrameLoader::ModifyRequestForCSP(ResourceRequest& resource_request,
Document* origin_document) const {
if (RuntimeEnabledFeatures::EmbedderCSPEnforcementEnabled() &&
!RequiredCSP().IsEmpty()) {
DCHECK(
ContentSecurityPolicy::IsValidCSPAttr(RequiredCSP().GetString(), ""));
resource_request.SetHTTPHeaderField(HTTPNames::Sec_Required_CSP,
RequiredCSP());
}
if (resource_request.GetFrameType() !=
network::mojom::RequestContextFrameType::kNone) {
if (!resource_request.HttpHeaderField(HTTPNames::Upgrade_Insecure_Requests)
.IsNull()) {
return;
}
resource_request.SetHTTPHeaderField(HTTPNames::Upgrade_Insecure_Requests,
"1");
}
UpgradeInsecureRequest(resource_request, origin_document);
}
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 DownloadItemImpl::OnDownloadCompleting(DownloadFileManager* file_manager) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
VLOG(20) << __FUNCTION__ << "()"
<< " needs rename = " << NeedsRename()
<< " " << DebugString(true);
DCHECK(!GetTargetName().empty());
DCHECK_NE(DANGEROUS, GetSafetyState());
DCHECK(file_manager);
bool should_overwrite =
(GetTargetDisposition() != DownloadItem::TARGET_DISPOSITION_UNIQUIFY);
DownloadFileManager::RenameCompletionCallback callback =
base::Bind(&DownloadItemImpl::OnDownloadRenamedToFinalName,
weak_ptr_factory_.GetWeakPtr(),
base::Unretained(file_manager));
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&DownloadFileManager::RenameCompletingDownloadFile,
file_manager, GetGlobalId(), GetTargetFilePath(),
should_overwrite, callback));
} else {
Completed();
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&DownloadFileManager::CompleteDownload,
file_manager, download_id_));
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: PaymentsRequestVisualTest() {}
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 SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
unsigned int sid_ctx_len)
{
if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
SSLerr(SSL_F_SSL_SESSION_SET1_ID_CONTEXT,
SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
return 0;
}
s->sid_ctx_length = sid_ctx_len;
memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
return 1;
}
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: ieee802_11_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int orig_caplen, int pad,
u_int fcslen)
{
uint16_t fc;
u_int caplen, hdrlen, meshdrlen;
struct lladdr_info src, dst;
int llc_hdrlen;
caplen = orig_caplen;
/* Remove FCS, if present */
if (length < fcslen) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
length -= fcslen;
if (caplen > length) {
/* Amount of FCS in actual packet data, if any */
fcslen = caplen - length;
caplen -= fcslen;
ndo->ndo_snapend -= fcslen;
}
if (caplen < IEEE802_11_FC_LEN) {
ND_PRINT((ndo, "%s", tstr));
return orig_caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(ndo, fc);
if (hdrlen == 0) {
/* Unknown frame type or control frame subtype; quit. */
return (0);
}
if (pad)
hdrlen = roundup2(hdrlen, 4);
if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA &&
DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) {
meshdrlen = extract_mesh_header_length(p+hdrlen);
hdrlen += meshdrlen;
} else
meshdrlen = 0;
if (caplen < hdrlen) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
if (ndo->ndo_eflag)
ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen);
/*
* Go past the 802.11 header.
*/
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
src.addr_string = etheraddr_string;
dst.addr_string = etheraddr_string;
switch (FC_TYPE(fc)) {
case T_MGMT:
get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr);
if (!mgmt_body_print(ndo, fc, src.addr, p, length)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_CTRL:
if (!ctrl_body_print(ndo, fc, p - hdrlen)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_DATA:
if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc)))
return hdrlen; /* no-data frame */
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc)) {
ND_PRINT((ndo, "Data"));
if (!wep_print(ndo, p)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
} else {
get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr);
llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst);
if (llc_hdrlen < 0) {
/*
* Some kinds of LLC packet we cannot
* handle intelligently
*/
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
hdrlen += llc_hdrlen;
}
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
return hdrlen;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void Document::writeln(v8::Isolate* isolate,
TrustedHTML* text,
ExceptionState& exception_state) {
DCHECK(origin_trials::TrustedDOMTypesEnabled(this));
writeln(text->toString(), EnteredDOMWindow(isolate)->document(),
exception_state);
}
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: krb5_gss_wrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 major_status;
major_status = kg_seal_iov(minor_status, context_handle, conf_req_flag,
qop_req, conf_state,
iov, iov_count, KG_TOK_WRAP_MSG);
return major_status;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void ext4_free_io_end(ext4_io_end_t *io)
{
BUG_ON(!io);
iput(io->inode);
kfree(io);
}
CWE ID:
Target: 1
Example 2:
Code: ~RestartTestJob() {}
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: raptor_rss_emit_item(raptor_parser* rdf_parser, raptor_rss_item *item)
{
raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context;
int f;
raptor_rss_block *block;
raptor_uri *type_uri;
if(!item->fields_count)
return 0;
/* HACK - FIXME - set correct atom output class type */
if(item->node_typei == RAPTOR_ATOM_AUTHOR)
type_uri = rdf_parser->world->rss_fields_info_uris[RAPTOR_RSS_RDF_ATOM_AUTHOR_CLASS];
else
type_uri = rdf_parser->world->rss_types_info_uris[item->node_typei];
if(raptor_rss_emit_type_triple(rdf_parser, item->term, type_uri))
return 1;
for(f = 0; f< RAPTOR_RSS_FIELDS_SIZE; f++) {
raptor_rss_field* field;
raptor_uri* predicate_uri = NULL;
raptor_term* predicate_term = NULL;
/* This is only made by a connection */
if(f == RAPTOR_RSS_FIELD_ITEMS)
continue;
/* skip predicates with no URI (no namespace e.g. RSS 2) */
predicate_uri = rdf_parser->world->rss_fields_info_uris[f];
if(!predicate_uri)
continue;
predicate_term = raptor_new_term_from_uri(rdf_parser->world,
predicate_uri);
if(!predicate_term)
continue;
rss_parser->statement.predicate = predicate_term;
for(field = item->fields[f]; field; field = field->next) {
raptor_term* object_term;
if(field->value) {
/* FIXME - should store and emit languages */
object_term = raptor_new_term_from_literal(rdf_parser->world,
field->value,
NULL, NULL);
} else {
object_term = raptor_new_term_from_uri(rdf_parser->world,
field->uri);
}
rss_parser->statement.object = object_term;
/* Generate the statement */
(*rdf_parser->statement_handler)(rdf_parser->user_data,
&rss_parser->statement);
raptor_free_term(object_term);
}
raptor_free_term(predicate_term);
}
for(block = item->blocks; block; block = block->next) {
raptor_rss_emit_block(rdf_parser, item->term, block);
}
return 0;
}
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SPL_METHOD(GlobIterator, count)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {
RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
} else {
/* should not happen */
php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state");
}
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: decode_OFPAT_RAW_SET_MPLS_TTL(uint8_t ttl,
enum ofp_version ofp_version OVS_UNUSED,
struct ofpbuf *out)
{
ofpact_put_SET_MPLS_TTL(out)->ttl = ttl;
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: v8::Handle<v8::Value> V8TestInterface::constructorCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestInterface.Constructor");
if (!args.IsConstructCall())
return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function.");
if (ConstructorMode::current() == ConstructorMode::WrapExistingObject)
return args.Holder();
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
ExceptionCode ec = 0;
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
ScriptExecutionContext* context = getScriptExecutionContext();
if (!context)
return V8Proxy::throwError(V8Proxy::ReferenceError, "TestInterface constructor's associated context is not available", args.GetIsolate());
RefPtr<TestInterface> impl = TestInterface::create(context, str1, str2, ec);
v8::Handle<v8::Object> wrapper = args.Holder();
if (ec)
goto fail;
V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get());
V8DOMWrapper::setJSWrapperForActiveDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate());
return args.Holder();
fail:
return throwError(ec, args.GetIsolate());
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool Track::VetEntry(const BlockEntry* pBlockEntry) const
{
assert(pBlockEntry);
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
assert(pBlock->GetTrackNumber() == m_info.number);
if (!pBlock || pBlock->GetTrackNumber() != m_info.number)
return false;
return true;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void reds_enable_mm_timer(void)
{
core->timer_start(reds->mm_timer, MM_TIMER_GRANULARITY_MS);
reds->mm_timer_enabled = TRUE;
reds->mm_time_latency = MM_TIME_DELTA;
reds_send_mm_time();
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void peer_abort_upcall(struct iwch_ep *ep)
{
struct iw_cm_event event;
PDBG("%s ep %p\n", __func__, ep);
memset(&event, 0, sizeof(event));
event.event = IW_CM_EVENT_CLOSE;
event.status = -ECONNRESET;
if (ep->com.cm_id) {
PDBG("abort delivered ep %p cm_id %p tid %d\n", ep,
ep->com.cm_id, ep->hwtid);
ep->com.cm_id->event_handler(ep->com.cm_id, &event);
ep->com.cm_id->rem_ref(ep->com.cm_id);
ep->com.cm_id = NULL;
ep->com.qp = NULL;
}
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
alphaBits,
x,
y;
unsigned short
color;
alphaBits=0;
if (dds_info->pixelformat.rgb_bitcount == 16)
{
if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
alphaBits=1;
else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
{
alphaBits=2;
(void) SetImageType(image,GrayscaleMatteType);
}
else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
alphaBits=4;
else
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
}
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
if (alphaBits == 1)
{
SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 1) >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 6) >> 11)/31.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else if (alphaBits == 2)
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(color >> 8)));
SetPixelGray(q,ScaleCharToQuantum((unsigned char)color));
}
else
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(((color >> 12)/15.0)*255)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 4) >> 12)/15.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 8) >> 12)/15.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 12) >> 12)/15.0)*255)));
}
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
SkipRGBMipmaps(image, dds_info, 4);
return MagickTrue;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: void BookmarkManagerView::FileSelected(const FilePath& path,
int index,
void* params) {
int id = reinterpret_cast<int>(params);
if (id == IDS_BOOKMARK_MANAGER_IMPORT_MENU) {
ImporterHost* host = new ImporterHost();
ProfileInfo profile_info;
profile_info.browser_type = BOOKMARKS_HTML;
profile_info.source_path = path.ToWStringHack();
StartImportingWithUI(GetWidget()->GetNativeView(), FAVORITES, host,
profile_info, profile_,
new ImportObserverImpl(profile()), false);
} else if (id == IDS_BOOKMARK_MANAGER_EXPORT_MENU) {
if (g_browser_process->io_thread()) {
bookmark_html_writer::WriteBookmarks(
g_browser_process->io_thread()->message_loop(), GetBookmarkModel(),
path.ToWStringHack());
}
} else {
NOTREACHED();
}
}
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 BackingStoreGtk::PaintRectWithoutXrender(
TransportDIB* bitmap,
const gfx::Rect& bitmap_rect,
const std::vector<gfx::Rect>& copy_rects) {
const int width = bitmap_rect.width();
const int height = bitmap_rect.height();
Pixmap pixmap = XCreatePixmap(display_, root_window_, width, height,
visual_depth_);
ui::PutARGBImage(display_, visual_, visual_depth_, pixmap,
pixmap_gc_, static_cast<uint8*>(bitmap->memory()),
width, height);
for (size_t i = 0; i < copy_rects.size(); i++) {
const gfx::Rect& copy_rect = copy_rects[i];
XCopyArea(display_,
pixmap, // src
pixmap_, // dest
static_cast<GC>(pixmap_gc_), // gc
copy_rect.x() - bitmap_rect.x(), // src_x
copy_rect.y() - bitmap_rect.y(), // src_y
copy_rect.width(), // width
copy_rect.height(), // height
copy_rect.x(), // dest_x
copy_rect.y()); // dest_y
}
XFreePixmap(display_, pixmap);
}
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: static void bgp_packet_mpattr_tea(struct bgp *bgp, struct peer *peer,
struct stream *s, struct attr *attr,
uint8_t attrtype)
{
unsigned int attrlenfield = 0;
unsigned int attrhdrlen = 0;
struct bgp_attr_encap_subtlv *subtlvs;
struct bgp_attr_encap_subtlv *st;
const char *attrname;
if (!attr || (attrtype == BGP_ATTR_ENCAP
&& (!attr->encap_tunneltype
|| attr->encap_tunneltype == BGP_ENCAP_TYPE_MPLS)))
return;
switch (attrtype) {
case BGP_ATTR_ENCAP:
attrname = "Tunnel Encap";
subtlvs = attr->encap_subtlvs;
if (subtlvs == NULL) /* nothing to do */
return;
/*
* The tunnel encap attr has an "outer" tlv.
* T = tunneltype,
* L = total length of subtlvs,
* V = concatenated subtlvs.
*/
attrlenfield = 2 + 2; /* T + L */
attrhdrlen = 1 + 1; /* subTLV T + L */
break;
#if ENABLE_BGP_VNC
case BGP_ATTR_VNC:
attrname = "VNC";
subtlvs = attr->vnc_subtlvs;
if (subtlvs == NULL) /* nothing to do */
return;
attrlenfield = 0; /* no outer T + L */
attrhdrlen = 2 + 2; /* subTLV T + L */
break;
#endif
default:
assert(0);
}
/* compute attr length */
for (st = subtlvs; st; st = st->next) {
attrlenfield += (attrhdrlen + st->length);
}
if (attrlenfield > 0xffff) {
zlog_info("%s attribute is too long (length=%d), can't send it",
attrname, attrlenfield);
return;
}
if (attrlenfield > 0xff) {
/* 2-octet length field */
stream_putc(s,
BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL
| BGP_ATTR_FLAG_EXTLEN);
stream_putc(s, attrtype);
stream_putw(s, attrlenfield & 0xffff);
} else {
/* 1-octet length field */
stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL);
stream_putc(s, attrtype);
stream_putc(s, attrlenfield & 0xff);
}
if (attrtype == BGP_ATTR_ENCAP) {
/* write outer T+L */
stream_putw(s, attr->encap_tunneltype);
stream_putw(s, attrlenfield - 4);
}
/* write each sub-tlv */
for (st = subtlvs; st; st = st->next) {
if (attrtype == BGP_ATTR_ENCAP) {
stream_putc(s, st->type);
stream_putc(s, st->length);
#if ENABLE_BGP_VNC
} else {
stream_putw(s, st->type);
stream_putw(s, st->length);
#endif
}
stream_put(s, st->value, st->length);
}
}
CWE ID:
Target: 1
Example 2:
Code: void AutoFillManager::Reset() {
form_structures_.reset();
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int create_fixed_stream_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
struct audioformat *fp;
struct usb_host_interface *alts;
struct usb_interface_descriptor *altsd;
int stream, err;
unsigned *rate_table = NULL;
fp = kmemdup(quirk->data, sizeof(*fp), GFP_KERNEL);
if (!fp) {
usb_audio_err(chip, "cannot memdup\n");
return -ENOMEM;
}
if (fp->nr_rates > MAX_NR_RATES) {
kfree(fp);
return -EINVAL;
}
if (fp->nr_rates > 0) {
rate_table = kmemdup(fp->rate_table,
sizeof(int) * fp->nr_rates, GFP_KERNEL);
if (!rate_table) {
kfree(fp);
return -ENOMEM;
}
fp->rate_table = rate_table;
}
stream = (fp->endpoint & USB_DIR_IN)
? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
err = snd_usb_add_audio_stream(chip, stream, fp);
if (err < 0) {
kfree(fp);
kfree(rate_table);
return err;
}
if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber ||
fp->altset_idx >= iface->num_altsetting) {
kfree(fp);
kfree(rate_table);
return -EINVAL;
}
alts = &iface->altsetting[fp->altset_idx];
altsd = get_iface_desc(alts);
fp->protocol = altsd->bInterfaceProtocol;
if (fp->datainterval == 0)
fp->datainterval = snd_usb_parse_datainterval(chip, alts);
if (fp->maxpacksize == 0)
fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
usb_set_interface(chip->dev, fp->iface, 0);
snd_usb_init_pitch(chip, fp->iface, alts, fp);
snd_usb_init_sample_rate(chip, fp->iface, alts, fp, fp->rate_max);
return 0;
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::unique_ptr<base::SharedMemory> GetShmFromMojoHandle(
mojo::ScopedSharedBufferHandle handle) {
base::SharedMemoryHandle memory_handle;
size_t memory_size = 0;
bool read_only_flag = false;
const MojoResult result = mojo::UnwrapSharedMemoryHandle(
std::move(handle), &memory_handle, &memory_size, &read_only_flag);
if (result != MOJO_RESULT_OK)
return nullptr;
DCHECK_GT(memory_size, 0u);
std::unique_ptr<base::SharedMemory> shm =
std::make_unique<base::SharedMemory>(memory_handle, read_only_flag);
if (!shm->Map(memory_size)) {
DLOG(ERROR) << "Map shared memory failed.";
return nullptr;
}
return shm;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: GahpClient::cream_delegate(const char *delg_service, const char *delg_id)
{
static const char* command = "CREAM_DELEGATE";
if (server->m_commands_supported->contains_anycase(command)==FALSE) {
return GAHPCLIENT_COMMAND_NOT_SUPPORTED;
}
if (!delg_service) delg_service=NULLSTRING;
if (!delg_id) delg_id=NULLSTRING;
std::string reqline;
char *esc1 = strdup( escapeGahpString(delg_service) );
char *esc2 = strdup( escapeGahpString(delg_id) );
int x = sprintf(reqline, "%s %s", esc2, esc1);
free( esc1 );
free( esc2 );
ASSERT( x > 0 );
const char *buf = reqline.c_str();
if ( !is_pending(command,buf) ) {
if ( m_mode == results_only ) {
return GAHPCLIENT_COMMAND_NOT_SUBMITTED;
}
now_pending(command,buf,deleg_proxy,high_prio);
}
Gahp_Args* result = get_pending_result(command,buf);
if ( result ) {
if (result->argc != 2) {
EXCEPT("Bad %s Result",command);
}
int rc;
if (strcmp(result->argv[1], NULLSTRING) == 0) {
rc = 0;
} else {
rc = 1;
error_string = result->argv[1];
}
delete result;
return rc;
}
if ( check_pending_timeout(command,buf) ) {
sprintf( error_string, "%s timed out", command );
return GAHPCLIENT_COMMAND_TIMED_OUT;
}
return GAHPCLIENT_COMMAND_PENDING;
}
CWE ID: CWE-134
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher(
const GURL& url) {
std::unique_ptr<net::URLFetcher> fetcher =
net::URLFetcher::Create(0, url, net::URLFetcher::GET, this);
fetcher->SetRequestContext(helper_->request_context());
fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
fetcher->SetAutomaticallyRetryOnNetworkChanges(1);
return fetcher;
}
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static size_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(image,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if (next_image->storage_class != PseudoClass)
{
if (IsImageGray(next_image) == MagickFalse)
channels=next_image->colorspace == CMYKColorspace ? 4 : 3;
if (next_image->alpha_trait != UndefinedPixelTrait)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if (next_image->storage_class == PseudoClass)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsImageGray(next_image) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->alpha_trait != UndefinedPixelTrait)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
exception);
if (mask != (Image *) NULL)
{
if (mask->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue,exception);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void recordSurroundingText(const std::string& after_text) {
after_text_ = after_text;
}
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: jbig2_sd_release(Jbig2Ctx *ctx, Jbig2SymbolDict *dict)
{
int i;
if (dict == NULL)
return;
for (i = 0; i < dict->n_symbols; i++)
if (dict->glyphs[i])
jbig2_image_release(ctx, dict->glyphs[i]);
jbig2_free(ctx->allocator, dict->glyphs);
jbig2_free(ctx->allocator, dict);
}
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: BGD_DECLARE(gdImagePtr) gdImageCreateFromTgaCtx(gdIOCtx* ctx)
{
int bitmap_caret = 0;
oTga *tga = NULL;
/* int pixel_block_size = 0;
int image_block_size = 0; */
volatile gdImagePtr image = NULL;
int x = 0;
int y = 0;
tga = (oTga *) gdMalloc(sizeof(oTga));
if (!tga) {
return NULL;
}
tga->bitmap = NULL;
tga->ident = NULL;
if (read_header_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
/*TODO: Will this be used?
pixel_block_size = tga->bits / 8;
image_block_size = (tga->width * tga->height) * pixel_block_size;
*/
if (read_image_tga(ctx, tga) < 0) {
free_tga(tga);
return NULL;
}
image = gdImageCreateTrueColor((int)tga->width, (int)tga->height );
if (image == 0) {
free_tga( tga );
return NULL;
}
/*! \brief Populate GD image object
* Copy the pixel data from our tga bitmap buffer into the GD image
* Disable blending and save the alpha channel per default
*/
if (tga->alphabits) {
gdImageAlphaBlending(image, 0);
gdImageSaveAlpha(image, 1);
}
/* TODO: use alphabits as soon as we support 24bit and other alpha bps (ie != 8bits) */
for (y = 0; y < tga->height; y++) {
register int *tpix = image->tpixels[y];
for ( x = 0; x < tga->width; x++, tpix++) {
if (tga->bits == TGA_BPP_24) {
*tpix = gdTrueColor(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret]);
bitmap_caret += 3;
} else if (tga->bits == TGA_BPP_32 || tga->alphabits) {
register int a = tga->bitmap[bitmap_caret + 3];
*tpix = gdTrueColorAlpha(tga->bitmap[bitmap_caret + 2], tga->bitmap[bitmap_caret + 1], tga->bitmap[bitmap_caret], gdAlphaMax - (a >> 1));
bitmap_caret += 4;
}
}
}
if (tga->flipv && tga->fliph) {
gdImageFlipBoth(image);
} else if (tga->flipv) {
gdImageFlipVertical(image);
} else if (tga->fliph) {
gdImageFlipHorizontal(image);
}
free_tga(tga);
return image;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: DH *get_dh2048()
{
DH *dh;
if ((dh = DH_new()) == NULL)
return NULL;
dh->p=BN_bin2bn(dh2048_p, sizeof(dh2048_p), NULL);
dh->g=BN_bin2bn(dh2048_g, sizeof(dh2048_g), NULL);
if (dh->p == NULL || dh->g == NULL) {
DH_free(dh);
return NULL;
}
return dh;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void disable_MAC( struct airo_info *ai, int lock ) {
Cmd cmd;
Resp rsp;
if (lock && down_interruptible(&ai->sem))
return;
if (test_bit(FLAG_ENABLED, &ai->flags)) {
memset(&cmd, 0, sizeof(cmd));
cmd.cmd = MAC_DISABLE; // disable in case already enabled
issuecommand(ai, &cmd, &rsp);
clear_bit(FLAG_ENABLED, &ai->flags);
}
if (lock)
up(&ai->sem);
}
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: xsltCopyTreeInternal(xsltTransformContextPtr ctxt,
xmlNodePtr invocNode,
xmlNodePtr node,
xmlNodePtr insert, int isLRE, int topElemVisited)
{
xmlNodePtr copy;
if (node == NULL)
return(NULL);
switch (node->type) {
case XML_ELEMENT_NODE:
case XML_ENTITY_REF_NODE:
case XML_ENTITY_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
case XML_DOCUMENT_NODE:
case XML_HTML_DOCUMENT_NODE:
#ifdef LIBXML_DOCB_ENABLED
case XML_DOCB_DOCUMENT_NODE:
#endif
break;
case XML_TEXT_NODE: {
int noenc = (node->name == xmlStringTextNoenc);
return(xsltCopyTextString(ctxt, insert, node->content, noenc));
}
case XML_CDATA_SECTION_NODE:
return(xsltCopyTextString(ctxt, insert, node->content, 0));
case XML_ATTRIBUTE_NODE:
return((xmlNodePtr)
xsltShallowCopyAttr(ctxt, invocNode, insert, (xmlAttrPtr) node));
case XML_NAMESPACE_DECL:
return((xmlNodePtr) xsltShallowCopyNsNode(ctxt, invocNode,
insert, (xmlNsPtr) node));
case XML_DOCUMENT_TYPE_NODE:
case XML_DOCUMENT_FRAG_NODE:
case XML_NOTATION_NODE:
case XML_DTD_NODE:
case XML_ELEMENT_DECL:
case XML_ATTRIBUTE_DECL:
case XML_ENTITY_DECL:
case XML_XINCLUDE_START:
case XML_XINCLUDE_END:
return(NULL);
}
if (XSLT_IS_RES_TREE_FRAG(node)) {
if (node->children != NULL)
copy = xsltCopyTreeList(ctxt, invocNode,
node->children, insert, 0, 0);
else
copy = NULL;
return(copy);
}
copy = xmlDocCopyNode(node, insert->doc, 0);
if (copy != NULL) {
copy->doc = ctxt->output;
copy = xsltAddChild(insert, copy);
/*
* The node may have been coalesced into another text node.
*/
if (insert->last != copy)
return(insert->last);
copy->next = NULL;
if (node->type == XML_ELEMENT_NODE) {
/*
* Copy in-scope namespace nodes.
*
* REVISIT: Since we try to reuse existing in-scope ns-decls by
* using xmlSearchNsByHref(), this will eventually change
* the prefix of an original ns-binding; thus it might
* break QNames in element/attribute content.
* OPTIMIZE TODO: If we had a xmlNsPtr * on the transformation
* context, plus a ns-lookup function, which writes directly
* to a given list, then we wouldn't need to create/free the
* nsList every time.
*/
if ((topElemVisited == 0) &&
(node->parent != NULL) &&
(node->parent->type != XML_DOCUMENT_NODE) &&
(node->parent->type != XML_HTML_DOCUMENT_NODE))
{
xmlNsPtr *nsList, *curns, ns;
/*
* If this is a top-most element in a tree to be
* copied, then we need to ensure that all in-scope
* namespaces are copied over. For nodes deeper in the
* tree, it is sufficient to reconcile only the ns-decls
* (node->nsDef entries).
*/
nsList = xmlGetNsList(node->doc, node);
if (nsList != NULL) {
curns = nsList;
do {
/*
* Search by prefix first in order to break as less
* QNames in element/attribute content as possible.
*/
ns = xmlSearchNs(insert->doc, insert,
(*curns)->prefix);
if ((ns == NULL) ||
(! xmlStrEqual(ns->href, (*curns)->href)))
{
ns = NULL;
/*
* Search by namespace name.
* REVISIT TODO: Currently disabled.
*/
#if 0
ns = xmlSearchNsByHref(insert->doc,
insert, (*curns)->href);
#endif
}
if (ns == NULL) {
/*
* Declare a new namespace on the copied element.
*/
ns = xmlNewNs(copy, (*curns)->href,
(*curns)->prefix);
/* TODO: Handle errors */
}
if (node->ns == *curns) {
/*
* If this was the original's namespace then set
* the generated counterpart on the copy.
*/
copy->ns = ns;
}
curns++;
} while (*curns != NULL);
xmlFree(nsList);
}
} else if (node->nsDef != NULL) {
/*
* Copy over all namespace declaration attributes.
*/
if (node->nsDef != NULL) {
if (isLRE)
xsltCopyNamespaceList(ctxt, copy, node->nsDef);
else
xsltCopyNamespaceListInternal(copy, node->nsDef);
}
}
/*
* Set the namespace.
*/
if (node->ns != NULL) {
if (copy->ns == NULL) {
/*
* This will map copy->ns to one of the newly created
* in-scope ns-decls, OR create a new ns-decl on @copy.
*/
copy->ns = xsltGetSpecialNamespace(ctxt, invocNode,
node->ns->href, node->ns->prefix, copy);
}
} else if ((insert->type == XML_ELEMENT_NODE) &&
(insert->ns != NULL))
{
/*
* "Undeclare" the default namespace on @copy with xmlns="".
*/
xsltGetSpecialNamespace(ctxt, invocNode, NULL, NULL, copy);
}
/*
* Copy attribute nodes.
*/
if (node->properties != NULL) {
xsltCopyAttrListNoOverwrite(ctxt, invocNode,
copy, node->properties);
}
if (topElemVisited == 0)
topElemVisited = 1;
}
/*
* Copy the subtree.
*/
if (node->children != NULL) {
xsltCopyTreeList(ctxt, invocNode,
node->children, copy, isLRE, topElemVisited);
}
} else {
xsltTransformError(ctxt, NULL, invocNode,
"xsltCopyTreeInternal: Copying of '%s' failed.\n", node->name);
}
return(copy);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: std::unique_ptr<TracedValue> InspectorSetLayerTreeId::Data(
const String& session_id,
int layer_tree_id) {
std::unique_ptr<TracedValue> value = TracedValue::Create();
value->SetString("sessionId", session_id);
value->SetInteger("layerTreeId", layer_tree_id);
return value;
}
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: TIFFOpen(const char* name, const char* mode)
{
static const char module[] = "TIFFOpen";
int m, fd;
TIFF* tif;
m = _TIFFgetMode(mode, module);
if (m == -1)
return ((TIFF*)0);
/* for cygwin and mingw */
#ifdef O_BINARY
m |= O_BINARY;
#endif
fd = open(name, m, 0666);
if (fd < 0) {
if (errno > 0 && strerror(errno) != NULL ) {
TIFFErrorExt(0, module, "%s: %s", name, strerror(errno) );
} else {
TIFFErrorExt(0, module, "%s: Cannot open", name);
}
return ((TIFF *)0);
}
tif = TIFFFdOpen((int)fd, name, mode);
if(!tif)
close(fd);
return tif;
}
CWE ID: CWE-369
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d) {
FakeResponseMap::const_iterator it = fake_responses_.find(url);
if (it == fake_responses_.end()) {
DLOG(ERROR) << "No baked response for URL: " << url.spec();
return NULL;
}
return new FakeURLFetcher(url, request_type, d,
it->second.first, it->second.second);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int update_filter(struct tap_filter *filter, void __user *arg)
{
struct { u8 u[ETH_ALEN]; } *addr;
struct tun_filter uf;
int err, alen, n, nexact;
if (copy_from_user(&uf, arg, sizeof(uf)))
return -EFAULT;
if (!uf.count) {
/* Disabled */
filter->count = 0;
return 0;
}
alen = ETH_ALEN * uf.count;
addr = memdup_user(arg + sizeof(uf), alen);
if (IS_ERR(addr))
return PTR_ERR(addr);
/* The filter is updated without holding any locks. Which is
* perfectly safe. We disable it first and in the worst
* case we'll accept a few undesired packets. */
filter->count = 0;
wmb();
/* Use first set of addresses as an exact filter */
for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
nexact = n;
/* Remaining multicast addresses are hashed,
* unicast will leave the filter disabled. */
memset(filter->mask, 0, sizeof(filter->mask));
for (; n < uf.count; n++) {
if (!is_multicast_ether_addr(addr[n].u)) {
err = 0; /* no filter */
goto free_addr;
}
addr_hash_set(filter->mask, addr[n].u);
}
/* For ALLMULTI just set the mask to all ones.
* This overrides the mask populated above. */
if ((uf.flags & TUN_FLT_ALLMULTI))
memset(filter->mask, ~0, sizeof(filter->mask));
/* Now enable the filter */
wmb();
filter->count = nexact;
/* Return the number of exact filters */
err = nexact;
free_addr:
kfree(addr);
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: SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,
unsigned int, flags, struct sockaddr __user *, addr,
int __user *, addr_len)
{
struct socket *sock;
struct iovec iov;
struct msghdr msg;
struct sockaddr_storage address;
int err, err2;
int fput_needed;
if (size > INT_MAX)
size = INT_MAX;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
goto out;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_iovlen = 1;
msg.msg_iov = &iov;
iov.iov_len = size;
iov.iov_base = ubuf;
msg.msg_name = (struct sockaddr *)&address;
msg.msg_namelen = sizeof(address);
if (sock->file->f_flags & O_NONBLOCK)
flags |= MSG_DONTWAIT;
err = sock_recvmsg(sock, &msg, size, flags);
if (err >= 0 && addr != NULL) {
err2 = move_addr_to_user(&address,
msg.msg_namelen, addr, addr_len);
if (err2 < 0)
err = err2;
}
fput_light(sock->file, fput_needed);
out:
return err;
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(mcrypt_list_algorithms)
{
char **modules;
char *lib_dir = MCG(algorithms_dir);
int lib_dir_len;
int i, count;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s",
&lib_dir, &lib_dir_len) == FAILURE) {
return;
}
array_init(return_value);
modules = mcrypt_list_algorithms(lib_dir, &count);
if (count == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir");
}
for (i = 0; i < count; i++) {
add_index_string(return_value, i, modules[i], 1);
}
mcrypt_free_p(modules, count);
}
CWE ID: CWE-190
Target: 1
Example 2:
Code: proto_register_u3v(void)
{
static gint *ett[] = {
&ett_u3v,
&ett_u3v_cmd,
&ett_u3v_flags,
&ett_u3v_ack,
&ett_u3v_payload_cmd,
&ett_u3v_payload_ack,
&ett_u3v_payload_ack_subtree,
&ett_u3v_payload_cmd_subtree,
&ett_u3v_bootstrap_fields,
&ett_u3v_stream_leader,
&ett_u3v_stream_trailer,
&ett_u3v_stream_payload,
&ett_u3v_device_info_descriptor,
&ett_u3v_device_info_descriptor_speed_support,
&ett_u3v_device_info_descriptor_gencp_version,
&ett_u3v_device_info_descriptor_u3v_version,
};
proto_u3v = proto_register_protocol("USB 3 Vision", "U3V", "u3v");
proto_register_field_array(proto_u3v, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
register_dissector("u3v", dissect_u3v, proto_u3v);
}
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: on_handler_vanished(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
char *reason;
reason = g_strdup_printf("Cannot find handler bus name: "
"org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", FALSE, reason));
g_free(reason);
}
tcmur_unregister_handler(handler);
dbus_unexport_handler(handler);
}
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: int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len, addr_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;
/*
* 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_msg(skb, sizeof(struct udphdr),
msg, copied);
else {
err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr),
msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv_offset(msg, skb, sizeof(struct udphdr));
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)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_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-399
Target: 1
Example 2:
Code: static void acpi_hotplug_work_fn(struct work_struct *work)
{
struct acpi_hp_work *hpw = container_of(work, struct acpi_hp_work, work);
acpi_os_wait_events_complete();
acpi_device_hotplug(hpw->adev, hpw->src);
kfree(hpw);
}
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: scoped_refptr<Resource> ResourceTracker::GetResource(PP_Resource res) const {
DLOG_IF(ERROR, !CheckIdType(res, PP_ID_TYPE_RESOURCE))
<< res << " is not a PP_Resource.";
ResourceMap::const_iterator result = live_resources_.find(res);
if (result == live_resources_.end()) {
return scoped_refptr<Resource>();
}
return result->second.first;
}
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 ogg_uint32_t decpack(long entry,long used_entry,long quantvals,
codebook *b,oggpack_buffer *opb,int maptype){
ogg_uint32_t ret=0;
int j;
switch(b->dec_type){
case 0:
return (ogg_uint32_t)entry;
case 1:
if(maptype==1){
/* vals are already read into temporary column vector here */
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=((ogg_uint16_t *)(b->q_val))[off]<<(b->q_bits*j);
}
}else{
for(j=0;j<b->dim;j++)
ret|=oggpack_read(opb,b->q_bits)<<(b->q_bits*j);
}
return ret;
case 2:
for(j=0;j<b->dim;j++){
ogg_uint32_t off=entry%quantvals;
entry/=quantvals;
ret|=off<<(b->q_pack*j);
}
return ret;
case 3:
return (ogg_uint32_t)used_entry;
}
return 0; /* silence compiler */
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void InputDispatcher::EventEntry::release() {
refCount -= 1;
if (refCount == 0) {
delete this;
} else {
ALOG_ASSERT(refCount > 0);
}
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void AutofillManager::Reset() {
form_structures_.reset();
has_logged_autofill_enabled_ = false;
has_logged_address_suggestions_count_ = false;
}
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 UpdateAtlas::didSwapBuffers()
{
m_areaAllocator.clear();
buildLayoutIfNeeded();
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: pkinit_find_private_key(pkinit_identity_crypto_context id_cryptoctx,
CK_ATTRIBUTE_TYPE usage,
CK_OBJECT_HANDLE *objp)
{
CK_OBJECT_CLASS cls;
CK_ATTRIBUTE attrs[4];
CK_ULONG count;
CK_KEY_TYPE keytype;
unsigned int nattrs = 0;
int r;
#ifdef PKINIT_USE_KEY_USAGE
CK_BBOOL true_false;
#endif
cls = CKO_PRIVATE_KEY;
attrs[nattrs].type = CKA_CLASS;
attrs[nattrs].pValue = &cls;
attrs[nattrs].ulValueLen = sizeof cls;
nattrs++;
#ifdef PKINIT_USE_KEY_USAGE
/*
* Some cards get confused if you try to specify a key usage,
* so don't, and hope for the best. This will fail if you have
* several keys with the same id and different usages but I have
* not seen this on real cards.
*/
true_false = TRUE;
attrs[nattrs].type = usage;
attrs[nattrs].pValue = &true_false;
attrs[nattrs].ulValueLen = sizeof true_false;
nattrs++;
#endif
keytype = CKK_RSA;
attrs[nattrs].type = CKA_KEY_TYPE;
attrs[nattrs].pValue = &keytype;
attrs[nattrs].ulValueLen = sizeof keytype;
nattrs++;
attrs[nattrs].type = CKA_ID;
attrs[nattrs].pValue = id_cryptoctx->cert_id;
attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len;
nattrs++;
r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs);
if (r != CKR_OK) {
pkiDebug("krb5_pkinit_sign_data: C_FindObjectsInit: %s\n",
pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session, objp, 1, &count);
id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session);
pkiDebug("found %d private keys (%s)\n", (int) count, pkinit_pkcs11_code_to_text(r));
if (r != CKR_OK || count < 1)
return KRB5KDC_ERR_PREAUTH_FAILED;
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: xmlParseElement(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
const xmlChar *prefix = NULL;
const xmlChar *URI = NULL;
xmlParserNodeInfo node_info;
int line, tlen;
xmlNodePtr ret;
int nsNr = ctxt->nsNr;
if (((unsigned int) ctxt->nameNr > xmlParserMaxDepth) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR,
"Excessive depth in document: %d use XML_PARSE_HUGE option\n",
xmlParserMaxDepth);
ctxt->instate = XML_PARSER_EOF;
return;
}
/* Capture start position */
if (ctxt->record_info) {
node_info.begin_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.begin_line = ctxt->input->line;
}
if (ctxt->spaceNr == 0)
spacePush(ctxt, -1);
else if (*ctxt->space == -2)
spacePush(ctxt, -1);
else
spacePush(ctxt, *ctxt->space);
line = ctxt->input->line;
#ifdef LIBXML_SAX1_ENABLED
if (ctxt->sax2)
#endif /* LIBXML_SAX1_ENABLED */
name = xmlParseStartTag2(ctxt, &prefix, &URI, &tlen);
#ifdef LIBXML_SAX1_ENABLED
else
name = xmlParseStartTag(ctxt);
#endif /* LIBXML_SAX1_ENABLED */
if (ctxt->instate == XML_PARSER_EOF)
return;
if (name == NULL) {
spacePop(ctxt);
return;
}
namePush(ctxt, name);
ret = ctxt->node;
#ifdef LIBXML_VALID_ENABLED
/*
* [ VC: Root Element Type ]
* The Name in the document type declaration must match the element
* type of the root element.
*/
if (ctxt->validate && ctxt->wellFormed && ctxt->myDoc &&
ctxt->node && (ctxt->node == ctxt->myDoc->children))
ctxt->valid &= xmlValidateRoot(&ctxt->vctxt, ctxt->myDoc);
#endif /* LIBXML_VALID_ENABLED */
/*
* Check for an Empty Element.
*/
if ((RAW == '/') && (NXT(1) == '>')) {
SKIP(2);
if (ctxt->sax2) {
if ((ctxt->sax != NULL) && (ctxt->sax->endElementNs != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElementNs(ctxt->userData, name, prefix, URI);
#ifdef LIBXML_SAX1_ENABLED
} else {
if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->endElement(ctxt->userData, name);
#endif /* LIBXML_SAX1_ENABLED */
}
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
return;
}
if (RAW == '>') {
NEXT1;
} else {
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_GT_REQUIRED,
"Couldn't find end of Start Tag %s line %d\n",
name, line, NULL);
/*
* end of parsing of this node.
*/
nodePop(ctxt);
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
/*
* Capture end position and add node
*/
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
return;
}
/*
* Parse the content of the element:
*/
xmlParseContent(ctxt);
if (!IS_BYTE_CHAR(RAW)) {
xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
"Premature end of data in tag %s line %d\n",
name, line, NULL);
/*
* end of parsing of this node.
*/
nodePop(ctxt);
namePop(ctxt);
spacePop(ctxt);
if (nsNr != ctxt->nsNr)
nsPop(ctxt, ctxt->nsNr - nsNr);
return;
}
/*
* parse the end of tag: '</' should be here.
*/
if (ctxt->sax2) {
xmlParseEndTag2(ctxt, prefix, URI, line, ctxt->nsNr - nsNr, tlen);
namePop(ctxt);
}
#ifdef LIBXML_SAX1_ENABLED
else
xmlParseEndTag1(ctxt, line);
#endif /* LIBXML_SAX1_ENABLED */
/*
* Capture end position and add node
*/
if ( ret != NULL && ctxt->record_info ) {
node_info.end_pos = ctxt->input->consumed +
(CUR_PTR - ctxt->input->base);
node_info.end_line = ctxt->input->line;
node_info.node = ret;
xmlParserAddNodeInfo(ctxt, &node_info);
}
}
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 HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name)
{
if (name.isEmpty())
return;
map.add(name.impl());
if (Frame* f = frame())
f->script()->namedItemAdded(this, name);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool TextureManager::TextureInfo::MarkMipmapsGenerated(
const FeatureInfo* feature_info) {
if (!CanGenerateMipmaps(feature_info)) {
return false;
}
for (size_t ii = 0; ii < level_infos_.size(); ++ii) {
const TextureInfo::LevelInfo& info1 = level_infos_[ii][0];
GLsizei width = info1.width;
GLsizei height = info1.height;
GLsizei depth = info1.depth;
GLenum target = target_ == GL_TEXTURE_2D ? GL_TEXTURE_2D :
FaceIndexToGLTarget(ii);
int num_mips = ComputeMipMapCount(width, height, depth);
for (int level = 1; level < num_mips; ++level) {
width = std::max(1, width >> 1);
height = std::max(1, height >> 1);
depth = std::max(1, depth >> 1);
SetLevelInfo(feature_info,
target,
level,
info1.internal_format,
width,
height,
depth,
info1.border,
info1.format,
info1.type,
true);
}
}
return true;
}
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 PopupContainer::showInRect(const IntRect& r, FrameView* v, int index)
{
listBox()->setBaseWidth(max(r.width() - kBorderSize * 2, 0));
listBox()->updateFromElement();
IntPoint location = v->contentsToWindow(r.location());
location.move(0, r.height());
m_originalFrameRect = IntRect(location, r.size());
setFrameRect(m_originalFrameRect);
showPopup(v);
}
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: error::Error GLES2DecoderPassthroughImpl::DoLinkProgram(GLuint program) {
TRACE_EVENT0("gpu", "GLES2DecoderPassthroughImpl::DoLinkProgram");
SCOPED_UMA_HISTOGRAM_TIMER("GPU.PassthroughDoLinkProgramTime");
api()->glLinkProgramFn(GetProgramServiceID(program, resources_));
ExitCommandProcessingEarly();
return error::kNoError;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) {
if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL ||
lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL ||
lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL ||
lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL ||
lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) {
JsVar *rhs;
int op = lex->tk;
JSP_ASSERT_MATCH(op);
rhs = jspeAssignmentExpression();
rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS
if (JSP_SHOULD_EXECUTE && lhs) {
if (op=='=') {
/* If we're assigning to this and we don't have a parent,
* add it to the symbol table root */
if (!jsvGetRefs(lhs) && jsvIsName(lhs)) {
if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs))
jsvAddName(execInfo.root, lhs);
}
jspReplaceWith(lhs, rhs);
} else {
if (op==LEX_PLUSEQUAL) op='+';
else if (op==LEX_MINUSEQUAL) op='-';
else if (op==LEX_MULEQUAL) op='*';
else if (op==LEX_DIVEQUAL) op='/';
else if (op==LEX_MODEQUAL) op='%';
else if (op==LEX_ANDEQUAL) op='&';
else if (op==LEX_OREQUAL) op='|';
else if (op==LEX_XOREQUAL) op='^';
else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT;
else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT;
else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED;
if (op=='+' && jsvIsName(lhs)) {
JsVar *currentValue = jsvSkipName(lhs);
if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) {
/* A special case for string += where this is the only use of the string
* and we're not appending to ourselves. In this case we can do a
* simple append (rather than clone + append)*/
JsVar *str = jsvAsString(rhs, false);
jsvAppendStringVarComplete(currentValue, str);
jsvUnLock(str);
op = 0;
}
jsvUnLock(currentValue);
}
if (op) {
/* Fallback which does a proper add */
JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op);
jspReplaceWith(lhs, res);
jsvUnLock(res);
}
}
}
jsvUnLock(rhs);
}
return lhs;
}
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: status_t BnHDCP::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case HDCP_SET_OBSERVER:
{
CHECK_INTERFACE(IHDCP, data, reply);
sp<IHDCPObserver> observer =
interface_cast<IHDCPObserver>(data.readStrongBinder());
reply->writeInt32(setObserver(observer));
return OK;
}
case HDCP_INIT_ASYNC:
{
CHECK_INTERFACE(IHDCP, data, reply);
const char *host = data.readCString();
unsigned port = data.readInt32();
reply->writeInt32(initAsync(host, port));
return OK;
}
case HDCP_SHUTDOWN_ASYNC:
{
CHECK_INTERFACE(IHDCP, data, reply);
reply->writeInt32(shutdownAsync());
return OK;
}
case HDCP_GET_CAPS:
{
CHECK_INTERFACE(IHDCP, data, reply);
reply->writeInt32(getCaps());
return OK;
}
case HDCP_ENCRYPT:
{
size_t size = data.readInt32();
void *inData = malloc(2 * size);
void *outData = (uint8_t *)inData + size;
data.read(inData, size);
uint32_t streamCTR = data.readInt32();
uint64_t inputCTR;
status_t err = encrypt(inData, size, streamCTR, &inputCTR, outData);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt64(inputCTR);
reply->write(outData, size);
}
free(inData);
inData = outData = NULL;
return OK;
}
case HDCP_ENCRYPT_NATIVE:
{
CHECK_INTERFACE(IHDCP, data, reply);
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
size_t offset = data.readInt32();
size_t size = data.readInt32();
uint32_t streamCTR = data.readInt32();
void *outData = malloc(size);
uint64_t inputCTR;
status_t err = encryptNative(graphicBuffer, offset, size,
streamCTR, &inputCTR, outData);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt64(inputCTR);
reply->write(outData, size);
}
free(outData);
outData = NULL;
return OK;
}
case HDCP_DECRYPT:
{
size_t size = data.readInt32();
void *inData = malloc(2 * size);
void *outData = (uint8_t *)inData + size;
data.read(inData, size);
uint32_t streamCTR = data.readInt32();
uint64_t inputCTR = data.readInt64();
status_t err = decrypt(inData, size, streamCTR, inputCTR, outData);
reply->writeInt32(err);
if (err == OK) {
reply->write(outData, size);
}
free(inData);
inData = outData = NULL;
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
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: mainloop_destroy_trigger(crm_trigger_t * source)
{
source->trigger = FALSE;
if (source->id > 0) {
g_source_remove(source->id);
}
return TRUE;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: Extension::~Extension() {
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline void atalk_dev_down(struct net_device *dev)
{
atrtr_device_down(dev); /* Remove all routes for the device */
aarp_device_down(dev); /* Remove AARP entries for the device */
atif_drop_device(dev); /* Remove the device */
}
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: bool Track::GetLacing() const
{
return m_info.lacing;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: status_t CameraClient::connect(const sp<ICameraClient>& client) {
int callingPid = getCallingPid();
LOG1("connect E (pid %d)", callingPid);
Mutex::Autolock lock(mLock);
if (mClientPid != 0 && checkPid() != NO_ERROR) {
ALOGW("Tried to connect to a locked camera (old pid %d, new pid %d)",
mClientPid, callingPid);
return EBUSY;
}
if (mRemoteCallback != 0 &&
(client->asBinder() == mRemoteCallback->asBinder())) {
LOG1("Connect to the same client");
return NO_ERROR;
}
mPreviewCallbackFlag = CAMERA_FRAME_CALLBACK_FLAG_NOOP;
mClientPid = callingPid;
mRemoteCallback = client;
LOG1("connect X (pid %d)", callingPid);
return NO_ERROR;
}
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 OpenSSL_add_all_ciphers(void)
{
#ifndef OPENSSL_NO_DES
EVP_add_cipher(EVP_des_cfb());
EVP_add_cipher(EVP_des_cfb1());
EVP_add_cipher(EVP_des_cfb8());
EVP_add_cipher(EVP_des_ede_cfb());
EVP_add_cipher(EVP_des_ede3_cfb());
EVP_add_cipher(EVP_des_ede3_cfb1());
EVP_add_cipher(EVP_des_ede3_cfb8());
EVP_add_cipher(EVP_des_ofb());
EVP_add_cipher(EVP_des_ede_ofb());
EVP_add_cipher(EVP_des_ede3_ofb());
EVP_add_cipher(EVP_desx_cbc());
EVP_add_cipher_alias(SN_desx_cbc,"DESX");
EVP_add_cipher_alias(SN_desx_cbc,"desx");
EVP_add_cipher(EVP_des_cbc());
EVP_add_cipher_alias(SN_des_cbc,"DES");
EVP_add_cipher_alias(SN_des_cbc,"des");
EVP_add_cipher(EVP_des_ede_cbc());
EVP_add_cipher(EVP_des_ede3_cbc());
EVP_add_cipher_alias(SN_des_ede3_cbc,"DES3");
EVP_add_cipher_alias(SN_des_ede3_cbc,"des3");
EVP_add_cipher(EVP_des_ecb());
EVP_add_cipher(EVP_des_ede());
EVP_add_cipher(EVP_des_ede3());
#endif
#ifndef OPENSSL_NO_RC4
EVP_add_cipher(EVP_rc4());
EVP_add_cipher(EVP_rc4_40());
#ifndef OPENSSL_NO_MD5
EVP_add_cipher(EVP_rc4_hmac_md5());
#endif
#endif
#ifndef OPENSSL_NO_IDEA
EVP_add_cipher(EVP_idea_ecb());
EVP_add_cipher(EVP_idea_cfb());
EVP_add_cipher(EVP_idea_ofb());
EVP_add_cipher(EVP_idea_cbc());
EVP_add_cipher_alias(SN_idea_cbc,"IDEA");
EVP_add_cipher_alias(SN_idea_cbc,"idea");
#endif
#ifndef OPENSSL_NO_SEED
EVP_add_cipher(EVP_seed_ecb());
EVP_add_cipher(EVP_seed_cfb());
EVP_add_cipher(EVP_seed_ofb());
EVP_add_cipher(EVP_seed_cbc());
EVP_add_cipher_alias(SN_seed_cbc,"SEED");
EVP_add_cipher_alias(SN_seed_cbc,"seed");
#endif
#ifndef OPENSSL_NO_RC2
EVP_add_cipher(EVP_rc2_ecb());
EVP_add_cipher(EVP_rc2_cfb());
EVP_add_cipher(EVP_rc2_ofb());
EVP_add_cipher(EVP_rc2_cbc());
EVP_add_cipher(EVP_rc2_40_cbc());
EVP_add_cipher(EVP_rc2_64_cbc());
EVP_add_cipher_alias(SN_rc2_cbc,"RC2");
EVP_add_cipher_alias(SN_rc2_cbc,"rc2");
#endif
#ifndef OPENSSL_NO_BF
EVP_add_cipher(EVP_bf_ecb());
EVP_add_cipher(EVP_bf_cfb());
EVP_add_cipher(EVP_bf_ofb());
EVP_add_cipher(EVP_bf_cbc());
EVP_add_cipher_alias(SN_bf_cbc,"BF");
EVP_add_cipher_alias(SN_bf_cbc,"bf");
EVP_add_cipher_alias(SN_bf_cbc,"blowfish");
#endif
#ifndef OPENSSL_NO_CAST
EVP_add_cipher(EVP_cast5_ecb());
EVP_add_cipher(EVP_cast5_cfb());
EVP_add_cipher(EVP_cast5_ofb());
EVP_add_cipher(EVP_cast5_cbc());
EVP_add_cipher_alias(SN_cast5_cbc,"CAST");
EVP_add_cipher_alias(SN_cast5_cbc,"cast");
EVP_add_cipher_alias(SN_cast5_cbc,"CAST-cbc");
EVP_add_cipher_alias(SN_cast5_cbc,"cast-cbc");
#endif
#ifndef OPENSSL_NO_RC5
EVP_add_cipher(EVP_rc5_32_12_16_ecb());
EVP_add_cipher(EVP_rc5_32_12_16_cfb());
EVP_add_cipher(EVP_rc5_32_12_16_ofb());
EVP_add_cipher(EVP_rc5_32_12_16_cbc());
EVP_add_cipher_alias(SN_rc5_cbc,"rc5");
EVP_add_cipher_alias(SN_rc5_cbc,"RC5");
#endif
#ifndef OPENSSL_NO_AES
EVP_add_cipher(EVP_aes_128_ecb());
EVP_add_cipher(EVP_aes_128_cbc());
EVP_add_cipher(EVP_aes_128_cfb());
EVP_add_cipher(EVP_aes_128_cfb1());
EVP_add_cipher(EVP_aes_128_cfb8());
EVP_add_cipher(EVP_aes_128_ofb());
EVP_add_cipher(EVP_aes_128_ctr());
EVP_add_cipher(EVP_aes_128_gcm());
EVP_add_cipher(EVP_aes_128_xts());
EVP_add_cipher_alias(SN_aes_128_cbc,"AES128");
EVP_add_cipher_alias(SN_aes_128_cbc,"aes128");
EVP_add_cipher(EVP_aes_192_ecb());
EVP_add_cipher(EVP_aes_192_cbc());
EVP_add_cipher(EVP_aes_192_cfb());
EVP_add_cipher(EVP_aes_192_cfb1());
EVP_add_cipher(EVP_aes_192_cfb8());
EVP_add_cipher(EVP_aes_192_ofb());
EVP_add_cipher(EVP_aes_192_ctr());
EVP_add_cipher(EVP_aes_192_gcm());
EVP_add_cipher_alias(SN_aes_192_cbc,"AES192");
EVP_add_cipher_alias(SN_aes_192_cbc,"aes192");
EVP_add_cipher(EVP_aes_256_ecb());
EVP_add_cipher(EVP_aes_256_cbc());
EVP_add_cipher(EVP_aes_256_cfb());
EVP_add_cipher(EVP_aes_256_cfb1());
EVP_add_cipher(EVP_aes_256_cfb8());
EVP_add_cipher(EVP_aes_256_ofb());
EVP_add_cipher(EVP_aes_256_ctr());
EVP_add_cipher(EVP_aes_256_gcm());
EVP_add_cipher(EVP_aes_256_xts());
EVP_add_cipher_alias(SN_aes_256_cbc,"AES256");
EVP_add_cipher_alias(SN_aes_256_cbc,"aes256");
#if 0 /* Disabled because of timing side-channel leaks. */
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1)
EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1());
EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1());
#endif
#endif
#endif
#ifndef OPENSSL_NO_CAMELLIA
EVP_add_cipher(EVP_camellia_128_ecb());
#ifndef OPENSSL_NO_CAMELLIA
EVP_add_cipher(EVP_camellia_128_ecb());
EVP_add_cipher(EVP_camellia_128_cbc());
EVP_add_cipher(EVP_camellia_128_cfb());
EVP_add_cipher(EVP_camellia_128_cfb1());
EVP_add_cipher(EVP_camellia_128_cfb8());
EVP_add_cipher(EVP_camellia_128_ofb());
EVP_add_cipher_alias(SN_camellia_128_cbc,"CAMELLIA128");
EVP_add_cipher_alias(SN_camellia_128_cbc,"camellia128");
EVP_add_cipher(EVP_camellia_192_ecb());
EVP_add_cipher(EVP_camellia_192_cbc());
EVP_add_cipher(EVP_camellia_192_cfb());
EVP_add_cipher(EVP_camellia_192_cfb1());
EVP_add_cipher(EVP_camellia_192_cfb8());
EVP_add_cipher(EVP_camellia_192_ofb());
EVP_add_cipher_alias(SN_camellia_192_cbc,"CAMELLIA192");
EVP_add_cipher_alias(SN_camellia_192_cbc,"camellia192");
EVP_add_cipher(EVP_camellia_256_ecb());
EVP_add_cipher(EVP_camellia_256_cbc());
EVP_add_cipher(EVP_camellia_256_cfb());
EVP_add_cipher(EVP_camellia_256_cfb1());
EVP_add_cipher(EVP_camellia_256_cfb8());
EVP_add_cipher(EVP_camellia_256_ofb());
EVP_add_cipher_alias(SN_camellia_256_cbc,"CAMELLIA256");
EVP_add_cipher_alias(SN_camellia_256_cbc,"camellia256");
#endif
}
CWE ID: CWE-310
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ecryptfs_decode_from_filename(unsigned char *dst, size_t *dst_size,
const unsigned char *src, size_t src_size)
{
u8 current_bit_offset = 0;
size_t src_byte_offset = 0;
size_t dst_byte_offset = 0;
if (dst == NULL) {
(*dst_size) = ecryptfs_max_decoded_size(src_size);
goto out;
}
while (src_byte_offset < src_size) {
unsigned char src_byte =
filename_rev_map[(int)src[src_byte_offset]];
switch (current_bit_offset) {
case 0:
dst[dst_byte_offset] = (src_byte << 2);
current_bit_offset = 6;
break;
case 6:
dst[dst_byte_offset++] |= (src_byte >> 4);
dst[dst_byte_offset] = ((src_byte & 0xF)
<< 4);
current_bit_offset = 4;
break;
case 4:
dst[dst_byte_offset++] |= (src_byte >> 2);
dst[dst_byte_offset] = (src_byte << 6);
current_bit_offset = 2;
break;
case 2:
dst[dst_byte_offset++] |= (src_byte);
dst[dst_byte_offset] = 0;
current_bit_offset = 0;
break;
}
src_byte_offset++;
}
(*dst_size) = dst_byte_offset;
out:
return;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: vmxnet3_inc_rx_completion_counter(VMXNET3State *s, int qidx)
{
vmxnet3_ring_inc(&s->rxq_descr[qidx].comp_ring);
}
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: get_mech_oid(OM_uint32 *minor_status, unsigned char **buff_in, size_t length)
{
OM_uint32 status;
gss_OID_desc toid;
gss_OID mech_out = NULL;
unsigned char *start, *end;
if (length < 1 || **buff_in != MECH_OID)
return (NULL);
start = *buff_in;
end = start + length;
(*buff_in)++;
toid.length = *(*buff_in)++;
if ((*buff_in + toid.length) > end)
return (NULL);
toid.elements = *buff_in;
*buff_in += toid.length;
status = generic_gss_copy_oid(minor_status, &toid, &mech_out);
if (status != GSS_S_COMPLETE) {
map_errcode(minor_status);
mech_out = NULL;
}
return (mech_out);
}
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: my_object_get_val (MyObject *obj, guint *ret, GError **error)
{
*ret = obj->val;
return TRUE;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool ChromeClientImpl::toolbarsVisible()
{
return m_toolbarsVisible;
}
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 ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
const char* name;
size_t namelen;
if (node->graft_path) {
name = node->graft_path;
namelen = node->graft_pathlen;
} else if (node->actual_name) {
name = node->actual_name;
namelen = node->namelen;
} else {
name = node->name;
namelen = node->namelen;
}
if (bufsize < namelen + 1) {
return -1;
}
ssize_t pathlen = 0;
if (node->parent && node->graft_path == NULL) {
pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 2);
if (pathlen < 0) {
return -1;
}
buf[pathlen++] = '/';
}
memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
return pathlen + namelen;
}
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 find_low_bit(unsigned int x)
{
int i;
for(i=0;i<=31;i++) {
if(x&(1<<i)) return i;
}
return 0;
}
CWE ID: CWE-682
Target: 1
Example 2:
Code: static __be32 *xdr_check_write_list(__be32 *p, __be32 *end)
{
__be32 *next;
while (*p++ != xdr_zero) {
next = p + 1 + be32_to_cpup(p) * rpcrdma_segment_maxsz;
if (next > end)
return NULL;
p = next;
}
return p;
}
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: LazyBackgroundPageNativeHandler::LazyBackgroundPageNativeHandler(
ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"IncrementKeepaliveCount",
base::Bind(&LazyBackgroundPageNativeHandler::IncrementKeepaliveCount,
base::Unretained(this)));
RouteFunction(
"DecrementKeepaliveCount",
base::Bind(&LazyBackgroundPageNativeHandler::DecrementKeepaliveCount,
base::Unretained(this)));
}
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 int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
{
struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
int err = 0;
mutex_lock(&swhash->hlist_mutex);
if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
struct swevent_hlist *hlist;
hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
if (!hlist) {
err = -ENOMEM;
goto exit;
}
rcu_assign_pointer(swhash->swevent_hlist, hlist);
}
swhash->hlist_refcount++;
exit:
mutex_unlock(&swhash->hlist_mutex);
return err;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: isoent_collect_dirs(struct vdd *vdd, struct isoent *rootent, int depth)
{
struct isoent *np;
if (rootent == NULL)
rootent = vdd->rootent;
np = rootent;
do {
/* Register current directory to pathtable. */
path_table_add_entry(&(vdd->pathtbl[depth]), np);
if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) {
/* Enter to sub directories. */
np = np->subdirs.first;
depth++;
continue;
}
while (np != rootent) {
if (np->drnext == NULL) {
/* Return to the parent directory. */
np = np->parent;
depth--;
} else {
np = np->drnext;
break;
}
}
} while (np != rootent);
return (ARCHIVE_OK);
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PrintJobWorker::~PrintJobWorker() {
DCHECK(owner_->RunsTasksInCurrentSequence());
Stop();
}
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 ptrace_setxregs(struct task_struct *child, void __user *uregs)
{
struct thread_info *ti = task_thread_info(child);
struct pt_regs *regs = task_pt_regs(child);
elf_xtregs_t *xtregs = uregs;
int ret = 0;
#if XTENSA_HAVE_COPROCESSORS
/* Flush all coprocessors before we overwrite them. */
coprocessor_flush_all(ti);
coprocessor_release_all(ti);
ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0,
sizeof(xtregs_coprocessor_t));
#endif
ret |= __copy_from_user(®s->xtregs_opt, &xtregs->opt,
sizeof(xtregs->opt));
ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user,
sizeof(xtregs->user));
return ret ? -EFAULT : 0;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void findHotKeys(void) {
redisReply *keys, *reply;
unsigned long long counters[HOTKEYS_SAMPLE] = {0};
sds hotkeys[HOTKEYS_SAMPLE] = {NULL};
unsigned long long sampled = 0, total_keys, *freqs = NULL, it = 0;
unsigned int arrsize = 0, i, k;
double pct;
/* Total keys pre scanning */
total_keys = getDbSize();
/* Status message */
printf("\n# Scanning the entire keyspace to find hot keys as well as\n");
printf("# average sizes per key type. You can use -i 0.1 to sleep 0.1 sec\n");
printf("# per 100 SCAN commands (not usually needed).\n\n");
/* SCAN loop */
do {
/* Calculate approximate percentage completion */
pct = 100 * (double)sampled/total_keys;
/* Grab some keys and point to the keys array */
reply = sendScan(&it);
keys = reply->element[1];
/* Reallocate our freqs array if we need to */
if(keys->elements > arrsize) {
freqs = zrealloc(freqs, sizeof(unsigned long long)*keys->elements);
if(!freqs) {
fprintf(stderr, "Failed to allocate storage for keys!\n");
exit(1);
}
arrsize = keys->elements;
}
getKeyFreqs(keys, freqs);
/* Now update our stats */
for(i=0;i<keys->elements;i++) {
sampled++;
/* Update overall progress */
if(sampled % 1000000 == 0) {
printf("[%05.2f%%] Sampled %llu keys so far\n", pct, sampled);
}
/* Use eviction pool here */
k = 0;
while (k < HOTKEYS_SAMPLE && freqs[i] > counters[k]) k++;
if (k == 0) continue;
k--;
if (k == 0 || counters[k] == 0) {
sdsfree(hotkeys[k]);
} else {
sdsfree(hotkeys[0]);
memmove(counters,counters+1,sizeof(counters[0])*k);
memmove(hotkeys,hotkeys+1,sizeof(hotkeys[0])*k);
}
counters[k] = freqs[i];
hotkeys[k] = sdsnew(keys->element[i]->str);
printf(
"[%05.2f%%] Hot key '%s' found so far with counter %llu\n",
pct, keys->element[i]->str, freqs[i]);
}
/* Sleep if we've been directed to do so */
if(sampled && (sampled %100) == 0 && config.interval) {
usleep(config.interval);
}
freeReplyObject(reply);
} while(it != 0);
if (freqs) zfree(freqs);
/* We're done */
printf("\n-------- summary -------\n\n");
printf("Sampled %llu keys in the keyspace!\n", sampled);
for (i=1; i<= HOTKEYS_SAMPLE; i++) {
k = HOTKEYS_SAMPLE - i;
if(counters[k]>0) {
printf("hot key found with counter: %llu\tkeyname: %s\n", counters[k], hotkeys[k]);
sdsfree(hotkeys[k]);
}
}
exit(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: xmlParse3986Authority(xmlURIPtr uri, const char **str)
{
const char *cur;
int ret;
cur = *str;
/*
* try to parse an userinfo and check for the trailing @
*/
ret = xmlParse3986Userinfo(uri, &cur);
if ((ret != 0) || (*cur != '@'))
cur = *str;
else
cur++;
ret = xmlParse3986Host(uri, &cur);
if (ret != 0) return(ret);
if (*cur == ':') {
cur++;
ret = xmlParse3986Port(uri, &cur);
if (ret != 0) return(ret);
}
*str = cur;
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: ext2_xattr_get(struct inode *inode, int name_index, const char *name,
void *buffer, size_t buffer_size)
{
struct buffer_head *bh = NULL;
struct ext2_xattr_entry *entry;
size_t name_len, size;
char *end;
int error;
ea_idebug(inode, "name=%d.%s, buffer=%p, buffer_size=%ld",
name_index, name, buffer, (long)buffer_size);
if (name == NULL)
return -EINVAL;
name_len = strlen(name);
if (name_len > 255)
return -ERANGE;
down_read(&EXT2_I(inode)->xattr_sem);
error = -ENODATA;
if (!EXT2_I(inode)->i_file_acl)
goto cleanup;
ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl);
bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl);
error = -EIO;
if (!bh)
goto cleanup;
ea_bdebug(bh, "b_count=%d, refcount=%d",
atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount));
end = bh->b_data + bh->b_size;
if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) ||
HDR(bh)->h_blocks != cpu_to_le32(1)) {
bad_block: ext2_error(inode->i_sb, "ext2_xattr_get",
"inode %ld: bad block %d", inode->i_ino,
EXT2_I(inode)->i_file_acl);
error = -EIO;
goto cleanup;
}
/* find named attribute */
entry = FIRST_ENTRY(bh);
while (!IS_LAST_ENTRY(entry)) {
struct ext2_xattr_entry *next =
EXT2_XATTR_NEXT(entry);
if ((char *)next >= end)
goto bad_block;
if (name_index == entry->e_name_index &&
name_len == entry->e_name_len &&
memcmp(name, entry->e_name, name_len) == 0)
goto found;
entry = next;
}
if (ext2_xattr_cache_insert(bh))
ea_idebug(inode, "cache insert failed");
error = -ENODATA;
goto cleanup;
found:
/* check the buffer size */
if (entry->e_value_block != 0)
goto bad_block;
size = le32_to_cpu(entry->e_value_size);
if (size > inode->i_sb->s_blocksize ||
le16_to_cpu(entry->e_value_offs) + size > inode->i_sb->s_blocksize)
goto bad_block;
if (ext2_xattr_cache_insert(bh))
ea_idebug(inode, "cache insert failed");
if (buffer) {
error = -ERANGE;
if (size > buffer_size)
goto cleanup;
/* return value of attribute */
memcpy(buffer, bh->b_data + le16_to_cpu(entry->e_value_offs),
size);
}
error = size;
cleanup:
brelse(bh);
up_read(&EXT2_I(inode)->xattr_sem);
return error;
}
CWE ID: CWE-19
Target: 1
Example 2:
Code: static void mini_header_set_msg_serial(SpiceDataHeaderOpaque *header, uint64_t serial)
{
spice_error("attempt to set header serial on mini header");
}
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: parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
p += sizeof ( short );
for ( i = 0; i < string_count && i < 64; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= FT_MIN( string_count, 64 ) )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int try_smi_init(struct smi_info *new_smi)
{
int rv = 0;
int i;
char *init_name = NULL;
pr_info("Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\n",
ipmi_addr_src_to_str(new_smi->io.addr_source),
si_to_str[new_smi->io.si_type],
addr_space_to_str[new_smi->io.addr_type],
new_smi->io.addr_data,
new_smi->io.slave_addr, new_smi->io.irq);
switch (new_smi->io.si_type) {
case SI_KCS:
new_smi->handlers = &kcs_smi_handlers;
break;
case SI_SMIC:
new_smi->handlers = &smic_smi_handlers;
break;
case SI_BT:
new_smi->handlers = &bt_smi_handlers;
break;
default:
/* No support for anything else yet. */
rv = -EIO;
goto out_err;
}
new_smi->si_num = smi_num;
/* Do this early so it's available for logs. */
if (!new_smi->io.dev) {
init_name = kasprintf(GFP_KERNEL, "ipmi_si.%d",
new_smi->si_num);
/*
* If we don't already have a device from something
* else (like PCI), then register a new one.
*/
new_smi->pdev = platform_device_alloc("ipmi_si",
new_smi->si_num);
if (!new_smi->pdev) {
pr_err("Unable to allocate platform device\n");
rv = -ENOMEM;
goto out_err;
}
new_smi->io.dev = &new_smi->pdev->dev;
new_smi->io.dev->driver = &ipmi_platform_driver.driver;
/* Nulled by device_add() */
new_smi->io.dev->init_name = init_name;
}
/* Allocate the state machine's data and initialize it. */
new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL);
if (!new_smi->si_sm) {
rv = -ENOMEM;
goto out_err;
}
new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm,
&new_smi->io);
/* Now that we know the I/O size, we can set up the I/O. */
rv = new_smi->io.io_setup(&new_smi->io);
if (rv) {
dev_err(new_smi->io.dev, "Could not set up I/O space\n");
goto out_err;
}
/* Do low-level detection first. */
if (new_smi->handlers->detect(new_smi->si_sm)) {
if (new_smi->io.addr_source)
dev_err(new_smi->io.dev,
"Interface detection failed\n");
rv = -ENODEV;
goto out_err;
}
/*
* Attempt a get device id command. If it fails, we probably
* don't have a BMC here.
*/
rv = try_get_dev_id(new_smi);
if (rv) {
if (new_smi->io.addr_source)
dev_err(new_smi->io.dev,
"There appears to be no BMC at this location\n");
goto out_err;
}
setup_oem_data_handler(new_smi);
setup_xaction_handlers(new_smi);
check_for_broken_irqs(new_smi);
new_smi->waiting_msg = NULL;
new_smi->curr_msg = NULL;
atomic_set(&new_smi->req_events, 0);
new_smi->run_to_completion = false;
for (i = 0; i < SI_NUM_STATS; i++)
atomic_set(&new_smi->stats[i], 0);
new_smi->interrupt_disabled = true;
atomic_set(&new_smi->need_watch, 0);
rv = try_enable_event_buffer(new_smi);
if (rv == 0)
new_smi->has_event_buffer = true;
/*
* Start clearing the flags before we enable interrupts or the
* timer to avoid racing with the timer.
*/
start_clear_flags(new_smi);
/*
* IRQ is defined to be set when non-zero. req_events will
* cause a global flags check that will enable interrupts.
*/
if (new_smi->io.irq) {
new_smi->interrupt_disabled = false;
atomic_set(&new_smi->req_events, 1);
}
if (new_smi->pdev && !new_smi->pdev_registered) {
rv = platform_device_add(new_smi->pdev);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to register system interface device: %d\n",
rv);
goto out_err;
}
new_smi->pdev_registered = true;
}
dev_set_drvdata(new_smi->io.dev, new_smi);
rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to add device attributes: error %d\n",
rv);
goto out_err;
}
new_smi->dev_group_added = true;
rv = ipmi_register_smi(&handlers,
new_smi,
new_smi->io.dev,
new_smi->io.slave_addr);
if (rv) {
dev_err(new_smi->io.dev,
"Unable to register device: error %d\n",
rv);
goto out_err;
}
/* Don't increment till we know we have succeeded. */
smi_num++;
dev_info(new_smi->io.dev, "IPMI %s interface initialized\n",
si_to_str[new_smi->io.si_type]);
WARN_ON(new_smi->io.dev->init_name != NULL);
out_err:
kfree(init_name);
return rv;
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType httpRefreshType)
{
if (m_isViewSource || !m_frame)
return;
double delay;
String refreshURL;
if (!parseHTTPRefresh(content, httpRefreshType == HttpRefreshFromMetaTag, delay, refreshURL))
return;
if (refreshURL.isEmpty())
refreshURL = url().string();
else
refreshURL = completeURL(refreshURL).string();
if (protocolIsJavaScript(refreshURL)) {
String message = "Refused to refresh " + m_url.elidedString() + " to a javascript: URL";
addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message));
return;
}
if (httpRefreshType == HttpRefreshFromMetaTag && isSandboxed(SandboxAutomaticFeatures)) {
String message = "Refused to execute the redirect specified via '<meta http-equiv='refresh' content='...'>'. The document is sandboxed, and the 'allow-scripts' keyword is not set.";
addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, message));
return;
}
m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
}
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 show_object_with_name(FILE *out, struct object *obj,
struct strbuf *path, const char *component)
{
char *name = path_name(path, component);
char *p;
fprintf(out, "%s ", oid_to_hex(&obj->oid));
for (p = name; *p && *p != '\n'; p++)
fputc(*p, out);
fputc('\n', out);
free(name);
}
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 RenderThread::Init() {
TRACE_EVENT_BEGIN_ETW("RenderThread::Init", 0, "");
#if defined(OS_MACOSX)
WebKit::WebView::setUseExternalPopupMenus(true);
#endif
lazy_tls.Pointer()->Set(this);
#if defined(OS_WIN)
if (RenderProcessImpl::InProcessPlugins())
CoInitialize(0);
#endif
suspend_webkit_shared_timer_ = true;
notify_webkit_of_modal_loop_ = true;
plugin_refresh_allowed_ = true;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_s_ = kInitialIdleHandlerDelayS;
task_factory_.reset(new ScopedRunnableMethodFactory<RenderThread>(this));
appcache_dispatcher_.reset(new AppCacheDispatcher(this));
indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
db_message_filter_ = new DBMessageFilter();
AddFilter(db_message_filter_.get());
vc_manager_ = new VideoCaptureImplManager();
AddFilter(vc_manager_->video_capture_message_filter());
audio_input_message_filter_ = new AudioInputMessageFilter();
AddFilter(audio_input_message_filter_.get());
audio_message_filter_ = new AudioMessageFilter();
AddFilter(audio_message_filter_.get());
content::GetContentClient()->renderer()->RenderThreadStarted();
TRACE_EVENT_END_ETW("RenderThread::Init", 0, "");
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int ocfs2_file_clone_range(struct file *file_in,
loff_t pos_in,
struct file *file_out,
loff_t pos_out,
u64 len)
{
return ocfs2_reflink_remap_range(file_in, pos_in, file_out, pos_out,
len, false);
}
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_MSHUTDOWN_FUNCTION(bcmath)
{
UNREGISTER_INI_ENTRIES();
return SUCCESS;
}
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void SetImePropertyActivated(const char* key, bool activated) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImePropertyActivated: IBus connection is not alive";
return;
}
if (!key || (key[0] == '\0')) {
return;
}
if (input_context_path_.empty()) {
LOG(ERROR) << "Input context is unknown";
return;
}
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
ibus_input_context_property_activate(
context, key, (activated ? PROP_STATE_CHECKED : PROP_STATE_UNCHECKED));
g_object_unref(context);
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static inline void cond_local_irq_disable(struct pt_regs *regs)
{
if (regs->flags & X86_EFLAGS_IF)
local_irq_disable();
}
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 xstateregs_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct fpu *fpu = &target->thread.fpu;
struct xregs_state *xsave;
int ret;
if (!boot_cpu_has(X86_FEATURE_XSAVE))
return -ENODEV;
/*
* A whole standard-format XSAVE buffer is needed:
*/
if ((pos != 0) || (count < fpu_user_xstate_size))
return -EFAULT;
xsave = &fpu->state.xsave;
fpu__activate_fpstate_write(fpu);
if (boot_cpu_has(X86_FEATURE_XSAVES)) {
if (kbuf)
ret = copy_kernel_to_xstate(xsave, kbuf);
else
ret = copy_user_to_xstate(xsave, ubuf);
} else {
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, xsave, 0, -1);
}
/*
* In case of failure, mark all states as init:
*/
if (ret)
fpstate_init(&fpu->state);
/*
* mxcsr reserved bits must be masked to zero for security reasons.
*/
xsave->i387.mxcsr &= mxcsr_feature_mask;
xsave->header.xfeatures &= xfeatures_mask;
/*
* These bits must be zero.
*/
memset(&xsave->header.reserved, 0, 48);
return ret;
}
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int sock_recv_all(int sock_fd, uint8_t* buf, int len)
{
int r = len;
int ret = -1;
while(r)
{
do ret = recv(sock_fd, buf, r, MSG_WAITALL);
while(ret < 0 && errno == EINTR);
if(ret <= 0)
{
BTIF_TRACE_ERROR("sock fd:%d recv errno:%d, ret:%d", sock_fd, errno, ret);
return -1;
}
buf += ret;
r -= ret;
}
return len;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength,
uint32 imagewidth, tsample_t spp,
struct dump_opts * dump)
{
tdata_t obuf = _TIFFmalloc(TIFFTileSize(out));
uint32 tl, tw;
uint32 row, col, nrow, ncol;
uint32 src_rowsize, col_offset;
uint16 bps;
tsample_t s;
uint8* bufp = (uint8*) buf;
if (obuf == NULL)
return 1;
TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps);
if( imagewidth == 0 ||
(uint32)bps * (uint32)spp > TIFF_UINT32_MAX / imagewidth ||
bps * spp * imagewidth > TIFF_UINT32_MAX - 7 )
{
TIFFError(TIFFFileName(out),
"Error, uint32 overflow when computing (imagewidth * bps * spp) + 7");
_TIFFfree(obuf);
return 1;
}
src_rowsize = ((imagewidth * spp * bps) + 7U) / 8;
for (row = 0; row < imagelength; row += tl)
{
nrow = (row + tl > imagelength) ? imagelength - row : tl;
for (col = 0; col < imagewidth; col += tw)
{
/* Calculate visible portion of tile. */
if (col + tw > imagewidth)
ncol = imagewidth - col;
else
ncol = tw;
col_offset = (((col * bps * spp) + 7) / 8);
bufp = buf + (row * src_rowsize) + col_offset;
for (s = 0; s < spp; s++)
{
if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth,
tw, s, 1, spp, bps, dump) > 0)
{
TIFFError("writeBufferToSeparateTiles",
"Unable to extract data to tile for row %lu, col %lu sample %d",
(unsigned long) row, (unsigned long)col, (int)s);
_TIFFfree(obuf);
return 1;
}
if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0)
{
TIFFError("writeBufferToseparateTiles",
"Cannot write tile at %lu %lu sample %lu",
(unsigned long) col, (unsigned long) row,
(unsigned long) s);
_TIFFfree(obuf);
return 1;
}
}
}
}
_TIFFfree(obuf);
return 0;
} /* end writeBufferToSeparateTiles */
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_FUNCTION(pg_num_fields)
{
php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS);
}
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 cap_bprm_set_creds(struct linux_binprm *bprm)
{
const struct cred *old = current_cred();
struct cred *new = bprm->cred;
bool effective, has_cap = false;
int ret;
effective = false;
ret = get_file_caps(bprm, &effective, &has_cap);
if (ret < 0)
return ret;
if (!issecure(SECURE_NOROOT)) {
/*
* If the legacy file capability is set, then don't set privs
* for a setuid root binary run by a non-root user. Do set it
* for a root user just to cause least surprise to an admin.
*/
if (has_cap && new->uid != 0 && new->euid == 0) {
warn_setuid_and_fcaps_mixed(bprm->filename);
goto skip;
}
/*
* To support inheritance of root-permissions and suid-root
* executables under compatibility mode, we override the
* capability sets for the file.
*
* If only the real uid is 0, we do not set the effective bit.
*/
if (new->euid == 0 || new->uid == 0) {
/* pP' = (cap_bset & ~0) | (pI & ~0) */
new->cap_permitted = cap_combine(old->cap_bset,
old->cap_inheritable);
}
if (new->euid == 0)
effective = true;
}
skip:
/* Don't let someone trace a set[ug]id/setpcap binary with the revised
* credentials unless they have the appropriate permit
*/
if ((new->euid != old->uid ||
new->egid != old->gid ||
!cap_issubset(new->cap_permitted, old->cap_permitted)) &&
bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) {
/* downgrade; they get no more than they had, and maybe less */
if (!capable(CAP_SETUID)) {
new->euid = new->uid;
new->egid = new->gid;
}
new->cap_permitted = cap_intersect(new->cap_permitted,
old->cap_permitted);
}
new->suid = new->fsuid = new->euid;
new->sgid = new->fsgid = new->egid;
if (effective)
new->cap_effective = new->cap_permitted;
else
cap_clear(new->cap_effective);
bprm->cap_effective = effective;
/*
* Audit candidate if current->cap_effective is set
*
* We do not bother to audit if 3 things are true:
* 1) cap_effective has all caps
* 2) we are root
* 3) root is supposed to have all caps (SECURE_NOROOT)
* Since this is just a normal root execing a process.
*
* Number 1 above might fail if you don't have a full bset, but I think
* that is interesting information to audit.
*/
if (!cap_isclear(new->cap_effective)) {
if (!cap_issubset(CAP_FULL_SET, new->cap_effective) ||
new->euid != 0 || new->uid != 0 ||
issecure(SECURE_NOROOT)) {
ret = audit_log_bprm_fcaps(bprm, new, old);
if (ret < 0)
return ret;
}
}
new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS);
return 0;
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: BOOLEAN btif_hl_if_channel_setup_pending(int channel_id, UINT8 *p_app_idx, UINT8 *p_mcl_idx)
{
btif_hl_app_cb_t *p_acb;
btif_hl_mcl_cb_t *p_mcb;
UINT8 i, j;
BOOLEAN found=FALSE;
*p_app_idx = 0;
*p_mcl_idx = 0;
for (i=0; i < BTA_HL_NUM_APPS ; i ++)
{
p_acb =BTIF_HL_GET_APP_CB_PTR(i);
if (p_acb->in_use)
{
for (j=0; j< BTA_HL_NUM_MCLS; j++)
{
p_mcb = BTIF_HL_GET_MCL_CB_PTR(i, j);
if (p_mcb->in_use &&
p_mcb->is_connected && p_mcb->pcb.channel_id == channel_id )
{
found = TRUE;
*p_app_idx = i;
*p_mcl_idx = j;
break;
}
}
}
if (found)
break;
}
BTIF_TRACE_DEBUG("%s found=%d channel_id=0x%08x",
__FUNCTION__, found, channel_id, *p_app_idx, *p_mcl_idx);
return found;
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void TabStrip::SetStackedLayout(bool stacked_layout) {
if (stacked_layout == stacked_layout_)
return;
stacked_layout_ = stacked_layout;
SetResetToShrinkOnExit(false);
SwapLayoutIfNecessary();
const int active_index = controller_->GetActiveIndex();
if (touch_layout_ && active_index != -1) {
touch_layout_->SetActiveTabLocation(ideal_bounds(active_index).x());
AnimateToIdealBounds();
}
for (int i = 0; i < tab_count(); ++i)
tab_at(i)->Layout();
}
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 spl_array_has_dimension_ex(int check_inherited, zval *object, zval *offset, int check_empty TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
long index;
zval *rv, *value = NULL, **tmp;
if (check_inherited && intern->fptr_offset_has) {
zval *offset_tmp = offset;
SEPARATE_ARG_IF_REF(offset_tmp);
zend_call_method_with_1_params(&object, Z_OBJCE_P(object), &intern->fptr_offset_has, "offsetExists", &rv, offset_tmp);
zval_ptr_dtor(&offset_tmp);
if (rv && zend_is_true(rv)) {
zval_ptr_dtor(&rv);
if (check_empty != 1) {
return 1;
} else if (intern->fptr_offset_get) {
value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);
}
} else {
if (rv) {
zval_ptr_dtor(&rv);
}
return 0;
}
}
if (!value) {
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
switch(Z_TYPE_P(offset)) {
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) {
if (check_empty == 2) {
return 1;
}
} else {
return 0;
}
break;
case IS_DOUBLE:
case IS_RESOURCE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **)&tmp) != FAILURE) {
if (check_empty == 2) {
return 1;
}
} else {
return 0;
}
break;
default:
zend_error(E_WARNING, "Illegal offset type");
return 0;
}
if (check_empty && check_inherited && intern->fptr_offset_get) {
value = spl_array_read_dimension_ex(1, object, offset, BP_VAR_R TSRMLS_CC);
} else {
value = *tmp;
}
}
return check_empty ? zend_is_true(value) : Z_TYPE_P(value) != IS_NULL;
} /* }}} */
CWE ID: CWE-20
Target: 1
Example 2:
Code: xmlBufSetAllocationScheme(xmlBufPtr buf,
xmlBufferAllocationScheme scheme) {
if ((buf == NULL) || (buf->error != 0)) {
#ifdef DEBUG_BUFFER
xmlGenericError(xmlGenericErrorContext,
"xmlBufSetAllocationScheme: buf == NULL or in error\n");
#endif
return(-1);
}
if ((buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) ||
(buf->alloc == XML_BUFFER_ALLOC_IO))
return(-1);
if ((scheme == XML_BUFFER_ALLOC_DOUBLEIT) ||
(scheme == XML_BUFFER_ALLOC_EXACT) ||
(scheme == XML_BUFFER_ALLOC_HYBRID) ||
(scheme == XML_BUFFER_ALLOC_IMMUTABLE) ||
(scheme == XML_BUFFER_ALLOC_BOUNDED)) {
buf->alloc = scheme;
if (buf->buffer)
buf->buffer->alloc = scheme;
return(0);
}
/*
* Switching a buffer ALLOC_IO has the side effect of initializing
* the contentIO field with the current content
*/
if (scheme == XML_BUFFER_ALLOC_IO) {
buf->alloc = XML_BUFFER_ALLOC_IO;
buf->contentIO = buf->content;
}
return(-1);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool __mpol_equal(struct mempolicy *a, struct mempolicy *b)
{
if (!a || !b)
return false;
if (a->mode != b->mode)
return false;
if (a->flags != b->flags)
return false;
if (mpol_store_user_nodemask(a))
if (!nodes_equal(a->w.user_nodemask, b->w.user_nodemask))
return false;
switch (a->mode) {
case MPOL_BIND:
/* Fall through */
case MPOL_INTERLEAVE:
return !!nodes_equal(a->v.nodes, b->v.nodes);
case MPOL_PREFERRED:
return a->v.preferred_node == b->v.preferred_node;
default:
BUG();
return false;
}
}
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: midi_synth_load_patch(int dev, int format, const char __user *addr,
int offs, int count, int pmgr_flag)
{
int orig_dev = synth_devs[dev]->midi_dev;
struct sysex_info sysex;
int i;
unsigned long left, src_offs, eox_seen = 0;
int first_byte = 1;
int hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex;
leave_sysex(dev);
if (!prefix_cmd(orig_dev, 0xf0))
return 0;
if (format != SYSEX_PATCH)
{
/* printk("MIDI Error: Invalid patch format (key) 0x%x\n", format);*/
return -EINVAL;
}
if (count < hdr_size)
{
/* printk("MIDI Error: Patch header too short\n");*/
return -EINVAL;
}
count -= hdr_size;
/*
* Copy the header from user space but ignore the first bytes which have
* been transferred already.
*/
if(copy_from_user(&((char *) &sysex)[offs], &(addr)[offs], hdr_size - offs))
return -EFAULT;
if (count < sysex.len)
{
/* printk(KERN_WARNING "MIDI Warning: Sysex record too short (%d<%d)\n", count, (int) sysex.len);*/
sysex.len = count;
}
left = sysex.len;
src_offs = 0;
for (i = 0; i < left && !signal_pending(current); i++)
{
unsigned char data;
if (get_user(data,
(unsigned char __user *)(addr + hdr_size + i)))
return -EFAULT;
eox_seen = (i > 0 && data & 0x80); /* End of sysex */
if (eox_seen && data != 0xf7)
data = 0xf7;
if (i == 0)
{
if (data != 0xf0)
{
printk(KERN_WARNING "midi_synth: Sysex start missing\n");
return -EINVAL;
}
}
while (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) &&
!signal_pending(current))
schedule();
if (!first_byte && data & 0x80)
return 0;
first_byte = 0;
}
if (!eox_seen)
midi_outc(orig_dev, 0xf7);
return 0;
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static struct rb_node *key_serial_next(struct seq_file *p, struct rb_node *n)
{
struct user_namespace *user_ns = seq_user_ns(p);
n = rb_next(n);
while (n) {
struct key *key = rb_entry(n, struct key, serial_node);
if (kuid_has_mapping(user_ns, key->user->uid))
break;
n = rb_next(n);
}
return n;
}
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 size_t StringSize(const uint8_t *start, size_t limit, uint8_t encoding) {
if (encoding == 0x00 || encoding == 0x03) {
return strnlen((const char *)start, limit) + 1;
}
size_t n = 0;
while ((n+1 < limit) && (start[n] != '\0' || start[n + 1] != '\0')) {
n += 2;
}
n += 2;
return n;
}
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 faad_resetbits(bitfile *ld, int bits)
{
uint32_t tmp;
int words = bits >> 5;
int remainder = bits & 0x1F;
ld->bytes_left = ld->buffer_size - words*4;
if (ld->bytes_left >= 4)
{
tmp = getdword(&ld->start[words]);
ld->bytes_left -= 4;
} else {
tmp = getdword_n(&ld->start[words], ld->bytes_left);
ld->bytes_left = 0;
}
ld->bufa = tmp;
if (ld->bytes_left >= 4)
{
tmp = getdword(&ld->start[words+1]);
ld->bytes_left -= 4;
} else {
tmp = getdword_n(&ld->start[words+1], ld->bytes_left);
ld->bytes_left = 0;
}
ld->bufb = tmp;
ld->bits_left = 32 - remainder;
ld->tail = &ld->start[words+2];
/* recheck for reading too many bytes */
ld->error = 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct perf_guest_switch_msr *intel_guest_get_msrs(int *nr)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs;
arr[0].msr = MSR_CORE_PERF_GLOBAL_CTRL;
arr[0].host = x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_guest_mask;
arr[0].guest = x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_host_mask;
/*
* If PMU counter has PEBS enabled it is not enough to disable counter
* on a guest entry since PEBS memory write can overshoot guest entry
* and corrupt guest memory. Disabling PEBS solves the problem.
*/
arr[1].msr = MSR_IA32_PEBS_ENABLE;
arr[1].host = cpuc->pebs_enabled;
arr[1].guest = 0;
*nr = 2;
return arr;
}
CWE ID: CWE-20
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool AXLayoutObject::elementAttributeValue(
const QualifiedName& attributeName) const {
if (!m_layoutObject)
return false;
return equalIgnoringCase(getAttribute(attributeName), "true");
}
CWE ID: CWE-254
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: WebGLRenderingContextBase::~WebGLRenderingContextBase() {
destruction_in_progress_ = true;
DestroyContext();
RestoreEvictedContext(this);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: ChromeUserMetricsExtension* mutable_uma_proto() {
return MetricsLog::uma_proto();
}
CWE ID: CWE-79
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static inline Image *GetImageCache(const ImageInfo *image_info,const char *path,
ExceptionInfo *exception)
{
char
key[MagickPathExtent];
ExceptionInfo
*sans_exception;
Image
*image;
ImageInfo
*read_info;
(void) FormatLocaleString(key,MagickPathExtent,"cache:%s",path);
sans_exception=AcquireExceptionInfo();
image=(Image *) GetImageRegistry(ImageRegistryType,key,sans_exception);
sans_exception=DestroyExceptionInfo(sans_exception);
if (image != (Image *) NULL)
return(image);
read_info=CloneImageInfo(image_info);
if (path != (const char *) NULL)
(void) CopyMagickString(read_info->filename,path,MagickPathExtent);
image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
(void) SetImageRegistry(ImageRegistryType,key,image,exception);
return(image);
}
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 LoadingStatsCollector::RecordPreconnectStats(
std::unique_ptr<PreconnectStats> stats) {
const GURL& main_frame_url = stats->url;
auto it = preconnect_stats_.find(main_frame_url);
if (it != preconnect_stats_.end()) {
ReportPreconnectAccuracy(*it->second,
std::map<GURL, OriginRequestSummary>());
preconnect_stats_.erase(it);
}
preconnect_stats_.emplace(main_frame_url, std::move(stats));
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: uint32_t red_channel_max_pipe_size(RedChannel *channel)
{
RingItem *link;
RedChannelClient *rcc;
uint32_t pipe_size = 0;
RING_FOREACH(link, &channel->clients) {
rcc = SPICE_CONTAINEROF(link, RedChannelClient, channel_link);
pipe_size = pipe_size > rcc->pipe_size ? pipe_size : rcc->pipe_size;
}
return pipe_size;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int rpng2_win_create_window()
{
uch bg_red = rpng2_info.bg_red;
uch bg_green = rpng2_info.bg_green;
uch bg_blue = rpng2_info.bg_blue;
uch *dest;
int extra_width, extra_height;
ulg i, j;
WNDCLASSEX wndclass;
RECT rect;
/*---------------------------------------------------------------------------
Allocate memory for the display-specific version of the image (round up
to multiple of 4 for Windows DIB).
---------------------------------------------------------------------------*/
wimage_rowbytes = ((3*rpng2_info.width + 3L) >> 2) << 2;
if (!(dib = (uch *)malloc(sizeof(BITMAPINFOHEADER) +
wimage_rowbytes*rpng2_info.height)))
{
return 4; /* fail */
}
/*---------------------------------------------------------------------------
Initialize the DIB. Negative height means to use top-down BMP ordering
(must be uncompressed, but that's what we want). Bit count of 1, 4 or 8
implies a colormap of RGBX quads, but 24-bit BMPs just use B,G,R values
directly => wimage_data begins immediately after BMP header.
---------------------------------------------------------------------------*/
memset(dib, 0, sizeof(BITMAPINFOHEADER));
bmih = (BITMAPINFOHEADER *)dib;
bmih->biSize = sizeof(BITMAPINFOHEADER);
bmih->biWidth = rpng2_info.width;
bmih->biHeight = -((long)rpng2_info.height);
bmih->biPlanes = 1;
bmih->biBitCount = 24;
bmih->biCompression = 0;
wimage_data = dib + sizeof(BITMAPINFOHEADER);
/*---------------------------------------------------------------------------
Fill window with the specified background color (default is black), but
defer loading faked "background image" until window is displayed (may be
slow to compute). Data are in BGR order.
---------------------------------------------------------------------------*/
if (bg_image) { /* just fill with black for now */
memset(wimage_data, 0, wimage_rowbytes*rpng2_info.height);
} else {
for (j = 0; j < rpng2_info.height; ++j) {
dest = wimage_data + j*wimage_rowbytes;
for (i = rpng2_info.width; i > 0; --i) {
*dest++ = bg_blue;
*dest++ = bg_green;
*dest++ = bg_red;
}
}
}
/*---------------------------------------------------------------------------
Set the window parameters.
---------------------------------------------------------------------------*/
memset(&wndclass, 0, sizeof(wndclass));
wndclass.cbSize = sizeof(wndclass);
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = rpng2_win_wndproc;
wndclass.hInstance = global_hInst;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(DKGRAY_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = progname;
wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wndclass);
/*---------------------------------------------------------------------------
Finally, create the window.
---------------------------------------------------------------------------*/
extra_width = 2*(GetSystemMetrics(SM_CXBORDER) +
GetSystemMetrics(SM_CXDLGFRAME));
extra_height = 2*(GetSystemMetrics(SM_CYBORDER) +
GetSystemMetrics(SM_CYDLGFRAME)) +
GetSystemMetrics(SM_CYCAPTION);
global_hwnd = CreateWindow(progname, titlebar, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, rpng2_info.width+extra_width,
rpng2_info.height+extra_height, NULL, NULL, global_hInst, NULL);
ShowWindow(global_hwnd, global_showmode);
UpdateWindow(global_hwnd);
/*---------------------------------------------------------------------------
Now compute the background image and display it. If it fails (memory
allocation), revert to a plain background color.
---------------------------------------------------------------------------*/
if (bg_image) {
static const char *msg = "Computing background image...";
int x, y, len = strlen(msg);
HDC hdc = GetDC(global_hwnd);
TEXTMETRIC tm;
GetTextMetrics(hdc, &tm);
x = (rpng2_info.width - len*tm.tmAveCharWidth)/2;
y = (rpng2_info.height - tm.tmHeight)/2;
SetBkMode(hdc, TRANSPARENT);
SetTextColor(hdc, GetSysColor(COLOR_HIGHLIGHTTEXT));
/* this can still begin out of bounds even if x is positive (???): */
TextOut(hdc, ((x < 0)? 0 : x), ((y < 0)? 0 : y), msg, len);
ReleaseDC(global_hwnd, hdc);
rpng2_win_load_bg_image(); /* resets bg_image if fails */
}
if (!bg_image) {
for (j = 0; j < rpng2_info.height; ++j) {
dest = wimage_data + j*wimage_rowbytes;
for (i = rpng2_info.width; i > 0; --i) {
*dest++ = bg_blue;
*dest++ = bg_green;
*dest++ = bg_red;
}
}
}
rect.left = 0L;
rect.top = 0L;
rect.right = (LONG)rpng2_info.width; /* possibly off by one? */
rect.bottom = (LONG)rpng2_info.height; /* possibly off by one? */
InvalidateRect(global_hwnd, &rect, FALSE);
UpdateWindow(global_hwnd); /* similar to XFlush() */
return 0;
} /* end function rpng2_win_create_window() */
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadWBMPImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
int
byte;
MagickBooleanType
status;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
ssize_t
y;
unsigned char
bit;
unsigned short
header;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (ReadBlob(image,2,(unsigned char *) &header) == 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (header != 0)
ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported");
/*
Initialize image structure.
*/
if (WBMPReadInteger(image,&image->columns) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if (WBMPReadInteger(image,&image->rows) == MagickFalse)
ThrowReaderException(CorruptImageError,"CorruptWBMPimage");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (DiscardBlobBytes(image,image->offset) == MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert bi-level image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (bit == 0)
{
byte=ReadBlobByte(image);
if (byte == EOF)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 1 : 0);
bit++;
if (bit == 8)
bit=0;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: read_file(Image *image, png_uint_32 format, png_const_colorp background)
{
memset(&image->image, 0, sizeof image->image);
image->image.version = PNG_IMAGE_VERSION;
if (image->input_memory != NULL)
{
if (!png_image_begin_read_from_memory(&image->image, image->input_memory,
image->input_memory_size))
return logerror(image, "memory init: ", image->file_name, "");
}
# ifdef PNG_STDIO_SUPPORTED
else if (image->input_file != NULL)
{
if (!png_image_begin_read_from_stdio(&image->image, image->input_file))
return logerror(image, "stdio init: ", image->file_name, "");
}
else
{
if (!png_image_begin_read_from_file(&image->image, image->file_name))
return logerror(image, "file init: ", image->file_name, "");
}
# else
else
{
return logerror(image, "unsupported file/stdio init: ",
image->file_name, "");
}
# endif
/* This must be set after the begin_read call: */
if (image->opts & sRGB_16BIT)
image->image.flags |= PNG_IMAGE_FLAG_16BIT_sRGB;
/* Have an initialized image with all the data we need plus, maybe, an
* allocated file (myfile) or buffer (mybuffer) that need to be freed.
*/
{
int result;
png_uint_32 image_format;
/* Print both original and output formats. */
image_format = image->image.format;
if (image->opts & VERBOSE)
{
printf("%s %lu x %lu %s -> %s", image->file_name,
(unsigned long)image->image.width,
(unsigned long)image->image.height,
format_names[image_format & FORMAT_MASK],
(format & FORMAT_NO_CHANGE) != 0 || image->image.format == format
? "no change" : format_names[format & FORMAT_MASK]);
if (background != NULL)
printf(" background(%d,%d,%d)\n", background->red,
background->green, background->blue);
else
printf("\n");
fflush(stdout);
}
/* 'NO_CHANGE' combined with the color-map flag forces the base format
* flags to be set on read to ensure that the original representation is
* not lost in the pass through a colormap format.
*/
if ((format & FORMAT_NO_CHANGE) != 0)
{
if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0 &&
(image_format & PNG_FORMAT_FLAG_COLORMAP) != 0)
format = (image_format & ~BASE_FORMATS) | (format & BASE_FORMATS);
else
format = image_format;
}
image->image.format = format;
image->stride = PNG_IMAGE_ROW_STRIDE(image->image) + image->stride_extra;
allocbuffer(image);
result = png_image_finish_read(&image->image, background,
image->buffer+16, (png_int_32)image->stride, image->colormap);
checkbuffer(image, image->file_name);
if (result)
return checkopaque(image);
else
return logerror(image, image->file_name, ": image read failed", "");
}
}
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 Append(int pos, int size) {
target_.Append(data_, data_->data() + pos, size);
}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BufferMeta(size_t size, OMX_U32 portIndex)
: mSize(size),
mIsBackup(false),
mPortIndex(portIndex) {
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void dentry_reset_mounted(struct dentry *dentry)
{
unsigned u;
for (u = 0; u < HASH_SIZE; u++) {
struct mount *p;
list_for_each_entry(p, &mount_hashtable[u], mnt_hash) {
if (p->mnt_mountpoint == dentry)
return;
}
}
spin_lock(&dentry->d_lock);
dentry->d_flags &= ~DCACHE_MOUNTED;
spin_unlock(&dentry->d_lock);
}
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: long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const
{
assert(m_pos >= m_element_start);
pEntry = NULL;
if (index < 0)
return -1; //generic error
if (m_entries_count < 0)
return E_BUFFER_NOT_FULL;
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count <= m_entries_size);
if (index < m_entries_count)
{
pEntry = m_entries[index];
assert(pEntry);
return 1; //found entry
}
if (m_element_size < 0) //we don't know cluster end yet
return E_BUFFER_NOT_FULL; //underflow
const long long element_stop = m_element_start + m_element_size;
if (m_pos >= element_stop)
return 0; //nothing left to parse
return E_BUFFER_NOT_FULL; //underflow, since more remains to be parsed
}
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: mark_context_stack(mrb_state *mrb, struct mrb_context *c)
{
size_t i;
size_t e;
if (c->stack == NULL) return;
e = c->stack - c->stbase;
if (c->ci) e += c->ci->nregs;
if (c->stbase + e > c->stend) e = c->stend - c->stbase;
for (i=0; i<e; i++) {
mrb_value v = c->stbase[i];
if (!mrb_immediate_p(v)) {
if (mrb_basic_ptr(v)->tt == MRB_TT_FREE) {
c->stbase[i] = mrb_nil_value();
}
else {
mrb_gc_mark(mrb, mrb_basic_ptr(v));
}
}
}
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: get_tls_handshake_key (const struct key_type *key_type,
struct key_ctx_bi *ctx,
const char *passphrase_file,
const int key_direction,
const unsigned int flags)
{
if (passphrase_file && key_type->hmac_length)
{
struct key2 key2;
struct key_type kt = *key_type;
struct key_direction_state kds;
/* for control channel we are only authenticating, not encrypting */
kt.cipher_length = 0;
kt.cipher = NULL;
if (flags & GHK_INLINE)
{
/* key was specified inline, key text is in passphrase_file */
read_key_file (&key2, passphrase_file, RKF_INLINE|RKF_MUST_SUCCEED);
/* succeeded? */
if (key2.n == 2)
msg (M_INFO, "Control Channel Authentication: tls-auth using INLINE static key file");
else
msg (M_FATAL, "INLINE tls-auth file lacks the requisite 2 keys");
}
else
{
/* first try to parse as an OpenVPN static key file */
read_key_file (&key2, passphrase_file, 0);
/* succeeded? */
if (key2.n == 2)
{
msg (M_INFO,
"Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file",
passphrase_file);
}
else
{
int hash_size;
CLEAR (key2);
/* failed, now try to get hash from a freeform file */
hash_size = read_passphrase_hash (passphrase_file,
kt.digest,
key2.keys[0].hmac,
MAX_HMAC_KEY_LENGTH);
ASSERT (hash_size == kt.hmac_length);
/* suceeded */
key2.n = 1;
msg (M_INFO,
"Control Channel Authentication: using '%s' as a free-form passphrase file",
passphrase_file);
}
}
/* handle key direction */
key_direction_state_init (&kds, key_direction);
must_have_n_keys (passphrase_file, "tls-auth", &key2, kds.need_keys);
/* initialize hmac key in both directions */
init_key_ctx (&ctx->encrypt, &key2.keys[kds.out_key], &kt, OPENVPN_OP_ENCRYPT,
"Outgoing Control Channel Authentication");
init_key_ctx (&ctx->decrypt, &key2.keys[kds.in_key], &kt, OPENVPN_OP_DECRYPT,
"Incoming Control Channel Authentication");
CLEAR (key2);
}
else
{
CLEAR (*ctx);
}
}
CWE ID: CWE-200
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void activityLoggedAttrSetter1AttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
TestObjectV8Internal::activityLoggedAttrSetter1AttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: BurnLibrary* CrosLibrary::GetBurnLibrary() {
return burn_lib_.GetDefaultImpl(use_stub_impl_);
}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static int crc32_pclmul_setkey(struct crypto_shash *hash, const u8 *key,
unsigned int keylen)
{
u32 *mctx = crypto_shash_ctx(hash);
if (keylen != sizeof(u32)) {
crypto_shash_set_flags(hash, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
*mctx = le32_to_cpup((__le32 *)key);
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 ClientControlledShellSurface::UpdateBackdrop() {
aura::Window* window = widget_->GetNativeWindow();
bool enable_backdrop = (widget_->IsFullscreen() || widget_->IsMaximized());
ash::BackdropWindowMode target_backdrop_mode =
enable_backdrop ? ash::BackdropWindowMode::kEnabled
: ash::BackdropWindowMode::kAuto;
if (window->GetProperty(ash::kBackdropWindowMode) != target_backdrop_mode)
window->SetProperty(ash::kBackdropWindowMode, target_backdrop_mode);
}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void ShellWindowFrameView::Layout() {
gfx::Size close_size = close_button_->GetPreferredSize();
int closeButtonOffsetY =
(kCaptionHeight - close_size.height()) / 2;
int closeButtonOffsetX = closeButtonOffsetY;
close_button_->SetBounds(
width() - closeButtonOffsetX - close_size.width(),
closeButtonOffsetY,
close_size.width(),
close_size.height());
}
CWE ID: CWE-79
Target: 1
Example 2:
Code: EXPORTED int mboxlist_lookup_allow_all(const char *name,
mbentry_t **entryptr,
struct txn **tid)
{
return mboxlist_mylookup(name, entryptr, tid, 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: ScriptValue WebGLRenderingContextBase::getRenderbufferParameter(
ScriptState* script_state,
GLenum target,
GLenum pname) {
if (isContextLost())
return ScriptValue::CreateNull(script_state);
if (target != GL_RENDERBUFFER) {
SynthesizeGLError(GL_INVALID_ENUM, "getRenderbufferParameter",
"invalid target");
return ScriptValue::CreateNull(script_state);
}
if (!renderbuffer_binding_ || !renderbuffer_binding_->Object()) {
SynthesizeGLError(GL_INVALID_OPERATION, "getRenderbufferParameter",
"no renderbuffer bound");
return ScriptValue::CreateNull(script_state);
}
GLint value = 0;
switch (pname) {
case GL_RENDERBUFFER_SAMPLES:
if (!IsWebGL2OrHigher()) {
SynthesizeGLError(GL_INVALID_ENUM, "getRenderbufferParameter",
"invalid parameter name");
return ScriptValue::CreateNull(script_state);
}
case GL_RENDERBUFFER_WIDTH:
case GL_RENDERBUFFER_HEIGHT:
case GL_RENDERBUFFER_RED_SIZE:
case GL_RENDERBUFFER_GREEN_SIZE:
case GL_RENDERBUFFER_BLUE_SIZE:
case GL_RENDERBUFFER_ALPHA_SIZE:
case GL_RENDERBUFFER_DEPTH_SIZE:
ContextGL()->GetRenderbufferParameteriv(target, pname, &value);
return WebGLAny(script_state, value);
case GL_RENDERBUFFER_STENCIL_SIZE:
ContextGL()->GetRenderbufferParameteriv(target, pname, &value);
return WebGLAny(script_state, value);
case GL_RENDERBUFFER_INTERNAL_FORMAT:
return WebGLAny(script_state, renderbuffer_binding_->InternalFormat());
default:
SynthesizeGLError(GL_INVALID_ENUM, "getRenderbufferParameter",
"invalid parameter name");
return ScriptValue::CreateNull(script_state);
}
}
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 ObjectBackedNativeHandler::Router(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Object> data = args.Data().As<v8::Object>();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Value> handler_function_value;
v8::Local<v8::Value> feature_name_value;
if (!GetPrivate(context, data, kHandlerFunction, &handler_function_value) ||
handler_function_value->IsUndefined() ||
!GetPrivate(context, data, kFeatureName, &feature_name_value) ||
!feature_name_value->IsString()) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
console::Error(script_context ? script_context->GetRenderFrame() : nullptr,
"Extension view no longer exists");
return;
}
if (content::WorkerThread::GetCurrentId() == 0) {
ScriptContext* script_context =
ScriptContextSet::GetContextByV8Context(context);
v8::Local<v8::String> feature_name_string =
feature_name_value->ToString(context).ToLocalChecked();
std::string feature_name = *v8::String::Utf8Value(feature_name_string);
if (script_context &&
!feature_name.empty() &&
!script_context->GetAvailability(feature_name).is_available()) {
return;
}
}
CHECK(handler_function_value->IsExternal());
static_cast<HandlerFunction*>(
handler_function_value.As<v8::External>()->Value())->Run(args);
v8::ReturnValue<v8::Value> ret = args.GetReturnValue();
v8::Local<v8::Value> ret_value = ret.Get();
if (ret_value->IsObject() && !ret_value->IsNull() &&
!ContextCanAccessObject(context, v8::Local<v8::Object>::Cast(ret_value),
true)) {
NOTREACHED() << "Insecure return value";
ret.SetUndefined();
}
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: base::Time ProtoTimeToTime(int64_t proto_t) {
return base::Time::FromDeltaSinceWindowsEpoch(
base::TimeDelta::FromMicroseconds(proto_t));
}
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: encode_STRIP_VLAN(const struct ofpact_null *null OVS_UNUSED,
enum ofp_version ofp_version, struct ofpbuf *out)
{
if (ofp_version == OFP10_VERSION) {
put_OFPAT10_STRIP_VLAN(out);
} else {
put_OFPAT11_POP_VLAN(out);
}
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void ProxyLocaltimeCallToBrowser(time_t input, struct tm* output,
char* timezone_out,
size_t timezone_out_len) {
base::Pickle request;
request.WriteInt(LinuxSandbox::METHOD_LOCALTIME);
request.WriteString(
std::string(reinterpret_cast<char*>(&input), sizeof(input)));
uint8_t reply_buf[512];
const ssize_t r = base::UnixDomainSocket::SendRecvMsg(
GetSandboxFD(), reply_buf, sizeof(reply_buf), NULL, request);
if (r == -1) {
memset(output, 0, sizeof(struct tm));
return;
}
base::Pickle reply(reinterpret_cast<char*>(reply_buf), r);
base::PickleIterator iter(reply);
std::string result;
std::string timezone;
if (!iter.ReadString(&result) ||
!iter.ReadString(&timezone) ||
result.size() != sizeof(struct tm)) {
memset(output, 0, sizeof(struct tm));
return;
}
memcpy(output, result.data(), sizeof(struct tm));
if (timezone_out_len) {
const size_t copy_len = std::min(timezone_out_len - 1, timezone.size());
memcpy(timezone_out, timezone.data(), copy_len);
timezone_out[copy_len] = 0;
output->tm_zone = timezone_out;
} else {
base::AutoLock lock(g_timezones_lock.Get());
auto ret_pair = g_timezones.Get().insert(timezone);
output->tm_zone = ret_pair.first->c_str();
}
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool RenderFrameImpl::IsLocalRoot() const {
bool is_local_root = static_cast<bool>(render_widget_);
DCHECK_EQ(is_local_root,
!(frame_->Parent() && frame_->Parent()->IsWebLocalFrame()));
return is_local_root;
}
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: data_sock_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sockaddr_mISDN *maddr = (struct sockaddr_mISDN *) addr;
struct sock *sk = sock->sk;
if (!_pms(sk)->dev)
return -EBADFD;
lock_sock(sk);
*addr_len = sizeof(*maddr);
maddr->family = AF_ISDN;
maddr->dev = _pms(sk)->dev->id;
maddr->channel = _pms(sk)->ch.nr;
maddr->sapi = _pms(sk)->ch.addr & 0xff;
maddr->tei = (_pms(sk)->ch.addr >> 8) & 0xff;
release_sock(sk);
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: void jslGetTokenString(char *str, size_t len) {
if (lex->tk == LEX_ID) {
strncpy(str, "ID:", len);
strncat(str, jslGetTokenValueAsString(), len);
} else if (lex->tk == LEX_STR) {
strncpy(str, "String:'", len);
strncat(str, jslGetTokenValueAsString(), len);
strncat(str, "'", len);
} else
jslTokenAsString(lex->tk, str, len);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void Gfx::opMarkPoint(Object args[], int numArgs) {
if (printCommands) {
printf(" mark point: %s ", args[0].getName());
if (numArgs == 2)
args[1].print(stdout);
printf("\n");
fflush(stdout);
}
if(numArgs == 2 && args[1].isDict()) {
out->markPoint(args[0].getName(),args[1].getDict());
} else {
out->markPoint(args[0].getName());
}
}
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: generate_palette(png_colorp palette, png_bytep trans, int bit_depth,
png_const_bytep gamma_table, unsigned int *colors)
{
/*
* 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
* 2-bit: entry 0: transparent-green
* entry 1: 40%-red
* entry 2: 80%-blue
* entry 3: opaque-white
* 4-bit: the 16 combinations of the 2-bit case
* 8-bit: the 256 combinations of the 4-bit case
*/
switch (colors[0])
{
default:
fprintf(stderr, "makepng: --colors=...: invalid count %u\n",
colors[0]);
exit(1);
case 1:
set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255,
gamma_table);
return 1;
case 2:
set_color(palette+0, trans+0, colors[1], colors[1], colors[1],
colors[2], gamma_table);
return 1;
case 3:
set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255,
gamma_table);
return 1;
case 4:
set_color(palette+0, trans+0, colors[1], colors[2], colors[3],
colors[4], gamma_table);
return 1;
case 0:
if (bit_depth == 1)
{
set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table);
set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table);
return 2;
}
else
{
unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */
unsigned int x, y, ip;
for (x=0; x<size; ++x) for (y=0; y<size; ++y)
{
ip = x + (size * y);
/* size is at most 16, so the scaled value below fits in 16 bits
*/
# define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2))
# define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\
(interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\
(size*size))
set_color(palette+ip, trans+ip,
/* color: green, red,blue,white */
xyinterp(x, y, 0, 255, 0, 255),
xyinterp(x, y, 255, 0, 0, 255),
xyinterp(x, y, 0, 0, 255, 255),
/* alpha: 0, 102, 204, 255) */
xyinterp(x, y, 0, 102, 204, 255),
gamma_table);
}
return ip+1;
}
}
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long SegmentInfo::Parse()
{
assert(m_pMuxingAppAsUTF8 == NULL);
assert(m_pWritingAppAsUTF8 == NULL);
assert(m_pTitleAsUTF8 == NULL);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
m_timecodeScale = 1000000;
m_duration = -1;
while (pos < stop)
{
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x0AD7B1) //Timecode Scale
{
m_timecodeScale = UnserializeUInt(pReader, pos, size);
if (m_timecodeScale <= 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0489) //Segment duration
{
const long status = UnserializeFloat(
pReader,
pos,
size,
m_duration);
if (status < 0)
return status;
if (m_duration < 0)
return E_FILE_FORMAT_INVALID;
}
else if (id == 0x0D80) //MuxingApp
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pMuxingAppAsUTF8);
if (status)
return status;
}
else if (id == 0x1741) //WritingApp
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pWritingAppAsUTF8);
if (status)
return status;
}
else if (id == 0x3BA9) //Title
{
const long status = UnserializeString(
pReader,
pos,
size,
m_pTitleAsUTF8);
if (status)
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void V8Console::inspectCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
inspectImpl(info, false);
}
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: media::VideoCaptureSessionId session_id() const { return session_id_; }
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 ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
{
if (isMainThread()) {
blobRegistry().addDataToStream(url, streamData);
} else {
OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
callOnMainThread(&addDataToStreamTask, context.leakPtr());
}
}
CWE ID:
Target: 1
Example 2:
Code: static inline void shmem_unacct_size(unsigned long flags, loff_t size)
{
if (!(flags & VM_NORESERVE))
vm_unacct_memory(VM_ACCT(size));
}
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: PHP_METHOD(Phar, hasMetadata)
{
PHAR_ARCHIVE_OBJECT();
RETURN_BOOL(phar_obj->arc.archive->metadata != NULL);
}
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: cherokee_validator_ldap_check (cherokee_validator_ldap_t *ldap,
cherokee_connection_t *conn)
{
int re;
ret_t ret;
size_t size;
char *dn;
LDAPMessage *message;
LDAPMessage *first;
char *attrs[] = { LDAP_NO_ATTRS, NULL };
cherokee_validator_ldap_props_t *props = VAL_LDAP_PROP(ldap);
/* Sanity checks
*/
if ((conn->validator == NULL) ||
cherokee_buffer_is_empty (&conn->validator->user))
return ret_error;
size = cherokee_buffer_cnt_cspn (&conn->validator->user, 0, "*()");
if (size != conn->validator->user.len)
return ret_error;
/* Build filter
*/
ret = init_filter (ldap, props, conn);
if (ret != ret_ok)
return ret;
/* Search
*/
re = ldap_search_s (ldap->conn, props->basedn.buf, LDAP_SCOPE_SUBTREE, ldap->filter.buf, attrs, 0, &message);
if (re != LDAP_SUCCESS) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_SEARCH,
props->filter.buf ? props->filter.buf : "");
return ret_error;
}
TRACE (ENTRIES, "subtree search (%s): done\n", ldap->filter.buf ? ldap->filter.buf : "");
/* Check that there a single entry
*/
re = ldap_count_entries (ldap->conn, message);
if (re != 1) {
ldap_msgfree (message);
return ret_not_found;
}
/* Pick up the first one
*/
first = ldap_first_entry (ldap->conn, message);
if (first == NULL) {
ldap_msgfree (message);
return ret_not_found;
}
/* Get DN
*/
dn = ldap_get_dn (ldap->conn, first);
if (dn == NULL) {
ldap_msgfree (message);
return ret_error;
}
ldap_msgfree (message);
/* Check that it's right
*/
ret = validate_dn (props, dn, conn->validator->passwd.buf);
if (ret != ret_ok)
return ret;
/* Disconnect from the LDAP server
*/
re = ldap_unbind_s (ldap->conn);
if (re != LDAP_SUCCESS)
return ret_error;
/* Validated!
*/
TRACE (ENTRIES, "Access to use %s has been granted\n", conn->validator->user.buf);
return ret_ok;
}
CWE ID: CWE-287
Target: 1
Example 2:
Code: CIFSSMBWrite2(const int xid, struct cifs_io_parms *io_parms,
unsigned int *nbytes, struct kvec *iov, int n_vec,
const int long_op)
{
int rc = -EACCES;
WRITE_REQ *pSMB = NULL;
int wct;
int smb_hdr_len;
int resp_buf_type = 0;
__u32 pid = io_parms->pid;
__u16 netfid = io_parms->netfid;
__u64 offset = io_parms->offset;
struct cifs_tcon *tcon = io_parms->tcon;
unsigned int count = io_parms->length;
*nbytes = 0;
cFYI(1, "write2 at %lld %d bytes", (long long)offset, count);
if (tcon->ses->capabilities & CAP_LARGE_FILES) {
wct = 14;
} else {
wct = 12;
if ((offset >> 32) > 0) {
/* can not handle big offset for old srv */
return -EIO;
}
}
rc = small_smb_init(SMB_COM_WRITE_ANDX, wct, tcon, (void **) &pSMB);
if (rc)
return rc;
pSMB->hdr.Pid = cpu_to_le16((__u16)pid);
pSMB->hdr.PidHigh = cpu_to_le16((__u16)(pid >> 16));
/* tcon and ses pointer are checked in smb_init */
if (tcon->ses->server == NULL)
return -ECONNABORTED;
pSMB->AndXCommand = 0xFF; /* none */
pSMB->Fid = netfid;
pSMB->OffsetLow = cpu_to_le32(offset & 0xFFFFFFFF);
if (wct == 14)
pSMB->OffsetHigh = cpu_to_le32(offset >> 32);
pSMB->Reserved = 0xFFFFFFFF;
pSMB->WriteMode = 0;
pSMB->Remaining = 0;
pSMB->DataOffset =
cpu_to_le16(offsetof(struct smb_com_write_req, Data) - 4);
pSMB->DataLengthLow = cpu_to_le16(count & 0xFFFF);
pSMB->DataLengthHigh = cpu_to_le16(count >> 16);
/* header + 1 byte pad */
smb_hdr_len = be32_to_cpu(pSMB->hdr.smb_buf_length) + 1;
if (wct == 14)
inc_rfc1001_len(pSMB, count + 1);
else /* wct == 12 */
inc_rfc1001_len(pSMB, count + 5); /* smb data starts later */
if (wct == 14)
pSMB->ByteCount = cpu_to_le16(count + 1);
else /* wct == 12 */ /* bigger pad, smaller smb hdr, keep offset ok */ {
struct smb_com_writex_req *pSMBW =
(struct smb_com_writex_req *)pSMB;
pSMBW->ByteCount = cpu_to_le16(count + 5);
}
iov[0].iov_base = pSMB;
if (wct == 14)
iov[0].iov_len = smb_hdr_len + 4;
else /* wct == 12 pad bigger by four bytes */
iov[0].iov_len = smb_hdr_len + 8;
rc = SendReceive2(xid, tcon->ses, iov, n_vec + 1, &resp_buf_type,
long_op);
cifs_stats_inc(&tcon->num_writes);
if (rc) {
cFYI(1, "Send error Write2 = %d", rc);
} else if (resp_buf_type == 0) {
/* presumably this can not happen, but best to be safe */
rc = -EIO;
} else {
WRITE_RSP *pSMBr = (WRITE_RSP *)iov[0].iov_base;
*nbytes = le16_to_cpu(pSMBr->CountHigh);
*nbytes = (*nbytes) << 16;
*nbytes += le16_to_cpu(pSMBr->Count);
/*
* Mask off high 16 bits when bytes written as returned by the
* server is greater than bytes requested by the client. OS/2
* servers are known to set incorrect CountHigh values.
*/
if (*nbytes > count)
*nbytes &= 0xFFFF;
}
/* cifs_small_buf_release(pSMB); */ /* Freed earlier now in SendReceive2 */
if (resp_buf_type == CIFS_SMALL_BUFFER)
cifs_small_buf_release(iov[0].iov_base);
else if (resp_buf_type == CIFS_LARGE_BUFFER)
cifs_buf_release(iov[0].iov_base);
/* Note: On -EAGAIN error only caller can retry on handle based calls
since file handle passed in no longer valid */
return rc;
}
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 zend_throw_exception_internal(zval *exception TSRMLS_DC) /* {{{ */
{
#ifdef HAVE_DTRACE
if (DTRACE_EXCEPTION_THROWN_ENABLED()) {
const char *classname;
zend_uint name_len;
if (exception != NULL) {
zend_get_object_classname(exception, &classname, &name_len TSRMLS_CC);
DTRACE_EXCEPTION_THROWN((char *)classname);
} else {
DTRACE_EXCEPTION_THROWN(NULL);
}
}
#endif /* HAVE_DTRACE */
if (exception != NULL) {
zval *previous = EG(exception);
zend_exception_set_previous(exception, EG(exception) TSRMLS_CC);
EG(exception) = exception;
if (previous) {
return;
}
}
if (!EG(current_execute_data)) {
if(EG(exception)) {
zend_exception_error(EG(exception), E_ERROR TSRMLS_CC);
}
zend_error(E_ERROR, "Exception thrown without a stack frame");
}
if (zend_throw_exception_hook) {
zend_throw_exception_hook(exception TSRMLS_CC);
}
if (EG(current_execute_data)->opline == NULL ||
(EG(current_execute_data)->opline+1)->opcode == ZEND_HANDLE_EXCEPTION) {
/* no need to rethrow the exception */
return;
}
EG(opline_before_exception) = EG(current_execute_data)->opline;
EG(current_execute_data)->opline = EG(exception_op);
}
/* }}} */
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void FrameSelection::FocusedOrActiveStateChanged() {
bool active_and_focused = FrameIsFocusedAndActive();
if (Element* element = GetDocument().FocusedElement())
element->FocusStateChanged();
GetDocument().UpdateStyleAndLayoutTree();
auto* view = GetDocument().GetLayoutView();
if (view)
layout_selection_->InvalidatePaintForSelection();
if (active_and_focused)
SetSelectionFromNone();
frame_caret_->SetCaretVisibility(active_and_focused
? CaretVisibility::kVisible
: CaretVisibility::kHidden);
frame_->GetEventHandler().CapsLockStateMayHaveChanged();
if (use_secure_keyboard_entry_when_active_)
SetUseSecureKeyboardEntry(active_and_focused);
}
CWE ID:
Target: 1
Example 2:
Code: CreateDefaultRequestHandlerForNonNetworkService(
net::URLRequestContextGetter* url_request_context_getter,
storage::FileSystemContext* upload_file_system_context,
ServiceWorkerNavigationHandleCore* service_worker_navigation_handle_core,
AppCacheNavigationHandleCore* appcache_handle_core,
bool was_request_intercepted) const {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(!base::FeatureList::IsEnabled(network::features::kNetworkService));
DCHECK(started_);
return base::BindOnce(
&URLLoaderRequestController::CreateNonNetworkServiceURLLoader,
weak_factory_.GetWeakPtr(),
base::Unretained(url_request_context_getter),
base::Unretained(upload_file_system_context),
std::make_unique<NavigationRequestInfo>(*request_info_),
base::Unretained(
blink::ServiceWorkerUtils::IsServicificationEnabled() ||
was_request_intercepted
? nullptr
: service_worker_navigation_handle_core),
base::Unretained(was_request_intercepted ? nullptr
: appcache_handle_core));
}
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: exsltDateFormatDuration (const exsltDateValDurationPtr dt)
{
xmlChar buf[100], *cur = buf;
double secs, days;
double years, months;
if (dt == NULL)
return NULL;
/* quick and dirty check */
if ((dt->sec == 0.0) && (dt->day == 0) && (dt->mon == 0))
return xmlStrdup((xmlChar*)"P0D");
secs = dt->sec;
days = (double)dt->day;
years = (double)(dt->mon / 12);
months = (double)(dt->mon % 12);
*cur = '\0';
if (secs < 0.0) {
secs = -secs;
*cur = '-';
}
if (days < 0) {
days = -days;
*cur = '-';
}
if (years < 0) {
years = -years;
*cur = '-';
}
if (months < 0) {
months = -months;
*cur = '-';
}
if (*cur == '-')
cur++;
*cur++ = 'P';
if (years != 0.0) {
FORMAT_ITEM(years, cur, 1, 'Y');
}
if (months != 0.0) {
FORMAT_ITEM(months, cur, 1, 'M');
}
if (secs >= SECS_PER_DAY) {
double tmp = floor(secs / SECS_PER_DAY);
days += tmp;
secs -= (tmp * SECS_PER_DAY);
}
FORMAT_ITEM(days, cur, 1, 'D');
if (secs > 0.0) {
*cur++ = 'T';
}
FORMAT_ITEM(secs, cur, SECS_PER_HOUR, 'H');
FORMAT_ITEM(secs, cur, SECS_PER_MIN, 'M');
if (secs > 0.0) {
FORMAT_FLOAT(secs, cur, 0);
*cur++ = 'S';
}
*cur = 0;
return xmlStrdup(buf);
}
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 ImageBitmapFactories::Trace(blink::Visitor* visitor) {
visitor->Trace(pending_loaders_);
Supplement<LocalDOMWindow>::Trace(visitor);
Supplement<WorkerGlobalScope>::Trace(visitor);
}
CWE ID: CWE-416
Target: 1
Example 2:
Code: AXLayoutObject* AXLayoutObject::create(LayoutObject* layoutObject,
AXObjectCacheImpl& axObjectCache) {
return new AXLayoutObject(layoutObject, axObjectCache);
}
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 XMLHttpRequest::abortError()
{
genericError();
if (!m_uploadComplete) {
m_uploadComplete = true;
if (m_upload && m_uploadEventsAllowed)
m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent));
}
m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent));
}
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: bool CreateIpcChannel(
const std::string& channel_name,
const std::string& pipe_security_descriptor,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
IPC::Listener* delegate,
scoped_ptr<IPC::ChannelProxy>* channel_out) {
SECURITY_ATTRIBUTES security_attributes;
security_attributes.nLength = sizeof(security_attributes);
security_attributes.bInheritHandle = FALSE;
ULONG security_descriptor_length = 0;
if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
UTF8ToUTF16(pipe_security_descriptor).c_str(),
SDDL_REVISION_1,
reinterpret_cast<PSECURITY_DESCRIPTOR*>(
&security_attributes.lpSecurityDescriptor),
&security_descriptor_length)) {
LOG_GETLASTERROR(ERROR) <<
"Failed to create a security descriptor for the Chromoting IPC channel";
return false;
}
std::string pipe_name(kChromePipeNamePrefix);
pipe_name.append(channel_name);
base::win::ScopedHandle pipe;
pipe.Set(CreateNamedPipe(
UTF8ToUTF16(pipe_name).c_str(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
1,
IPC::Channel::kReadBufferSize,
IPC::Channel::kReadBufferSize,
5000,
&security_attributes));
if (!pipe.IsValid()) {
LOG_GETLASTERROR(ERROR) <<
"Failed to create the server end of the Chromoting IPC channel";
LocalFree(security_attributes.lpSecurityDescriptor);
return false;
}
LocalFree(security_attributes.lpSecurityDescriptor);
channel_out->reset(new IPC::ChannelProxy(
IPC::ChannelHandle(pipe),
IPC::Channel::MODE_SERVER,
delegate,
io_task_runner));
return true;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void computeLogicalTopPositionedOffset(LayoutUnit& logicalTopPos, const RenderBox* child, LayoutUnit logicalHeightValue, const RenderBoxModelObject* containerBlock, LayoutUnit containerLogicalHeight)
{
if ((child->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() != containerBlock->isHorizontalWritingMode())
|| (child->style()->isFlippedBlocksWritingMode() != containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()))
logicalTopPos = containerLogicalHeight - logicalHeightValue - logicalTopPos;
if (containerBlock->style()->isFlippedBlocksWritingMode() && child->isHorizontalWritingMode() == containerBlock->isHorizontalWritingMode()) {
if (child->isHorizontalWritingMode())
logicalTopPos += containerBlock->borderBottom();
else
logicalTopPos += containerBlock->borderRight();
} else {
if (child->isHorizontalWritingMode())
logicalTopPos += containerBlock->borderTop();
else
logicalTopPos += containerBlock->borderLeft();
}
}
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: apr_status_t h2_stream_add_header(h2_stream *stream,
const char *name, size_t nlen,
const char *value, size_t vlen)
{
ap_assert(stream);
if (!stream->has_response) {
if (name[0] == ':') {
if ((vlen) > stream->session->s->limit_req_line) {
/* pseudo header: approximation of request line size check */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): pseudo header %s too long",
stream->session->id, stream->id, name);
return h2_stream_set_error(stream,
HTTP_REQUEST_URI_TOO_LARGE);
}
}
else if ((nlen + 2 + vlen) > stream->session->s->limit_req_fieldsize) {
/* header too long */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): header %s too long",
stream->session->id, stream->id, name);
return h2_stream_set_error(stream,
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
if (name[0] != ':') {
++stream->request_headers_added;
if (stream->request_headers_added
> stream->session->s->limit_req_fields) {
/* too many header lines */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): too many header lines",
stream->session->id, stream->id);
return h2_stream_set_error(stream,
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
}
}
if (h2_stream_is_scheduled(stream)) {
return add_trailer(stream, name, nlen, value, vlen);
}
else {
if (!stream->rtmp) {
stream->rtmp = h2_req_create(stream->id, stream->pool,
NULL, NULL, NULL, NULL, NULL, 0);
}
if (stream->state != H2_STREAM_ST_OPEN) {
return APR_ECONNRESET;
}
return h2_request_add_header(stream->rtmp, stream->pool,
name, nlen, value, vlen);
}
}
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: gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id,
double file_gamma, double screen_gamma, png_byte sbit, int threshold_test,
int use_input_precision, int scale16, int expand16,
int do_background, PNG_CONST png_color_16 *pointer_to_the_background_color,
double background_gamma)
{
/* Standard fields */
standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/,
pm->use_update_info);
/* Parameter fields */
dp->pm = pm;
dp->file_gamma = file_gamma;
dp->screen_gamma = screen_gamma;
dp->background_gamma = background_gamma;
dp->sbit = sbit;
dp->threshold_test = threshold_test;
dp->use_input_precision = use_input_precision;
dp->scale16 = scale16;
dp->expand16 = expand16;
dp->do_background = do_background;
if (do_background && pointer_to_the_background_color != 0)
dp->background_color = *pointer_to_the_background_color;
else
memset(&dp->background_color, 0, sizeof dp->background_color);
/* Local variable fields */
dp->maxerrout = dp->maxerrpc = dp->maxerrabs = 0;
}
CWE ID:
Target: 1
Example 2:
Code: static void arcmsr_free_ccb_pool(struct AdapterControlBlock *acb)
{
dma_free_coherent(&acb->pdev->dev, acb->uncache_size, acb->dma_coherent, acb->dma_coherent_handle);
}
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: AuthenticatorBleActivateSheetModel::GetAdditionalDescription() const {
return PossibleResidentKeyWarning(dialog_model());
}
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 blkcg_init_queue(struct request_queue *q)
{
struct blkcg_gq *new_blkg, *blkg;
bool preloaded;
int ret;
new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL);
if (!new_blkg)
return -ENOMEM;
preloaded = !radix_tree_preload(GFP_KERNEL);
/*
* Make sure the root blkg exists and count the existing blkgs. As
* @q is bypassing at this point, blkg_lookup_create() can't be
* used. Open code insertion.
*/
rcu_read_lock();
spin_lock_irq(q->queue_lock);
blkg = blkg_create(&blkcg_root, q, new_blkg);
spin_unlock_irq(q->queue_lock);
rcu_read_unlock();
if (preloaded)
radix_tree_preload_end();
if (IS_ERR(blkg)) {
blkg_free(new_blkg);
return PTR_ERR(blkg);
}
q->root_blkg = blkg;
q->root_rl.blkg = blkg;
ret = blk_throtl_init(q);
if (ret) {
spin_lock_irq(q->queue_lock);
blkg_destroy_all(q);
spin_unlock_irq(q->queue_lock);
}
return ret;
}
CWE ID: CWE-415
Target: 1
Example 2:
Code: targetport_to_tgtport(struct nvmet_fc_target_port *targetport)
{
return container_of(targetport, struct nvmet_fc_tgtport,
fc_target_port);
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void addr_handler(int status, struct sockaddr *src_addr,
struct rdma_dev_addr *dev_addr, void *context)
{
struct rdma_id_private *id_priv = context;
struct rdma_cm_event event;
memset(&event, 0, sizeof event);
mutex_lock(&id_priv->handler_mutex);
if (!cma_comp_exch(id_priv, RDMA_CM_ADDR_QUERY,
RDMA_CM_ADDR_RESOLVED))
goto out;
memcpy(cma_src_addr(id_priv), src_addr, rdma_addr_size(src_addr));
if (!status && !id_priv->cma_dev)
status = cma_acquire_dev(id_priv, NULL);
if (status) {
if (!cma_comp_exch(id_priv, RDMA_CM_ADDR_RESOLVED,
RDMA_CM_ADDR_BOUND))
goto out;
event.event = RDMA_CM_EVENT_ADDR_ERROR;
event.status = status;
} else
event.event = RDMA_CM_EVENT_ADDR_RESOLVED;
if (id_priv->id.event_handler(&id_priv->id, &event)) {
cma_exch(id_priv, RDMA_CM_DESTROYING);
mutex_unlock(&id_priv->handler_mutex);
cma_deref_id(id_priv);
rdma_destroy_id(&id_priv->id);
return;
}
out:
mutex_unlock(&id_priv->handler_mutex);
cma_deref_id(id_priv);
}
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 handle_unaligned_access(insn_size_t instruction, struct pt_regs *regs,
struct mem_access *ma, int expected,
unsigned long address)
{
u_int rm;
int ret, index;
/*
* XXX: We can't handle mixed 16/32-bit instructions yet
*/
if (instruction_size(instruction) != 2)
return -EINVAL;
index = (instruction>>8)&15; /* 0x0F00 */
rm = regs->regs[index];
/*
* Log the unexpected fixups, and then pass them on to perf.
*
* We intentionally don't report the expected cases to perf as
* otherwise the trapped I/O case will skew the results too much
* to be useful.
*/
if (!expected) {
unaligned_fixups_notify(current, instruction, regs);
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0,
regs, address);
}
ret = -EFAULT;
switch (instruction&0xF000) {
case 0x0000:
if (instruction==0x000B) {
/* rts */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc = regs->pr;
}
else if ((instruction&0x00FF)==0x0023) {
/* braf @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc += rm + 4;
}
else if ((instruction&0x00FF)==0x0003) {
/* bsrf @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc += rm + 4;
}
}
else {
/* mov.[bwl] to/from memory via r0+rn */
goto simple;
}
break;
case 0x1000: /* mov.l Rm,@(disp,Rn) */
goto simple;
case 0x2000: /* mov.[bwl] to memory, possibly with pre-decrement */
goto simple;
case 0x4000:
if ((instruction&0x00FF)==0x002B) {
/* jmp @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc = rm;
}
else if ((instruction&0x00FF)==0x000B) {
/* jsr @Rm */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc = rm;
}
}
else {
/* mov.[bwl] to/from memory via r0+rn */
goto simple;
}
break;
case 0x5000: /* mov.l @(disp,Rm),Rn */
goto simple;
case 0x6000: /* mov.[bwl] from memory, possibly with post-increment */
goto simple;
case 0x8000: /* bf lab, bf/s lab, bt lab, bt/s lab */
switch (instruction&0x0F00) {
case 0x0100: /* mov.w R0,@(disp,Rm) */
goto simple;
case 0x0500: /* mov.w @(disp,Rm),R0 */
goto simple;
case 0x0B00: /* bf lab - no delayslot*/
break;
case 0x0F00: /* bf/s lab */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_SH7705_CACHE_32KB)
if ((regs->sr & 0x00000001) != 0)
regs->pc += 4; /* next after slot */
else
#endif
regs->pc += SH_PC_8BIT_OFFSET(instruction);
}
break;
case 0x0900: /* bt lab - no delayslot */
break;
case 0x0D00: /* bt/s lab */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_SH7705_CACHE_32KB)
if ((regs->sr & 0x00000001) == 0)
regs->pc += 4; /* next after slot */
else
#endif
regs->pc += SH_PC_8BIT_OFFSET(instruction);
}
break;
}
break;
case 0xA000: /* bra label */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0)
regs->pc += SH_PC_12BIT_OFFSET(instruction);
break;
case 0xB000: /* bsr label */
ret = handle_delayslot(regs, instruction, ma);
if (ret==0) {
regs->pr = regs->pc + 4;
regs->pc += SH_PC_12BIT_OFFSET(instruction);
}
break;
}
return ret;
/* handle non-delay-slot instruction */
simple:
ret = handle_unaligned_ins(instruction, regs, ma);
if (ret==0)
regs->pc += instruction_size(instruction);
return ret;
}
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void security_premaster_hash(const char* input, int length, const BYTE* premaster_secret, const BYTE* client_random, const BYTE* server_random, BYTE* output)
{
/* PremasterHash(Input) = SaltedHash(PremasterSecret, Input, ClientRandom, ServerRandom) */
security_salted_hash(premaster_secret, (BYTE*)input, length, client_random, server_random, output);
}
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: pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel)
{
uint16 shortv;
uint32 w, l, tw, tl;
int bychunk;
(void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv);
if (shortv != config && bitspersample != 8 && samplesperpixel > 1) {
fprintf(stderr,
"%s: Cannot handle different planar configuration w/ bits/sample != 8\n",
TIFFFileName(in));
return (NULL);
}
TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l);
if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) {
uint32 irps = (uint32) -1L;
TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps);
/* if biased, force decoded copying to allow image subtraction */
bychunk = !bias && (rowsperstrip == irps);
}else{ /* either in or out is tiled */
if (bias) {
fprintf(stderr,
"%s: Cannot handle tiled configuration w/bias image\n",
TIFFFileName(in));
return (NULL);
}
if (TIFFIsTiled(out)) {
if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw))
tw = w;
if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl))
tl = l;
bychunk = (tw == tilewidth && tl == tilelength);
} else { /* out's not, so in must be tiled */
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
bychunk = (tw == w && tl == rowsperstrip);
}
}
#define T 1
#define F 0
#define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e)))
switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) {
/* Strips -> Tiles */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T):
return cpContigStrips2ContigTiles;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T):
return cpContigStrips2SeparateTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T):
return cpSeparateStrips2ContigTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T):
return cpSeparateStrips2SeparateTiles;
/* Tiles -> Tiles */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T):
return cpContigTiles2ContigTiles;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T):
return cpContigTiles2SeparateTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T):
return cpSeparateTiles2ContigTiles;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T):
return cpSeparateTiles2SeparateTiles;
/* Tiles -> Strips */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T):
return cpContigTiles2ContigStrips;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T):
return cpContigTiles2SeparateStrips;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T):
return cpSeparateTiles2ContigStrips;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T):
return cpSeparateTiles2SeparateStrips;
/* Strips -> Strips */
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F):
return bias ? cpBiasedContig2Contig : cpContig2ContigByRow;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T):
return cpDecodedStrips;
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F):
case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T):
return cpContig2SeparateByRow;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T):
return cpSeparate2ContigByRow;
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F):
case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T):
return cpSeparate2SeparateByRow;
}
#undef pack
#undef F
#undef T
fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n",
TIFFFileName(in));
return (NULL);
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static inline int mk_vhost_fdt_open(int id, unsigned int hash,
struct session_request *sr)
{
int i;
int fd;
struct vhost_fdt_hash_table *ht = NULL;
struct vhost_fdt_hash_chain *hc;
if (config->fdt == MK_FALSE) {
return open(sr->real_path.data, sr->file_info.flags_read_only);
}
ht = mk_vhost_fdt_table_lookup(id, sr->host_conf);
if (mk_unlikely(!ht)) {
return open(sr->real_path.data, sr->file_info.flags_read_only);
}
/* We got the hash table, now look around the chains array */
hc = mk_vhost_fdt_chain_lookup(hash, ht);
if (hc) {
/* Increment the readers and return the shared FD */
hc->readers++;
return hc->fd;
}
/*
* Get here means that no entry exists in the hash table for the
* requested file descriptor and hash, we must try to open the file
* and register the entry in the table.
*/
fd = open(sr->real_path.data, sr->file_info.flags_read_only);
if (fd == -1) {
return -1;
}
/* If chains are full, just return the new FD, bad luck... */
if (ht->av_slots <= 0) {
return fd;
}
/* Register the new entry in an available slot */
for (i = 0; i < VHOST_FDT_HASHTABLE_CHAINS; i++) {
hc = &ht->chain[i];
if (hc->fd == -1) {
hc->fd = fd;
hc->hash = hash;
hc->readers++;
ht->av_slots--;
sr->vhost_fdt_id = id;
sr->vhost_fdt_hash = hash;
return fd;
}
}
return -1;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int is_not_headers(apr_bucket *b)
{
return !H2_BUCKET_IS_HEADERS(b);
}
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: dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo,
proto_tree *tree, dcerpc_info *di, guint8 *drep)
{
guint32 size;
int end_offset;
if (di->conformant_run)
return offset;
/* Dissect size and data */
offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep,
hf_keybuffer_size, &size);
end_offset = offset + (size*2);
if (end_offset < offset) {
/*
* Overflow - make the end offset one past the end of
* the packet data, so we throw an exception (as the
* size is almost certainly too big).
*/
end_offset = tvb_reported_length_remaining(tvb, offset) + 1;
}
while (offset < end_offset)
offset = dissect_spoolss_uint16uni(
tvb, offset, pinfo, tree, drep, NULL, hf_keybuffer);
return offset;
}
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: ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval)
{
jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
if (txtdesc->ascdata) {
jas_free(txtdesc->ascdata);
txtdesc->ascdata = 0;
}
if (txtdesc->ucdata) {
jas_free(txtdesc->ucdata);
txtdesc->ucdata = 0;
}
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int unix_dgram_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = msg->msg_name;
struct sock *other = NULL;
int namelen = 0; /* fake GCC */
int err;
unsigned int hash;
struct sk_buff *skb;
long timeo;
struct scm_cookie tmp_scm;
int max_level;
int data_len = 0;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out;
if (msg->msg_namelen) {
err = unix_mkname(sunaddr, msg->msg_namelen, &hash);
if (err < 0)
goto out;
namelen = err;
} else {
sunaddr = NULL;
err = -ENOTCONN;
other = unix_peer_get(sk);
if (!other)
goto out;
}
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr
&& (err = unix_autobind(sock)) != 0)
goto out;
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
if (len > SKB_MAX_ALLOC)
data_len = min_t(size_t,
len - SKB_MAX_ALLOC,
MAX_SKB_FRAGS * PAGE_SIZE);
skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out;
err = unix_scm_to_skb(siocb->scm, skb, true);
if (err < 0)
goto out_free;
max_level = err + 1;
unix_get_secdata(siocb->scm, skb);
skb_put(skb, len - data_len);
skb->data_len = data_len;
skb->len = len;
err = skb_copy_datagram_from_iovec(skb, 0, msg->msg_iov, 0, len);
if (err)
goto out_free;
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
restart:
if (!other) {
err = -ECONNRESET;
if (sunaddr == NULL)
goto out_free;
other = unix_find_other(net, sunaddr, namelen, sk->sk_type,
hash, &err);
if (other == NULL)
goto out_free;
}
if (sk_filter(other, skb) < 0) {
/* Toss the packet but do not return any error to the sender */
err = len;
goto out_free;
}
unix_state_lock(other);
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
if (sock_flag(other, SOCK_DEAD)) {
/*
* Check with 1003.1g - what should
* datagram error
*/
unix_state_unlock(other);
sock_put(other);
err = 0;
unix_state_lock(sk);
if (unix_peer(sk) == other) {
unix_peer(sk) = NULL;
unix_state_unlock(sk);
unix_dgram_disconnected(sk, other);
sock_put(other);
err = -ECONNREFUSED;
} else {
unix_state_unlock(sk);
}
other = NULL;
if (err)
goto out_free;
goto restart;
}
err = -EPIPE;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (sk->sk_type != SOCK_SEQPACKET) {
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
}
if (unix_peer(other) != sk && unix_recvq_full(other)) {
if (!timeo) {
err = -EAGAIN;
goto out_unlock;
}
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out_free;
goto restart;
}
if (sock_flag(other, SOCK_RCVTSTAMP))
__net_timestamp(skb);
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, len);
sock_put(other);
scm_destroy(siocb->scm);
return len;
out_unlock:
unix_state_unlock(other);
out_free:
kfree_skb(skb);
out:
if (other)
sock_put(other);
scm_destroy(siocb->scm);
return err;
}
CWE ID: CWE-287
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: header_put_be_int (SF_PRIVATE *psf, int x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4)
{ psf->header [psf->headindex++] = (x >> 24) ;
psf->header [psf->headindex++] = (x >> 16) ;
psf->header [psf->headindex++] = (x >> 8) ;
psf->header [psf->headindex++] = x ;
} ;
} /* header_put_be_int */
CWE ID: CWE-119
Target: 1
Example 2:
Code: int readlink_malloc(const char *p, char **ret) {
return readlinkat_malloc(AT_FDCWD, p, ret);
}
CWE ID: CWE-264
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirargs *args)
{
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->cookie);
args->verf = p; p += 2;
args->dircount = ~0;
args->count = ntohl(*p++);
args->count = min_t(u32, args->count, PAGE_SIZE);
args->buffer = page_address(*(rqstp->rq_next_page++));
return xdr_argsize_check(rqstp, p);
}
CWE ID: CWE-404
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BluetoothDeviceChromeOS::DisplayPasskey(
const dbus::ObjectPath& device_path,
uint32 passkey,
uint16 entered) {
DCHECK(agent_.get());
DCHECK(device_path == object_path_);
VLOG(1) << object_path_.value() << ": DisplayPasskey: " << passkey
<< " (" << entered << " entered)";
if (entered == 0)
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_DISPLAY_PASSKEY,
UMA_PAIRING_METHOD_COUNT);
DCHECK(pairing_delegate_);
if (entered == 0)
pairing_delegate_->DisplayPasskey(this, passkey);
pairing_delegate_->KeysEntered(this, entered);
pairing_delegate_used_ = true;
}
CWE ID:
Target: 1
Example 2:
Code: void OfflinePageModelImpl::DeletePages(
const DeletePageCallback& callback,
const MultipleOfflinePageItemResult& pages) {
DCHECK(is_loaded_);
std::vector<int64_t> offline_ids;
for (auto& page : pages)
offline_ids.emplace_back(page.offline_id);
DoDeletePagesByOfflineId(offline_ids, callback);
}
CWE ID: CWE-787
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool __is_local_mountpoint(struct dentry *dentry)
{
struct mnt_namespace *ns = current->nsproxy->mnt_ns;
struct mount *mnt;
bool is_covered = false;
if (!d_mountpoint(dentry))
goto out;
down_read(&namespace_sem);
list_for_each_entry(mnt, &ns->list, mnt_list) {
is_covered = (mnt->mnt_mountpoint == dentry);
if (is_covered)
break;
}
up_read(&namespace_sem);
out:
return is_covered;
}
CWE ID: CWE-400
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: uint32_t ClientSharedBitmapManager::NotifyAllocatedSharedBitmap(
base::SharedMemory* memory,
const SharedBitmapId& id) {
base::SharedMemoryHandle handle_to_send =
base::SharedMemory::DuplicateHandle(memory->handle());
if (!base::SharedMemory::IsHandleValid(handle_to_send)) {
LOG(ERROR) << "Failed to duplicate shared memory handle for bitmap.";
return 0;
}
mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(
handle_to_send, memory->mapped_size(), true /* read_only */);
{
base::AutoLock lock(lock_);
(*shared_bitmap_allocation_notifier_)
->DidAllocateSharedBitmap(std::move(buffer_handle), id);
return ++last_sequence_number_;
}
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: PHP_FUNCTION(pg_last_notice)
{
zval *pgsql_link;
PGconn *pg_link;
int id = -1;
php_pgsql_notice **notice;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == FAILURE) {
return;
}
/* Just to check if user passed valid resoruce */
ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
if (zend_hash_index_find(&PGG(notices), Z_RESVAL_P(pgsql_link), (void **)¬ice) == FAILURE) {
RETURN_FALSE;
}
RETURN_STRINGL((*notice)->message, (*notice)->len, 1);
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: insert_prefix(int options, char **buffer, int *offset, int *max, int depth)
{
if (options & xml_log_option_formatted) {
size_t spaces = 2 * depth;
if ((*buffer) == NULL || spaces >= ((*max) - (*offset))) {
(*max) = QB_MAX(CHUNK_SIZE, (*max) * 2);
(*buffer) = realloc_safe((*buffer), (*max) + 1);
}
memset((*buffer) + (*offset), ' ', spaces);
(*offset) += spaces;
}
}
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: on_response(void *data, krb5_error_code retval, otp_response response)
{
struct request_state rs = *(struct request_state *)data;
free(data);
if (retval == 0 && response != otp_response_success)
retval = KRB5_PREAUTH_FAILED;
rs.respond(rs.arg, retval, NULL, NULL, NULL);
}
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void set_var_mtrr_msr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
struct kvm_mtrr *mtrr_state = &vcpu->arch.mtrr_state;
struct kvm_mtrr_range *tmp, *cur;
int index, is_mtrr_mask;
index = (msr - 0x200) / 2;
is_mtrr_mask = msr - 0x200 - 2 * index;
cur = &mtrr_state->var_ranges[index];
/* remove the entry if it's in the list. */
if (var_mtrr_range_is_valid(cur))
list_del(&mtrr_state->var_ranges[index].node);
/* Extend the mask with all 1 bits to the left, since those
* bits must implicitly be 0. The bits are then cleared
* when reading them.
*/
if (!is_mtrr_mask)
cur->base = data;
else
cur->mask = data | (-1LL << cpuid_maxphyaddr(vcpu));
/* add it to the list if it's enabled. */
if (var_mtrr_range_is_valid(cur)) {
list_for_each_entry(tmp, &mtrr_state->head, node)
if (cur->base >= tmp->base)
break;
list_add_tail(&cur->node, &tmp->node);
}
}
CWE ID: CWE-284
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
{
char buf[150];
len = FFMIN(sizeof(buf) / 2 - 1, len);
ff_data_to_hex(buf, value, len, 0);
buf[2 * len] = '\0';
avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
}
CWE ID: CWE-369
Output: | 0 |
Here are some example code snippets. Analyze the following 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 rose_loopback_timer(unsigned long param)
{
struct sk_buff *skb;
struct net_device *dev;
rose_address *dest;
struct sock *sk;
unsigned short frametype;
unsigned int lci_i, lci_o;
while ((skb = skb_dequeue(&loopback_queue)) != NULL) {
lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF);
frametype = skb->data[2];
dest = (rose_address *)(skb->data + 4);
lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i;
skb_reset_transport_header(skb);
sk = rose_find_socket(lci_o, rose_loopback_neigh);
if (sk) {
if (rose_process_rx_frame(sk, skb) == 0)
kfree_skb(skb);
continue;
}
if (frametype == ROSE_CALL_REQUEST) {
if ((dev = rose_dev_get(dest)) != NULL) {
if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0)
kfree_skb(skb);
} else {
kfree_skb(skb);
}
} else {
kfree_skb(skb);
}
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int in_set_gain(struct audio_stream_in *stream, float gain)
{
(void)stream;
(void)gain;
return 0;
}
CWE ID: CWE-125
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int tls1_ec_nid2curve_id(int nid)
{
/* ECC curves from RFC 4492 */
switch (nid) {
case NID_sect163k1: /* sect163k1 (1) */
return 1;
case NID_sect163r1: /* sect163r1 (2) */
return 2;
case NID_sect163r2: /* sect163r2 (3) */
return 3;
case NID_sect193r1: /* sect193r1 (4) */
return 4;
case NID_sect193r2: /* sect193r2 (5) */
return 5;
case NID_sect233k1: /* sect233k1 (6) */
return 6;
case NID_sect233r1: /* sect233r1 (7) */
return 7;
case NID_sect239k1: /* sect239k1 (8) */
return 8;
case NID_sect283k1: /* sect283k1 (9) */
return 9;
case NID_sect283r1: /* sect283r1 (10) */
return 10;
case NID_sect409k1: /* sect409k1 (11) */
return 11;
case NID_sect409r1: /* sect409r1 (12) */
return 12;
case NID_sect571k1: /* sect571k1 (13) */
return 13;
case NID_sect571r1: /* sect571r1 (14) */
return 14;
case NID_secp160k1: /* secp160k1 (15) */
return 15;
case NID_secp160r1: /* secp160r1 (16) */
return 16;
case NID_secp160r2: /* secp160r2 (17) */
return 17;
case NID_secp192k1: /* secp192k1 (18) */
return 18;
case NID_X9_62_prime192v1: /* secp192r1 (19) */
return 19;
case NID_secp224k1: /* secp224k1 (20) */
return 20;
case NID_secp224r1: /* secp224r1 (21) */
return 21;
case NID_secp256k1: /* secp256k1 (22) */
return 22;
case NID_X9_62_prime256v1: /* secp256r1 (23) */
return 23;
case NID_secp384r1: /* secp384r1 (24) */
return 24;
case NID_secp521r1: /* secp521r1 (25) */
return 25;
default:
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: setup_connection (GsmXSMPClient *client)
{
GIOChannel *channel;
int fd;
g_debug ("GsmXSMPClient: Setting up new connection");
fd = IceConnectionNumber (client->priv->ice_connection);
fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);
channel = g_io_channel_unix_new (fd);
client->priv->watch_id = g_io_add_watch (channel,
G_IO_IN | G_IO_ERR,
(GIOFunc)client_iochannel_watch,
client);
g_io_channel_unref (channel);
client->priv->protocol_timeout = g_timeout_add_seconds (5,
(GSourceFunc)_client_protocol_timeout,
client);
set_description (client);
g_debug ("GsmXSMPClient: New client '%s'", client->priv->description);
}
CWE ID: CWE-835
Target: 1
Example 2:
Code: void S_AL_Respatialize( int entityNum, const vec3_t origin, vec3_t axis[3], int inwater )
{
float orientation[6];
vec3_t sorigin;
VectorCopy( origin, sorigin );
S_AL_SanitiseVector( sorigin );
S_AL_SanitiseVector( axis[ 0 ] );
S_AL_SanitiseVector( axis[ 1 ] );
S_AL_SanitiseVector( axis[ 2 ] );
orientation[0] = axis[0][0]; orientation[1] = axis[0][1]; orientation[2] = axis[0][2];
orientation[3] = axis[2][0]; orientation[4] = axis[2][1]; orientation[5] = axis[2][2];
lastListenerNumber = entityNum;
VectorCopy( sorigin, lastListenerOrigin );
qalListenerfv(AL_POSITION, (ALfloat *)sorigin);
qalListenerfv(AL_VELOCITY, vec3_origin);
qalListenerfv(AL_ORIENTATION, orientation);
}
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: SplashCoord Splash::getMiterLimit() {
return state->miterLimit;
}
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: ExtensionScriptAndCaptureVisibleTest()
: http_url("http://www.google.com"),
http_url_with_path("http://www.google.com/index.html"),
https_url("https://www.google.com"),
example_com("https://example.com"),
test_example_com("https://test.example.com"),
sample_example_com("https://sample.example.com"),
file_url("file:///foo/bar"),
favicon_url("chrome://favicon/http://www.google.com"),
extension_url("chrome-extension://" +
crx_file::id_util::GenerateIdForPath(
base::FilePath(FILE_PATH_LITERAL("foo")))),
settings_url("chrome://settings"),
about_url("about:flags") {
urls_.insert(http_url);
urls_.insert(http_url_with_path);
urls_.insert(https_url);
urls_.insert(example_com);
urls_.insert(test_example_com);
urls_.insert(sample_example_com);
urls_.insert(file_url);
urls_.insert(favicon_url);
urls_.insert(extension_url);
urls_.insert(settings_url);
urls_.insert(about_url);
PermissionsData::SetPolicyDelegate(NULL);
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: RenderWidgetHost* TabLoader::GetRenderWidgetHost(NavigationController* tab) {
WebContents* web_contents = tab->GetWebContents();
if (web_contents) {
RenderWidgetHostView* render_widget_host_view =
web_contents->GetRenderWidgetHostView();
if (render_widget_host_view)
return render_widget_host_view->GetRenderWidgetHost();
}
return NULL;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: BOOL region16_is_empty(const REGION16* region)
{
assert(region);
assert(region->data);
return (region->data->nbRects == 0);
}
CWE ID: CWE-772
Output: | 0 |
Here are some example code snippets. Analyze the following 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 PassRefPtr<Uint8Array> copySkImageData(SkImage* input,
const SkImageInfo& info) {
size_t width = static_cast<size_t>(input->width());
RefPtr<ArrayBuffer> dstBuffer =
ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel());
if (!dstBuffer)
return nullptr;
RefPtr<Uint8Array> dstPixels =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
input->readPixels(info, dstPixels->data(), width * info.bytesPerPixel(), 0,
0);
return dstPixels;
}
CWE ID: CWE-787
Target: 1
Example 2:
Code: void msix_set_pending(PCIDevice *dev, unsigned int vector)
{
*msix_pending_byte(dev, vector) |= msix_pending_mask(vector);
}
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 kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
struct kvm_guest_debug *dbg)
{
return -EINVAL;
}
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 MultibufferDataSource::StartCallback() {
DCHECK(render_task_runner_->BelongsToCurrentThread());
if (!init_cb_) {
SetReader(nullptr);
return;
}
bool success = reader_ && reader_->Available() > 0 && url_data() &&
(!assume_fully_buffered() ||
url_data()->length() != kPositionNotSpecified);
if (success) {
{
base::AutoLock auto_lock(lock_);
total_bytes_ = url_data()->length();
}
streaming_ =
!assume_fully_buffered() && (total_bytes_ == kPositionNotSpecified ||
!url_data()->range_supported());
media_log_->SetDoubleProperty("total_bytes",
static_cast<double>(total_bytes_));
media_log_->SetBooleanProperty("streaming", streaming_);
} else {
SetReader(nullptr);
}
base::AutoLock auto_lock(lock_);
if (stop_signal_received_)
return;
if (success) {
if (total_bytes_ != kPositionNotSpecified) {
host_->SetTotalBytes(total_bytes_);
if (assume_fully_buffered())
host_->AddBufferedByteRange(0, total_bytes_);
}
media_log_->SetBooleanProperty("single_origin", single_origin_);
media_log_->SetBooleanProperty("passed_cors_access_check",
DidPassCORSAccessCheck());
media_log_->SetBooleanProperty("range_header_supported",
url_data()->range_supported());
}
render_task_runner_->PostTask(FROM_HERE,
base::Bind(std::move(init_cb_), success));
UpdateBufferSizes();
UpdateLoadingState_Locked(true);
}
CWE ID: CWE-732
Target: 1
Example 2:
Code: DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_ciphers)
{
/*
* OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
* pulling in all the ciphers during static linking
*/
#ifndef OPENSSL_NO_AUTOALGINIT
# ifdef OPENSSL_INIT_DEBUG
fprintf(stderr, "OPENSSL_INIT: ossl_init_add_all_ciphers: "
"openssl_add_all_ciphers_int()\n");
# endif
openssl_add_all_ciphers_int();
#endif
return 1;
}
CWE ID: CWE-330
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 add_param_to_argv(char *parsestart, int line)
{
int quote_open = 0, escaped = 0, param_len = 0;
char param_buffer[1024], *curchar;
/* After fighting with strtok enough, here's now
* a 'real' parser. According to Rusty I'm now no
} else {
param_buffer[param_len++] = *curchar;
for (curchar = parsestart; *curchar; curchar++) {
if (quote_open) {
if (escaped) {
param_buffer[param_len++] = *curchar;
escaped = 0;
continue;
} else if (*curchar == '\\') {
}
switch (*curchar) {
quote_open = 0;
*curchar = '"';
} else {
param_buffer[param_len++] = *curchar;
continue;
}
} else {
continue;
}
break;
default:
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
case ' ':
case '\t':
case '\n':
if (!param_len) {
/* two spaces? */
continue;
}
break;
default:
/* regular character, copy to buffer */
param_buffer[param_len++] = *curchar;
if (param_len >= sizeof(param_buffer))
xtables_error(PARAMETER_PROBLEM,
"Parameter too long!");
continue;
}
param_buffer[param_len] = '\0';
/* check if table name specified */
if ((param_buffer[0] == '-' &&
param_buffer[1] != '-' &&
strchr(param_buffer, 't')) ||
(!strncmp(param_buffer, "--t", 3) &&
!strncmp(param_buffer, "--table", strlen(param_buffer)))) {
xtables_error(PARAMETER_PROBLEM,
"The -t option (seen in line %u) cannot be used in %s.\n",
line, xt_params->program_name);
}
add_argv(param_buffer, 0);
param_len = 0;
}
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {
OPCODE_DESC *opcode_desc;
ut16 ins = (buf[1] << 8) | buf[0];
int fail;
char *t;
memset (op, 0, sizeof (RAnalOp));
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->jump = UT64_MAX;
r_strbuf_init (&op->esil);
for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {
if ((ins & opcode_desc->mask) == opcode_desc->selector) {
fail = 0;
op->cycles = opcode_desc->cycles;
op->size = opcode_desc->size;
op->type = opcode_desc->type;
op->jump = UT64_MAX;
op->fail = UT64_MAX;
op->addr = addr;
r_strbuf_setf (&op->esil, "");
opcode_desc->handler (anal, op, buf, len, &fail, cpu);
if (fail) {
goto INVALID_OP;
}
if (op->cycles <= 0) {
opcode_desc->cycles = 2;
}
op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);
t = r_strbuf_get (&op->esil);
if (t && strlen (t) > 1) {
t += strlen (t) - 1;
if (*t == ',') {
*t = '\0';
}
}
return opcode_desc;
}
}
if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {
goto INVALID_OP;
}
INVALID_OP:
op->family = R_ANAL_OP_FAMILY_UNKNOWN;
op->type = R_ANAL_OP_TYPE_UNK;
op->addr = addr;
op->fail = UT64_MAX;
op->jump = UT64_MAX;
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->nopcode = 1;
op->cycles = 1;
op->size = 2;
r_strbuf_set (&op->esil, "1,$");
return NULL;
}
CWE ID: CWE-125
Target: 1
Example 2:
Code: void RunAllPendingForIO() {
message_loop_.RunAllPending();
BrowserThread::GetBlockingPool()->FlushForTesting();
message_loop_.RunAllPending();
}
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: v8::Handle<v8::Value> V8DataView::getInt8Callback(const v8::Arguments& args)
{
INC_STATS("DOM.DataView.getInt8");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
DataView* imp = V8DataView::toNative(args.Holder());
ExceptionCode ec = 0;
EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0]));
int8_t result = imp->getInt8(byteOffset, ec);
if (UNLIKELY(ec)) {
V8Proxy::setDOMException(ec, args.GetIsolate());
return v8::Handle<v8::Value>();
}
return v8::Integer::New(result);
}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
int dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, *iter, *iteriter, *regexiter = NULL;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->arc.archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
MAKE_STD_ZVAL(iter);
if (SUCCESS != object_init_ex(iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg);
ZVAL_STRINGL(&arg, dir, dir_len, 0);
INIT_PZVAL(&arg2);
#if PHP_VERSION_ID < 50300
ZVAL_LONG(&arg2, 0);
#else
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
#endif
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
MAKE_STD_ZVAL(iteriter);
if (SUCCESS != object_init_ex(iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate directory iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
MAKE_STD_ZVAL(regexiter);
if (SUCCESS != object_init_ex(regexiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(regexiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, "Unable to instantiate regex iterator for %s", phar_obj->arc.archive->fname);
RETURN_FALSE;
}
INIT_PZVAL(&arg2);
ZVAL_STRINGL(&arg2, regex, regex_len, 0);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, iteriter, &arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE_P(regexiter) : Z_OBJCE_P(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" unable to create temporary file", phar_obj->arc.archive->fname);
return;
}
if (phar_obj->arc.archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->arc.archive) TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "phar \"%s\" is persistent, unable to copy on write", phar_obj->arc.archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? regexiter : iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass TSRMLS_CC)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->arc.archive->ufp = pass.fp;
phar_flush(phar_obj->arc.archive, 0, 0, 0, &error TSRMLS_CC);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int skcipher_walk_aead_encrypt(struct skcipher_walk *walk,
struct aead_request *req, bool atomic)
{
walk->total = req->cryptlen;
return skcipher_walk_aead_common(walk, req, atomic);
}
CWE ID: CWE-476
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
OPJ_UINT32 index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
OPJ_UINT32 compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
OPJ_UINT32 dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
OPJ_UINT32 levelno;
OPJ_INT32 trx0, try0;
OPJ_INT32 trx1, try1;
OPJ_UINT32 rpx, rpy;
OPJ_INT32 prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
(OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
- opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
(OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
- opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
CWE ID: CWE-369
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static uint64_t ReadBits(BitReader* reader, int num_bits) {
DCHECK_GE(reader->bits_available(), num_bits);
DCHECK((num_bits > 0) && (num_bits <= 64));
uint64_t value;
reader->ReadBits(num_bits, &value);
return value;
}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int __init init(void)
{
int err;
pdrvdata.class = class_create(THIS_MODULE, "virtio-ports");
if (IS_ERR(pdrvdata.class)) {
err = PTR_ERR(pdrvdata.class);
pr_err("Error %d creating virtio-ports class\n", err);
return err;
}
pdrvdata.debugfs_dir = debugfs_create_dir("virtio-ports", NULL);
if (!pdrvdata.debugfs_dir)
pr_warning("Error creating debugfs dir for virtio-ports\n");
INIT_LIST_HEAD(&pdrvdata.consoles);
INIT_LIST_HEAD(&pdrvdata.portdevs);
err = register_virtio_driver(&virtio_console);
if (err < 0) {
pr_err("Error %d registering virtio driver\n", err);
goto free;
}
err = register_virtio_driver(&virtio_rproc_serial);
if (err < 0) {
pr_err("Error %d registering virtio rproc serial driver\n",
err);
goto unregister;
}
return 0;
unregister:
unregister_virtio_driver(&virtio_console);
free:
debugfs_remove_recursive(pdrvdata.debugfs_dir);
class_destroy(pdrvdata.class);
return err;
}
CWE ID: CWE-119
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static ssize_t abi_version_show(struct device *device,
struct device_attribute *attr, char *buf)
{
struct ib_uverbs_device *dev =
container_of(device, struct ib_uverbs_device, dev);
int ret = -ENODEV;
int srcu_key;
struct ib_device *ib_dev;
srcu_key = srcu_read_lock(&dev->disassociate_srcu);
ib_dev = srcu_dereference(dev->ib_dev, &dev->disassociate_srcu);
if (ib_dev)
ret = sprintf(buf, "%d\n", ib_dev->uverbs_abi_ver);
srcu_read_unlock(&dev->disassociate_srcu, srcu_key);
return ret;
}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef _WIN32
/*
* Warning: the user which launches the process must have the
* SE_TCB_NAME right.
* This corresponds to have the "Act as part of the Operating System"
* turned on (administrative tools, local security settings, local
* policies, user right assignment)
* However, it seems to me that if you run it as a service, this
* right should be provided by default.
*
* XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
* which merely indicates that the user name or password is
* incorrect, not whether it's the user name or the password
* that's incorrect, so a client that's trying to brute-force
* accounts doesn't know whether it's the user name or the
* password that's incorrect, so it doesn't know whether to
* stop trying to log in with a given user name and move on
* to another user name.
*/
HANDLE Token;
if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "LogonUser() failed");
return -1;
}
if (ImpersonateLoggedOnUser(Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "ImpersonateLoggedOnUser() failed");
CloseHandle(Token);
return -1;
}
CloseHandle(Token);
return 0;
#else
/*
* See
*
* http://www.unixpapa.com/incnote/passwd.html
*
* We use the Solaris/Linux shadow password authentication if
* we have getspnam(), otherwise we just do traditional
* authentication, which, on some platforms, might work, even
* with shadow passwords, if we're running as root. Traditional
* authenticaion won't work if we're not running as root, as
* I think these days all UN*Xes either won't return the password
* at all with getpwnam() or will only do so if you're root.
*
* XXX - perhaps what we *should* be using is PAM, if we have
* it. That might hide all the details of username/password
* authentication, whether it's done with a visible-to-root-
* only password database or some other authentication mechanism,
* behind its API.
*/
struct passwd *user;
char *user_password;
#ifdef HAVE_GETSPNAM
struct spwd *usersp;
#endif
char *crypt_password;
if ((user = getpwnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
#ifdef HAVE_GETSPNAM
if ((usersp = getspnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
user_password = usersp->sp_pwdp;
#else
/*
* XXX - what about other platforms?
* The unixpapa.com page claims this Just Works on *BSD if you're
* running as root - it's from 2000, so it doesn't indicate whether
* macOS (which didn't come out until 2001, under the name Mac OS
* X) behaves like the *BSDs or not, and might also work on AIX.
* HP-UX does something else.
*
* Again, hopefully PAM hides all that.
*/
user_password = user->pw_passwd;
#endif
crypt_password = crypt(password, user_password);
if (crypt_password == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
if (strcmp(user_password, crypt_password) != 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
if (setuid(user->pw_uid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setuid");
return -1;
}
/* if (setgid(user->pw_gid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setgid");
return -1;
}
*/
return 0;
#endif
}
CWE ID: CWE-345
Target: 1
Example 2:
Code: static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags)
{
struct sock *new_sk, *sk = sock->sk;
struct sk_buff *buf;
struct tipc_sock *new_tsock;
struct tipc_msg *msg;
long timeo;
int res;
lock_sock(sk);
if (sock->state != SS_LISTENING) {
res = -EINVAL;
goto exit;
}
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
res = tipc_wait_for_accept(sock, timeo);
if (res)
goto exit;
buf = skb_peek(&sk->sk_receive_queue);
res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, 1);
if (res)
goto exit;
security_sk_clone(sock->sk, new_sock->sk);
new_sk = new_sock->sk;
new_tsock = tipc_sk(new_sk);
msg = buf_msg(buf);
/* we lock on new_sk; but lockdep sees the lock on sk */
lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
/*
* Reject any stray messages received by new socket
* before the socket lock was taken (very, very unlikely)
*/
tsk_rej_rx_queue(new_sk);
/* Connect new socket to it's peer */
tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg));
new_sock->state = SS_CONNECTED;
tsk_set_importance(new_tsock, msg_importance(msg));
if (msg_named(msg)) {
new_tsock->conn_type = msg_nametype(msg);
new_tsock->conn_instance = msg_nameinst(msg);
}
/*
* Respond to 'SYN-' by discarding it & returning 'ACK'-.
* Respond to 'SYN+' by queuing it on new socket.
*/
if (!msg_data_sz(msg)) {
struct msghdr m = {NULL,};
tsk_advance_rx_queue(sk);
__tipc_send_stream(new_sock, &m, 0);
} else {
__skb_dequeue(&sk->sk_receive_queue);
__skb_queue_head(&new_sk->sk_receive_queue, buf);
skb_set_owner_r(buf, new_sk);
}
release_sock(new_sk);
exit:
release_sock(sk);
return res;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virtual void willSendRequest(WebFrame* frame, unsigned, WebURLRequest&, const WebURLResponse&)
{
if (toWebFrameImpl(frame)->frame()->loader()->loadType() == WebCore::FrameLoadTypeSame)
m_frameLoadTypeSameSeen = true;
}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)
{
zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];
obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);;
obj_bucket->destructor_called = 1;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void markBoxForRelayoutAfterSplit(RenderBox* box)
{
if (box->isTable()) {
toRenderTable(box)->forceSectionsRecalc();
} else if (box->isTableSection())
toRenderTableSection(box)->setNeedsCellRecalc();
box->setNeedsLayoutAndPrefWidthsRecalc();
}
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: explicit ElementsAccessorBase(const char* name)
: ElementsAccessor(name) { }
CWE ID: CWE-704
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 _c2s_sx_sasl_callback(int cb, void *arg, void **res, sx_t s, void *cbarg) {
c2s_t c2s = (c2s_t) cbarg;
const char *my_realm, *mech;
sx_sasl_creds_t creds;
static char buf[3072];
char mechbuf[256];
struct jid_st jid;
jid_static_buf jid_buf;
int i, r;
sess_t sess;
char skey[44];
host_t host;
/* init static jid */
jid_static(&jid,&jid_buf);
/* retrieve our session */
assert(s != NULL);
sprintf(skey, "%d", s->tag);
/*
* Retrieve the session, note that depending on the operation,
* session may be null.
*/
sess = xhash_get(c2s->sessions, skey);
switch(cb) {
case sx_sasl_cb_GET_REALM:
if(s->req_to == NULL) /* this shouldn't happen */
my_realm = "";
else {
/* get host for request */
host = xhash_get(c2s->hosts, s->req_to);
if(host == NULL) {
log_write(c2s->log, LOG_ERR, "SASL callback for non-existing host: %s", s->req_to);
*res = (void *)NULL;
return sx_sasl_ret_FAIL;
}
my_realm = host->realm;
if(my_realm == NULL)
my_realm = s->req_to;
}
strncpy(buf, my_realm, 256);
*res = (void *)buf;
log_debug(ZONE, "sx sasl callback: get realm: realm is '%s'", buf);
return sx_sasl_ret_OK;
break;
case sx_sasl_cb_GET_PASS:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
log_debug(ZONE, "sx sasl callback: get pass (authnid=%s, realm=%s)", creds->authnid, creds->realm);
if(sess->host->ar->get_password && (sess->host->ar->get_password)(
sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm: "", buf) == 0) {
*res = buf;
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
case sx_sasl_cb_CHECK_PASS:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
log_debug(ZONE, "sx sasl callback: check pass (authnid=%s, realm=%s)", creds->authnid, creds->realm);
if(sess->host->ar->check_password != NULL) {
if ((sess->host->ar->check_password)(
sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm : "", (char *)creds->pass) == 0)
return sx_sasl_ret_OK;
else
return sx_sasl_ret_FAIL;
}
if(sess->host->ar->get_password != NULL) {
if ((sess->host->ar->get_password)(sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm : "", buf) != 0)
return sx_sasl_ret_FAIL;
if (strcmp(creds->pass, buf)==0)
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
break;
case sx_sasl_cb_CHECK_AUTHZID:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
/* we need authzid to validate */
if(creds->authzid == NULL || creds->authzid[0] == '\0')
return sx_sasl_ret_FAIL;
/* authzid must be a valid jid */
if(jid_reset(&jid, creds->authzid, -1) == NULL)
return sx_sasl_ret_FAIL;
/* and have domain == stream to addr */
if(!s->req_to || (strcmp(jid.domain, s->req_to) != 0))
return sx_sasl_ret_FAIL;
/* and have no resource */
if(jid.resource[0] != '\0')
return sx_sasl_ret_FAIL;
/* and user has right to authorize as */
if (sess->host->ar->user_authz_allowed) {
if (sess->host->ar->user_authz_allowed(sess->host->ar, sess, (char *)creds->authnid, (char *)creds->realm, (char *)creds->authzid))
return sx_sasl_ret_OK;
} else {
if (strcmp(creds->authnid, jid.node) == 0 &&
(sess->host->ar->user_exists)(sess->host->ar, sess, jid.node, jid.domain))
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
case sx_sasl_cb_GEN_AUTHZID:
/* generate a jid for SASL ANONYMOUS */
jid_reset(&jid, s->req_to, -1);
/* make node a random string */
jid_random_part(&jid, jid_NODE);
strcpy(buf, jid.node);
*res = (void *)buf;
return sx_sasl_ret_OK;
break;
case sx_sasl_cb_CHECK_MECH:
mech = (char *)arg;
strncpy(mechbuf, mech, sizeof(mechbuf));
mechbuf[sizeof(mechbuf)-1]='\0';
for(i = 0; mechbuf[i]; i++) mechbuf[i] = tolower(mechbuf[i]);
/* get host for request */
host = xhash_get(c2s->hosts, s->req_to);
if(host == NULL) {
log_write(c2s->log, LOG_WARNING, "SASL callback for non-existing host: %s", s->req_to);
return sx_sasl_ret_FAIL;
}
/* Determine if our configuration will let us use this mechanism.
* We support different mechanisms for both SSL and normal use */
if (strcmp(mechbuf, "digest-md5") == 0) {
/* digest-md5 requires that our authreg support get_password */
if (host->ar->get_password == NULL)
return sx_sasl_ret_FAIL;
} else if (strcmp(mechbuf, "plain") == 0) {
/* plain requires either get_password or check_password */
if (host->ar->get_password == NULL && host->ar->check_password == NULL)
return sx_sasl_ret_FAIL;
}
/* Using SSF is potentially dangerous, as SASL can also set the
* SSF of the connection. However, SASL shouldn't do so until after
* we've finished mechanism establishment
*/
if (s->ssf>0) {
r = snprintf(buf, sizeof(buf), "authreg.ssl-mechanisms.sasl.%s",mechbuf);
if (r < -1 || r > sizeof(buf))
return sx_sasl_ret_FAIL;
if(config_get(c2s->config,buf) != NULL)
return sx_sasl_ret_OK;
}
r = snprintf(buf, sizeof(buf), "authreg.mechanisms.sasl.%s",mechbuf);
if (r < -1 || r > sizeof(buf))
return sx_sasl_ret_FAIL;
/* Work out if our configuration will let us use this mechanism */
if(config_get(c2s->config,buf) != NULL)
return sx_sasl_ret_OK;
else
return sx_sasl_ret_FAIL;
default:
break;
}
return sx_sasl_ret_FAIL;
}
CWE ID: CWE-287
Target: 1
Example 2:
Code: void RenderFrameHostImpl::OnPortalActivated(blink::TransferableMessage data) {
frame_->OnPortalActivated(std::move(data));
}
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: store_memory_free(png_const_structp pp, store_pool *pool, store_memory *memory)
{
/* Note that pp may be NULL (see store_pool_delete below), the caller has
* found 'memory' in pool->list *and* unlinked this entry, so this is a valid
* pointer (for sure), but the contents may have been trashed.
*/
if (memory->pool != pool)
store_pool_error(pool->store, pp, "memory corrupted (pool)");
else if (memcmp(memory->mark, pool->mark, sizeof memory->mark) != 0)
store_pool_error(pool->store, pp, "memory corrupted (start)");
/* It should be safe to read the size field now. */
else
{
png_alloc_size_t cb = memory->size;
if (cb > pool->max)
store_pool_error(pool->store, pp, "memory corrupted (size)");
else if (memcmp((png_bytep)(memory+1)+cb, pool->mark, sizeof pool->mark)
!= 0)
store_pool_error(pool->store, pp, "memory corrupted (end)");
/* Finally give the library a chance to find problems too: */
else
{
pool->current -= cb;
free(memory);
}
}
}
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: xps_parse_gradient_stops(xps_document *doc, char *base_uri, fz_xml *node,
struct stop *stops, int maxcount)
{
fz_colorspace *colorspace;
float sample[8];
float rgb[3];
int before, after;
int count;
int i;
/* We may have to insert 2 extra stops when postprocessing */
maxcount -= 2;
count = 0;
while (node && count < maxcount)
{
if (!strcmp(fz_xml_tag(node), "GradientStop"))
{
char *offset = fz_xml_att(node, "Offset");
char *color = fz_xml_att(node, "Color");
if (offset && color)
{
stops[count].offset = fz_atof(offset);
stops[count].index = count;
xps_parse_color(doc, base_uri, color, &colorspace, sample);
fz_convert_color(doc->ctx, fz_device_rgb(doc->ctx), rgb, colorspace, sample + 1);
stops[count].r = rgb[0];
stops[count].g = rgb[1];
stops[count].b = rgb[2];
stops[count].a = sample[0];
count ++;
}
}
node = fz_xml_next(node);
}
if (count == 0)
{
fz_warn(doc->ctx, "gradient brush has no gradient stops");
stops[0].offset = 0;
stops[0].r = 0;
stops[0].g = 0;
stops[0].b = 0;
stops[0].a = 1;
stops[1].offset = 1;
stops[1].r = 1;
stops[1].g = 1;
stops[1].b = 1;
stops[1].a = 1;
return 2;
}
if (count == maxcount)
fz_warn(doc->ctx, "gradient brush exceeded maximum number of gradient stops");
/* Postprocess to make sure the range of offsets is 0.0 to 1.0 */
qsort(stops, count, sizeof(struct stop), cmp_stop);
before = -1;
after = -1;
for (i = 0; i < count; i++)
{
if (stops[i].offset < 0)
before = i;
if (stops[i].offset > 1)
{
after = i;
break;
}
}
/* Remove all stops < 0 except the largest one */
if (before > 0)
{
memmove(stops, stops + before, (count - before) * sizeof(struct stop));
count -= before;
}
/* Remove all stops > 1 except the smallest one */
if (after >= 0)
count = after + 1;
/* Expand single stop to 0 .. 1 */
if (count == 1)
{
stops[1] = stops[0];
stops[0].offset = 0;
stops[1].offset = 1;
return 2;
}
/* First stop < 0 -- interpolate value to 0 */
if (stops[0].offset < 0)
{
float d = -stops[0].offset / (stops[1].offset - stops[0].offset);
stops[0].offset = 0;
stops[0].r = lerp(stops[0].r, stops[1].r, d);
stops[0].g = lerp(stops[0].g, stops[1].g, d);
stops[0].b = lerp(stops[0].b, stops[1].b, d);
stops[0].a = lerp(stops[0].a, stops[1].a, d);
}
/* Last stop > 1 -- interpolate value to 1 */
if (stops[count-1].offset > 1)
{
float d = (1 - stops[count-2].offset) / (stops[count-1].offset - stops[count-2].offset);
stops[count-1].offset = 1;
stops[count-1].r = lerp(stops[count-2].r, stops[count-1].r, d);
stops[count-1].g = lerp(stops[count-2].g, stops[count-1].g, d);
stops[count-1].b = lerp(stops[count-2].b, stops[count-1].b, d);
stops[count-1].a = lerp(stops[count-2].a, stops[count-1].a, d);
}
/* First stop > 0 -- insert a duplicate at 0 */
if (stops[0].offset > 0)
{
memmove(stops + 1, stops, count * sizeof(struct stop));
stops[0] = stops[1];
stops[0].offset = 0;
count++;
}
/* Last stop < 1 -- insert a duplicate at 1 */
if (stops[count-1].offset < 1)
{
stops[count] = stops[count-1];
stops[count].offset = 1;
count++;
}
return count;
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: ZEND_API int ZEND_FASTCALL zend_hash_move_backwards_ex(HashTable *ht, HashPosition *pos)
{
uint32_t idx = *pos;
IS_CONSISTENT(ht);
HT_ASSERT(&ht->nInternalPointer != pos || GC_REFCOUNT(ht) == 1);
if (idx != HT_INVALID_IDX) {
while (idx > 0) {
idx--;
if (Z_TYPE(ht->arData[idx].val) != IS_UNDEF) {
*pos = idx;
return SUCCESS;
}
}
*pos = HT_INVALID_IDX;
return SUCCESS;
} else {
return FAILURE;
}
}
CWE ID: CWE-190
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int trusted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct trusted_key_payload *p = key->payload.data[0];
struct trusted_key_payload *new_p;
struct trusted_key_options *new_o;
size_t datalen = prep->datalen;
char *datablob;
int ret = 0;
if (!p->migratable)
return -EPERM;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
datablob = kmalloc(datalen + 1, GFP_KERNEL);
if (!datablob)
return -ENOMEM;
new_o = trusted_options_alloc();
if (!new_o) {
ret = -ENOMEM;
goto out;
}
new_p = trusted_payload_alloc(key);
if (!new_p) {
ret = -ENOMEM;
goto out;
}
memcpy(datablob, prep->data, datalen);
datablob[datalen] = '\0';
ret = datablob_parse(datablob, new_p, new_o);
if (ret != Opt_update) {
ret = -EINVAL;
kfree(new_p);
goto out;
}
if (!new_o->keyhandle) {
ret = -EINVAL;
kfree(new_p);
goto out;
}
/* copy old key values, and reseal with new pcrs */
new_p->migratable = p->migratable;
new_p->key_len = p->key_len;
memcpy(new_p->key, p->key, p->key_len);
dump_payload(p);
dump_payload(new_p);
ret = key_seal(new_p, new_o);
if (ret < 0) {
pr_info("trusted_key: key_seal failed (%d)\n", ret);
kfree(new_p);
goto out;
}
if (new_o->pcrlock) {
ret = pcrlock(new_o->pcrlock);
if (ret < 0) {
pr_info("trusted_key: pcrlock failed (%d)\n", ret);
kfree(new_p);
goto out;
}
}
rcu_assign_keypointer(key, new_p);
call_rcu(&p->rcu, trusted_rcu_free);
out:
kfree(datablob);
kfree(new_o);
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: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify(
tCompletePhysicalAddress *pDataPages,
ULONG ulDataLength,
ULONG ulStartOffset,
ULONG flags,
LPCSTR caller)
{
IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset);
tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength);
if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort)
return res;
if (res.ipStatus == ppresIPV4)
{
if (flags & pcrIpChecksum)
res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0);
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV4Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV4Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum));
}
}
}
}
else if (res.ipStatus == ppresIPV6)
{
if(res.xxpStatus == ppresXxpKnown)
{
if (res.TcpUdp == ppresIsTCP) /* TCP */
{
if(flags & pcrTcpV6Checksum)
{
res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum));
}
}
else /* UDP */
{
if (flags & pcrUdpV6Checksum)
{
res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum));
}
}
}
}
PrintOutParsingResult(res, 1, caller);
return res;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: bool RenderBlock::adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo* shapeInsideInfo, LayoutUnit absoluteLogicalTop, LineLayoutState& layoutState, InlineBidiResolver& resolver, FloatingObject* lastFloatFromPreviousLine, InlineIterator& end, WordMeasurements& wordMeasurements)
{
LayoutUnit adjustedLogicalLineTop = adjustLogicalLineTop(shapeInsideInfo, resolver.position(), end, wordMeasurements);
if (!adjustedLogicalLineTop)
return false;
LayoutUnit newLogicalHeight = adjustedLogicalLineTop - absoluteLogicalTop;
if (layoutState.flowThread()) {
layoutState.setAdjustedLogicalLineTop(adjustedLogicalLineTop);
newLogicalHeight = logicalHeight();
}
end = restartLayoutRunsAndFloatsInRange(logicalHeight(), newLogicalHeight, lastFloatFromPreviousLine, resolver, end);
return true;
}
CWE ID: CWE-399
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void fe_netjoin_init(void)
{
settings_add_bool("misc", "hide_netsplit_quits", TRUE);
settings_add_int("misc", "netjoin_max_nicks", 10);
join_tag = -1;
printing_joins = FALSE;
read_settings();
signal_add("setup changed", (SIGNAL_FUNC) read_settings);
}
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: mISDN_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sk_buff *skb;
struct sock *sk = sock->sk;
struct sockaddr_mISDN *maddr;
int copied, err;
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s: len %d, flags %x ch.nr %d, proto %x\n",
__func__, (int)len, flags, _pms(sk)->ch.nr,
sk->sk_protocol);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
if (sk->sk_state == MISDN_CLOSED)
return 0;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
if (msg->msg_namelen >= sizeof(struct sockaddr_mISDN)) {
msg->msg_namelen = sizeof(struct sockaddr_mISDN);
maddr = (struct sockaddr_mISDN *)msg->msg_name;
maddr->family = AF_ISDN;
maddr->dev = _pms(sk)->dev->id;
if ((sk->sk_protocol == ISDN_P_LAPD_TE) ||
(sk->sk_protocol == ISDN_P_LAPD_NT)) {
maddr->channel = (mISDN_HEAD_ID(skb) >> 16) & 0xff;
maddr->tei = (mISDN_HEAD_ID(skb) >> 8) & 0xff;
maddr->sapi = mISDN_HEAD_ID(skb) & 0xff;
} else {
maddr->channel = _pms(sk)->ch.nr;
maddr->sapi = _pms(sk)->ch.addr & 0xFF;
maddr->tei = (_pms(sk)->ch.addr >> 8) & 0xFF;
}
} else {
if (msg->msg_namelen)
printk(KERN_WARNING "%s: too small namelen %d\n",
__func__, msg->msg_namelen);
msg->msg_namelen = 0;
}
copied = skb->len + MISDN_HEADER_LEN;
if (len < copied) {
if (flags & MSG_PEEK)
atomic_dec(&skb->users);
else
skb_queue_head(&sk->sk_receive_queue, skb);
return -ENOSPC;
}
memcpy(skb_push(skb, MISDN_HEADER_LEN), mISDN_HEAD_P(skb),
MISDN_HEADER_LEN);
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
mISDN_sock_cmsg(sk, msg, skb);
skb_free_datagram(sk, skb);
return err ? : copied;
}
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void prb_close_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1,
struct packet_sock *po, unsigned int stat)
{
__u32 status = TP_STATUS_USER | stat;
struct tpacket3_hdr *last_pkt;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
if (po->stats.stats3.tp_drops)
status |= TP_STATUS_LOSING;
last_pkt = (struct tpacket3_hdr *)pkc1->prev;
last_pkt->tp_next_offset = 0;
/* Get the ts of the last pkt */
if (BLOCK_NUM_PKTS(pbd1)) {
h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
} else {
/* Ok, we tmo'd - so get the current time */
struct timespec ts;
getnstimeofday(&ts);
h1->ts_last_pkt.ts_sec = ts.tv_sec;
h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
}
smp_wmb();
/* Flush the block */
prb_flush_block(pkc1, pbd1, status);
pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
}
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 f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)
{
__issue_discard_cmd(sbi, false);
__drop_discard_cmd(sbi);
__wait_discard_cmd(sbi, false);
}
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: HRESULT WaitForLoginUIAndGetResult(
CGaiaCredentialBase::UIProcessInfo* uiprocinfo,
std::string* json_result,
DWORD* exit_code,
BSTR* status_text) {
LOGFN(INFO);
DCHECK(uiprocinfo);
DCHECK(json_result);
DCHECK(exit_code);
DCHECK(status_text);
const int kBufferSize = 4096;
std::vector<char> output_buffer(kBufferSize, '\0');
base::ScopedClosureRunner zero_buffer_on_exit(
base::BindOnce(base::IgnoreResult(&RtlSecureZeroMemory),
&output_buffer[0], kBufferSize));
HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(),
uiprocinfo->parent_handles, exit_code,
&output_buffer[0], kBufferSize);
LOGFN(INFO) << "exit_code=" << exit_code;
if (*exit_code == kUiecAbort) {
LOGFN(ERROR) << "Aborted hr=" << putHR(hr);
return E_ABORT;
} else if (*exit_code != kUiecSuccess) {
LOGFN(ERROR) << "Error hr=" << putHR(hr);
*status_text =
CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE);
return E_FAIL;
}
*json_result = std::string(&output_buffer[0]);
return S_OK;
}
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void get_openreq6(struct seq_file *seq,
struct sock *sk, struct request_sock *req, int i, int uid)
{
int ttd = req->expires - jiffies;
const struct in6_addr *src = &inet6_rsk(req)->loc_addr;
const struct in6_addr *dest = &inet6_rsk(req)->rmt_addr;
if (ttd < 0)
ttd = 0;
seq_printf(seq,
"%4d: %08X%08X%08X%08X:%04X %08X%08X%08X%08X:%04X "
"%02X %08X:%08X %02X:%08lX %08X %5d %8d %d %d %p\n",
i,
src->s6_addr32[0], src->s6_addr32[1],
src->s6_addr32[2], src->s6_addr32[3],
ntohs(inet_rsk(req)->loc_port),
dest->s6_addr32[0], dest->s6_addr32[1],
dest->s6_addr32[2], dest->s6_addr32[3],
ntohs(inet_rsk(req)->rmt_port),
TCP_SYN_RECV,
0,0, /* could print option size, but that is af dependent. */
1, /* timers active (only the expire timer) */
jiffies_to_clock_t(ttd),
req->retrans,
uid,
0, /* non standard timer */
0, /* open_requests have no inode */
0, req);
}
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: GeometryMapper::SourceToDestinationProjectionInternal(
const TransformPaintPropertyNode* source,
const TransformPaintPropertyNode* destination,
bool& success) {
DCHECK(source && destination);
DEFINE_STATIC_LOCAL(TransformationMatrix, identity, (TransformationMatrix()));
DEFINE_STATIC_LOCAL(TransformationMatrix, temp, (TransformationMatrix()));
if (source == destination) {
success = true;
return identity;
}
const GeometryMapperTransformCache& source_cache =
source->GetTransformCache();
const GeometryMapperTransformCache& destination_cache =
destination->GetTransformCache();
if (source_cache.plane_root() == destination_cache.plane_root()) {
success = true;
if (source == destination_cache.plane_root())
return destination_cache.from_plane_root();
if (destination == source_cache.plane_root())
return source_cache.to_plane_root();
temp = destination_cache.from_plane_root();
temp.Multiply(source_cache.to_plane_root());
return temp;
}
if (!destination_cache.projection_from_screen_is_valid()) {
success = false;
return identity;
}
const auto* root = TransformPaintPropertyNode::Root();
success = true;
if (source == root)
return destination_cache.projection_from_screen();
if (destination == root) {
temp = source_cache.to_screen();
} else {
temp = destination_cache.projection_from_screen();
temp.Multiply(source_cache.to_screen());
}
temp.FlattenTo2d();
return temp;
}
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: MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
{
#define EnhanceImageTag "Enhance/Image"
#define EnhancePixel(weight) \
mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \
distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \
distance_squared=(4.0+mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \
distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \
distance_squared+=(7.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \
distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \
distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \
distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \
distance_squared+=(5.0-mean)*distance*distance; \
if (distance_squared < 0.069) \
{ \
aggregate.red+=(weight)*GetPixelRed(image,r); \
aggregate.green+=(weight)*GetPixelGreen(image,r); \
aggregate.blue+=(weight)*GetPixelBlue(image,r); \
aggregate.black+=(weight)*GetPixelBlack(image,r); \
aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \
total_weight+=(weight); \
} \
r+=GetPixelChannels(image);
CacheView
*enhance_view,
*image_view;
Image
*enhance_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize enhanced image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
enhance_image=CloneImage(image,0,0,MagickTrue,
exception);
if (enhance_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse)
{
enhance_image=DestroyImage(enhance_image);
return((Image *) NULL);
}
/*
Enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
enhance_view=AcquireAuthenticCacheView(enhance_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,enhance_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
center;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception);
q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2);
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
distance,
distance_squared,
mean,
total_weight;
PixelInfo
aggregate;
register const Quantum
*magick_restrict r;
GetPixelInfo(image,&aggregate);
total_weight=0.0;
GetPixelInfoPixel(image,p+center,&pixel);
r=p;
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
r=p+GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+2*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0);
EnhancePixel(40.0); EnhancePixel(10.0);
r=p+3*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+4*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
if (total_weight > MagickEpsilon)
{
pixel.red=((aggregate.red+total_weight/2.0)/total_weight);
pixel.green=((aggregate.green+total_weight/2.0)/total_weight);
pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight);
pixel.black=((aggregate.black+total_weight/2.0)/total_weight);
pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight);
}
SetPixelViaPixelInfo(image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(enhance_image);
}
if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
enhance_view=DestroyCacheView(enhance_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
enhance_image=DestroyImage(enhance_image);
return(enhance_image);
}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int nfs4_xdr_enc_open_noattr(struct rpc_rqst *req, __be32 *p, struct nfs_openargs *args)
{
struct xdr_stream xdr;
struct compound_hdr hdr = {
.nops = 3,
};
int status;
xdr_init_encode(&xdr, &req->rq_snd_buf, p);
encode_compound_hdr(&xdr, &hdr);
status = encode_putfh(&xdr, args->fh);
if (status)
goto out;
status = encode_open(&xdr, args);
if (status)
goto out;
status = encode_getfattr(&xdr, args->bitmask);
out:
return status;
}
CWE ID:
Target: 0
Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void ifb_setup(struct net_device *dev)
{
/* Initialize the device structure. */
dev->destructor = free_netdev;
dev->netdev_ops = &ifb_netdev_ops;
/* Fill in device structure with ethernet-generic values. */
ether_setup(dev);
dev->tx_queue_len = TX_Q_LIMIT;
dev->features |= IFB_FEATURES;
dev->vlan_features |= IFB_FEATURES;
dev->flags |= IFF_NOARP;
dev->flags &= ~IFF_MULTICAST;
dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
random_ether_addr(dev->dev_addr);
}
CWE ID: CWE-264
Output: | 1 |
Subsets and Splits