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: selaGetCombName(SELA *sela, l_int32 size, l_int32 direction) { char *selname; char combname[L_BUF_SIZE]; l_int32 i, nsels, sx, sy, found; SEL *sel; PROCNAME("selaGetCombName"); if (!sela) return (char *)ERROR_PTR("sela not defined", procName, NULL); if (direction != L_HORIZ && direction != L_VERT) return (char *)ERROR_PTR("invalid direction", procName, NULL); /* Derive the comb name we're looking for */ if (direction == L_HORIZ) snprintf(combname, L_BUF_SIZE, "sel_comb_%dh", size); else /* direction == L_VERT */ snprintf(combname, L_BUF_SIZE, "sel_comb_%dv", size); found = FALSE; nsels = selaGetCount(sela); for (i = 0; i < nsels; i++) { sel = selaGetSel(sela, i); selGetParameters(sel, &sy, &sx, NULL, NULL); if (sy != 1 && sx != 1) /* 2-D; not a comb */ continue; selname = selGetName(sel); if (!strcmp(selname, combname)) { found = TRUE; break; } } if (found) return stringNew(selname); else return (char *)ERROR_PTR("sel not found", procName, NULL); } CWE ID: CWE-119 Target: 1 Example 2: Code: void JBIG2Stream::readProfilesSeg(Guint length) { Guint i; for (i = 0; i < length; ++i) { curStr->getChar(); } } 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: rend_service_update_descriptor(rend_service_t *service) { rend_service_descriptor_t *d; origin_circuit_t *circ; int i; rend_service_descriptor_free(service->desc); service->desc = NULL; d = service->desc = tor_malloc_zero(sizeof(rend_service_descriptor_t)); d->pk = crypto_pk_dup_key(service->private_key); d->timestamp = time(NULL); d->timestamp -= d->timestamp % 3600; /* Round down to nearest hour */ d->intro_nodes = smartlist_new(); /* Support intro protocols 2 and 3. */ d->protocols = (1 << 2) + (1 << 3); for (i = 0; i < smartlist_len(service->intro_nodes); ++i) { rend_intro_point_t *intro_svc = smartlist_get(service->intro_nodes, i); rend_intro_point_t *intro_desc; /* This intro point won't be listed in the descriptor... */ intro_svc->listed_in_last_desc = 0; circ = find_intro_circuit(intro_svc, service->pk_digest); if (!circ || circ->base_.purpose != CIRCUIT_PURPOSE_S_INTRO) { /* This intro point's circuit isn't finished yet. Don't list it. */ continue; } /* ...unless this intro point is listed in the descriptor. */ intro_svc->listed_in_last_desc = 1; /* We have an entirely established intro circuit. Publish it in * our descriptor. */ intro_desc = tor_malloc_zero(sizeof(rend_intro_point_t)); intro_desc->extend_info = extend_info_dup(intro_svc->extend_info); if (intro_svc->intro_key) intro_desc->intro_key = crypto_pk_dup_key(intro_svc->intro_key); smartlist_add(d->intro_nodes, intro_desc); if (intro_svc->time_published == -1) { /* We are publishing this intro point in a descriptor for the * first time -- note the current time in the service's copy of * the intro point. */ intro_svc->time_published = time(NULL); } } } CWE ID: CWE-532 Output:
0
Here are some example code snippets. Analyze the following 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 char *pool_strdup(const char *s) { char *r = pool_alloc(strlen(s) + 1); strcpy(r, s); return r; } CWE ID: CWE-119 Target: 1 Example 2: Code: control_persist_detach(void) { pid_t pid; int devnull; debug("%s: backgrounding master process", __func__); /* * master (current process) into the background, and make the * foreground process a client of the backgrounded master. */ switch ((pid = fork())) { case -1: fatal("%s: fork: %s", __func__, strerror(errno)); case 0: /* Child: master process continues mainloop */ break; default: /* Parent: set up mux slave to connect to backgrounded master */ debug2("%s: background process is %ld", __func__, (long)pid); stdin_null_flag = ostdin_null_flag; options.request_tty = orequest_tty; tty_flag = otty_flag; close(muxserver_sock); muxserver_sock = -1; options.control_master = SSHCTL_MASTER_NO; muxclient(options.control_path); /* muxclient() doesn't return on success. */ fatal("Failed to connect to new control master"); } if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) { error("%s: open(\"/dev/null\"): %s", __func__, strerror(errno)); } else { if (dup2(devnull, STDIN_FILENO) == -1 || dup2(devnull, STDOUT_FILENO) == -1) error("%s: dup2: %s", __func__, strerror(errno)); if (devnull > STDERR_FILENO) close(devnull); } daemon(1, 1); setproctitle("%s [mux]", options.control_path); } 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: OMX_ERRORTYPE SoftMPEG4Encoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (bitRate->nPortIndex != 1 || bitRate->eControlRate != OMX_Video_ControlRateVariable) { return OMX_ErrorUndefined; } mBitrate = bitRate->nTargetBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE *h263type = (OMX_VIDEO_PARAM_H263TYPE *)params; if (h263type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (h263type->eProfile != OMX_VIDEO_H263ProfileBaseline || h263type->eLevel != OMX_VIDEO_H263Level45 || (h263type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || h263type->bPLUSPTYPEAllowed != OMX_FALSE || h263type->bForceRoundingTypeToZero != OMX_FALSE || h263type->nPictureHeaderRepetition != 0 || h263type->nGOBHeaderInterval != 0) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type = (OMX_VIDEO_PARAM_MPEG4TYPE *)params; if (mpeg4type->nPortIndex != 1) { return OMX_ErrorUndefined; } if (mpeg4type->eProfile != OMX_VIDEO_MPEG4ProfileCore || mpeg4type->eLevel != OMX_VIDEO_MPEG4Level2 || (mpeg4type->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) || mpeg4type->nBFrames != 0 || mpeg4type->nIDCVLCThreshold != 0 || mpeg4type->bACPred != OMX_TRUE || mpeg4type->nMaxPacketSize != 256 || mpeg4type->nTimeIncRes != 1000 || mpeg4type->nHeaderExtension != 0 || mpeg4type->bReversibleVLC != OMX_FALSE) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } } 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: long Cluster::CreateSimpleBlock( long long st, long long sz) { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count >= 0); assert(m_entries_count < m_entries_size); const long idx = m_entries_count; BlockEntry** const ppEntry = m_entries + idx; BlockEntry*& pEntry = *ppEntry; pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz); if (pEntry == NULL) return -1; //generic error SimpleBlock* const p = static_cast<SimpleBlock*>(pEntry); const long status = p->Parse(); if (status == 0) { ++m_entries_count; return 0; } delete pEntry; pEntry = 0; return status; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool PermissionPromptImpl::CanAcceptRequestUpdate() { return !(bubble_delegate_ && bubble_delegate_->IsMouseHovered()); } 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: ContentEncoding::GetCompressionByIndex(unsigned long idx) const { const ptrdiff_t count = compression_entries_end_ - compression_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return compression_entries_[idx]; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DeviceTokenFetcher::StopAutoRetry() { scheduler_->CancelDelayedWork(); backend_.reset(); } CWE ID: CWE-399 Target: 1 Example 2: Code: static void opj_tcd_code_block_dec_deallocate(opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno, l_nb_code_blocks; opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec; if (l_code_block) { /*fprintf(stderr,"deallocate codeblock:{\n");*/ /*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/ /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ", l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/ l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t); /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/ for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { opj_free(l_code_block->data); l_code_block->data = 00; } if (l_code_block->segs) { opj_free(l_code_block->segs); l_code_block->segs = 00; } ++l_code_block; } opj_free(p_precinct->cblks.dec); p_precinct->cblks.dec = 00; } } 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: file_ms_free(struct magic_set *ms) { size_t i; if (ms == NULL) return; for (i = 0; i < MAGIC_SETS; i++) mlist_free(ms->mlist[i]); free(ms->o.pbuf); free(ms->o.buf); free(ms->c.li); free(ms); } 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 WebGLRenderingContextBase::TexImageHelperDOMArrayBufferView( TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, DOMArrayBufferView* pixels, NullDisposition null_disposition, GLuint src_offset) { const char* func_name = GetTexImageFunctionName(function_id); if (isContextLost()) return; if (!ValidateTexImageBinding(func_name, function_id, target)) return; TexImageFunctionType function_type; if (function_id == kTexImage2D || function_id == kTexImage3D) function_type = kTexImage; else function_type = kTexSubImage; if (!ValidateTexFunc(func_name, function_type, kSourceArrayBufferView, target, level, internalformat, width, height, depth, border, format, type, xoffset, yoffset, zoffset)) return; TexImageDimension source_type; if (function_id == kTexImage2D || function_id == kTexSubImage2D) source_type = kTex2D; else source_type = kTex3D; if (!ValidateTexFuncData(func_name, source_type, level, width, height, depth, format, type, pixels, null_disposition, src_offset)) return; uint8_t* data = reinterpret_cast<uint8_t*>( pixels ? pixels->BaseAddressMaybeShared() : nullptr); if (src_offset) { DCHECK(pixels); data += src_offset * pixels->TypeSize(); } Vector<uint8_t> temp_data; bool change_unpack_alignment = false; if (data && (unpack_flip_y_ || unpack_premultiply_alpha_)) { if (source_type == kTex2D) { if (!WebGLImageConversion::ExtractTextureData( width, height, format, type, unpack_alignment_, unpack_flip_y_, unpack_premultiply_alpha_, data, temp_data)) { SynthesizeGLError(GL_INVALID_OPERATION, func_name, "Invalid format/type combination."); return; } data = temp_data.data(); } change_unpack_alignment = true; } ContextGL()->TexImage3D(target, level, ConvertTexInternalFormat(internalformat, type), width, height, depth, border, format, type, data); return; } if (function_id == kTexSubImage3D) { ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, data); return; } ScopedUnpackParametersResetRestore temporary_reset_unpack( this, change_unpack_alignment); if (function_id == kTexImage2D) TexImage2DBase(target, level, internalformat, width, height, border, format, type, data); else if (function_id == kTexSubImage2D) ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, data); } CWE ID: CWE-125 Target: 1 Example 2: Code: static int __split_huge_page_map(struct page *page, struct vm_area_struct *vma, unsigned long address) { struct mm_struct *mm = vma->vm_mm; pmd_t *pmd, _pmd; int ret = 0, i; pgtable_t pgtable; unsigned long haddr; spin_lock(&mm->page_table_lock); pmd = page_check_address_pmd(page, mm, address, PAGE_CHECK_ADDRESS_PMD_SPLITTING_FLAG); if (pmd) { pgtable = get_pmd_huge_pte(mm); pmd_populate(mm, &_pmd, pgtable); for (i = 0, haddr = address; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) { pte_t *pte, entry; BUG_ON(PageCompound(page+i)); entry = mk_pte(page + i, vma->vm_page_prot); entry = maybe_mkwrite(pte_mkdirty(entry), vma); if (!pmd_write(*pmd)) entry = pte_wrprotect(entry); else BUG_ON(page_mapcount(page) != 1); if (!pmd_young(*pmd)) entry = pte_mkold(entry); pte = pte_offset_map(&_pmd, haddr); BUG_ON(!pte_none(*pte)); set_pte_at(mm, haddr, pte, entry); pte_unmap(pte); } mm->nr_ptes++; smp_wmb(); /* make pte visible before pmd */ /* * Up to this point the pmd is present and huge and * userland has the whole access to the hugepage * during the split (which happens in place). If we * overwrite the pmd with the not-huge version * pointing to the pte here (which of course we could * if all CPUs were bug free), userland could trigger * a small page size TLB miss on the small sized TLB * while the hugepage TLB entry is still established * in the huge TLB. Some CPU doesn't like that. See * http://support.amd.com/us/Processor_TechDocs/41322.pdf, * Erratum 383 on page 93. Intel should be safe but is * also warns that it's only safe if the permission * and cache attributes of the two entries loaded in * the two TLB is identical (which should be the case * here). But it is generally safer to never allow * small and huge TLB entries for the same virtual * address to be loaded simultaneously. So instead of * doing "pmd_populate(); flush_tlb_range();" we first * mark the current pmd notpresent (atomically because * here the pmd_trans_huge and pmd_trans_splitting * must remain set at all times on the pmd until the * split is complete for this pmd), then we flush the * SMP TLB and finally we write the non-huge version * of the pmd entry with pmd_populate. */ set_pmd_at(mm, address, pmd, pmd_mknotpresent(*pmd)); flush_tlb_range(vma, address, address + HPAGE_PMD_SIZE); pmd_populate(mm, pmd, pgtable); ret = 1; } spin_unlock(&mm->page_table_lock); return ret; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ChromeExtensionWebContentsObserver::ChromeExtensionWebContentsObserver( content::WebContents* web_contents) : ExtensionWebContentsObserver(web_contents) {} 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: TabsCustomBindings::TabsCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("OpenChannelToTab", base::Bind(&TabsCustomBindings::OpenChannelToTab, base::Unretained(this))); } CWE ID: CWE-284 Target: 1 Example 2: Code: TestHistoryWebFrameClient() { m_replacesCurrentHistoryItem = false; m_frame = 0; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static ssize_t write_kmem(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { unsigned long p = *ppos; ssize_t wrote = 0; ssize_t virtr = 0; char *kbuf; /* k-addr because vwrite() takes vmlist_lock rwlock */ int err = 0; if (p < (unsigned long) high_memory) { unsigned long to_write = min_t(unsigned long, count, (unsigned long)high_memory - p); wrote = do_write_kmem(p, buf, to_write, ppos); if (wrote != to_write) return wrote; p += wrote; buf += wrote; count -= wrote; } if (count > 0) { kbuf = (char *)__get_free_page(GFP_KERNEL); if (!kbuf) return wrote ? wrote : -ENOMEM; while (count > 0) { unsigned long sz = size_inside_page(p, count); unsigned long n; if (!is_vmalloc_or_module_addr((void *)p)) { err = -ENXIO; break; } n = copy_from_user(kbuf, buf, sz); if (n) { err = -EFAULT; break; } vwrite(kbuf, (char *)p, sz); count -= sz; buf += sz; virtr += sz; p += sz; } free_page((unsigned long)kbuf); } *ppos = p; return virtr + wrote ? : err; } CWE ID: CWE-732 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static EAS_RESULT Parse_wave (SDLS_SYNTHESIZER_DATA *pDLSData, EAS_I32 pos, EAS_U16 waveIndex) { EAS_RESULT result; EAS_U32 temp; EAS_I32 size; EAS_I32 endChunk; EAS_I32 chunkPos; EAS_I32 wsmpPos = 0; EAS_I32 fmtPos = 0; EAS_I32 dataPos = 0; EAS_I32 dataSize = 0; S_WSMP_DATA *p; void *pSample; S_WSMP_DATA wsmp; /* seek to start of chunk */ chunkPos = pos + 12; if ((result = EAS_HWFileSeek(pDLSData->hwInstData, pDLSData->fileHandle, pos)) != EAS_SUCCESS) return result; /* get the chunk type */ if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS) return result; /* make sure it is a wave chunk */ if (temp != CHUNK_WAVE) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Offset in ptbl does not point to wave chunk\n"); */ } return EAS_ERROR_FILE_FORMAT; } /* read to end of chunk */ pos = chunkPos; endChunk = pos + size; while (pos < endChunk) { chunkPos = pos; /* get the chunk type */ if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS) return result; /* parse useful chunks */ switch (temp) { case CHUNK_WSMP: wsmpPos = chunkPos + 8; break; case CHUNK_FMT: fmtPos = chunkPos + 8; break; case CHUNK_DATA: dataPos = chunkPos + 8; dataSize = size; break; default: break; } } if (dataSize > MAX_DLS_WAVE_SIZE) { return EAS_ERROR_SOUND_LIBRARY; } /* for first pass, use temporary variable */ if (pDLSData->pDLS == NULL) p = &wsmp; else p = &pDLSData->wsmpData[waveIndex]; /* set the defaults */ p->fineTune = 0; p->unityNote = 60; p->gain = 0; p->loopStart = 0; p->loopLength = 0; /* must have a fmt chunk */ if (!fmtPos) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no fmt chunk\n"); */ } return EAS_ERROR_UNRECOGNIZED_FORMAT; } /* must have a data chunk */ if (!dataPos) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no data chunk\n"); */ } return EAS_ERROR_UNRECOGNIZED_FORMAT; } /* parse the wsmp chunk */ if (wsmpPos) { if ((result = Parse_wsmp(pDLSData, wsmpPos, p)) != EAS_SUCCESS) return result; } /* parse the fmt chunk */ if ((result = Parse_fmt(pDLSData, fmtPos, p)) != EAS_SUCCESS) return result; /* calculate the size of the wavetable needed. We need only half * the memory for 16-bit samples when in 8-bit mode, and we need * double the memory for 8-bit samples in 16-bit mode. For * unlooped samples, we may use ADPCM. If so, we need only 1/4 * the memory. * * We also need to add one for looped samples to allow for * the first sample to be copied to the end of the loop. */ /* use ADPCM encode for unlooped 16-bit samples if ADPCM is enabled */ /*lint -e{506} -e{774} groundwork for future version to support 8 & 16 bit */ if (bitDepth == 8) { if (p->bitsPerSample == 8) size = dataSize; else /*lint -e{704} use shift for performance */ size = dataSize >> 1; if (p->loopLength) size++; } else { if (p->bitsPerSample == 16) size = dataSize; else /*lint -e{703} use shift for performance */ size = dataSize << 1; if (p->loopLength) size += 2; } /* for first pass, add size to wave pool size and return */ if (pDLSData->pDLS == NULL) { pDLSData->wavePoolSize += (EAS_U32) size; return EAS_SUCCESS; } /* allocate memory and read in the sample data */ pSample = pDLSData->pDLS->pDLSSamples + pDLSData->wavePoolOffset; pDLSData->pDLS->pDLSSampleOffsets[waveIndex] = pDLSData->wavePoolOffset; pDLSData->pDLS->pDLSSampleLen[waveIndex] = (EAS_U32) size; pDLSData->wavePoolOffset += (EAS_U32) size; if (pDLSData->wavePoolOffset > pDLSData->wavePoolSize) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Wave pool exceeded allocation\n"); */ } return EAS_ERROR_SOUND_LIBRARY; } if ((result = Parse_data(pDLSData, dataPos, dataSize, p, pSample)) != EAS_SUCCESS) return result; return EAS_SUCCESS; } CWE ID: CWE-189 Target: 1 Example 2: Code: static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val) { return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val, sizeof(*val)); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static 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; 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-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: InputHandlerProxy::InputHandlerProxy(cc::InputHandler* input_handler, InputHandlerProxyClient* client, bool force_input_to_main_thread) : client_(client), input_handler_(input_handler), synchronous_input_handler_(nullptr), allow_root_animate_(true), #if DCHECK_IS_ON() expect_scroll_update_end_(false), #endif gesture_scroll_on_impl_thread_(false), scroll_sequence_ignored_(false), smooth_scroll_enabled_(false), touch_result_(kEventDispositionUndefined), mouse_wheel_result_(kEventDispositionUndefined), current_overscroll_params_(nullptr), has_ongoing_compositor_scroll_or_pinch_(false), is_first_gesture_scroll_update_(false), last_injected_gesture_was_begin_(false), tick_clock_(base::DefaultTickClock::GetInstance()), snap_fling_controller_(std::make_unique<cc::SnapFlingController>(this)), compositor_touch_action_enabled_( base::FeatureList::IsEnabled(features::kCompositorTouchAction)), force_input_to_main_thread_(force_input_to_main_thread) { DCHECK(client); input_handler_->BindToClient(this); cc::ScrollElasticityHelper* scroll_elasticity_helper = input_handler_->CreateScrollElasticityHelper(); if (scroll_elasticity_helper) { scroll_elasticity_controller_.reset( new InputScrollElasticityController(scroll_elasticity_helper)); } compositor_event_queue_ = std::make_unique<CompositorThreadEventQueue>(); scroll_predictor_ = std::make_unique<ScrollPredictor>( base::FeatureList::IsEnabled(features::kResamplingScrollEvents)); if (base::FeatureList::IsEnabled(features::kSkipTouchEventFilter) && GetFieldTrialParamValueByFeature( features::kSkipTouchEventFilter, features::kSkipTouchEventFilterFilteringProcessParamName) == features:: kSkipTouchEventFilterFilteringProcessParamValueBrowserAndRenderer) { skip_touch_filter_discrete_ = true; if (GetFieldTrialParamValueByFeature( features::kSkipTouchEventFilter, features::kSkipTouchEventFilterTypeParamName) == features::kSkipTouchEventFilterTypeParamValueAll) { skip_touch_filter_all_ = true; } } } CWE ID: CWE-281 Target: 1 Example 2: Code: static void cryptd_blkcipher_encrypt(struct crypto_async_request *req, int err) { struct cryptd_blkcipher_ctx *ctx = crypto_tfm_ctx(req->tfm); struct crypto_blkcipher *child = ctx->child; cryptd_blkcipher_crypt(ablkcipher_request_cast(req), child, err, crypto_blkcipher_crt(child)->encrypt); } 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 Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl) { if (equalIgnoringCase(dnsPrefetchControl, "on") && !m_haveExplicitlyDisabledDNSPrefetch) { m_isDNSPrefetchEnabled = true; return; } m_isDNSPrefetchEnabled = false; m_haveExplicitlyDisabledDNSPrefetch = true; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: vrrp_print_data(void) { FILE *file = fopen (dump_file, "w"); if (!file) { log_message(LOG_INFO, "Can't open %s (%d: %s)", dump_file, errno, strerror(errno)); return; } dump_data_vrrp(file); fclose(file); } CWE ID: CWE-59 Target: 1 Example 2: Code: static int oprep(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; LookupTable *lt_ptr; int retval; if (!strcmp (op->mnemonic, "rep") || !strcmp (op->mnemonic, "repe") || !strcmp (op->mnemonic, "repz")) { data[l++] = 0xf3; } else if (!strcmp (op->mnemonic, "repne") || !strcmp (op->mnemonic, "repnz")) { data[l++] = 0xf2; } Opcode instr = {0}; parseOpcode (a, op->operands[0].rep_op, &instr); for (lt_ptr = oplookup; strcmp (lt_ptr->mnemonic, "null"); lt_ptr++) { if (!r_str_casecmp (instr.mnemonic, lt_ptr->mnemonic)) { if (lt_ptr->opcode > 0) { if (lt_ptr->only_x32 && a->bits == 64) { free (instr.mnemonic); return -1; } ut8 *ptr = (ut8 *)&lt_ptr->opcode; int i = 0; for (; i < lt_ptr->size; i++) { data[i + l] = ptr[lt_ptr->size - (i + 1)]; } free (instr.mnemonic); return l + lt_ptr->size; } else { if (lt_ptr->opdo) { data += l; if (instr.has_bnd) { data[l] = 0xf2; data++; } retval = lt_ptr->opdo (a, data, &instr); if (instr.has_bnd) { retval++; } return l + retval; } break; } } } free (instr.mnemonic); return -1; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item ) { cJSON_AddItemToObject( object, string, create_reference( item ) ); } 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: DeviceOrientationController::DeviceOrientationController(Document* document) : DeviceSensorEventController(document) , DOMWindowLifecycleObserver(document->domWindow()) { } CWE ID: Target: 1 Example 2: Code: xfs_da3_node_read_verify( struct xfs_buf *bp) { struct xfs_mount *mp = bp->b_target->bt_mount; struct xfs_da_blkinfo *info = bp->b_addr; switch (be16_to_cpu(info->magic)) { case XFS_DA3_NODE_MAGIC: if (!xfs_verify_cksum(bp->b_addr, BBTOB(bp->b_length), XFS_DA3_NODE_CRC_OFF)) break; /* fall through */ case XFS_DA_NODE_MAGIC: if (!xfs_da3_node_verify(bp)) break; return; case XFS_ATTR_LEAF_MAGIC: case XFS_ATTR3_LEAF_MAGIC: bp->b_ops = &xfs_attr3_leaf_buf_ops; bp->b_ops->verify_read(bp); return; case XFS_DIR2_LEAFN_MAGIC: case XFS_DIR3_LEAFN_MAGIC: bp->b_ops = &xfs_dir3_leafn_buf_ops; bp->b_ops->verify_read(bp); return; default: break; } /* corrupt block */ XFS_CORRUPTION_ERROR(__func__, XFS_ERRLEVEL_LOW, mp, bp->b_addr); xfs_buf_ioerror(bp, EFSCORRUPTED); } 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 hash_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; msg->msg_namelen = 0; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_toiovec(msg->msg_iov, ctx->result, len); unlock: release_sock(sk); return err ?: len; } 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 char *print_string( cJSON *item ) { return print_string_ptr( item->valuestring ); } CWE ID: CWE-119 Target: 1 Example 2: Code: void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { mdct_lookup *M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } 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: NavigationPolicy GetNavigationPolicy(const WebInputEvent* current_event, const WebWindowFeatures& features) { //// Check that the desired NavigationPolicy |policy| is compatible with the //// observed input event |current_event|. bool as_popup = !features.tool_bar_visible || !features.status_bar_visible || !features.scrollbars_visible || !features.menu_bar_visible || !features.resizable; NavigationPolicy policy = as_popup ? kNavigationPolicyNewPopup : kNavigationPolicyNewForegroundTab; UpdatePolicyForEvent(current_event, &policy); return policy; } 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: cJSON *cJSON_CreateBool( int b ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = b ? cJSON_True : cJSON_False; return item; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void ip_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_copy(to, from); to->dev = from->dev; to->mark = from->mark; /* Copy the flags to each fragment. */ IPCB(to)->flags = IPCB(from)->flags; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); #if defined(CONFIG_NETFILTER_XT_TARGET_TRACE) || \ defined(CONFIG_NETFILTER_XT_TARGET_TRACE_MODULE) to->nf_trace = from->nf_trace; #endif #if defined(CONFIG_IP_VS) || defined(CONFIG_IP_VS_MODULE) to->ipvs_property = from->ipvs_property; #endif skb_copy_secmark(to, from); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline bool is_flush_request(struct request *rq, struct blk_flush_queue *fq, unsigned int tag) { return ((rq->cmd_flags & REQ_FLUSH_SEQ) && fq->flush_rq->tag == tag); } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct unix_sock *u = unix_sk(sk); DECLARE_SOCKADDR(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 scm; int max_level; int data_len = 0; wait_for_unix_gc(); err = scm_send(sock, msg, &scm, false); 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); data_len = PAGE_ALIGN(data_len); BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE); } skb = sock_alloc_send_pskb(sk, len - data_len, data_len, msg->msg_flags & MSG_DONTWAIT, &err, PAGE_ALLOC_COSTLY_ORDER); if (skb == NULL) goto out; err = unix_scm_to_skb(&scm, skb, true); if (err < 0) goto out_free; max_level = err + 1; skb_put(skb, len - data_len); skb->data_len = data_len; skb->len = len; err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, 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); sock_put(other); scm_destroy(&scm); return len; out_unlock: unix_state_unlock(other); out_free: kfree_skb(skb); out: if (other) sock_put(other); scm_destroy(&scm); return err; } CWE ID: Target: 1 Example 2: Code: void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *cons, struct irq_bypass_producer *prod) { int ret; struct kvm_kernel_irqfd *irqfd = container_of(cons, struct kvm_kernel_irqfd, consumer); if (!kvm_x86_ops->update_pi_irte) { WARN_ON(irqfd->producer != NULL); return; } WARN_ON(irqfd->producer != prod); irqfd->producer = NULL; /* * When producer of consumer is unregistered, we change back to * remapped mode, so we can re-use the current implementation * when the irq is masked/disabed or the consumer side (KVM * int this case doesn't want to receive the interrupts. */ ret = kvm_x86_ops->update_pi_irte(irqfd->kvm, prod->irq, irqfd->gsi, 0); if (ret) printk(KERN_INFO "irq bypass consumer (token %p) unregistration" " fails: %d\n", irqfd->consumer.token, ret); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: std::unique_ptr<base::DictionaryValue> ParsePrintSettings( int command_id, const base::DictionaryValue* params, HeadlessPrintSettings* settings) { if (const base::Value* landscape_value = params->FindKey("landscape")) settings->landscape = landscape_value->GetBool(); if (const base::Value* display_header_footer_value = params->FindKey("displayHeaderFooter")) { settings->display_header_footer = display_header_footer_value->GetBool(); } if (const base::Value* should_print_backgrounds_value = params->FindKey("printBackground")) { settings->should_print_backgrounds = should_print_backgrounds_value->GetBool(); } if (const base::Value* scale_value = params->FindKey("scale")) settings->scale = scale_value->GetDouble(); if (settings->scale > kScaleMaxVal / 100 || settings->scale < kScaleMinVal / 100) return CreateInvalidParamResponse(command_id, "scale"); if (const base::Value* page_ranges_value = params->FindKey("pageRanges")) settings->page_ranges = page_ranges_value->GetString(); if (const base::Value* ignore_invalid_page_ranges_value = params->FindKey("ignoreInvalidPageRanges")) { settings->ignore_invalid_page_ranges = ignore_invalid_page_ranges_value->GetBool(); } double paper_width_in_inch = printing::kLetterWidthInch; if (const base::Value* paper_width_value = params->FindKey("paperWidth")) paper_width_in_inch = paper_width_value->GetDouble(); double paper_height_in_inch = printing::kLetterHeightInch; if (const base::Value* paper_height_value = params->FindKey("paperHeight")) paper_height_in_inch = paper_height_value->GetDouble(); if (paper_width_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperWidth"); if (paper_height_in_inch <= 0) return CreateInvalidParamResponse(command_id, "paperHeight"); settings->paper_size_in_points = gfx::Size(paper_width_in_inch * printing::kPointsPerInch, paper_height_in_inch * printing::kPointsPerInch); double default_margin_in_inch = 1000.0 / printing::kHundrethsMMPerInch; double margin_top_in_inch = default_margin_in_inch; double margin_bottom_in_inch = default_margin_in_inch; double margin_left_in_inch = default_margin_in_inch; double margin_right_in_inch = default_margin_in_inch; if (const base::Value* margin_top_value = params->FindKey("marginTop")) margin_top_in_inch = margin_top_value->GetDouble(); if (const base::Value* margin_bottom_value = params->FindKey("marginBottom")) margin_bottom_in_inch = margin_bottom_value->GetDouble(); if (const base::Value* margin_left_value = params->FindKey("marginLeft")) margin_left_in_inch = margin_left_value->GetDouble(); if (const base::Value* margin_right_value = params->FindKey("marginRight")) margin_right_in_inch = margin_right_value->GetDouble(); if (margin_top_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginTop"); if (margin_bottom_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginBottom"); if (margin_left_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginLeft"); if (margin_right_in_inch < 0) return CreateInvalidParamResponse(command_id, "marginRight"); settings->margins_in_points.top = margin_top_in_inch * printing::kPointsPerInch; settings->margins_in_points.bottom = margin_bottom_in_inch * printing::kPointsPerInch; settings->margins_in_points.left = margin_left_in_inch * printing::kPointsPerInch; settings->margins_in_points.right = margin_right_in_inch * printing::kPointsPerInch; return nullptr; } 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: ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_n *p; struct ikev1_pl_n n; const u_char *cp; const u_char *ep2; uint32_t doi; uint32_t proto; static const char *notify_error_str[] = { NULL, "INVALID-PAYLOAD-TYPE", "DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED", "INVALID-COOKIE", "INVALID-MAJOR-VERSION", "INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE", "INVALID-FLAGS", "INVALID-MESSAGE-ID", "INVALID-PROTOCOL-ID", "INVALID-SPI", "INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED", "NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX", "PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION", "INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING", "INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED", "INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION", "AUTHENTICATION-FAILED", "INVALID-SIGNATURE", "ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME", "CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE", "UNEQUAL-PAYLOAD-LENGTHS", }; static const char *ipsec_notify_error_str[] = { "RESERVED", }; static const char *notify_status_str[] = { "CONNECTED", }; static const char *ipsec_notify_status_str[] = { "RESPONDER-LIFETIME", "REPLAY-STATUS", "INITIAL-CONTACT", }; /* NOTE: these macro must be called with x in proper range */ /* 0 - 8191 */ #define NOTIFY_ERROR_STR(x) \ STR_OR_ID((x), notify_error_str) /* 8192 - 16383 */ #define IPSEC_NOTIFY_ERROR_STR(x) \ STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) /* 16384 - 24575 */ #define NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 16384), notify_status_str) /* 24576 - 32767 */ #define IPSEC_NOTIFY_STATUS_STR(x) \ STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N))); p = (const struct ikev1_pl_n *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&n, ext, sizeof(n)); doi = ntohl(n.doi); proto = n.prot_id; if (doi != 1) { ND_PRINT((ndo," doi=%d", doi)); ND_PRINT((ndo," proto=%d", proto)); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } return (const u_char *)(p + 1) + n.spi_size; } ND_PRINT((ndo," doi=ipsec")); ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto))); if (ntohs(n.type) < 8192) ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 16384) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); else if (ntohs(n.type) < 24576) ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type)))); else if (ntohs(n.type) < 32768) ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); else ND_PRINT((ndo," type=%s", numstr(ntohs(n.type)))); if (n.spi_size) { ND_PRINT((ndo," spi=")); if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) goto trunc; } cp = (const u_char *)(p + 1) + n.spi_size; ep2 = (const u_char *)p + item_len; if (cp < ep) { switch (ntohs(n.type)) { case IPSECDOI_NTYPE_RESPONDER_LIFETIME: { const struct attrmap *map = oakley_t_map; size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); ND_PRINT((ndo," attrs=(")); while (cp < ep && cp < ep2) { cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); if (cp == NULL) { ND_PRINT((ndo,")")); goto trunc; } } ND_PRINT((ndo,")")); break; } case IPSECDOI_NTYPE_REPLAY_STATUS: ND_PRINT((ndo," status=(")); ND_PRINT((ndo,"replay detection %sabled", EXTRACT_32BITS(cp) ? "en" : "dis")); ND_PRINT((ndo,")")); break; default: /* * XXX - fill in more types here; see, for example, * draft-ietf-ipsec-notifymsg-04. */ if (ndo->ndo_vflag > 3) { ND_PRINT((ndo," data=(")); if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) goto trunc; ND_PRINT((ndo,")")); } else { if (!ike_show_somedata(ndo, cp, ep)) goto trunc; } break; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N))); return NULL; } CWE ID: CWE-125 Target: 1 Example 2: Code: void AutofillManager::OnSetDataList(const std::vector<base::string16>& values, const std::vector<base::string16>& labels) { if (!IsValidString16Vector(values) || !IsValidString16Vector(labels) || values.size() != labels.size()) return; external_delegate_->SetCurrentDataListValues(values, labels); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: t42_parse_sfnts( T42_Face face, T42_Loader loader ) { T42_Parser parser = &loader->parser; FT_Memory memory = parser->root.memory; FT_Byte* cur; FT_Byte* limit = parser->root.limit; FT_Error error; FT_Int num_tables = 0; FT_ULong count, ttf_size = 0; FT_Long n, string_size, old_string_size, real_size; FT_Byte* string_buf = NULL; FT_Bool allocated = 0; T42_Load_Status status; /* The format is */ /* */ /* /sfnts [ <hexstring> <hexstring> ... ] def */ /* */ /* or */ /* */ /* /sfnts [ */ /* <num_bin_bytes> RD <binary data> */ /* <num_bin_bytes> RD <binary data> */ /* ... */ /* ] def */ /* */ /* with exactly one space after the `RD' token. */ T1_Skip_Spaces( parser ); if ( parser->root.cursor >= limit || *parser->root.cursor++ != '[' ) { FT_ERROR(( "t42_parse_sfnts: can't find begin of sfnts vector\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } T1_Skip_Spaces( parser ); status = BEFORE_START; string_size = 0; old_string_size = 0; count = 0; while ( parser->root.cursor < limit ) { cur = parser->root.cursor; if ( *cur == ']' ) { parser->root.cursor++; goto Exit; } else if ( *cur == '<' ) { T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; /* don't include delimiters */ string_size = (FT_Long)( ( parser->root.cursor - cur - 2 + 1 ) / 2 ); if ( FT_REALLOC( string_buf, old_string_size, string_size ) ) goto Fail; allocated = 1; parser->root.cursor = cur; (void)T1_ToBytes( parser, string_buf, string_size, &real_size, 1 ); old_string_size = string_size; string_size = real_size; } else if ( ft_isdigit( *cur ) ) { if ( allocated ) { FT_ERROR(( "t42_parse_sfnts: " "can't handle mixed binary and hex strings\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } string_size = T1_ToInt( parser ); if ( string_size < 0 ) { FT_ERROR(( "t42_parse_sfnts: invalid string size\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } T1_Skip_PS_Token( parser ); /* `RD' */ if ( parser->root.error ) return; string_buf = parser->root.cursor + 1; /* one space after `RD' */ if ( limit - parser->root.cursor < string_size ) { FT_ERROR(( "t42_parse_sfnts: too many binary data\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } else parser->root.cursor += string_size + 1; } if ( !string_buf ) { FT_ERROR(( "t42_parse_sfnts: invalid data in sfnts array\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* A string can have a trailing zero (odd) byte for padding. */ /* Ignore it. */ if ( ( string_size & 1 ) && string_buf[string_size - 1] == 0 ) string_size--; if ( !string_size ) { FT_ERROR(( "t42_parse_sfnts: invalid string\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } for ( n = 0; n < string_size; n++ ) { switch ( status ) { case BEFORE_START: /* load offset table, 12 bytes */ if ( count < 12 ) { face->ttf_data[count++] = string_buf[n]; continue; } else { num_tables = 16 * face->ttf_data[4] + face->ttf_data[5]; status = BEFORE_TABLE_DIR; ttf_size = 12 + 16 * num_tables; if ( FT_REALLOC( face->ttf_data, 12, ttf_size ) ) goto Fail; } /* fall through */ case BEFORE_TABLE_DIR: /* the offset table is read; read the table directory */ if ( count < ttf_size ) { face->ttf_data[count++] = string_buf[n]; continue; } else { int i; FT_ULong len; for ( i = 0; i < num_tables; i++ ) { FT_Byte* p = face->ttf_data + 12 + 16 * i + 12; len = FT_PEEK_ULONG( p ); /* Pad to a 4-byte boundary length */ ttf_size += ( len + 3 ) & ~3; } status = OTHER_TABLES; face->ttf_size = ttf_size; /* there are no more than 256 tables, so no size check here */ if ( FT_REALLOC( face->ttf_data, 12 + 16 * num_tables, ttf_size + 1 ) ) goto Fail; } /* fall through */ case OTHER_TABLES: /* all other tables are just copied */ if ( count >= ttf_size ) { FT_ERROR(( "t42_parse_sfnts: too many binary data\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } } face->ttf_data[count++] = string_buf[n]; } } T1_Skip_Spaces( parser ); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void xgroupCommand(client *c) { const char *help[] = { "CREATE <key> <groupname> <id or $> -- Create a new consumer group.", "SETID <key> <groupname> <id or $> -- Set the current group ID.", "DELGROUP <key> <groupname> -- Remove the specified group.", "DELCONSUMER <key> <groupname> <consumer> -- Remove the specified conusmer.", "HELP -- Prints this help.", NULL }; stream *s = NULL; sds grpname = NULL; streamCG *cg = NULL; char *opt = c->argv[1]->ptr; /* Subcommand name. */ /* Lookup the key now, this is common for all the subcommands but HELP. */ if (c->argc >= 4) { robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr); if (o == NULL) return; s = o->ptr; grpname = c->argv[3]->ptr; /* Certain subcommands require the group to exist. */ if ((cg = streamLookupCG(s,grpname)) == NULL && (!strcasecmp(opt,"SETID") || !strcasecmp(opt,"DELCONSUMER"))) { addReplyErrorFormat(c, "-NOGROUP No such consumer group '%s' " "for key name '%s'", (char*)grpname, (char*)c->argv[2]->ptr); return; } } /* Dispatch the different subcommands. */ if (!strcasecmp(opt,"CREATE") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,"$")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id); if (cg) { addReply(c,shared.ok); server.dirty++; } else { addReplySds(c, sdsnew("-BUSYGROUP Consumer Group name already exists\r\n")); } } else if (!strcasecmp(opt,"SETID") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,"$")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } cg->last_id = id; addReply(c,shared.ok); } else if (!strcasecmp(opt,"DESTROY") && c->argc == 4) { if (cg) { raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL); streamFreeCG(cg); addReply(c,shared.cone); } else { addReply(c,shared.czero); } } else if (!strcasecmp(opt,"DELCONSUMER") && c->argc == 5) { /* Delete the consumer and returns the number of pending messages * that were yet associated with such a consumer. */ long long pending = streamDelConsumer(cg,c->argv[4]->ptr); addReplyLongLong(c,pending); server.dirty++; } else if (!strcasecmp(opt,"HELP")) { addReplyHelp(c, help); } else { addReply(c,shared.syntaxerr); } } CWE ID: CWE-704 Target: 1 Example 2: Code: xscale1pmu_read_counter(int counter) { u32 val = 0; switch (counter) { case XSCALE_CYCLE_COUNTER: asm volatile("mrc p14, 0, %0, c1, c0, 0" : "=r" (val)); break; case XSCALE_COUNTER0: asm volatile("mrc p14, 0, %0, c2, c0, 0" : "=r" (val)); break; case XSCALE_COUNTER1: asm volatile("mrc p14, 0, %0, c3, c0, 0" : "=r" (val)); break; } return val; } 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: scoped_refptr<base::debug::ConvertableToTraceFormat> Layer::TakeDebugInfo() { if (client_) return client_->TakeDebugInfo(); else return NULL; } 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: iakerb_gss_accept_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 major_status = GSS_S_FAILURE; OM_uint32 code; iakerb_ctx_id_t ctx; int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); if (initialContextToken) { code = iakerb_alloc_context(&ctx); if (code != 0) goto cleanup; } else ctx = (iakerb_ctx_id_t)*context_handle; if (iakerb_is_iakerb_token(input_token)) { if (ctx->gssc != GSS_C_NO_CONTEXT) { /* We shouldn't get an IAKERB token now. */ code = G_WRONG_TOKID; major_status = GSS_S_DEFECTIVE_TOKEN; goto cleanup; } code = iakerb_acceptor_step(ctx, initialContextToken, input_token, output_token); if (code == (OM_uint32)KRB5_BAD_MSIZE) major_status = GSS_S_DEFECTIVE_TOKEN; if (code != 0) goto cleanup; if (initialContextToken) { *context_handle = (gss_ctx_id_t)ctx; ctx = NULL; } if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_iakerb; if (ret_flags != NULL) *ret_flags = 0; if (time_rec != NULL) *time_rec = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; major_status = GSS_S_CONTINUE_NEEDED; } else { krb5_gss_ctx_ext_rec exts; iakerb_make_exts(ctx, &exts); major_status = krb5_gss_accept_sec_context_ext(&code, &ctx->gssc, verifier_cred_handle, input_token, input_chan_bindings, src_name, NULL, output_token, ret_flags, time_rec, delegated_cred_handle, &exts); if (major_status == GSS_S_COMPLETE) { *context_handle = ctx->gssc; ctx->gssc = NULL; iakerb_release_context(ctx); } if (mech_type != NULL) *mech_type = (gss_OID)gss_mech_krb5; } cleanup: if (initialContextToken && GSS_ERROR(major_status)) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } *minor_status = code; return major_status; } CWE ID: CWE-18 Target: 1 Example 2: Code: static HB_Error default_mmfunc( HB_Font font, HB_UShort metric_id, HB_Fixed* metric_value, void* data ) { HB_UNUSED(font); HB_UNUSED(metric_id); HB_UNUSED(metric_value); HB_UNUSED(data); return ERR(HB_Err_Not_Covered); /* ERR() call intended */ } 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: lldp_mgmt_addr_tlv_print(netdissect_options *ndo, const u_char *pptr, u_int len) { uint8_t mgmt_addr_len, intf_num_subtype, oid_len; const u_char *tptr; u_int tlen; char *mgmt_addr; tlen = len; tptr = pptr; if (tlen < 1) { return 0; } mgmt_addr_len = *tptr++; tlen--; if (tlen < mgmt_addr_len) { return 0; } mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len); if (mgmt_addr == NULL) { return 0; } ND_PRINT((ndo, "\n\t Management Address length %u, %s", mgmt_addr_len, mgmt_addr)); tptr += mgmt_addr_len; tlen -= mgmt_addr_len; if (tlen < LLDP_INTF_NUM_LEN) { return 0; } intf_num_subtype = *tptr; ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u", tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype), intf_num_subtype, EXTRACT_32BITS(tptr + 1))); tptr += LLDP_INTF_NUM_LEN; tlen -= LLDP_INTF_NUM_LEN; /* * The OID is optional. */ if (tlen) { oid_len = *tptr; if (tlen < oid_len) { return 0; } if (oid_len) { ND_PRINT((ndo, "\n\t OID length %u", oid_len)); safeputs(ndo, tptr + 1, oid_len); } } return 1; } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation( const NavigationRequest& request) { DCHECK(!request.common_params().url.SchemeIs(url::kJavaScriptScheme)) << "Don't call this method for JavaScript URLs as those create a " "temporary NavigationRequest and we don't want to reset an ongoing " "navigation's speculative RFH."; RenderFrameHostImpl* navigation_rfh = nullptr; SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigationRequest(request); bool use_current_rfh = current_site_instance == dest_site_instance; bool notify_webui_of_rf_creation = false; if (use_current_rfh) { if (speculative_render_frame_host_) { if (speculative_render_frame_host_->navigation_handle()) { frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded( speculative_render_frame_host_->navigation_handle() ->pending_nav_entry_id()); } DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost()); } if (frame_tree_node_->IsMainFrame()) { UpdatePendingWebUIOnCurrentFrameHost(request.common_params().url, request.bindings()); } navigation_rfh = render_frame_host_.get(); DCHECK(!speculative_render_frame_host_); } else { if (!speculative_render_frame_host_ || speculative_render_frame_host_->GetSiteInstance() != dest_site_instance.get()) { CleanUpNavigation(); bool success = CreateSpeculativeRenderFrameHost(current_site_instance, dest_site_instance.get()); DCHECK(success); } DCHECK(speculative_render_frame_host_); if (frame_tree_node_->IsMainFrame()) { bool changed_web_ui = speculative_render_frame_host_->UpdatePendingWebUI( request.common_params().url, request.bindings()); speculative_render_frame_host_->CommitPendingWebUI(); DCHECK_EQ(GetNavigatingWebUI(), speculative_render_frame_host_->web_ui()); notify_webui_of_rf_creation = changed_web_ui && speculative_render_frame_host_->web_ui(); } navigation_rfh = speculative_render_frame_host_.get(); if (!render_frame_host_->IsRenderFrameLive()) { if (GetRenderFrameProxyHost(dest_site_instance.get())) { navigation_rfh->Send( new FrameMsg_SwapIn(navigation_rfh->GetRoutingID())); } CommitPending(); if (notify_webui_of_rf_creation && render_frame_host_->web_ui()) { render_frame_host_->web_ui()->RenderFrameCreated( render_frame_host_.get()); notify_webui_of_rf_creation = false; } } } DCHECK(navigation_rfh && (navigation_rfh == render_frame_host_.get() || navigation_rfh == speculative_render_frame_host_.get())); if (!navigation_rfh->IsRenderFrameLive()) { if (!ReinitializeRenderFrame(navigation_rfh)) return nullptr; notify_webui_of_rf_creation = true; if (navigation_rfh == render_frame_host_.get()) { EnsureRenderFrameHostVisibilityConsistent(); EnsureRenderFrameHostPageFocusConsistent(); delegate_->NotifyMainFrameSwappedFromRenderManager( nullptr, render_frame_host_->render_view_host()); } } if (notify_webui_of_rf_creation && GetNavigatingWebUI() && frame_tree_node_->IsMainFrame()) { GetNavigatingWebUI()->RenderFrameCreated(navigation_rfh); } return navigation_rfh; } CWE ID: CWE-20 Target: 1 Example 2: Code: int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char * Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) // should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = SafeArrayAlloc<char>(1, len + 1); if (dst == NULL) return -1; strcpy(dst, src); return 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int xhci_ep_nuke_xfers(XHCIState *xhci, unsigned int slotid, unsigned int epid, TRBCCode report) { XHCISlot *slot; XHCIEPContext *epctx; XHCITransfer *xfer; int killed = 0; USBEndpoint *ep = NULL; assert(slotid >= 1 && slotid <= xhci->numslots); assert(epid >= 1 && epid <= 31); DPRINTF("xhci_ep_nuke_xfers(%d, %d)\n", slotid, epid); slot = &xhci->slots[slotid-1]; if (!slot->eps[epid-1]) { return 0; } epctx = slot->eps[epid-1]; for (;;) { xfer = QTAILQ_FIRST(&epctx->transfers); if (xfer == NULL) { break; } killed += xhci_ep_nuke_one_xfer(xfer, report); if (killed) { report = 0; /* Only report once */ } xhci_ep_free_xfer(xfer); } ep = xhci_epid_to_usbep(epctx); if (ep) { usb_device_ep_stopped(ep->dev, ep); } return killed; } CWE ID: CWE-835 Output:
0
Here are some example code snippets. Analyze the following 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 webkitWebViewBaseSetInspectorViewHeight(WebKitWebViewBase* webkitWebViewBase, unsigned height) { if (!webkitWebViewBase->priv->inspectorView) return; if (webkitWebViewBase->priv->inspectorViewHeight == height) return; webkitWebViewBase->priv->inspectorViewHeight = height; gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webkitWebViewBase)); } CWE ID: CWE-399 Target: 1 Example 2: Code: xscale2pmu_read_overflow_flags(void) { u32 val; asm volatile("mrc p14, 0, %0, c5, c1, 0" : "=r" (val)); return val; } 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 Set(const std::string& addr, int value) { base::AutoLock lock(lock_); map_[addr] = value; } 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: CCLayerTreeHostTest() : m_beginning(false) , m_endWhenBeginReturns(false) , m_running(false) , m_timedOut(false) { m_webThread = adoptPtr(webKitPlatformSupport()->createThread("CCLayerTreeHostTest")); WebCompositor::setThread(m_webThread.get()); #if USE(THREADED_COMPOSITING) m_settings.enableCompositorThread = true; #else m_settings.enableCompositorThread = false; #endif } CWE ID: CWE-119 Target: 1 Example 2: Code: ReadableStreamReaderTest() : m_page(DummyPageHolder::create(IntSize(1, 1))) , m_stream(new StringStream(new NoopUnderlyingSource, new PermissiveStrategy)) { m_stream->didSourceStart(); } 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: PlatformSensorLinux::PlatformSensorLinux( mojom::SensorType type, mojo::ScopedSharedBufferMapping mapping, PlatformSensorProvider* provider, const SensorInfoLinux* sensor_device, scoped_refptr<base::SingleThreadTaskRunner> polling_thread_task_runner) : PlatformSensor(type, std::move(mapping), provider), default_configuration_( PlatformSensorConfiguration(sensor_device->device_frequency)), reporting_mode_(sensor_device->reporting_mode), polling_thread_task_runner_(std::move(polling_thread_task_runner)), weak_factory_(this) { sensor_reader_ = SensorReader::Create( sensor_device, weak_factory_.GetWeakPtr(), task_runner_); } CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: v8::Handle<v8::Value> V8Proxy::throwNotEnoughArgumentsError() { return throwError(TypeError, "Not enough arguments"); } CWE ID: Target: 1 Example 2: Code: static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg) { switch (reg) { case VCPU_EXREG_PDPTR: BUG_ON(!npt_enabled); load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu)); break; default: BUG(); } } 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: Guchar SplashBitmap::getAlpha(int x, int y) { return alpha[y * width + x]; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len) { int offset = 0; const uint8_t *ptr = NULL; if (asn1_next_obj(asn1_sig, &offset, ASN1_SEQUENCE) < 0 || asn1_skip_obj(asn1_sig, &offset, ASN1_SEQUENCE)) goto end_get_sig; if (asn1_sig[offset++] != ASN1_OCTET_STRING) goto end_get_sig; *len = get_asn1_length(asn1_sig, &offset); ptr = &asn1_sig[offset]; /* all ok */ end_get_sig: return ptr; } CWE ID: CWE-347 Target: 1 Example 2: Code: int test_rshift1(BIO *bp) { BIGNUM *a, *b, *c; int i; a = BN_new(); b = BN_new(); c = BN_new(); BN_bntest_rand(a, 200, 0, 0); a->neg = rand_neg(); for (i = 0; i < num0; i++) { BN_rshift1(b, a); if (bp != NULL) { if (!results) { BN_print(bp, a); BIO_puts(bp, " / 2"); BIO_puts(bp, " - "); } BN_print(bp, b); BIO_puts(bp, "\n"); } BN_sub(c, a, b); BN_sub(c, c, b); if (!BN_is_zero(c) && !BN_abs_is_word(c, 1)) { fprintf(stderr, "Right shift one test failed!\n"); return 0; } BN_copy(a, b); } BN_free(a); BN_free(b); BN_free(c); return (1); } 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: WebsiteSettingsPopupView::WebsiteSettingsPopupView( views::View* anchor_view, gfx::NativeView parent_window, Profile* profile, content::WebContents* web_contents, const GURL& url, const content::SSLStatus& ssl) : BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT), web_contents_(web_contents), header_(nullptr), tabbed_pane_(nullptr), permissions_tab_(nullptr), site_data_content_(nullptr), cookie_dialog_link_(nullptr), permissions_content_(nullptr), connection_tab_(nullptr), identity_info_content_(nullptr), certificate_dialog_link_(nullptr), reset_decisions_button_(nullptr), help_center_content_(nullptr), cert_id_(0), help_center_link_(nullptr), connection_info_content_(nullptr), weak_factory_(this) { set_parent_window(parent_window); set_anchor_view_insets(gfx::Insets(kLocationIconVerticalMargin, 0, kLocationIconVerticalMargin, 0)); views::GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int content_column = 0; views::ColumnSet* column_set = layout->AddColumnSet(content_column); column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1, views::GridLayout::USE_PREF, 0, 0); header_ = new PopupHeaderView(this); layout->StartRow(1, content_column); layout->AddView(header_); layout->AddPaddingRow(1, kHeaderMarginBottom); tabbed_pane_ = new views::TabbedPane(); layout->StartRow(1, content_column); layout->AddView(tabbed_pane_); permissions_tab_ = CreatePermissionsTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_PERMISSIONS, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_PERMISSIONS), permissions_tab_); connection_tab_ = CreateConnectionTab(); tabbed_pane_->AddTabAtIndex( TAB_ID_CONNECTION, l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_CONNECTION), connection_tab_); DCHECK_EQ(tabbed_pane_->GetTabCount(), NUM_TAB_IDS); tabbed_pane_->set_listener(this); set_margins(gfx::Insets(kPopupMarginTop, kPopupMarginLeft, kPopupMarginBottom, kPopupMarginRight)); views::BubbleDelegateView::CreateBubble(this); presenter_.reset(new WebsiteSettings( this, profile, TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), url, ssl, content::CertStore::GetInstance())); } 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: SProcXFixesQueryVersion(ClientPtr client) { REQUEST(xXFixesQueryVersionReq); swaps(&stuff->length); swapl(&stuff->majorVersion); return (*ProcXFixesVector[stuff->xfixesReqType]) (client); } CWE ID: CWE-20 Target: 1 Example 2: Code: void MaybeNotifyDelegateOnMounted() { if (mounted()) { host_->timer_->Stop(); host_->mount_observer_->OnMounted(mount_path()); } } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int check_ptr_alignment(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, int off, int size) { bool strict = env->strict_alignment; const char *pointer_desc = ""; switch (reg->type) { case PTR_TO_PACKET: case PTR_TO_PACKET_META: /* Special case, because of NET_IP_ALIGN. Given metadata sits * right in front, treat it the very same way. */ return check_pkt_ptr_alignment(env, reg, off, size, strict); case PTR_TO_MAP_VALUE: pointer_desc = "value "; break; case PTR_TO_CTX: pointer_desc = "context "; break; case PTR_TO_STACK: pointer_desc = "stack "; break; default: break; } return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, strict); } 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 SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nOffset == 0) { mAnchorTimeUs = inHeader->nTimeStamp; mNumSamplesOutput = 0; } const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; int32_t numBytesRead; if (mMode == MODE_NARROW) { numBytesRead = AMRDecode(mState, (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), (UWord8 *)&inputPtr[1], reinterpret_cast<int16_t *>(outHeader->pBuffer), MIME_IETF); if (numBytesRead == -1) { ALOGE("PV AMR decoder AMRDecode() call failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } ++numBytesRead; // Include the frame type header byte. if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } } else { int16 mode = ((inputPtr[0] >> 3) & 0x0f); if (mode >= 10 && mode <= 13) { ALOGE("encountered illegal frame type %d in AMR WB content.", mode); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } size_t frameSize = getFrameSize(mode); CHECK_GE(inHeader->nFilledLen, frameSize); int16_t *outPtr = (int16_t *)outHeader->pBuffer; if (mode >= 9) { memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); } else if (mode < 9) { int16 frameType; RX_State_wb rx_state; mime_unsorting( const_cast<uint8_t *>(&inputPtr[1]), mInputSampleBuffer, &frameType, &mode, 1, &rx_state); int16_t numSamplesOutput; pvDecoder_AmrWb( mode, mInputSampleBuffer, outPtr, &numSamplesOutput, mDecoderBuf, frameType, mDecoderCookie); CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { /* Delete the 2 LSBs (14-bit output) */ outPtr[i] &= 0xfffC; } } numBytesRead = frameSize; } inHeader->nOffset += numBytesRead; inHeader->nFilledLen -= numBytesRead; outHeader->nFlags = 0; outHeader->nOffset = 0; if (mMode == MODE_NARROW) { outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; mNumSamplesOutput += kNumSamplesPerFrameNB; } else { outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; mNumSamplesOutput += kNumSamplesPerFrameWB; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mInputBufferCount; } } CWE ID: CWE-264 Target: 1 Example 2: Code: static int fsmUtime(const char *path, mode_t mode, time_t mtime) { int rc = 0; struct timeval stamps[2] = { { .tv_sec = mtime, .tv_usec = 0 }, { .tv_sec = mtime, .tv_usec = 0 }, }; #if HAVE_LUTIMES rc = lutimes(path, stamps); #else if (!S_ISLNK(mode)) rc = utimes(path, stamps); #endif if (_fsm_debug) rpmlog(RPMLOG_DEBUG, " %8s (%s, 0x%x) %s\n", __func__, path, (unsigned)mtime, (rc < 0 ? strerror(errno) : "")); if (rc < 0) rc = RPMERR_UTIME_FAILED; /* ...but utime error is not critical for directories */ if (rc && S_ISDIR(mode)) rc = 0; return rc; } CWE ID: CWE-59 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BufferQueueConsumer::dump(String8& result, const char* prefix) const { const IPCThreadState* ipc = IPCThreadState::self(); const pid_t pid = ipc->getCallingPid(); const uid_t uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(String16( "android.permission.DUMP"), pid, uid)) { result.appendFormat("Permission Denial: can't dump BufferQueueConsumer " "from pid=%d, uid=%d\n", pid, uid); } else { mCore->dump(result, prefix); } } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DatabaseMessageFilter::OnDatabaseOpened(const string16& origin_identifier, const string16& database_name, const string16& description, int64 estimated_size) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); int64 database_size = 0; db_tracker_->DatabaseOpened(origin_identifier, database_name, description, estimated_size, &database_size); database_connections_.AddConnection(origin_identifier, database_name); Send(new DatabaseMsg_UpdateSize(origin_identifier, database_name, database_size)); } CWE ID: CWE-22 Target: 1 Example 2: Code: _krb5_pk_set_user_id(krb5_context context, krb5_principal principal, krb5_pk_init_ctx ctx, struct hx509_certs_data *certs) { hx509_certs c = hx509_certs_ref(certs); hx509_query *q = NULL; int ret; if (ctx->id->certs) hx509_certs_free(&ctx->id->certs); if (ctx->id->cert) { hx509_cert_free(ctx->id->cert); ctx->id->cert = NULL; } ctx->id->certs = c; ctx->anonymous = 0; ret = hx509_query_alloc(context->hx509ctx, &q); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Allocate query to find signing certificate"); return ret; } hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE); if (principal && strncmp("LKDC:SHA1.", krb5_principal_get_realm(context, principal), 9) == 0) { ctx->id->flags |= PKINIT_BTMM; } ret = find_cert(context, ctx->id, q, &ctx->id->cert); hx509_query_free(context->hx509ctx, q); if (ret == 0 && _krb5_have_debug(context, 2)) { hx509_name name; char *str, *sn; heim_integer i; ret = hx509_cert_get_subject(ctx->id->cert, &name); if (ret) goto out; ret = hx509_name_to_string(name, &str); hx509_name_free(&name); if (ret) goto out; ret = hx509_cert_get_serialnumber(ctx->id->cert, &i); if (ret) { free(str); goto out; } ret = der_print_hex_heim_integer(&i, &sn); der_free_heim_integer(&i); if (ret) { free(name); goto out; } _krb5_debug(context, 2, "using cert: subject: %s sn: %s", str, sn); free(str); free(sn); } out: return ret; } CWE ID: CWE-320 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool HTMLInputElement::IsRequiredFormControl() const { return input_type_->SupportsRequired() && IsRequired(); } 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 oz_usb_handle_ep_data(struct oz_usb_ctx *usb_ctx, struct oz_usb_hdr *usb_hdr, int len) { struct oz_data *data_hdr = (struct oz_data *)usb_hdr; switch (data_hdr->format) { case OZ_DATA_F_MULTIPLE_FIXED: { struct oz_multiple_fixed *body = (struct oz_multiple_fixed *)data_hdr; u8 *data = body->data; int n; if (!body->unit_size) break; n = (len - sizeof(struct oz_multiple_fixed)+1) / body->unit_size; while (n--) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, body->unit_size); data += body->unit_size; } } break; case OZ_DATA_F_ISOC_FIXED: { struct oz_isoc_fixed *body = (struct oz_isoc_fixed *)data_hdr; int data_len = len-sizeof(struct oz_isoc_fixed)+1; int unit_size = body->unit_size; u8 *data = body->data; int count; int i; if (!unit_size) break; count = data_len/unit_size; for (i = 0; i < count; i++) { oz_hcd_data_ind(usb_ctx->hport, body->endpoint, data, unit_size); data += unit_size; } } break; } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int uvesafb_exec(struct uvesafb_ktask *task) { static int seq; struct cn_msg *m; int err; int len = sizeof(task->t) + task->t.buf_len; /* * Check whether the message isn't longer than the maximum * allowed by connector. */ if (sizeof(*m) + len > CONNECTOR_MAX_MSG_SIZE) { pr_warn("message too long (%d), can't execute task\n", (int)(sizeof(*m) + len)); return -E2BIG; } m = kzalloc(sizeof(*m) + len, GFP_KERNEL); if (!m) return -ENOMEM; init_completion(task->done); memcpy(&m->id, &uvesafb_cn_id, sizeof(m->id)); m->seq = seq; m->len = len; m->ack = prandom_u32(); /* uvesafb_task structure */ memcpy(m + 1, &task->t, sizeof(task->t)); /* Buffer */ memcpy((u8 *)(m + 1) + sizeof(task->t), task->buf, task->t.buf_len); /* * Save the message ack number so that we can find the kernel * part of this task when a reply is received from userspace. */ task->ack = m->ack; mutex_lock(&uvfb_lock); /* If all slots are taken -- bail out. */ if (uvfb_tasks[seq]) { mutex_unlock(&uvfb_lock); err = -EBUSY; goto out; } /* Save a pointer to the kernel part of the task struct. */ uvfb_tasks[seq] = task; mutex_unlock(&uvfb_lock); err = cn_netlink_send(m, 0, 0, GFP_KERNEL); if (err == -ESRCH) { /* * Try to start the userspace helper if sending * the request failed the first time. */ err = uvesafb_helper_start(); if (err) { pr_err("failed to execute %s\n", v86d_path); pr_err("make sure that the v86d helper is installed and executable\n"); } else { v86d_started = 1; err = cn_netlink_send(m, 0, 0, gfp_any()); if (err == -ENOBUFS) err = 0; } } else if (err == -ENOBUFS) err = 0; if (!err && !(task->t.flags & TF_EXIT)) err = !wait_for_completion_timeout(task->done, msecs_to_jiffies(UVESAFB_TIMEOUT)); mutex_lock(&uvfb_lock); uvfb_tasks[seq] = NULL; mutex_unlock(&uvfb_lock); seq++; if (seq >= UVESAFB_TASKS_MAX) seq = 0; out: kfree(m); return err; } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DevToolsAgentHostImpl::ForceAttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; scoped_refptr<DevToolsAgentHostImpl> protect(this); if (!sessions_.empty()) ForceDetachAllClients(); DCHECK(sessions_.empty()); InnerAttachClient(client); } 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: delete_principal_2_svc(dprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, arg->princ, NULL)) { ret.code = KADM5_AUTH_DELETE; log_unauth("kadm5_delete_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_delete_principal((void *)handle, arg->princ); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int do_huge_pmd_wp_page_fallback(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, pmd_t orig_pmd, struct page *page, unsigned long haddr) { pgtable_t pgtable; pmd_t _pmd; int ret = 0, i; struct page **pages; pages = kmalloc(sizeof(struct page *) * HPAGE_PMD_NR, GFP_KERNEL); if (unlikely(!pages)) { ret |= VM_FAULT_OOM; goto out; } for (i = 0; i < HPAGE_PMD_NR; i++) { pages[i] = alloc_page_vma_node(GFP_HIGHUSER_MOVABLE | __GFP_OTHER_NODE, vma, address, page_to_nid(page)); if (unlikely(!pages[i] || mem_cgroup_newpage_charge(pages[i], mm, GFP_KERNEL))) { if (pages[i]) put_page(pages[i]); mem_cgroup_uncharge_start(); while (--i >= 0) { mem_cgroup_uncharge_page(pages[i]); put_page(pages[i]); } mem_cgroup_uncharge_end(); kfree(pages); ret |= VM_FAULT_OOM; goto out; } } for (i = 0; i < HPAGE_PMD_NR; i++) { copy_user_highpage(pages[i], page + i, haddr + PAGE_SHIFT*i, vma); __SetPageUptodate(pages[i]); cond_resched(); } spin_lock(&mm->page_table_lock); if (unlikely(!pmd_same(*pmd, orig_pmd))) goto out_free_pages; VM_BUG_ON(!PageHead(page)); pmdp_clear_flush_notify(vma, haddr, pmd); /* leave pmd empty until pte is filled */ pgtable = get_pmd_huge_pte(mm); pmd_populate(mm, &_pmd, pgtable); for (i = 0; i < HPAGE_PMD_NR; i++, haddr += PAGE_SIZE) { pte_t *pte, entry; entry = mk_pte(pages[i], vma->vm_page_prot); entry = maybe_mkwrite(pte_mkdirty(entry), vma); page_add_new_anon_rmap(pages[i], vma, haddr); pte = pte_offset_map(&_pmd, haddr); VM_BUG_ON(!pte_none(*pte)); set_pte_at(mm, haddr, pte, entry); pte_unmap(pte); } kfree(pages); mm->nr_ptes++; smp_wmb(); /* make pte visible before pmd */ pmd_populate(mm, pmd, pgtable); page_remove_rmap(page); spin_unlock(&mm->page_table_lock); ret |= VM_FAULT_WRITE; put_page(page); out: return ret; out_free_pages: spin_unlock(&mm->page_table_lock); mem_cgroup_uncharge_start(); for (i = 0; i < HPAGE_PMD_NR; i++) { mem_cgroup_uncharge_page(pages[i]); put_page(pages[i]); } mem_cgroup_uncharge_end(); kfree(pages); goto out; } 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 opmul(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; if ( op->operands[0].type & OT_QWORD ) { data[l++] = 0x48; } switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x66; } if (op->operands[0].type & OT_BYTE) { data[l++] = 0xf6; } else { data[l++] = 0xf7; } if (op->operands[0].type & OT_MEMORY) { data[l++] = 0x20 | op->operands[0].regs[0]; } else { data[l++] = 0xe0 | op->operands[0].reg; } break; default: return -1; } return l; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; php_stream *file; size_t memsize; char *membuf; off_t pos; assert(ts != NULL); if (!ts->innerstream) { return FAILURE; } if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) { return php_stream_cast(ts->innerstream, castas, ret, 0); } /* we are still using a memory based backing. If they are if we can be * a FILE*, say yes because we can perform the conversion. * If they actually want to perform the conversion, we need to switch * the memory stream to a tmpfile stream */ if (ret == NULL && castas == PHP_STREAM_AS_STDIO) { return SUCCESS; } /* say "no" to other stream forms */ if (ret == NULL) { return FAILURE; } /* perform the conversion and then pass the request on to the innerstream */ membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize); file = php_stream_fopen_tmpfile(); php_stream_write(file, membuf, memsize); pos = php_stream_tell(ts->innerstream); php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE); ts->innerstream = file; php_stream_encloses(stream, ts->innerstream); php_stream_seek(ts->innerstream, pos, SEEK_SET); return php_stream_cast(ts->innerstream, castas, ret, 1); } CWE ID: CWE-20 Target: 1 Example 2: Code: bool ChildProcessSecurityPolicyImpl::CanCommitURL(int child_id, const GURL& url) { if (!url.is_valid()) return false; // Can't commit invalid URLs. if (IsPseudoScheme(url.scheme())) return base::LowerCaseEqualsASCII(url.spec(), url::kAboutBlankURL); if (IsWebSafeScheme(url.scheme())) return true; // The scheme has been white-listed for every child process. { base::AutoLock lock(lock_); SecurityStateMap::iterator state = security_state_.find(child_id); if (state == security_state_.end()) return false; return state->second->CanCommitURL(url); } } 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 HTMLFormElement::setMethod(const String &value) { setAttribute(methodAttr, value); } 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: WORD32 ih264d_parse_nal_unit(iv_obj_t *dec_hdl, ivd_video_decode_op_t *ps_dec_op, UWORD8 *pu1_buf, UWORD32 u4_length) { dec_bit_stream_t *ps_bitstrm; dec_struct_t *ps_dec = (dec_struct_t *)dec_hdl->pv_codec_handle; ivd_video_decode_ip_t *ps_dec_in = (ivd_video_decode_ip_t *)ps_dec->pv_dec_in; dec_slice_params_t * ps_cur_slice = ps_dec->ps_cur_slice; UWORD8 u1_first_byte, u1_nal_ref_idc; UWORD8 u1_nal_unit_type; WORD32 i_status = OK; ps_bitstrm = ps_dec->ps_bitstrm; if(pu1_buf) { if(u4_length) { ps_dec_op->u4_frame_decoded_flag = 0; ih264d_process_nal_unit(ps_dec->ps_bitstrm, pu1_buf, u4_length); SWITCHOFFTRACE; u1_first_byte = ih264d_get_bits_h264(ps_bitstrm, 8); if(NAL_FORBIDDEN_BIT(u1_first_byte)) { H264_DEC_DEBUG_PRINT("\nForbidden bit set in Nal Unit, Let's try\n"); } u1_nal_unit_type = NAL_UNIT_TYPE(u1_first_byte); if ((ps_dec->u4_slice_start_code_found == 1) && (ps_dec->u1_pic_decode_done != 1) && (u1_nal_unit_type > IDR_SLICE_NAL)) { return ERROR_INCOMPLETE_FRAME; } ps_dec->u1_nal_unit_type = u1_nal_unit_type; u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_first_byte)); switch(u1_nal_unit_type) { case SLICE_DATA_PARTITION_A_NAL: case SLICE_DATA_PARTITION_B_NAL: case SLICE_DATA_PARTITION_C_NAL: if(!ps_dec->i4_decode_header) ih264d_parse_slice_partition(ps_dec, ps_bitstrm); break; case IDR_SLICE_NAL: case SLICE_NAL: /* ! */ DEBUG_THREADS_PRINTF("Decoding a slice NAL\n"); if(!ps_dec->i4_decode_header) { if(ps_dec->i4_header_decoded == 3) { /* ! */ ps_dec->u4_slice_start_code_found = 1; ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_decode_slice( (UWORD8)(u1_nal_unit_type == IDR_SLICE_NAL), u1_nal_ref_idc, ps_dec); if((ps_dec->u4_first_slice_in_pic != 0)&& ((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0)) { /* if the first slice header was not valid set to 1 */ ps_dec->u4_first_slice_in_pic = 1; } if(i_status != OK) { return i_status; } } else { H264_DEC_DEBUG_PRINT( "\nSlice NAL Supplied but no header has been supplied\n"); } } break; case SEI_NAL: if(!ps_dec->i4_decode_header) { ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sei_message(ps_dec, ps_bitstrm); if(i_status != OK) return i_status; ih264d_parse_sei(ps_dec, ps_bitstrm); } break; case SEQ_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_sps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x1; break; case PIC_PARAM_NAL: /* ! */ ih264d_rbsp_to_sodb(ps_dec->ps_bitstrm); i_status = ih264d_parse_pps(ps_dec, ps_bitstrm); if(i_status == ERROR_INV_SPS_PPS_T) return i_status; if(!i_status) ps_dec->i4_header_decoded |= 0x2; break; case ACCESS_UNIT_DELIMITER_RBSP: if(!ps_dec->i4_decode_header) { ih264d_access_unit_delimiter_rbsp(ps_dec); } break; case END_OF_STREAM_RBSP: if(!ps_dec->i4_decode_header) { ih264d_parse_end_of_stream(ps_dec); } break; case FILLER_DATA_NAL: if(!ps_dec->i4_decode_header) { ih264d_parse_filler_data(ps_dec, ps_bitstrm); } break; default: H264_DEC_DEBUG_PRINT("\nUnknown NAL type %d\n", u1_nal_unit_type); break; } } } return i_status; } CWE ID: CWE-200 Target: 1 Example 2: Code: MediaStreamImpl::VideoRendererWrapper::VideoRendererWrapper() {} 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: kdc_get_ticket_renewtime(kdc_realm_t *realm, krb5_kdc_req *request, krb5_enc_tkt_part *tgt, krb5_db_entry *client, krb5_db_entry *server, krb5_enc_tkt_part *tkt) { krb5_timestamp rtime, max_rlife; tkt->times.renew_till = 0; /* Don't issue renewable tickets if the client or server don't allow it, * or if this is a TGS request and the TGT isn't renewable. */ if (server->attributes & KRB5_KDB_DISALLOW_RENEWABLE) return; if (client != NULL && (client->attributes & KRB5_KDB_DISALLOW_RENEWABLE)) return; if (tgt != NULL && !(tgt->flags & TKT_FLG_RENEWABLE)) return; /* Determine the requested renewable time. */ if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE)) rtime = request->rtime ? request->rtime : kdc_infinity; else if (isflagset(request->kdc_options, KDC_OPT_RENEWABLE_OK) && ts_after(request->till, tkt->times.endtime)) rtime = request->till; else return; /* Truncate it to the allowable renewable time. */ if (tgt != NULL) rtime = ts_min(rtime, tgt->times.renew_till); max_rlife = min(server->max_renewable_life, realm->realm_maxrlife); if (client != NULL) max_rlife = min(max_rlife, client->max_renewable_life); rtime = ts_min(rtime, ts_incr(tkt->times.starttime, max_rlife)); /* Make the ticket renewable if the truncated requested time is larger than * the ticket end time. */ if (ts_after(rtime, tkt->times.endtime)) { setflag(tkt->flags, TKT_FLG_RENEWABLE); tkt->times.renew_till = rtime; } } CWE ID: CWE-617 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ServiceWorkerHandler::ServiceWorkerHandler() : DevToolsDomainHandler(ServiceWorker::Metainfo::domainName), enabled_(false), process_(nullptr), weak_factory_(this) {} CWE ID: CWE-20 Target: 1 Example 2: Code: void DrawingBuffer::MailboxReleasedGpu(RefPtr<ColorBuffer> color_buffer, const gpu::SyncToken& sync_token, bool lost_resource) { if (color_buffer == front_color_buffer_) front_color_buffer_ = nullptr; color_buffer->receive_sync_token = sync_token; if (destruction_in_progress_ || color_buffer->size != size_ || gl_->GetGraphicsResetStatusKHR() != GL_NO_ERROR || lost_resource || is_hidden_) { return; } size_t cache_limit = 1; if (ShouldUseChromiumImage()) cache_limit = 4; while (recycled_color_buffer_queue_.size() >= cache_limit) recycled_color_buffer_queue_.TakeLast(); recycled_color_buffer_queue_.push_front(color_buffer); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static long kvm_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; int r; struct kvm_fpu *fpu = NULL; struct kvm_sregs *kvm_sregs = NULL; if (vcpu->kvm->mm != current->mm) return -EIO; #if defined(CONFIG_S390) || defined(CONFIG_PPC) /* * Special cases: vcpu ioctls that are asynchronous to vcpu execution, * so vcpu_load() would break it. */ if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT) return kvm_arch_vcpu_ioctl(filp, ioctl, arg); #endif vcpu_load(vcpu); switch (ioctl) { case KVM_RUN: r = -EINVAL; if (arg) goto out; r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run); trace_kvm_userspace_exit(vcpu->run->exit_reason, r); break; case KVM_GET_REGS: { struct kvm_regs *kvm_regs; r = -ENOMEM; kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); if (!kvm_regs) goto out; r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs); if (r) goto out_free1; r = -EFAULT; if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs))) goto out_free1; r = 0; out_free1: kfree(kvm_regs); break; } case KVM_SET_REGS: { struct kvm_regs *kvm_regs; r = -ENOMEM; kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); if (!kvm_regs) goto out; r = -EFAULT; if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs))) goto out_free2; r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs); if (r) goto out_free2; r = 0; out_free2: kfree(kvm_regs); break; } case KVM_GET_SREGS: { kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL); r = -ENOMEM; if (!kvm_sregs) goto out; r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs))) goto out; r = 0; break; } case KVM_SET_SREGS: { kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL); r = -ENOMEM; if (!kvm_sregs) goto out; r = -EFAULT; if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs))) goto out; r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs); if (r) goto out; r = 0; break; } case KVM_GET_MP_STATE: { struct kvm_mp_state mp_state; r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &mp_state, sizeof mp_state)) goto out; r = 0; break; } case KVM_SET_MP_STATE: { struct kvm_mp_state mp_state; r = -EFAULT; if (copy_from_user(&mp_state, argp, sizeof mp_state)) goto out; r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state); if (r) goto out; r = 0; break; } case KVM_TRANSLATE: { struct kvm_translation tr; r = -EFAULT; if (copy_from_user(&tr, argp, sizeof tr)) goto out; r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &tr, sizeof tr)) goto out; r = 0; break; } case KVM_SET_GUEST_DEBUG: { struct kvm_guest_debug dbg; r = -EFAULT; if (copy_from_user(&dbg, argp, sizeof dbg)) goto out; r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg); if (r) goto out; r = 0; break; } case KVM_SET_SIGNAL_MASK: { struct kvm_signal_mask __user *sigmask_arg = argp; struct kvm_signal_mask kvm_sigmask; sigset_t sigset, *p; p = NULL; if (argp) { r = -EFAULT; if (copy_from_user(&kvm_sigmask, argp, sizeof kvm_sigmask)) goto out; r = -EINVAL; if (kvm_sigmask.len != sizeof sigset) goto out; r = -EFAULT; if (copy_from_user(&sigset, sigmask_arg->sigset, sizeof sigset)) goto out; p = &sigset; } r = kvm_vcpu_ioctl_set_sigmask(vcpu, p); break; } case KVM_GET_FPU: { fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL); r = -ENOMEM; if (!fpu) goto out; r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu))) goto out; r = 0; break; } case KVM_SET_FPU: { fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL); r = -ENOMEM; if (!fpu) goto out; r = -EFAULT; if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu))) goto out; r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu); if (r) goto out; r = 0; break; } default: r = kvm_arch_vcpu_ioctl(filp, ioctl, arg); } out: vcpu_put(vcpu); kfree(fpu); kfree(kvm_sregs); return r; } 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: chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ", tok2str(chdlc_cast_values, "0x%02x", p[0]), tok2str(ethertype_values, "Unknown", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1); else isoclns_print(ndo, p, length, ndo->ndo_snapend - p); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, "[|chdlc]")); return ndo->ndo_snapend - bp; } CWE ID: CWE-125 Target: 1 Example 2: Code: bool SetCollectStatsInSample(bool in_sample) { std::wstring registry_path = GetRegistryPath(); HANDLE key_handle = INVALID_HANDLE_VALUE; if (!nt::CreateRegKey(nt::HKCU, registry_path.c_str(), KEY_SET_VALUE | KEY_WOW64_32KEY, &key_handle)) { return false; } bool success = nt::SetRegValueDWORD(key_handle, kRegValueChromeStatsSample, in_sample ? 1 : 0); nt::CloseRegKey(key_handle); return success; } CWE ID: CWE-77 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 FrameView::setTransparent(bool isTransparent) { m_isTransparent = isTransparent; DisableCompositingQueryAsserts disabler; if (renderView() && renderView()->layer()->hasCompositedLayerMapping()) renderView()->layer()->compositedLayerMapping()->updateContentsOpaque(); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) { if (network_state_ != kNetworkLoading) return; double time = WTF::CurrentTime(); double timedelta = time - previous_progress_time_; if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) { ScheduleEvent(EventTypeNames::progress); previous_progress_time_ = time; sent_stalled_event_ = false; if (GetLayoutObject()) GetLayoutObject()->UpdateFromElement(); } else if (timedelta > 3.0 && !sent_stalled_event_) { ScheduleEvent(EventTypeNames::stalled); sent_stalled_event_ = true; SetShouldDelayLoadEvent(false); } } CWE ID: CWE-200 Target: 1 Example 2: Code: cifs_put_tcp_session(struct TCP_Server_Info *server) { struct task_struct *task; spin_lock(&cifs_tcp_ses_lock); if (--server->srv_count > 0) { spin_unlock(&cifs_tcp_ses_lock); return; } put_net(cifs_net_ns(server)); list_del_init(&server->tcp_ses_list); spin_unlock(&cifs_tcp_ses_lock); cancel_delayed_work_sync(&server->echo); spin_lock(&GlobalMid_Lock); server->tcpStatus = CifsExiting; spin_unlock(&GlobalMid_Lock); cifs_crypto_shash_release(server); cifs_fscache_release_client_cookie(server); kfree(server->session_key.response); server->session_key.response = NULL; server->session_key.len = 0; task = xchg(&server->tsk, NULL); if (task) force_sig(SIGKILL, task); } 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 bool __init sparc64_has_crc32c_opcode(void) { unsigned long cfr; if (!(sparc64_elf_hwcap & HWCAP_SPARC_CRYPTO)) return false; __asm__ __volatile__("rd %%asr26, %0" : "=r" (cfr)); if (!(cfr & CFR_CRC32C)) return false; return true; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: FileStream::FileStream(const scoped_refptr<base::TaskRunner>& task_runner) : context_(base::MakeUnique<Context>(task_runner)) {} CWE ID: CWE-311 Target: 1 Example 2: Code: void DeviceOrientationController::didRemoveEventListener(DOMWindow* window, const AtomicString& eventType) { if (eventType == EventTypeNames::deviceorientation) { stopUpdating(); m_hasEventListener = 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: void BrowserChildProcessHostImpl::ShareMetricsAllocatorToProcess() { if (metrics_allocator_) { HistogramController::GetInstance()->SetHistogramMemory<ChildProcessHost>( GetHost(), mojo::WrapSharedMemoryHandle( metrics_allocator_->shared_memory()->handle().Duplicate(), metrics_allocator_->shared_memory()->mapped_size(), false)); } else { HistogramController::GetInstance()->SetHistogramMemory<ChildProcessHost>( GetHost(), mojo::ScopedSharedBufferHandle()); } } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GM2TabStyle::PaintBackgroundStroke(gfx::Canvas* canvas, bool active, SkColor stroke_color) const { SkPath outer_path = GetPath(TabStyle::PathType::kBorder, canvas->image_scale(), active); gfx::ScopedCanvas scoped_canvas(canvas); float scale = canvas->UndoDeviceScaleFactor(); cc::PaintFlags flags; flags.setAntiAlias(true); flags.setColor(stroke_color); flags.setStyle(cc::PaintFlags::kStroke_Style); flags.setStrokeWidth(GetStrokeThickness(active) * scale); canvas->DrawPath(outer_path, flags); } CWE ID: CWE-20 Target: 1 Example 2: Code: static bt_status_t btif_in_fetch_bonded_device(const char *bdstr) { BOOLEAN bt_linkkey_file_found=FALSE; LINK_KEY link_key; size_t size = sizeof(link_key); if(btif_config_get_bin(bdstr, "LinkKey", (uint8_t *)link_key, &size)) { int linkkey_type; if(btif_config_get_int(bdstr, "LinkKeyType", &linkkey_type)) { bt_linkkey_file_found = TRUE; } else { bt_linkkey_file_found = FALSE; } } #if (BLE_INCLUDED == TRUE) if((btif_in_fetch_bonded_ble_device(bdstr, FALSE, NULL) != BT_STATUS_SUCCESS) && (!bt_linkkey_file_found)) { BTIF_TRACE_DEBUG("Remote device:%s, no link key or ble key found", bdstr); return BT_STATUS_FAIL; } #else if((!bt_linkkey_file_found)) { BTIF_TRACE_DEBUG("Remote device:%s, no link key found", bdstr); return BT_STATUS_FAIL; } #endif return BT_STATUS_SUCCESS; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int hashtable_init(hashtable_t *hashtable) { size_t i; hashtable->size = 0; hashtable->num_buckets = 0; /* index to primes[] */ hashtable->buckets = jsonp_malloc(num_buckets(hashtable) * sizeof(bucket_t)); if(!hashtable->buckets) return -1; list_init(&hashtable->list); for(i = 0; i < num_buckets(hashtable); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } return 0; } 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: void FolderHeaderView::Update() { if (!folder_item_) return; folder_name_view_->SetVisible(folder_name_visible_); if (folder_name_visible_) folder_name_view_->SetText(base::UTF8ToUTF16(folder_item_->name())); Layout(); } CWE ID: CWE-399 Target: 1 Example 2: Code: void kmem_cache_free_bulk(struct kmem_cache *orig_s, size_t size, void **p) { struct kmem_cache *s; size_t i; local_irq_disable(); for (i = 0; i < size; i++) { void *objp = p[i]; if (!orig_s) /* called via kfree_bulk */ s = virt_to_cache(objp); else s = cache_from_obj(orig_s, objp); debug_check_no_locks_freed(objp, s->object_size); if (!(s->flags & SLAB_DEBUG_OBJECTS)) debug_check_no_obj_freed(objp, s->object_size); __cache_free(s, objp, _RET_IP_); } local_irq_enable(); /* FIXME: add tracing */ } 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: AutofillExternalDelegate::AutofillExternalDelegate(AutofillManager* manager, AutofillDriver* driver) : manager_(manager), driver_(driver) { DCHECK(manager); } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void encode_frame(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, "Failed to encode frame."); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) die_codec(ctx, "Failed to write compressed frame."); printf(keyframe ? "K" : "."); fflush(stdout); } } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int tg_unthrottle_up(struct task_group *tg, void *data) { struct rq *rq = data; struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; cfs_rq->throttle_count--; if (!cfs_rq->throttle_count) { /* adjust cfs_rq_clock_task() */ cfs_rq->throttled_clock_task_time += rq_clock_task(rq) - cfs_rq->throttled_clock_task; } return 0; } 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: const CuePoint* Cues::GetNext(const CuePoint* pCurr) const { if (pCurr == NULL) return NULL; assert(pCurr->GetTimeCode() >= 0); assert(m_cue_points); assert(m_count >= 1); #if 0 const size_t count = m_count + m_preload_count; size_t index = pCurr->m_index; assert(index < count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); pNext->Load(m_pSegment->m_pReader); #else long index = pCurr->m_index; assert(index < m_count); CuePoint* const* const pp = m_cue_points; assert(pp); assert(pp[index] == pCurr); ++index; if (index >= m_count) return NULL; CuePoint* const pNext = pp[index]; assert(pNext); assert(pNext->GetTimeCode() >= 0); #endif return pNext; } 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 user_update(struct key *key, struct key_preparsed_payload *prep) { struct user_key_payload *upayload, *zap; size_t datalen = prep->datalen; int ret; ret = -EINVAL; if (datalen <= 0 || datalen > 32767 || !prep->data) goto error; /* construct a replacement payload */ ret = -ENOMEM; upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); if (!upayload) goto error; upayload->datalen = datalen; memcpy(upayload->data, prep->data, datalen); /* check the quota and attach the new data */ zap = upayload; ret = key_payload_reserve(key, datalen); if (ret == 0) { /* attach the new data, displacing the old */ zap = key->payload.data[0]; rcu_assign_keypointer(key, upayload); key->expiry = 0; } if (zap) kfree_rcu(zap, rcu); error: return ret; } CWE ID: CWE-264 Target: 1 Example 2: Code: static int connect_server(const char *hostname, in_port_t port, bool nonblock) { struct addrinfo *ai = lookuphost(hostname, port); int sock = -1; if (ai != NULL) { if ((sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) != -1) { if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) { fprintf(stderr, "Failed to connect socket: %s\n", strerror(errno)); close(sock); sock = -1; } else if (nonblock) { int flags = fcntl(sock, F_GETFL, 0); if (flags < 0 || fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) { fprintf(stderr, "Failed to enable nonblocking mode: %s\n", strerror(errno)); close(sock); sock = -1; } } } else { fprintf(stderr, "Failed to create socket: %s\n", strerror(errno)); } freeaddrinfo(ai); } return sock; } 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: unsigned long Tracks::GetTracksCount() const { const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries; assert(result >= 0); return static_cast<unsigned long>(result); } 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: xlate_to_uni(const unsigned char *name, int len, unsigned char *outname, int *longlen, int *outlen, int escape, int utf8, struct nls_table *nls) { const unsigned char *ip; unsigned char nc; unsigned char *op; unsigned int ec; int i, k, fill; int charlen; if (utf8) { *outlen = utf8s_to_utf16s(name, len, (wchar_t *)outname); if (*outlen < 0) return *outlen; else if (*outlen > FAT_LFN_LEN) return -ENAMETOOLONG; op = &outname[*outlen * sizeof(wchar_t)]; } else { if (nls) { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; *outlen += 1) { if (escape && (*ip == ':')) { if (i > len - 5) return -EINVAL; ec = 0; for (k = 1; k < 5; k++) { nc = ip[k]; ec <<= 4; if (nc >= '0' && nc <= '9') { ec |= nc - '0'; continue; } if (nc >= 'a' && nc <= 'f') { ec |= nc - ('a' - 10); continue; } if (nc >= 'A' && nc <= 'F') { ec |= nc - ('A' - 10); continue; } return -EINVAL; } *op++ = ec & 0xFF; *op++ = ec >> 8; ip += 5; i += 5; } else { if ((charlen = nls->char2uni(ip, len - i, (wchar_t *)op)) < 0) return -EINVAL; ip += charlen; i += charlen; op += 2; } } if (i < len) return -ENAMETOOLONG; } else { for (i = 0, ip = name, op = outname, *outlen = 0; i < len && *outlen <= FAT_LFN_LEN; i++, *outlen += 1) { *op++ = *ip++; *op++ = 0; } if (i < len) return -ENAMETOOLONG; } } *longlen = *outlen; if (*outlen % 13) { *op++ = 0; *op++ = 0; *outlen += 1; if (*outlen % 13) { fill = 13 - (*outlen % 13); for (i = 0; i < fill; i++) { *op++ = 0xff; *op++ = 0xff; } *outlen += fill; } } return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: png_write_init(png_structp png_ptr) { /* We only come here via pre-1.0.7-compiled applications */ png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DataPipeConsumerDispatcher::StartSerialize(uint32_t* num_bytes, uint32_t* num_ports, uint32_t* num_handles) { base::AutoLock lock(lock_); DCHECK(in_transit_); *num_bytes = static_cast<uint32_t>(sizeof(SerializedState)); *num_ports = 1; *num_handles = 1; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> intMethodWithArgsCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.intMethodWithArgs"); if (args.Length() < 3) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, strArg, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 2, DefaultIsUndefined))) : 0); return v8::Integer::New(imp->intMethodWithArgs(intArg, strArg, objArg)); } CWE ID: Target: 1 Example 2: Code: static void setup_report_key(struct packet_command *cgc, unsigned agid, unsigned type) { cgc->cmd[0] = GPCMD_REPORT_KEY; cgc->cmd[10] = type | (agid << 6); switch (type) { case 0: case 8: case 5: { cgc->buflen = 8; break; } case 1: { cgc->buflen = 16; break; } case 2: case 4: { cgc->buflen = 12; break; } } cgc->cmd[9] = cgc->buflen; cgc->data_direction = CGC_DATA_READ; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AuthenticatorTouchIdIncognitoBumpSheetModel::OnAccept() { dialog_model()->HideDialogAndTryTouchId(); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool MessageLoop::NestableTasksAllowed() const { return nestable_tasks_allowed_; } CWE ID: Target: 1 Example 2: Code: iperf_setaffinity(int affinity) { #ifdef linux cpu_set_t cpu_set; CPU_ZERO(&cpu_set); CPU_SET(affinity, &cpu_set); if (sched_setaffinity(0, sizeof(cpu_set_t), &cpu_set) != 0) { i_errno = IEAFFINITY; return -1; } return 0; #else /*linux*/ i_errno = IEAFFINITY; return -1; #endif /*linux*/ } 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 proc_tgid_io_accounting(struct seq_file *m, struct pid_namespace *ns, struct pid *pid, struct task_struct *task) { return do_io_accounting(task, m, 1); } 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: my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error) { *ret = x +1; return TRUE; } CWE ID: CWE-264 Target: 1 Example 2: Code: static void reqsk_timer_handler(unsigned long data) { struct request_sock *req = (struct request_sock *)data; struct sock *sk_listener = req->rsk_listener; struct net *net = sock_net(sk_listener); struct inet_connection_sock *icsk = inet_csk(sk_listener); struct request_sock_queue *queue = &icsk->icsk_accept_queue; int qlen, expire = 0, resend = 0; int max_retries, thresh; u8 defer_accept; if (sk_state_load(sk_listener) != TCP_LISTEN) goto drop; max_retries = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_synack_retries; thresh = max_retries; /* Normally all the openreqs are young and become mature * (i.e. converted to established socket) for first timeout. * If synack was not acknowledged for 1 second, it means * one of the following things: synack was lost, ack was lost, * rtt is high or nobody planned to ack (i.e. synflood). * When server is a bit loaded, queue is populated with old * open requests, reducing effective size of queue. * When server is well loaded, queue size reduces to zero * after several minutes of work. It is not synflood, * it is normal operation. The solution is pruning * too old entries overriding normal timeout, when * situation becomes dangerous. * * Essentially, we reserve half of room for young * embrions; and abort old ones without pity, if old * ones are about to clog our table. */ qlen = reqsk_queue_len(queue); if ((qlen << 1) > max(8U, sk_listener->sk_max_ack_backlog)) { int young = reqsk_queue_len_young(queue) << 1; while (thresh > 2) { if (qlen < young) break; thresh--; young <<= 1; } } defer_accept = READ_ONCE(queue->rskq_defer_accept); if (defer_accept) max_retries = defer_accept; syn_ack_recalc(req, thresh, max_retries, defer_accept, &expire, &resend); req->rsk_ops->syn_ack_timeout(req); if (!expire && (!resend || !inet_rtx_syn_ack(sk_listener, req) || inet_rsk(req)->acked)) { unsigned long timeo; if (req->num_timeout++ == 0) atomic_dec(&queue->young); timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX); mod_timer(&req->rsk_timer, jiffies + timeo); return; } drop: inet_csk_reqsk_queue_drop_and_put(sk_listener, req); } CWE ID: CWE-415 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ScrollHitTestDisplayItem::ScrollHitTestDisplayItem( const DisplayItemClient& client, Type type, scoped_refptr<const TransformPaintPropertyNode> scroll_offset_node) : DisplayItem(client, type, sizeof(*this)), scroll_offset_node_(std::move(scroll_offset_node)) { DCHECK(RuntimeEnabledFeatures::SlimmingPaintV2Enabled()); DCHECK(IsScrollHitTestType(type)); DCHECK(scroll_offset_node_->ScrollNode()); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); BufferInfo *outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId); outHeader->nTimeStamp = header->nTimeStamp; outHeader->nFlags = header->nFlags; outHeader->nFilledLen = mWidth * mHeight * 3 / 2; uint8_t *dst = outHeader->pBuffer + outHeader->nOffset; const uint8_t *srcY = data; const uint8_t *srcU = srcY + mWidth * mHeight; const uint8_t *srcV = srcU + mWidth * mHeight / 4; size_t srcYStride = mWidth; size_t srcUStride = mWidth / 2; size_t srcVStride = srcUStride; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mPicToHeaderMap.removeItem(picId); delete header; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); } CWE ID: CWE-20 Target: 1 Example 2: Code: void CSSStyleSheetResource::SetDecodedSheetText( const String& decoded_sheet_text) { decoded_sheet_text_ = decoded_sheet_text; UpdateDecodedSize(); } 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 void dwc3_prepare_one_trb(struct dwc3_ep *dep, struct dwc3_request *req, unsigned chain, unsigned node) { struct dwc3_trb *trb; unsigned length = req->request.length; unsigned stream_id = req->request.stream_id; unsigned short_not_ok = req->request.short_not_ok; unsigned no_interrupt = req->request.no_interrupt; dma_addr_t dma = req->request.dma; trb = &dep->trb_pool[dep->trb_enqueue]; if (!req->trb) { dwc3_gadget_move_started_request(req); req->trb = trb; req->trb_dma = dwc3_trb_dma_offset(dep, trb); dep->queued_requests++; } __dwc3_prepare_one_trb(dep, trb, dma, length, chain, node, stream_id, short_not_ok, no_interrupt); } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int hi3660_stub_clk_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct resource *res; unsigned int i; int ret; /* Use mailbox client without blocking */ stub_clk_chan.cl.dev = dev; stub_clk_chan.cl.tx_done = NULL; stub_clk_chan.cl.tx_block = false; stub_clk_chan.cl.knows_txdone = false; /* Allocate mailbox channel */ stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0); if (IS_ERR(stub_clk_chan.mbox)) return PTR_ERR(stub_clk_chan.mbox); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); freq_reg = devm_ioremap(dev, res->start, resource_size(res)); if (!freq_reg) return -ENOMEM; freq_reg += HI3660_STUB_CLOCK_DATA; for (i = 0; i < HI3660_CLK_STUB_NUM; i++) { ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw); if (ret) return ret; } return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get, hi3660_stub_clks); } CWE ID: CWE-476 Target: 1 Example 2: Code: bool RenderBox::needsPreferredWidthsRecalculation() const { return style()->paddingStart().isPercent() || style()->paddingEnd().isPercent(); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void igmp_heard_query(struct in_device *in_dev, struct sk_buff *skb, int len) { struct igmphdr *ih = igmp_hdr(skb); struct igmpv3_query *ih3 = igmpv3_query_hdr(skb); struct ip_mc_list *im; __be32 group = ih->group; int max_delay; int mark = 0; if (len == 8) { if (ih->code == 0) { /* Alas, old v1 router presents here. */ max_delay = IGMP_Query_Response_Interval; in_dev->mr_v1_seen = jiffies + IGMP_V1_Router_Present_Timeout; group = 0; } else { /* v2 router present */ max_delay = ih->code*(HZ/IGMP_TIMER_SCALE); in_dev->mr_v2_seen = jiffies + IGMP_V2_Router_Present_Timeout; } /* cancel the interface change timer */ in_dev->mr_ifc_count = 0; if (del_timer(&in_dev->mr_ifc_timer)) __in_dev_put(in_dev); /* clear deleted report items */ igmpv3_clear_delrec(in_dev); } else if (len < 12) { return; /* ignore bogus packet; freed by caller */ } else if (IGMP_V1_SEEN(in_dev)) { /* This is a v3 query with v1 queriers present */ max_delay = IGMP_Query_Response_Interval; group = 0; } else if (IGMP_V2_SEEN(in_dev)) { /* this is a v3 query with v2 queriers present; * Interpretation of the max_delay code is problematic here. * A real v2 host would use ih_code directly, while v3 has a * different encoding. We use the v3 encoding as more likely * to be intended in a v3 query. */ max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE); } else { /* v3 */ if (!pskb_may_pull(skb, sizeof(struct igmpv3_query))) return; ih3 = igmpv3_query_hdr(skb); if (ih3->nsrcs) { if (!pskb_may_pull(skb, sizeof(struct igmpv3_query) + ntohs(ih3->nsrcs)*sizeof(__be32))) return; ih3 = igmpv3_query_hdr(skb); } max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE); if (!max_delay) max_delay = 1; /* can't mod w/ 0 */ in_dev->mr_maxdelay = max_delay; if (ih3->qrv) in_dev->mr_qrv = ih3->qrv; if (!group) { /* general query */ if (ih3->nsrcs) return; /* no sources allowed */ igmp_gq_start_timer(in_dev); return; } /* mark sources to include, if group & source-specific */ mark = ih3->nsrcs != 0; } /* * - Start the timers in all of our membership records * that the query applies to for the interface on * which the query arrived excl. those that belong * to a "local" group (224.0.0.X) * - For timers already running check if they need to * be reset. * - Use the igmp->igmp_code field as the maximum * delay possible */ rcu_read_lock(); for_each_pmc_rcu(in_dev, im) { int changed; if (group && group != im->multiaddr) continue; if (im->multiaddr == IGMP_ALL_HOSTS) continue; spin_lock_bh(&im->lock); if (im->tm_running) im->gsquery = im->gsquery && mark; else im->gsquery = mark; changed = !im->gsquery || igmp_marksources(im, ntohs(ih3->nsrcs), ih3->srcs); spin_unlock_bh(&im->lock); if (changed) igmp_mod_timer(im, max_delay); } rcu_read_unlock(); } 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: SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); } CWE ID: CWE-190 Target: 1 Example 2: Code: scoped_refptr<VideoFrame> WebMediaPlayerImpl::GetCurrentFrameFromCompositor() const { DCHECK(main_task_runner_->BelongsToCurrentThread()); TRACE_EVENT0("media", "WebMediaPlayerImpl::GetCurrentFrameFromCompositor"); scoped_refptr<VideoFrame> video_frame = compositor_->GetCurrentFrameOnAnyThread(); vfc_task_runner_->PostTask( FROM_HERE, base::BindOnce(&VideoFrameCompositor::UpdateCurrentFrameIfStale, base::Unretained(compositor_.get()))); return video_frame; } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: network_end () { #ifdef HAVE_GNUTLS if (network_init_ok) { network_init_ok = 0; gnutls_certificate_free_credentials (gnutls_xcred); gnutls_global_deinit(); } #endif } 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: mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; switch (cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m); size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) len = sizeof(p->s) - 1; while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } } CWE ID: CWE-399 Target: 1 Example 2: Code: static size_t curl_write(char *data, size_t size, size_t nmemb, void *ctx) { php_curl *ch = (php_curl *) ctx; php_curl_write *t = ch->handlers->write; size_t length = size * nmemb; #if PHP_CURL_DEBUG fprintf(stderr, "curl_write() called\n"); fprintf(stderr, "data = %s, size = %d, nmemb = %d, ctx = %x\n", data, size, nmemb, ctx); #endif switch (t->method) { case PHP_CURL_STDOUT: PHPWRITE(data, length); break; case PHP_CURL_FILE: return fwrite(data, size, nmemb, t->fp); case PHP_CURL_RETURN: if (length > 0) { smart_str_appendl(&t->buf, data, (int) length); } break; case PHP_CURL_USER: { zval argv[2]; zval retval; int error; zend_fcall_info fci; ZVAL_RES(&argv[0], ch->res); Z_ADDREF(argv[0]); ZVAL_STRINGL(&argv[1], data, length); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object = NULL; ZVAL_COPY_VALUE(&fci.function_name, &t->func_name); fci.retval = &retval; fci.param_count = 2; fci.params = argv; fci.no_separation = 0; fci.symbol_table = NULL; ch->in_callback = 1; error = zend_call_function(&fci, &t->fci_cache); ch->in_callback = 0; if (error == FAILURE) { php_error_docref(NULL, E_WARNING, "Could not call the CURLOPT_WRITEFUNCTION"); length = -1; } else if (!Z_ISUNDEF(retval)) { if (Z_TYPE(retval) != IS_LONG) { convert_to_long_ex(&retval); } length = Z_LVAL(retval); } zval_ptr_dtor(&argv[0]); zval_ptr_dtor(&argv[1]); break; } } return length; } 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: DownloadItemImpl::GetExternalData(const void* key) { return const_cast<DownloadItem::ExternalData*>( static_cast<const DownloadItemImpl&>(*this).GetExternalData(key)); } 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: jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; long rem; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; } CWE ID: CWE-189 Target: 1 Example 2: Code: void RunLoop::Run() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!BeforeRun()) return; DETACH_FROM_SEQUENCE(sequence_checker_); tracked_objects::TaskStopwatch stopwatch; stopwatch.Start(); delegate_->Run(); stopwatch.Stop(); DETACH_FROM_SEQUENCE(sequence_checker_); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); AfterRun(); } 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: BluetoothSocketSendFunction::BluetoothSocketSendFunction() : io_buffer_size_(0) {} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: crm_client_new(qb_ipcs_connection_t * c, uid_t uid_client, gid_t gid_client) { static uid_t uid_server = 0; static gid_t gid_cluster = 0; crm_client_t *client = NULL; CRM_LOG_ASSERT(c); if (c == NULL) { return NULL; } if (gid_cluster == 0) { uid_server = getuid(); if(crm_user_lookup(CRM_DAEMON_USER, NULL, &gid_cluster) < 0) { static bool have_error = FALSE; if(have_error == FALSE) { crm_warn("Could not find group for user %s", CRM_DAEMON_USER); have_error = TRUE; } } } if(gid_cluster != 0 && gid_client != 0) { uid_t best_uid = -1; /* Passing -1 to chown(2) means don't change */ if(uid_client == 0 || uid_server == 0) { /* Someone is priveliged, but the other may not be */ best_uid = QB_MAX(uid_client, uid_server); crm_trace("Allowing user %u to clean up after disconnect", best_uid); } crm_trace("Giving access to group %u", gid_cluster); qb_ipcs_connection_auth_set(c, best_uid, gid_cluster, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); } crm_client_init(); /* TODO: Do our own auth checking, return NULL if unauthorized */ client = calloc(1, sizeof(crm_client_t)); client->ipcs = c; client->kind = CRM_CLIENT_IPC; client->pid = crm_ipcs_client_pid(c); client->id = crm_generate_uuid(); crm_debug("Connecting %p for uid=%d gid=%d pid=%u id=%s", c, uid_client, gid_client, client->pid, client->id); #if ENABLE_ACL client->user = uid2username(uid_client); #endif g_hash_table_insert(client_connections, c, client); return client; } CWE ID: CWE-285 Target: 1 Example 2: Code: int tls1_set_server_sigalgs(SSL *s) { int al; size_t i; /* Clear any shared signature algorithms */ OPENSSL_free(s->cert->shared_sigalgs); s->cert->shared_sigalgs = NULL; s->cert->shared_sigalgslen = 0; /* Clear certificate digests and validity flags */ for (i = 0; i < SSL_PKEY_NUM; i++) { s->s3->tmp.md[i] = NULL; s->s3->tmp.valid_flags[i] = 0; } /* If sigalgs received process it. */ if (s->s3->tmp.peer_sigalgs) { if (!tls1_process_sigalgs(s)) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE); al = SSL_AD_INTERNAL_ERROR; goto err; } /* Fatal error is no shared signature algorithms */ if (!s->cert->shared_sigalgs) { SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS); al = SSL_AD_ILLEGAL_PARAMETER; goto err; } } else { ssl_set_default_md(s); } return 1; err: ssl3_send_alert(s, SSL3_AL_FATAL, al); return 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void OfflinePageModelImpl::CacheLoadedData( const std::vector<OfflinePageItem>& offline_pages) { offline_pages_.clear(); for (const auto& offline_page : offline_pages) offline_pages_[offline_page.offline_id] = offline_page; } 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: virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); set_cpu_used_ = GET_PARAM(2); } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderFrameHostImpl::UpdateAXTreeData() { AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode(); if (accessibility_mode.is_mode_off() || !is_active()) { return; } std::vector<AXEventNotificationDetails> details; details.reserve(1U); AXEventNotificationDetails detail; detail.ax_tree_id = GetAXTreeID(); detail.update.has_tree_data = true; AXContentTreeDataToAXTreeData(&detail.update.tree_data); details.push_back(detail); if (browser_accessibility_manager_) browser_accessibility_manager_->OnAccessibilityEvents(details); delegate_->AccessibilityEventReceived(details); } 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: int qcow2_snapshot_load_tmp(BlockDriverState *bs, const char *snapshot_id, const char *name, Error **errp) { int i, snapshot_index; BDRVQcowState *s = bs->opaque; QCowSnapshot *sn; uint64_t *new_l1_table; int new_l1_bytes; int ret; assert(bs->read_only); /* Search the snapshot */ snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name); if (snapshot_index < 0) { error_setg(errp, "Can't find snapshot"); return -ENOENT; } sn = &s->snapshots[snapshot_index]; /* Allocate and read in the snapshot's L1 table */ new_l1_bytes = sn->l1_size * sizeof(uint64_t); new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512)); return ret; } 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: bool AXNodeObject::canSetValueAttribute() const { if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true")) return false; if (isProgressIndicator() || isSlider()) return true; if (isTextControl() && !isNativeTextControl()) return true; return !isReadOnly(); } CWE ID: CWE-254 Target: 1 Example 2: Code: int RAND_DRBG_set(RAND_DRBG *drbg, int type, unsigned int flags) { int ret = 1; if (type == 0 && flags == 0) { type = rand_drbg_type; flags = rand_drbg_flags; } /* If set is called multiple times - clear the old one */ if (drbg->type != 0 && (type != drbg->type || flags != drbg->flags)) { drbg->meth->uninstantiate(drbg); rand_pool_free(drbg->adin_pool); drbg->adin_pool = NULL; } drbg->state = DRBG_UNINITIALISED; drbg->flags = flags; drbg->type = type; switch (type) { default: drbg->type = 0; drbg->flags = 0; drbg->meth = NULL; RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_UNSUPPORTED_DRBG_TYPE); return 0; case 0: /* Uninitialized; that's okay. */ drbg->meth = NULL; return 1; case NID_aes_128_ctr: case NID_aes_192_ctr: case NID_aes_256_ctr: ret = drbg_ctr_init(drbg); break; } if (ret == 0) { drbg->state = DRBG_ERROR; RANDerr(RAND_F_RAND_DRBG_SET, RAND_R_ERROR_INITIALISING_DRBG); } return ret; } 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: AudioMixerAlsa::AudioMixerAlsa() : min_volume_db_(kDefaultMinVolumeDb), max_volume_db_(kDefaultMaxVolumeDb), volume_db_(kDefaultVolumeDb), is_muted_(false), apply_is_pending_(true), alsa_mixer_(NULL), pcm_element_(NULL), prefs_(NULL), disconnected_event_(true, false), num_connection_attempts_(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: gst_vorbis_tag_add_coverart (GstTagList * tags, const gchar * img_data_base64, gint base64_len) { GstBuffer *img; guchar *img_data; gsize img_len; guint save = 0; gint state = 0; if (base64_len < 2) goto not_enough_data; img_data = g_try_malloc0 (base64_len * 3 / 4); if (img_data == NULL) goto alloc_failed; img_len = g_base64_decode_step (img_data_base64, base64_len, img_data, &state, &save); if (img_len == 0) goto decode_failed; img = gst_tag_image_data_to_image_buffer (img_data, img_len, GST_TAG_IMAGE_TYPE_NONE); if (img == NULL) gst_tag_list_add (tags, GST_TAG_MERGE_APPEND, GST_TAG_PREVIEW_IMAGE, img, NULL); GST_TAG_PREVIEW_IMAGE, img, NULL); gst_buffer_unref (img); g_free (img_data); return; /* ERRORS */ { GST_WARNING ("COVERART tag with too little base64-encoded data"); GST_WARNING ("COVERART tag with too little base64-encoded data"); return; } alloc_failed: { GST_WARNING ("Couldn't allocate enough memory to decode COVERART tag"); return; } decode_failed: { GST_WARNING ("Couldn't decode bas64 image data from COVERART tag"); g_free (img_data); return; } convert_failed: { GST_WARNING ("Couldn't extract image or image type from COVERART tag"); g_free (img_data); return; } } CWE ID: CWE-189 Target: 1 Example 2: Code: static void ffs_func_suspend(struct usb_function *f) { ENTER(); ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND); } 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: long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = key_validate(key); if (ret == 0) { ret = -EOPNOTSUPP; if (key->type->read) { /* read the data with the semaphore held (since we * might sleep) */ down_read(&key->sem); ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } } error2: key_put(key); error: return ret; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(size_t) (*p++ << 24); *quantum|=(size_t) (*p++ << 16); *quantum|=(size_t) (*p++ << 8); *quantum|=(size_t) (*p++ << 0); return(p); } CWE ID: CWE-125 Target: 1 Example 2: Code: t1_decoder_init( T1_Decoder decoder, FT_Face face, FT_Size size, FT_GlyphSlot slot, FT_Byte** glyph_names, PS_Blend blend, FT_Bool hinting, FT_Render_Mode hint_mode, T1_Decoder_Callback parse_callback ) { FT_ZERO( decoder ); /* retrieve PSNames interface from list of current modules */ { FT_Service_PsCMaps psnames; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); if ( !psnames ) { FT_ERROR(( "t1_decoder_init:" " the `psnames' module is not available\n" )); return FT_THROW( Unimplemented_Feature ); } decoder->psnames = psnames; } t1_builder_init( &decoder->builder, face, size, slot, hinting ); /* decoder->buildchar and decoder->len_buildchar have to be */ /* initialized by the caller since we cannot know the length */ /* of the BuildCharArray */ decoder->num_glyphs = (FT_UInt)face->num_glyphs; decoder->glyph_names = glyph_names; decoder->hint_mode = hint_mode; decoder->blend = blend; decoder->parse_callback = parse_callback; decoder->funcs = t1_decoder_funcs; return FT_Err_Ok; } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderWidgetHostViewGuest::SetBounds(const gfx::Rect& rect) { SetSize(rect.size()); } 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 bool check_underflow(const struct arpt_entry *e) { const struct xt_entry_target *t; unsigned int verdict; if (!unconditional(&e->arp)) return false; t = arpt_get_target_c(e); if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0) return false; verdict = ((struct xt_standard_target *)t)->verdict; verdict = -verdict - 1; return verdict == NF_DROP || verdict == NF_ACCEPT; } CWE ID: CWE-119 Target: 1 Example 2: Code: xfs_attr3_leaf_hdr_from_disk( struct xfs_da_geometry *geo, struct xfs_attr3_icleaf_hdr *to, struct xfs_attr_leafblock *from) { int i; ASSERT(from->hdr.info.magic == cpu_to_be16(XFS_ATTR_LEAF_MAGIC) || from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC)); if (from->hdr.info.magic == cpu_to_be16(XFS_ATTR3_LEAF_MAGIC)) { struct xfs_attr3_leaf_hdr *hdr3 = (struct xfs_attr3_leaf_hdr *)from; to->forw = be32_to_cpu(hdr3->info.hdr.forw); to->back = be32_to_cpu(hdr3->info.hdr.back); to->magic = be16_to_cpu(hdr3->info.hdr.magic); to->count = be16_to_cpu(hdr3->count); to->usedbytes = be16_to_cpu(hdr3->usedbytes); xfs_attr3_leaf_firstused_from_disk(geo, to, from); to->holes = hdr3->holes; for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { to->freemap[i].base = be16_to_cpu(hdr3->freemap[i].base); to->freemap[i].size = be16_to_cpu(hdr3->freemap[i].size); } return; } to->forw = be32_to_cpu(from->hdr.info.forw); to->back = be32_to_cpu(from->hdr.info.back); to->magic = be16_to_cpu(from->hdr.info.magic); to->count = be16_to_cpu(from->hdr.count); to->usedbytes = be16_to_cpu(from->hdr.usedbytes); xfs_attr3_leaf_firstused_from_disk(geo, to, from); to->holes = from->hdr.holes; for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { to->freemap[i].base = be16_to_cpu(from->hdr.freemap[i].base); to->freemap[i].size = be16_to_cpu(from->hdr.freemap[i].size); } } 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 int qeth_ulp_enable_cb(struct qeth_card *card, struct qeth_reply *reply, unsigned long data) { __u16 mtu, framesize; __u16 len; __u8 link_type; struct qeth_cmd_buffer *iob; QETH_DBF_TEXT(SETUP, 2, "ulpenacb"); iob = (struct qeth_cmd_buffer *) data; memcpy(&card->token.ulp_filter_r, QETH_ULP_ENABLE_RESP_FILTER_TOKEN(iob->data), QETH_MPC_TOKEN_LENGTH); if (card->info.type == QETH_CARD_TYPE_IQD) { memcpy(&framesize, QETH_ULP_ENABLE_RESP_MAX_MTU(iob->data), 2); mtu = qeth_get_mtu_outof_framesize(framesize); if (!mtu) { iob->rc = -EINVAL; QETH_DBF_TEXT_(SETUP, 2, " rc%d", iob->rc); return 0; } if (card->info.initial_mtu && (card->info.initial_mtu != mtu)) { /* frame size has changed */ if (card->dev && ((card->dev->mtu == card->info.initial_mtu) || (card->dev->mtu > mtu))) card->dev->mtu = mtu; qeth_free_qdio_buffers(card); } card->info.initial_mtu = mtu; card->info.max_mtu = mtu; card->qdio.in_buf_size = mtu + 2 * PAGE_SIZE; } else { card->info.max_mtu = *(__u16 *)QETH_ULP_ENABLE_RESP_MAX_MTU( iob->data); card->info.initial_mtu = min(card->info.max_mtu, qeth_get_initial_mtu_for_card(card)); card->qdio.in_buf_size = QETH_IN_BUF_SIZE_DEFAULT; } memcpy(&len, QETH_ULP_ENABLE_RESP_DIFINFO_LEN(iob->data), 2); if (len >= QETH_MPC_DIFINFO_LEN_INDICATES_LINK_TYPE) { memcpy(&link_type, QETH_ULP_ENABLE_RESP_LINK_TYPE(iob->data), 1); card->info.link_type = link_type; } else card->info.link_type = 0; QETH_DBF_TEXT_(SETUP, 2, "link%d", card->info.link_type); QETH_DBF_TEXT_(SETUP, 2, " rc%d", iob->rc); 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: SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ CWE ID: CWE-190 Target: 1 Example 2: Code: ber_wrap_hdr_data(int tagval, STREAM in) { STREAM out; int size = s_length(in) + 16; out = xmalloc(sizeof(struct stream)); memset(out, 0, sizeof(struct stream)); out->data = xmalloc(size); out->size = size; out->p = out->data; ber_out_header(out, tagval, s_length(in)); out_uint8p(out, in->data, s_length(in)); s_mark_end(out); return out; } 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: modify_policy_2_svc(mpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, NULL, NULL)) { log_unauth("kadm5_modify_policy", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_MODIFY; } else { ret.code = kadm5_modify_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_modify_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } CWE ID: CWE-119 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 CompileFromResponseCallback( const v8::FunctionCallbackInfo<v8::Value>& args) { ExceptionState exception_state(args.GetIsolate(), ExceptionState::kExecutionContext, "WebAssembly", "compile"); ExceptionToRejectPromiseScope reject_promise_scope(args, exception_state); ScriptState* script_state = ScriptState::ForRelevantRealm(args); if (!ExecutionContext::From(script_state)) { V8SetReturnValue(args, ScriptPromise().V8Value()); return; } if (args.Length() < 1 || !args[0]->IsObject() || !V8Response::hasInstance(args[0], args.GetIsolate())) { V8SetReturnValue( args, ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "An argument must be provided, which must be a" "Response or Promise<Response> object")) .V8Value()); return; } Response* response = V8Response::ToImpl(v8::Local<v8::Object>::Cast(args[0])); if (response->MimeType() != "application/wasm") { V8SetReturnValue( args, ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Incorrect response MIME type. Expected 'application/wasm'.")) .V8Value()); return; } v8::Local<v8::Value> promise; if (response->IsBodyLocked() || response->bodyUsed()) { promise = ScriptPromise::Reject(script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Cannot compile WebAssembly.Module " "from an already read Response")) .V8Value(); } else { if (response->BodyBuffer()) { FetchDataLoaderAsWasmModule* loader = new FetchDataLoaderAsWasmModule(script_state); promise = loader->GetPromise(); response->BodyBuffer()->StartLoading(loader, new WasmDataLoaderClient()); } else { promise = ScriptPromise::Reject(script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Response object has a null body.")) .V8Value(); } } V8SetReturnValue(args, promise); } CWE ID: CWE-79 Target: 1 Example 2: Code: bool GetIntArrayProperty(XID window, const std::string& property_name, std::vector<int>* value) { Atom type = None; int format = 0; // size in bits of each item in 'property' unsigned long num_items = 0; unsigned char* properties = NULL; int result = GetProperty(window, property_name, (~0L), // (all of them) &type, &format, &num_items, &properties); if (result != Success) return false; if (format != 32) { XFree(properties); return false; } long* int_properties = reinterpret_cast<long*>(properties); value->clear(); for (unsigned long i = 0; i < num_items; ++i) { value->push_back(static_cast<int>(int_properties[i])); } XFree(properties); return true; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PaymentRequest::Init(mojom::PaymentRequestClientPtr client, std::vector<mojom::PaymentMethodDataPtr> method_data, mojom::PaymentDetailsPtr details, mojom::PaymentOptionsPtr options) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); client_ = std::move(client); const GURL last_committed_url = delegate_->GetLastCommittedURL(); if (!OriginSecurityChecker::IsOriginSecure(last_committed_url)) { LOG(ERROR) << "Not in a secure origin"; OnConnectionTerminated(); return; } bool allowed_origin = OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) || OriginSecurityChecker::IsOriginLocalhostOrFile(last_committed_url); if (!allowed_origin) { LOG(ERROR) << "Only localhost, file://, and cryptographic scheme origins " "allowed"; } bool invalid_ssl = OriginSecurityChecker::IsSchemeCryptographic(last_committed_url) && !delegate_->IsSslCertificateValid(); if (invalid_ssl) LOG(ERROR) << "SSL certificate is not valid"; if (!allowed_origin || invalid_ssl) { return; } std::string error; if (!ValidatePaymentDetails(ConvertPaymentDetails(details), &error)) { LOG(ERROR) << error; OnConnectionTerminated(); return; } if (!details->total) { LOG(ERROR) << "Missing total"; OnConnectionTerminated(); return; } spec_ = std::make_unique<PaymentRequestSpec>( std::move(options), std::move(details), std::move(method_data), this, delegate_->GetApplicationLocale()); state_ = std::make_unique<PaymentRequestState>( web_contents_, top_level_origin_, frame_origin_, spec_.get(), this, delegate_->GetApplicationLocale(), delegate_->GetPersonalDataManager(), delegate_.get(), &journey_logger_); journey_logger_.SetRequestedInformation( spec_->request_shipping(), spec_->request_payer_email(), spec_->request_payer_phone(), spec_->request_payer_name()); GURL google_pay_url(kGooglePayMethodName); GURL android_pay_url(kAndroidPayMethodName); auto non_google_it = std::find_if(spec_->url_payment_method_identifiers().begin(), spec_->url_payment_method_identifiers().end(), [google_pay_url, android_pay_url](const GURL& url) { return url != google_pay_url && url != android_pay_url; }); journey_logger_.SetRequestedPaymentMethodTypes( /*requested_basic_card=*/!spec_->supported_card_networks().empty(), /*requested_method_google=*/ base::ContainsValue(spec_->url_payment_method_identifiers(), google_pay_url) || base::ContainsValue(spec_->url_payment_method_identifiers(), android_pay_url), /*requested_method_other=*/non_google_it != spec_->url_payment_method_identifiers().end()); } 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: bool DoCanonicalizePathComponent(const CHAR* source, const Component& component, char separator, CanonOutput* output, Component* new_component) { bool success = true; if (component.is_valid()) { if (separator) output->push_back(separator); new_component->begin = output->length(); int end = component.end(); for (int i = component.begin; i < end; i++) { UCHAR uch = static_cast<UCHAR>(source[i]); if (uch < 0x20 || uch >= 0x80) success &= AppendUTF8EscapedChar(source, &i, end, output); else output->push_back(static_cast<char>(uch)); } new_component->len = output->length() - new_component->begin; } else { new_component->reset(); } return success; } CWE ID: CWE-20 Target: 1 Example 2: Code: static void rfcomm_tty_set_termios(struct tty_struct *tty, struct ktermios *old) { struct ktermios *new = tty->termios; int old_baud_rate = tty_termios_baud_rate(old); int new_baud_rate = tty_termios_baud_rate(new); u8 baud, data_bits, stop_bits, parity, x_on, x_off; u16 changes = 0; struct rfcomm_dev *dev = (struct rfcomm_dev *) tty->driver_data; BT_DBG("tty %p termios %p", tty, old); if (!dev || !dev->dlc || !dev->dlc->session) return; /* Handle turning off CRTSCTS */ if ((old->c_cflag & CRTSCTS) && !(new->c_cflag & CRTSCTS)) BT_DBG("Turning off CRTSCTS unsupported"); /* Parity on/off and when on, odd/even */ if (((old->c_cflag & PARENB) != (new->c_cflag & PARENB)) || ((old->c_cflag & PARODD) != (new->c_cflag & PARODD))) { changes |= RFCOMM_RPN_PM_PARITY; BT_DBG("Parity change detected."); } /* Mark and space parity are not supported! */ if (new->c_cflag & PARENB) { if (new->c_cflag & PARODD) { BT_DBG("Parity is ODD"); parity = RFCOMM_RPN_PARITY_ODD; } else { BT_DBG("Parity is EVEN"); parity = RFCOMM_RPN_PARITY_EVEN; } } else { BT_DBG("Parity is OFF"); parity = RFCOMM_RPN_PARITY_NONE; } /* Setting the x_on / x_off characters */ if (old->c_cc[VSTOP] != new->c_cc[VSTOP]) { BT_DBG("XOFF custom"); x_on = new->c_cc[VSTOP]; changes |= RFCOMM_RPN_PM_XON; } else { BT_DBG("XOFF default"); x_on = RFCOMM_RPN_XON_CHAR; } if (old->c_cc[VSTART] != new->c_cc[VSTART]) { BT_DBG("XON custom"); x_off = new->c_cc[VSTART]; changes |= RFCOMM_RPN_PM_XOFF; } else { BT_DBG("XON default"); x_off = RFCOMM_RPN_XOFF_CHAR; } /* Handle setting of stop bits */ if ((old->c_cflag & CSTOPB) != (new->c_cflag & CSTOPB)) changes |= RFCOMM_RPN_PM_STOP; /* POSIX does not support 1.5 stop bits and RFCOMM does not * support 2 stop bits. So a request for 2 stop bits gets * translated to 1.5 stop bits */ if (new->c_cflag & CSTOPB) stop_bits = RFCOMM_RPN_STOP_15; else stop_bits = RFCOMM_RPN_STOP_1; /* Handle number of data bits [5-8] */ if ((old->c_cflag & CSIZE) != (new->c_cflag & CSIZE)) changes |= RFCOMM_RPN_PM_DATA; switch (new->c_cflag & CSIZE) { case CS5: data_bits = RFCOMM_RPN_DATA_5; break; case CS6: data_bits = RFCOMM_RPN_DATA_6; break; case CS7: data_bits = RFCOMM_RPN_DATA_7; break; case CS8: data_bits = RFCOMM_RPN_DATA_8; break; default: data_bits = RFCOMM_RPN_DATA_8; break; } /* Handle baudrate settings */ if (old_baud_rate != new_baud_rate) changes |= RFCOMM_RPN_PM_BITRATE; switch (new_baud_rate) { case 2400: baud = RFCOMM_RPN_BR_2400; break; case 4800: baud = RFCOMM_RPN_BR_4800; break; case 7200: baud = RFCOMM_RPN_BR_7200; break; case 9600: baud = RFCOMM_RPN_BR_9600; break; case 19200: baud = RFCOMM_RPN_BR_19200; break; case 38400: baud = RFCOMM_RPN_BR_38400; break; case 57600: baud = RFCOMM_RPN_BR_57600; break; case 115200: baud = RFCOMM_RPN_BR_115200; break; case 230400: baud = RFCOMM_RPN_BR_230400; break; default: /* 9600 is standard accordinag to the RFCOMM specification */ baud = RFCOMM_RPN_BR_9600; break; } if (changes) rfcomm_send_rpn(dev->dlc->session, 1, dev->dlc->dlci, baud, data_bits, stop_bits, parity, RFCOMM_RPN_FLOW_NONE, x_on, x_off, changes); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ipip_err(struct sk_buff *skb, u32 info) { /* All the routers (except for Linux) return only 8 bytes of packet payload. It means, that precise relaying of ICMP in the real Internet is absolutely infeasible. */ struct iphdr *iph = (struct iphdr *)skb->data; const int type = icmp_hdr(skb)->type; const int code = icmp_hdr(skb)->code; struct ip_tunnel *t; int err; switch (type) { default: case ICMP_PARAMETERPROB: return 0; case ICMP_DEST_UNREACH: switch (code) { case ICMP_SR_FAILED: case ICMP_PORT_UNREACH: /* Impossible event. */ return 0; case ICMP_FRAG_NEEDED: /* Soft state for pmtu is maintained by IP core. */ return 0; default: /* All others are translated to HOST_UNREACH. rfc2003 contains "deep thoughts" about NET_UNREACH, I believe they are just ether pollution. --ANK */ break; } break; case ICMP_TIME_EXCEEDED: if (code != ICMP_EXC_TTL) return 0; break; } err = -ENOENT; rcu_read_lock(); t = ipip_tunnel_lookup(dev_net(skb->dev), iph->daddr, iph->saddr); if (t == NULL || t->parms.iph.daddr == 0) goto out; err = 0; if (t->parms.iph.ttl == 0 && type == ICMP_TIME_EXCEEDED) goto out; if (time_before(jiffies, t->err_time + IPTUNNEL_ERR_TIMEO)) t->err_count++; else t->err_count = 1; t->err_time = jiffies; out: rcu_read_unlock(); return err; } 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: void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) { std::string path; CHECK(args->GetString(0, &path)); DCHECK(StartsWithASCII(path, "chrome://favicon/", false)) << "path is " << path; path = path.substr(arraysize("chrome://favicon/") - 1); double id; CHECK(args->GetDouble(1, &id)); FaviconService* favicon_service = web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS); if (!favicon_service || path.empty()) return; FaviconService::Handle handle = favicon_service->GetFaviconForURL( GURL(path), history::FAVICON, &consumer_, NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable)); consumer_.SetClientData(favicon_service, handle, static_cast<int>(id)); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void airo_handle_cisco_mic(struct airo_info *ai) { if (test_bit(FLAG_MIC_CAPABLE, &ai->flags)) { set_bit(JOB_MIC, &ai->jobs); wake_up_interruptible(&ai->thr_wait); } } 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 RenderViewTest::SetUp() { if (!GetContentClient()->renderer()) GetContentClient()->set_renderer(&mock_content_renderer_client_); if (!render_thread_.get()) render_thread_.reset(new MockRenderThread()); render_thread_->set_routing_id(kRouteId); render_thread_->set_surface_id(kSurfaceId); command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); params_.reset(new content::MainFunctionParams(*command_line_)); platform_.reset(new RendererMainPlatformDelegate(*params_)); platform_->PlatformInitialize(); webkit_glue::SetJavaScriptFlags(" --expose-gc"); WebKit::initialize(&webkit_platform_support_); mock_process_.reset(new MockRenderProcess); RenderViewImpl* view = RenderViewImpl::Create( 0, kOpenerId, content::RendererPreferences(), WebPreferences(), new SharedRenderViewCounter(0), kRouteId, kSurfaceId, kInvalidSessionStorageNamespaceId, string16(), 1, WebKit::WebScreenInfo()); view->AddRef(); view_ = view; mock_keyboard_.reset(new MockKeyboard()); } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GfxImageColorMap::getRGBLine(Guchar *in, unsigned int *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmalloc (length * nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getRGBLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getRGBLine(in, out, length); break; } } CWE ID: CWE-189 Target: 1 Example 2: Code: gfx::Vector2d RenderViewImpl::GetScrollOffset() { WebSize scroll_offset = webview()->mainFrame()->scrollOffset(); return gfx::Vector2d(scroll_offset.width, scroll_offset.height); } 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: hook_timer_init (struct t_hook *hook) { time_t time_now; struct tm *local_time, *gm_time; int local_hour, gm_hour, diff_hour; gettimeofday (&HOOK_TIMER(hook, last_exec), NULL); time_now = time (NULL); local_time = localtime(&time_now); local_hour = local_time->tm_hour; gm_time = gmtime(&time_now); gm_hour = gm_time->tm_hour; if ((local_time->tm_year > gm_time->tm_year) || (local_time->tm_mon > gm_time->tm_mon) || (local_time->tm_mday > gm_time->tm_mday)) { diff_hour = (24 - gm_hour) + local_hour; } else if ((gm_time->tm_year > local_time->tm_year) || (gm_time->tm_mon > local_time->tm_mon) || (gm_time->tm_mday > local_time->tm_mday)) { diff_hour = (-1) * ((24 - local_hour) + gm_hour); } else diff_hour = local_hour - gm_hour; if ((HOOK_TIMER(hook, interval) >= 1000) && (HOOK_TIMER(hook, align_second) > 0)) { /* * here we should use 0, but with this value timer is sometimes called * before second has changed, so for displaying time, it may display * 2 times the same second, that's why we use 1000 micro seconds */ HOOK_TIMER(hook, last_exec).tv_usec = 1000; HOOK_TIMER(hook, last_exec).tv_sec = HOOK_TIMER(hook, last_exec).tv_sec - ((HOOK_TIMER(hook, last_exec).tv_sec + (diff_hour * 3600)) % HOOK_TIMER(hook, align_second)); } /* init next call with date of last call */ HOOK_TIMER(hook, next_exec).tv_sec = HOOK_TIMER(hook, last_exec).tv_sec; HOOK_TIMER(hook, next_exec).tv_usec = HOOK_TIMER(hook, last_exec).tv_usec; /* add interval to next call date */ util_timeval_add (&HOOK_TIMER(hook, next_exec), HOOK_TIMER(hook, interval)); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void user_login(struct mt_connection *curconn, struct mt_mactelnet_hdr *pkthdr) { struct mt_packet pdata; unsigned char md5sum[17]; char md5data[100]; struct mt_credentials *user; char *slavename; /* Reparse user file before each login */ read_userfile(); if ((user = find_user(curconn->username)) != NULL) { md5_state_t state; #if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE) mlock(md5data, sizeof(md5data)); mlock(md5sum, sizeof(md5sum)); if (user->password != NULL) { mlock(user->password, strlen(user->password)); } #endif /* Concat string of 0 + password + pass_salt */ md5data[0] = 0; strncpy(md5data + 1, user->password, 82); memcpy(md5data + 1 + strlen(user->password), curconn->pass_salt, 16); /* Generate md5 sum of md5data with a leading 0 */ md5_init(&state); md5_append(&state, (const md5_byte_t *)md5data, strlen(user->password) + 17); md5_finish(&state, (md5_byte_t *)md5sum + 1); md5sum[0] = 0; init_packet(&pdata, MT_PTYPE_DATA, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter); curconn->outcounter += add_control_packet(&pdata, MT_CPTYPE_END_AUTH, NULL, 0); send_udp(curconn, &pdata); if (curconn->state == STATE_ACTIVE) { return; } } if (user == NULL || memcmp(md5sum, curconn->trypassword, 17) != 0) { syslog(LOG_NOTICE, _("(%d) Invalid login by %s."), curconn->seskey, curconn->username); /*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */ abort_connection(curconn, pkthdr, _("Login failed, incorrect username or password\r\n")); /* TODO: should wait some time (not with sleep) before returning, to minimalize brute force attacks */ return; } /* User is logged in */ curconn->state = STATE_ACTIVE; /* Enter terminal mode */ curconn->terminal_mode = 1; /* Open pts handle */ curconn->ptsfd = posix_openpt(O_RDWR); if (curconn->ptsfd == -1 || grantpt(curconn->ptsfd) == -1 || unlockpt(curconn->ptsfd) == -1) { syslog(LOG_ERR, "posix_openpt: %s", strerror(errno)); /*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */ abort_connection(curconn, pkthdr, _("Terminal error\r\n")); return; } /* Get file path for our pts */ slavename = ptsname(curconn->ptsfd); if (slavename != NULL) { pid_t pid; struct stat sb; struct passwd *user = (struct passwd *)malloc(sizeof(struct passwd)); struct passwd *tmpuser=user; char *buffer = malloc(1024); if (user == NULL || buffer == NULL) { syslog(LOG_CRIT, _("(%d) Error allocating memory."), curconn->seskey); /*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */ abort_connection(curconn, pkthdr, _("System error, out of memory\r\n")); return; } if (getpwnam_r(curconn->username, user, buffer, 1024, &tmpuser) != 0) { syslog(LOG_WARNING, _("(%d) Login ok, but local user not accessible (%s)."), curconn->seskey, curconn->username); /*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */ abort_connection(curconn, pkthdr, _("Local user not accessible\r\n")); free(user); free(buffer); return; } /* Change the owner of the slave pts */ chown(slavename, user->pw_uid, user->pw_gid); curconn->slavefd = open(slavename, O_RDWR); if (curconn->slavefd == -1) { syslog(LOG_ERR, _("Error opening %s: %s"), slavename, strerror(errno)); /*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */ abort_connection(curconn, pkthdr, _("Error opening terminal\r\n")); list_remove_connection(curconn); return; } if ((pid = fork()) == 0) { struct net_interface *interface; /* Add login information to utmp/wtmp */ uwtmp_login(curconn); syslog(LOG_INFO, _("(%d) User %s logged in."), curconn->seskey, curconn->username); /* Initialize terminal environment */ setenv("USER", user->pw_name, 1); setenv("HOME", user->pw_dir, 1); setenv("SHELL", user->pw_shell, 1); setenv("TERM", curconn->terminal_type, 1); close(sockfd); close(insockfd); DL_FOREACH(interfaces, interface) { if (interface->socketfd > 0) { close(interface->socketfd); } } setsid(); /* Don't let shell process inherit slavefd */ fcntl (curconn->slavefd, F_SETFD, FD_CLOEXEC); close(curconn->ptsfd); /* Redirect STDIN/STDIO/STDERR */ close(0); dup(curconn->slavefd); close(1); dup(curconn->slavefd); close(2); dup(curconn->slavefd); /* Set controlling terminal */ ioctl(0, TIOCSCTTY, 1); tcsetpgrp(0, getpid()); /* Set user id/group id */ if ((setgid(user->pw_gid) != 0) || (setuid(user->pw_uid) != 0)) { syslog(LOG_ERR, _("(%d) Could not log in %s (%d:%d): setuid/setgid: %s"), curconn->seskey, curconn->username, user->pw_uid, user->pw_gid, strerror(errno)); /*_ Please include both \r and \n in translation, this is needed for the terminal emulator. */ abort_connection(curconn, pkthdr, _("Internal error\r\n")); exit(0); } /* Abort login if /etc/nologin exists */ if (stat(_PATH_NOLOGIN, &sb) == 0 && getuid() != 0) { syslog(LOG_NOTICE, _("(%d) User %s disconnected with " _PATH_NOLOGIN " message."), curconn->seskey, curconn->username); display_nologin(); curconn->state = STATE_CLOSED; init_packet(&pdata, MT_PTYPE_END, pkthdr->dstaddr, pkthdr->srcaddr, pkthdr->seskey, curconn->outcounter); send_udp(curconn, &pdata); exit(0); } /* Display MOTD */ display_motd(); chdir(user->pw_dir); /* Spawn shell */ /* TODO: Maybe use "login -f USER" instead? renders motd and executes shell correctly for system */ execl(user->pw_shell, user->pw_shell, "-", (char *) 0); exit(0); // just to be sure. } free(user); free(buffer); close(curconn->slavefd); curconn->pid = pid; set_terminal_size(curconn->ptsfd, curconn->terminal_width, curconn->terminal_height); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void prb_freeze_queue(struct tpacket_kbdq_core *pkc, struct packet_sock *po) { pkc->reset_pending_on_curr_blk = 1; po->stats.stats3.tp_freeze_q_cnt++; } 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: raptor_rdfxml_parse_start(raptor_parser* rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rdfxml_parser* rdf_xml_parser; rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context; /* base URI required for RDF/XML */ if(!uri) return 1; /* Optionally normalize language to lowercase * http://www.w3.org/TR/rdf-concepts/#dfn-language-identifier */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NORMALIZE_LANGUAGE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NORMALIZE_LANGUAGE)); /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rdf_xml_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rdf_xml_parser->sax2, uri); /* Delete any existing id_set */ if(rdf_xml_parser->id_set) { raptor_free_id_set(rdf_xml_parser->id_set); rdf_xml_parser->id_set = NULL; } /* Create a new id_set if needed */ if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_CHECK_RDF_ID)) { rdf_xml_parser->id_set = raptor_new_id_set(rdf_parser->world); if(!rdf_xml_parser->id_set) return 1; } return 0; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: authentic_set_current_files(struct sc_card *card, struct sc_path *path, unsigned char *resp, size_t resplen, struct sc_file **file_out) { struct sc_context *ctx = card->ctx; struct sc_file *file = NULL; int rv; LOG_FUNC_CALLED(ctx); if (resplen) { switch (resp[0]) { case 0x62: case 0x6F: file = sc_file_new(); if (file == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); if (path) file->path = *path; rv = authentic_process_fci(card, file, resp, resplen); LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error"); break; default: LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED); } if (file->type == SC_FILE_TYPE_DF) { struct sc_path cur_df_path; memset(&cur_df_path, 0, sizeof(cur_df_path)); if (card->cache.valid && card->cache.current_df) { cur_df_path = card->cache.current_df->path; sc_file_free(card->cache.current_df); } card->cache.current_df = NULL; sc_file_dup(&card->cache.current_df, file); if (cur_df_path.len) { memcpy(card->cache.current_df->path.value + cur_df_path.len, card->cache.current_df->path.value, card->cache.current_df->path.len); memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len); card->cache.current_df->path.len += cur_df_path.len; } sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; card->cache.valid = 1; } else { sc_file_free(card->cache.current_ef); card->cache.current_ef = NULL; sc_file_dup(&card->cache.current_ef, file); } if (file_out) *file_out = file; else sc_file_free(file); } LOG_FUNC_RETURN(ctx, SC_SUCCESS); } CWE ID: CWE-125 Target: 1 Example 2: Code: void RenderBlockFlow::addOverflowFromFloats() { if (!m_floatingObjects) return; const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); FloatingObjectSetIterator end = floatingObjectSet.end(); for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) { FloatingObject* floatingObject = *it; if (floatingObject->isDescendant()) addOverflowFromChild(floatingObject->renderer(), IntSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject))); } } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long vorbis_book_decodev_add(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j; if (!v) return -1; for(i=0;i<n;){ if(decode_map(book,b,v,point))return -1; for (j=0;j<book->dim;j++) a[i++]+=v[j]; } } return 0; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb) { struct block_device *bdev; char b[BDEVNAME_SIZE]; bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb); if (IS_ERR(bdev)) goto fail; return bdev; fail: ext3_msg(sb, "error: failed to open journal device %s: %ld", __bdevname(dev, b), PTR_ERR(bdev)); return NULL; } CWE ID: CWE-20 Target: 1 Example 2: Code: sc_get_driver(void) { struct sc_card_driver *iso_drv = sc_get_iso7816_driver(); if (!iso_ops) iso_ops = iso_drv->ops; authentic_ops = *iso_ops; authentic_ops.match_card = authentic_match_card; authentic_ops.init = authentic_init; authentic_ops.finish = authentic_finish; authentic_ops.read_binary = authentic_read_binary; authentic_ops.write_binary = authentic_write_binary; authentic_ops.update_binary = authentic_update_binary; authentic_ops.erase_binary = authentic_erase_binary; /* authentic_ops.resize_file = authentic_resize_file; */ authentic_ops.select_file = authentic_select_file; /* get_response: Untested */ authentic_ops.get_challenge = authentic_get_challenge; authentic_ops.set_security_env = authentic_set_security_env; /* decipher: Untested */ authentic_ops.decipher = authentic_decipher; /* authentic_ops.compute_signature = authentic_compute_signature; */ authentic_ops.create_file = authentic_create_file; authentic_ops.delete_file = authentic_delete_file; authentic_ops.card_ctl = authentic_card_ctl; authentic_ops.process_fci = authentic_process_fci; authentic_ops.pin_cmd = authentic_pin_cmd; authentic_ops.card_reader_lock_obtained = authentic_card_reader_lock_obtained; return &authentic_drv; } 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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionRemoveEventListener(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); impl->removeEventListener(ustringToAtomicString(exec->argument(0).toString(exec)->value(exec)), JSEventListener::create(asObject(listener), castedThis, false, currentWorld(exec)).get(), exec->argument(2).toBoolean(exec)); return JSValue::encode(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: OMX_ERRORTYPE omx_video::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr) { unsigned int index = 0; OMX_U8 *temp_buff ; if (bufferHdr == NULL || m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: free_input: Invalid bufferHdr[%p] or m_inp_mem_ptr[%p]", bufferHdr, m_inp_mem_ptr); return OMX_ErrorBadParameter; } index = bufferHdr - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr); #ifdef _ANDROID_ICS_ if (meta_mode_enable) { if (index < m_sInPortDef.nBufferCountActual) { memset(&meta_buffer_hdr[index], 0, sizeof(meta_buffer_hdr[index])); memset(&meta_buffers[index], 0, sizeof(meta_buffers[index])); } if (!mUseProxyColorFormat) return OMX_ErrorNone; else { c2d_conv.close(); opaque_buffer_hdr[index] = NULL; } } #endif if (index < m_sInPortDef.nBufferCountActual && !mUseProxyColorFormat && dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_LOW("ERROR: dev_free_buf() Failed for i/p buf"); } if (index < m_sInPortDef.nBufferCountActual && m_pInput_pmem) { if (m_pInput_pmem[index].fd > 0 && input_use_buffer == false) { DEBUG_PRINT_LOW("FreeBuffer:: i/p AllocateBuffer case"); if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); } else { free(m_pInput_pmem[index].buffer); } close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else if (m_pInput_pmem[index].fd > 0 && (input_use_buffer == true && m_use_input_pmem == OMX_FALSE)) { DEBUG_PRINT_LOW("FreeBuffer:: i/p Heap UseBuffer case"); if (dev_free_buf(&m_pInput_pmem[index],PORT_INDEX_IN) != true) { DEBUG_PRINT_ERROR("ERROR: dev_free_buf() Failed for i/p buf"); } if(!secure_session) { munmap (m_pInput_pmem[index].buffer,m_pInput_pmem[index].size); } close (m_pInput_pmem[index].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[index]); #endif m_pInput_pmem[index].fd = -1; } else { DEBUG_PRINT_ERROR("FreeBuffer:: fd is invalid or i/p PMEM UseBuffer case"); } } return OMX_ErrorNone; } CWE ID: Target: 1 Example 2: Code: void Type_U16Fixed16_Free(struct _cms_typehandler_struct* self, void* Ptr) { _cmsFree(self ->ContextID, Ptr); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool UserActivityDetector::PreHandleMouseEvent(aura::Window* target, aura::MouseEvent* event) { MaybeNotify(); return false; } 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: long Cluster::Parse(long long& pos, long& len) const { long status = Load(pos, len); if (status < 0) return status; assert(m_pos >= m_element_start); assert(m_timecode >= 0); const long long cluster_stop = (m_element_size < 0) ? -1 : m_element_start + m_element_size; if ((cluster_stop >= 0) && (m_pos >= cluster_stop)) return 1; // nothing else to do IMkvReader* const pReader = m_pSegment->m_pReader; long long total, avail; status = pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = m_pos; for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) break; if ((total >= 0) && (pos >= total)) { if (m_element_size < 0) m_element_size = pos - m_element_start; break; } if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id == 0) // weird return E_FILE_FORMAT_INVALID; if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { // Cluster or Cues ID if (m_element_size < 0) m_element_size = pos - m_element_start; break; } pos += len; // consume ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; pos += len; // consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) // weird continue; const long long block_stop = pos + size; if (cluster_stop >= 0) { if (block_stop > cluster_stop) { if ((id == 0x20) || (id == 0x23)) return E_FILE_FORMAT_INVALID; pos = cluster_stop; break; } } else if ((total >= 0) && (block_stop > total)) { m_element_size = total - m_element_start; pos = total; break; } else if (block_stop > avail) { len = static_cast<long>(size); return E_BUFFER_NOT_FULL; } Cluster* const this_ = const_cast<Cluster*>(this); if (id == 0x20) // BlockGroup return this_->ParseBlockGroup(size, pos, len); if (id == 0x23) // SimpleBlock return this_->ParseSimpleBlock(size, pos, len); pos += size; // consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } assert(m_element_size > 0); m_pos = pos; assert((cluster_stop < 0) || (m_pos <= cluster_stop)); if (m_entries_count > 0) { const long idx = m_entries_count - 1; const BlockEntry* const pLast = m_entries[idx]; assert(pLast); const Block* const pBlock = pLast->GetBlock(); assert(pBlock); const long long start = pBlock->m_start; if ((total >= 0) && (start > total)) return -1; // defend against trucated stream const long long size = pBlock->m_size; const long long stop = start + size; assert((cluster_stop < 0) || (stop <= cluster_stop)); if ((total >= 0) && (stop > total)) return -1; // defend against trucated stream } return 1; // no more entries } CWE ID: CWE-20 Target: 1 Example 2: Code: static int WebPEncodeWriter(const unsigned char *stream,size_t length, const WebPPicture *const picture) { Image *image; image=(Image *) picture->custom_ptr; return(length != 0 ? (int) WriteBlob(image,length,stream) : 1); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void dccp_deliver_input_to_ccids(struct sock *sk, struct sk_buff *skb) { const struct dccp_sock *dp = dccp_sk(sk); /* Don't deliver to RX CCID when node has shut down read end. */ if (!(sk->sk_shutdown & RCV_SHUTDOWN)) ccid_hc_rx_packet_recv(dp->dccps_hc_rx_ccid, sk, skb); /* * Until the TX queue has been drained, we can not honour SHUT_WR, since * we need received feedback as input to adjust congestion control. */ if (sk->sk_write_queue.qlen > 0 || !(sk->sk_shutdown & SEND_SHUTDOWN)) ccid_hc_tx_packet_recv(dp->dccps_hc_tx_ccid, sk, skb); } CWE ID: CWE-415 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadSTEGANOImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define GetBit(alpha,i) MagickMin((((size_t) (alpha) >> (size_t) \ (i)) & 0x01),16) #define SetBit(indexes,i,set) SetPixelIndex(indexes,((set) != 0 ? \ (size_t) GetPixelIndex(indexes) | (one << (size_t) (i)) : (size_t) \ GetPixelIndex(indexes) & ~(one << (size_t) (i)))) Image *image, *watermark; ImageInfo *read_info; int c; MagickBooleanType status; PixelPacket pixel; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t depth, one; ssize_t i, j, k, y; /* Initialize Image structure. */ 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); one=1; image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); *read_info->magick='\0'; watermark=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (watermark == (Image *) NULL) return((Image *) NULL); watermark->depth=MAGICKCORE_QUANTUM_DEPTH; if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Get hidden watermark from low-order bits of image. */ c=0; i=0; j=0; i=(ssize_t) (watermark->depth-1); depth=watermark->depth; for (k=image->offset; (i >= 0) && (j < (ssize_t) depth); i--) { for (y=0; (y < (ssize_t) image->rows) && (j < (ssize_t) depth); y++) { x=0; for ( ; (x < (ssize_t) image->columns) && (j < (ssize_t) depth); x++) { if ((k/(ssize_t) watermark->columns) >= (ssize_t) watermark->rows) break; (void) GetOneVirtualPixel(watermark,k % (ssize_t) watermark->columns, k/(ssize_t) watermark->columns,&pixel,exception); q=GetAuthenticPixels(image,x,y,1,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); switch (c) { case 0: { SetBit(indexes,i,GetBit(pixel.red,j)); break; } case 1: { SetBit(indexes,i,GetBit(pixel.green,j)); break; } case 2: { SetBit(indexes,i,GetBit(pixel.blue,j)); break; } } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; c++; if (c == 3) c=0; k++; if (k == (ssize_t) (watermark->columns*watermark->columns)) k=0; if (k == image->offset) j++; } } status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i,depth); if (status == MagickFalse) break; } watermark=DestroyImage(watermark); (void) SyncImage(image); return(GetFirstImageInList(image)); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void stream_int_shutw(struct stream_interface *si) { si->ob->flags &= ~CF_SHUTW_NOW; if (si->ob->flags & CF_SHUTW) return; si->ob->flags |= CF_SHUTW; si->ob->wex = TICK_ETERNITY; si->flags &= ~SI_FL_WAIT_DATA; switch (si->state) { case SI_ST_EST: /* we have to shut before closing, otherwise some short messages * may never leave the system, especially when there are remaining * unread data in the socket input buffer, or when nolinger is set. * However, if SI_FL_NOLINGER is explicitly set, we know there is * no risk so we close both sides immediately. */ if (!(si->flags & (SI_FL_ERR | SI_FL_NOLINGER)) && !(si->ib->flags & (CF_SHUTR|CF_DONT_READ))) return; /* fall through */ case SI_ST_CON: case SI_ST_CER: case SI_ST_QUE: case SI_ST_TAR: /* Note that none of these states may happen with applets */ si->state = SI_ST_DIS; si_applet_release(si); default: si->flags &= ~(SI_FL_WAIT_ROOM | SI_FL_NOLINGER); si->ib->flags &= ~CF_SHUTR_NOW; si->ib->flags |= CF_SHUTR; si->ib->rex = TICK_ETERNITY; si->exp = TICK_ETERNITY; } /* note that if the task exists, it must unregister itself once it runs */ if (!(si->flags & SI_FL_DONT_WAKE) && si->owner) task_wakeup(si->owner, TASK_WOKEN_IO); } 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 out_packet(s2s_t s2s, pkt_t pkt) { char *rkey; int rkeylen; conn_t out; conn_state_t state; int ret; /* perform check against whitelist */ if (s2s->enable_whitelist > 0 && (pkt->to->domain != NULL) && (s2s_domain_in_whitelist(s2s, pkt->to->domain) == 0)) { log_write(s2s->log, LOG_NOTICE, "sending a packet to domain not in the whitelist, dropping it"); if (pkt->to != NULL) jid_free(pkt->to); if (pkt->from != NULL) jid_free(pkt->from); if (pkt->nad != NULL) nad_free(pkt->nad); free(pkt); return; } /* new route key */ rkey = s2s_route_key(NULL, pkt->from->domain, pkt->to->domain); rkeylen = strlen(rkey); /* get a connection */ ret = out_route(s2s, rkey, rkeylen, &out, 1); if (out == NULL) { /* connection not available, queue packet */ _out_packet_queue(s2s, pkt); /* check if out_route was successful in attempting a connection */ if (ret) { /* bounce queue */ out_bounce_route_queue(s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE); free(rkey); return -1; } free(rkey); return 0; } /* connection in progress */ if(!out->online) { log_debug(ZONE, "connection in progress, queueing packet"); _out_packet_queue(s2s, pkt); free(rkey); return 0; } /* connection state */ state = (conn_state_t) xhash_get(out->states, rkey); /* valid conns or dialback packets */ if(state == conn_VALID || pkt->db) { log_debug(ZONE, "writing packet for %s to outgoing conn %d", rkey, out->fd->fd); /* send it straight out */ if(pkt->db) { /* if this is a db:verify packet, increment counter and set timestamp */ if(NAD_ENAME_L(pkt->nad, 0) == 6 && strncmp("verify", NAD_ENAME(pkt->nad, 0), 6) == 0) { out->verify++; out->last_verify = time(NULL); } /* dialback packet */ sx_nad_write(out->s, pkt->nad); } else { /* if the outgoing stanza has a jabber:client namespace, remove it so that the stream jabber:server namespaces will apply (XMPP 11.2.2) */ int ns = nad_find_namespace(pkt->nad, 1, uri_CLIENT, NULL); if(ns >= 0) { /* clear the namespaces of elem 0 (internal route element) and elem 1 (message|iq|presence) */ pkt->nad->elems[0].ns = -1; pkt->nad->elems[0].my_ns = -1; pkt->nad->elems[1].ns = -1; pkt->nad->elems[1].my_ns = -1; } /* send it out */ sx_nad_write_elem(out->s, pkt->nad, 1); } /* update timestamp */ out->last_packet = time(NULL); jid_free(pkt->from); jid_free(pkt->to); free(pkt); free(rkey); return 0; } /* can't be handled yet, queue */ _out_packet_queue(s2s, pkt); /* if dialback is in progress, then we're done for now */ if(state == conn_INPROGRESS) { free(rkey); return 0; } /* this is a new route - send dialback auth request to piggyback on the existing connection */ if (out->s2s->require_tls == 0 || out->s->ssf > 0) { _out_dialback(out, rkey, rkeylen); } free(rkey); 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: xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; xmlChar stop; int state = ctxt->instate; int count = 0; SHRINK; if (RAW == '"') { NEXT; stop = '"'; } else if (RAW == '\'') { NEXT; stop = '\''; } else { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_STARTED, NULL); return(NULL); } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); return(NULL); } ctxt->instate = XML_PARSER_SYSTEM_LITERAL; cur = CUR_CHAR(l); while ((IS_CHAR(cur)) && (cur != stop)) { /* checked */ if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlFree(buf); xmlErrMemory(ctxt, NULL); ctxt->instate = (xmlParserInputState) state; return(NULL); } buf = tmp; } count++; if (count > 50) { GROW; count = 0; } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { GROW; SHRINK; cur = CUR_CHAR(l); } } buf[len] = 0; ctxt->instate = (xmlParserInputState) state; if (!IS_CHAR(cur)) { xmlFatalErr(ctxt, XML_ERR_LITERAL_NOT_FINISHED, NULL); } else { NEXT; } return(buf); } CWE ID: CWE-119 Target: 1 Example 2: Code: const CompositorElementId PropertyTreeState::GetCompositorElementId( const CompositorElementIdSet& element_ids) const { if (Effect()->GetCompositorElementId() && !element_ids.Contains(Effect()->GetCompositorElementId())) return Effect()->GetCompositorElementId(); if (Transform()->GetCompositorElementId() && !element_ids.Contains(Transform()->GetCompositorElementId())) return Transform()->GetCompositorElementId(); return CompositorElementId(); } 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 inline char *get_default_content_type(uint prefix_len, uint *len TSRMLS_DC) { char *mimetype, *charset, *content_type; uint mimetype_len, charset_len; if (SG(default_mimetype)) { mimetype = SG(default_mimetype); mimetype_len = strlen(SG(default_mimetype)); } else { mimetype = SAPI_DEFAULT_MIMETYPE; mimetype_len = sizeof(SAPI_DEFAULT_MIMETYPE) - 1; } if (SG(default_charset)) { charset = SG(default_charset); charset_len = strlen(SG(default_charset)); } else { charset = SAPI_DEFAULT_CHARSET; charset_len = sizeof(SAPI_DEFAULT_CHARSET) - 1; } if (*charset && strncasecmp(mimetype, "text/", 5) == 0) { char *p; *len = prefix_len + mimetype_len + sizeof("; charset=") - 1 + charset_len; content_type = (char*)emalloc(*len + 1); p = content_type + prefix_len; memcpy(p, mimetype, mimetype_len); p += mimetype_len; memcpy(p, "; charset=", sizeof("; charset=") - 1); p += sizeof("; charset=") - 1; memcpy(p, charset, charset_len + 1); } else { *len = prefix_len + mimetype_len; content_type = (char*)emalloc(*len + 1); memcpy(content_type + prefix_len, mimetype, mimetype_len + 1); } return content_type; } CWE ID: CWE-79 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: accept_ice_connection (GIOChannel *source, GIOCondition condition, GsmIceConnectionData *data) { IceListenObj listener; IceConn ice_conn; IceAcceptStatus status; GsmClient *client; GsmXsmpServer *server; listener = data->listener; server = data->server; g_debug ("GsmXsmpServer: accept_ice_connection()"); ice_conn = IceAcceptConnection (listener, &status); if (status != IceAcceptSuccess) { g_debug ("GsmXsmpServer: IceAcceptConnection returned %d", status); return TRUE; } client = gsm_xsmp_client_new (ice_conn); ice_conn->context = client; gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client)); /* the store will own the ref */ g_object_unref (client); return TRUE; } CWE ID: CWE-835 Target: 1 Example 2: Code: void CardUnmaskPromptViews::FadeOutView::PaintChildren( const PaintContext& context) { if (opacity_ > 0.99) return views::View::PaintChildren(context); gfx::Canvas* canvas = context.canvas(); canvas->SaveLayerAlpha(0xff * opacity_); views::View::PaintChildren(context); canvas->Restore(); } 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 PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) { if (node.isNull() || !node.document().frame()) { return; } if (is_preview_enabled_) { print_preview_context_.InitWithNode(node); RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE); } else { WebKit::WebNode duplicate_node(node); Print(duplicate_node.document().frame(), duplicate_node); } } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int vol_prc_lib_release(effect_handle_t handle) { struct listnode *node, *temp_node_next; vol_listener_context_t *context = NULL; vol_listener_context_t *recv_contex = (vol_listener_context_t *)handle; int status = -1; bool recompute_flag = false; int active_stream_count = 0; ALOGV("%s context %p", __func__, handle); pthread_mutex_lock(&vol_listner_init_lock); list_for_each_safe(node, temp_node_next, &vol_effect_list) { context = node_to_item(node, struct vol_listener_context_s, effect_list_node); if ((memcmp(&(context->desc->uuid), &(recv_contex->desc->uuid), sizeof(effect_uuid_t)) == 0) && (context->session_id == recv_contex->session_id) && (context->stream_type == recv_contex->stream_type)) { ALOGV("--- Found something to remove ---"); list_remove(&context->effect_list_node); PRINT_STREAM_TYPE(context->stream_type); if (context->dev_id && AUDIO_DEVICE_OUT_SPEAKER) { recompute_flag = true; } free(context); status = 0; } else { ++active_stream_count; } } if (status != 0) { ALOGE("something wrong ... <<<--- Found NOTHING to remove ... ???? --->>>>>"); } if (active_stream_count == 0) { current_gain_dep_cal_level = -1; current_vol = 0.0; } if (recompute_flag) { check_and_set_gain_dep_cal(); } if (dumping_enabled) { dump_list_l(); } pthread_mutex_unlock(&vol_listner_init_lock); return status; } CWE ID: CWE-119 Target: 1 Example 2: Code: int fd_lines(int fd) { struct winsize ws = {}; if (ioctl(fd, TIOCGWINSZ, &ws) < 0) return -errno; if (ws.ws_row <= 0) return -EIO; return ws.ws_row; } CWE ID: CWE-255 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: mrb_define_module_under(mrb_state *mrb, struct RClass *outer, const char *name) { mrb_sym id = mrb_intern_cstr(mrb, name); struct RClass * c = define_module(mrb, id, outer); setup_class(mrb, outer, c, id); return c; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, "%d", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError("Display name `%s' is too long\n", port); (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError("Could not create lock file in %s\n", tmp); (void) sprintf(pid_str, "%10ld\n", (long)getpid()); (void) write(lfd, pid_str, 11); (void) chmod(tmp, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY|O_NOFOLLOW); if (lfd < 0) { unlink(tmp); FatalError("Can't read lock file %s\n", LockFile); } pid_str[0] = '\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\0'; sscanf(pid_str, "%d", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError("Server is already active for display %s\n%s %s\n%s\n", port, "\tIf this server is no longer running, remove", LockFile, "\tand start again."); } } } unlink(tmp); if (!haslock) FatalError("Could not create server lock file: %s\n", LockFile); StillLocking = FALSE; } CWE ID: CWE-362 Target: 1 Example 2: Code: int cap_inode_setxattr(struct dentry *dentry, const char *name, const void *value, size_t size, int flags) { if (!strcmp(name, XATTR_NAME_CAPS)) { if (!capable(CAP_SETFCAP)) return -EPERM; return 0; } if (!strncmp(name, XATTR_SECURITY_PREFIX, sizeof(XATTR_SECURITY_PREFIX) - 1) && !capable(CAP_SYS_ADMIN)) return -EPERM; return 0; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool venc_dev::venc_loaded_stop_done() { return true; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GpuChannel::OnInitialize(base::ProcessHandle renderer_process) { DCHECK(!renderer_process_); if (base::GetProcId(renderer_process) == renderer_pid_) renderer_process_ = renderer_process; } CWE ID: Target: 1 Example 2: Code: kwsalloc (char const *trans) { struct kwset *kwset; kwset = (struct kwset *) malloc(sizeof (struct kwset)); if (!kwset) return NULL; obstack_init(&kwset->obstack); kwset->words = 0; kwset->trie = (struct trie *) obstack_alloc(&kwset->obstack, sizeof (struct trie)); if (!kwset->trie) { kwsfree((kwset_t) kwset); return NULL; } kwset->trie->accepting = 0; kwset->trie->links = NULL; kwset->trie->parent = NULL; kwset->trie->next = NULL; kwset->trie->fail = NULL; kwset->trie->depth = 0; kwset->trie->shift = 0; kwset->mind = INT_MAX; kwset->maxd = -1; kwset->target = NULL; kwset->trans = trans; return (kwset_t) kwset; } 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 LauncherView::UpdateFirstButtonPadding() { if (view_model_->view_size() > 0) { view_model_->view_at(0)->set_border(views::Border::CreateEmptyBorder( primary_axis_coordinate(0, kLeadingInset), primary_axis_coordinate(kLeadingInset, 0), 0, 0)); } } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, &unmounted); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); umount_mnt(p); } change_mnt_propagation(p, MS_PRIVATE); } } CWE ID: CWE-284 Target: 1 Example 2: Code: const SkBitmap* PPB_ImageData_Impl::GetMappedBitmap() const { return backend_->GetMappedBitmap(); } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void InvokeResetScreen() { ASSERT_TRUE(JSExecuted("cr.ui.Oobe.handleAccelerator('reset');")); OobeScreenWaiter(OobeDisplay::SCREEN_OOBE_RESET).Wait(); } 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: ConvolveFunctions(convolve_fn_t h8, convolve_fn_t h8_avg, convolve_fn_t v8, convolve_fn_t v8_avg, convolve_fn_t hv8, convolve_fn_t hv8_avg) : h8_(h8), v8_(v8), hv8_(hv8), h8_avg_(h8_avg), v8_avg_(v8_avg), hv8_avg_(hv8_avg) {} CWE ID: CWE-119 Target: 1 Example 2: Code: void MediaStreamManager::StopRemovedDevice( MediaDeviceType type, const MediaDeviceInfo& media_device_info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(type == MEDIA_DEVICE_TYPE_AUDIO_INPUT || type == MEDIA_DEVICE_TYPE_VIDEO_INPUT); MediaStreamType stream_type = ConvertToMediaStreamType(type); std::vector<int> session_ids; for (const LabeledDeviceRequest& labeled_request : requests_) { const DeviceRequest* request = labeled_request.second; for (const MediaStreamDevice& device : request->devices) { const std::string source_id = GetHMACForMediaDeviceID( request->salt, request->security_origin, media_device_info.device_id); if (device.id == source_id && device.type == stream_type) { session_ids.push_back(device.session_id); if (request->device_stopped_cb) { request->device_stopped_cb.Run(labeled_request.first, device); } } } } for (const int session_id : session_ids) StopDevice(stream_type, session_id); AddLogMessageOnIOThread( base::StringPrintf( "Media input device removed: type=%s, id=%s, name=%s ", (stream_type == MEDIA_DEVICE_AUDIO_CAPTURE ? "audio" : "video"), media_device_info.device_id.c_str(), media_device_info.label.c_str()) .c_str()); } 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 vpx_codec_err_t decoder_peek_si_internal(const uint8_t *data, unsigned int data_sz, vpx_codec_stream_info_t *si, int *is_intra_only, vpx_decrypt_cb decrypt_cb, void *decrypt_state) { int intra_only_flag = 0; uint8_t clear_buffer[9]; if (data + data_sz <= data) return VPX_CODEC_INVALID_PARAM; si->is_kf = 0; si->w = si->h = 0; if (decrypt_cb) { data_sz = VPXMIN(sizeof(clear_buffer), data_sz); decrypt_cb(decrypt_state, data, clear_buffer, data_sz); data = clear_buffer; } { int show_frame; int error_resilient; struct vpx_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL }; const int frame_marker = vpx_rb_read_literal(&rb, 2); const BITSTREAM_PROFILE profile = vp9_read_profile(&rb); if (frame_marker != VP9_FRAME_MARKER) return VPX_CODEC_UNSUP_BITSTREAM; if (profile >= MAX_PROFILES) return VPX_CODEC_UNSUP_BITSTREAM; if ((profile >= 2 && data_sz <= 1) || data_sz < 1) return VPX_CODEC_UNSUP_BITSTREAM; if (vpx_rb_read_bit(&rb)) { // show an existing frame vpx_rb_read_literal(&rb, 3); // Frame buffer to show. return VPX_CODEC_OK; } if (data_sz <= 8) return VPX_CODEC_UNSUP_BITSTREAM; si->is_kf = !vpx_rb_read_bit(&rb); show_frame = vpx_rb_read_bit(&rb); error_resilient = vpx_rb_read_bit(&rb); if (si->is_kf) { if (!vp9_read_sync_code(&rb)) return VPX_CODEC_UNSUP_BITSTREAM; if (!parse_bitdepth_colorspace_sampling(profile, &rb)) return VPX_CODEC_UNSUP_BITSTREAM; vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h); } else { intra_only_flag = show_frame ? 0 : vpx_rb_read_bit(&rb); rb.bit_offset += error_resilient ? 0 : 2; // reset_frame_context if (intra_only_flag) { if (!vp9_read_sync_code(&rb)) return VPX_CODEC_UNSUP_BITSTREAM; if (profile > PROFILE_0) { if (!parse_bitdepth_colorspace_sampling(profile, &rb)) return VPX_CODEC_UNSUP_BITSTREAM; } rb.bit_offset += REF_FRAMES; // refresh_frame_flags vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h); } } } if (is_intra_only != NULL) *is_intra_only = intra_only_flag; return VPX_CODEC_OK; } 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 *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); if (free_source) { efree(source); } zend_shared_alloc_register_xlat_entry(source, retval); return retval; } CWE ID: CWE-416 Target: 1 Example 2: Code: update_info_drive_can_spindown (Device *device) { gboolean drive_can_spindown; /* Right now we only know how to spin down ATA devices (including those USB devices * that can do ATA SMART) * * This would probably also work for SCSI devices (since the helper is doing SCSI * STOP (which translated in libata to ATA's STANDBY IMMEDIATE) - but that needs * testing... */ drive_can_spindown = FALSE; if (g_strcmp0 (device->priv->drive_connection_interface, "ata") == 0 || device->priv->drive_ata_smart_is_available) { drive_can_spindown = TRUE; } if (g_udev_device_has_property (device->priv->d, "ID_DRIVE_CAN_SPINDOWN")) { drive_can_spindown = g_udev_device_get_property_as_boolean (device->priv->d, "ID_DRIVE_CAN_SPINDOWN"); } device_set_drive_can_spindown (device, drive_can_spindown); return TRUE; } 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: drop_capabilities(int parent) { 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 vp8mt_de_alloc_temp_buffers(VP8D_COMP *pbi, int mb_rows) { int i; if (pbi->b_multithreaded_rd) { vpx_free(pbi->mt_current_mb_col); pbi->mt_current_mb_col = NULL ; /* Free above_row buffers. */ if (pbi->mt_yabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_yabove_row[i]); pbi->mt_yabove_row[i] = NULL ; } vpx_free(pbi->mt_yabove_row); pbi->mt_yabove_row = NULL ; } if (pbi->mt_uabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_uabove_row[i]); pbi->mt_uabove_row[i] = NULL ; } vpx_free(pbi->mt_uabove_row); pbi->mt_uabove_row = NULL ; } if (pbi->mt_vabove_row) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_vabove_row[i]); pbi->mt_vabove_row[i] = NULL ; } vpx_free(pbi->mt_vabove_row); pbi->mt_vabove_row = NULL ; } /* Free left_col buffers. */ if (pbi->mt_yleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_yleft_col[i]); pbi->mt_yleft_col[i] = NULL ; } vpx_free(pbi->mt_yleft_col); pbi->mt_yleft_col = NULL ; } if (pbi->mt_uleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_uleft_col[i]); pbi->mt_uleft_col[i] = NULL ; } vpx_free(pbi->mt_uleft_col); pbi->mt_uleft_col = NULL ; } if (pbi->mt_vleft_col) { for (i=0; i< mb_rows; i++) { vpx_free(pbi->mt_vleft_col[i]); pbi->mt_vleft_col[i] = NULL ; } vpx_free(pbi->mt_vleft_col); pbi->mt_vleft_col = NULL ; } } } CWE ID: Target: 1 Example 2: Code: status_t GraphicBuffer::initCheck() const { return mInitCheck; } 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: menu_add_edit(WebKitWebView *page, GArray *argv, GString *result) { (void) page; (void) result; add_to_menu(argv, WEBKIT_HIT_TEST_RESULT_CONTEXT_EDITABLE); } 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 int flakey_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct flakey_c *fc = ti->private; return __blkdev_driver_ioctl(fc->dev->bdev, fc->dev->mode, cmd, arg); } CWE ID: CWE-264 Target: 1 Example 2: Code: void RenderViewImpl::willPerformClientRedirect( WebFrame* frame, const WebURL& from, const WebURL& to, double interval, double fire_time) { const WebURL& blank_url = GURL(chrome::kAboutBlankURL); FOR_EACH_OBSERVER( RenderViewObserver, observers_, WillPerformClientRedirect(frame, from == GURL(kSwappedOutURL) ? blank_url : from, to, interval, fire_time)); } 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: pvscsi_get_next_sg_elem(PVSCSISGState *sg) { struct PVSCSISGElement elem; cpu_physical_memory_read(sg->elemAddr, (void *)&elem, sizeof(elem)); if ((elem.flags & ~PVSCSI_KNOWN_FLAGS) != 0) { /* * There is PVSCSI_SGE_FLAG_CHAIN_ELEMENT flag described in * header file but its value is unknown. This flag requires * additional processing, so we put warning here to catch it * some day and make proper implementation */ trace_pvscsi_get_next_sg_elem(elem.flags); } sg->elemAddr += sizeof(elem); sg->dataAddr = elem.addr; sg->resid = elem.length; } 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 sk_sp<SkImage> premulSkImageToUnPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kUnpremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(input->width()) * info.bytesPerPixel()); } CWE ID: CWE-787 Target: 1 Example 2: Code: bool ChromeExtensionsAPIClient::ShouldHideResponseHeader( const GURL& url, const std::string& header_name) const { return ( (url.host_piece() == GaiaUrls::GetInstance()->gaia_url().host_piece()) && (base::CompareCaseInsensitiveASCII(header_name, signin::kDiceResponseHeader) == 0)); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameHostImpl::GetInterface( const std::string& interface_name, mojo::ScopedMessagePipeHandle interface_pipe) { if (!registry_ || !registry_->TryBindInterface(interface_name, &interface_pipe)) { delegate_->OnInterfaceRequest(this, interface_name, &interface_pipe); if (interface_pipe->is_valid() && !TryBindFrameInterface(interface_name, &interface_pipe, this)) { GetContentClient()->browser()->BindInterfaceRequestFromFrame( this, interface_name, std::move(interface_pipe)); } } } 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 UninstallExtension(ExtensionService* service, const std::string& id) { if (service && service->GetInstalledExtension(id)) { service->UninstallExtension(id, extensions::UNINSTALL_REASON_SYNC, base::Bind(&base::DoNothing), NULL); } } CWE ID: Target: 1 Example 2: Code: void ContainerNode::parserRemoveChild(Node* oldChild) { ASSERT(oldChild); ASSERT(oldChild->parentNode() == this); ASSERT(!oldChild->isDocumentFragment()); Node* prev = oldChild->previousSibling(); Node* next = oldChild->nextSibling(); oldChild->updateAncestorConnectedSubframeCountForRemoval(); ChildListMutationScope(this).willRemoveChild(oldChild); oldChild->notifyMutationObserversNodeWillDetach(); removeBetween(prev, next, oldChild); childrenChanged(true, prev, next, -1); ChildNodeRemovalNotifier(this).notify(oldChild); } 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 struct sock *__llc_lookup_established(struct llc_sap *sap, struct llc_addr *daddr, struct llc_addr *laddr) { struct sock *rc; struct hlist_nulls_node *node; int slot = llc_sk_laddr_hashfn(sap, laddr); struct hlist_nulls_head *laddr_hb = &sap->sk_laddr_hash[slot]; rcu_read_lock(); again: sk_nulls_for_each_rcu(rc, node, laddr_hb) { if (llc_estab_match(sap, daddr, laddr, rc)) { /* Extra checks required by SLAB_DESTROY_BY_RCU */ if (unlikely(!atomic_inc_not_zero(&rc->sk_refcnt))) goto again; if (unlikely(llc_sk(rc)->sap != sap || !llc_estab_match(sap, daddr, laddr, rc))) { sock_put(rc); continue; } goto found; } } rc = NULL; /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (unlikely(get_nulls_value(node) != slot)) goto again; found: rcu_read_unlock(); return rc; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EncodedJSValue JSC_HOST_CALL JSSharedWorkerConstructor::constructJSSharedWorker(ExecState* exec) { JSSharedWorkerConstructor* jsConstructor = jsCast<JSSharedWorkerConstructor*>(exec->callee()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); UString scriptURL = exec->argument(0).toString(exec)->value(exec); UString name; if (exec->argumentCount() > 1) name = exec->argument(1).toString(exec)->value(exec); if (exec->hadException()) return JSValue::encode(JSValue()); DOMWindow* window = asJSDOMWindow(exec->lexicalGlobalObject())->impl(); ExceptionCode ec = 0; RefPtr<SharedWorker> worker = SharedWorker::create(window->document(), ustringToString(scriptURL), ustringToString(name), ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, jsConstructor->globalObject(), worker.release()))); } CWE ID: CWE-20 Target: 1 Example 2: Code: static int cdrom_mrw_exit(struct cdrom_device_info *cdi) { disc_information di; int ret; ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < (int)offsetof(typeof(di),disc_type)) return 1; ret = 0; if (di.mrw_status == CDM_MRW_BGFORMAT_ACTIVE) { pr_info("issuing MRW background format suspend\n"); ret = cdrom_mrw_bgformat_susp(cdi, 0); } if (!ret && cdi->media_written) ret = cdrom_flush_cache(cdi); return ret; } 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: check_1_6_dummy(kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr) { int i; char *password = *passptr; /* Old-style randkey operations disallowed tickets to start. */ if (!(mask & KADM5_ATTRIBUTES) || !(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)) return; /* The 1.6 dummy password was the octets 1..255. */ for (i = 0; (unsigned char) password[i] == i + 1; i++); if (password[i] != '\0' || i != 255) return; /* This will make the caller use a random password instead. */ *passptr = NULL; } 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: htmlParseElementInternal(htmlParserCtxtPtr ctxt) { const xmlChar *name; const htmlElemDesc * info; htmlParserNodeInfo node_info = { 0, }; int failed; if ((ctxt == NULL) || (ctxt->input == NULL)) { htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR, "htmlParseElementInternal: context error\n", NULL, NULL); return; } if (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; } failed = htmlParseStartTag(ctxt); name = ctxt->name; if ((failed == -1) || (name == NULL)) { if (CUR == '>') NEXT; return; } /* * Lookup the info for that element. */ info = htmlTagLookup(name); if (info == NULL) { htmlParseErr(ctxt, XML_HTML_UNKNOWN_TAG, "Tag %s invalid\n", name, NULL); } /* * Check for an Empty Element labeled the XML/SGML way */ if ((CUR == '/') && (NXT(1) == '>')) { SKIP(2); if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL)) ctxt->sax->endElement(ctxt->userData, name); htmlnamePop(ctxt); return; } if (CUR == '>') { NEXT; } else { htmlParseErr(ctxt, XML_ERR_GT_REQUIRED, "Couldn't find end of Start Tag %s\n", name, NULL); /* * end of parsing of this node. */ if (xmlStrEqual(name, ctxt->name)) { nodePop(ctxt); htmlnamePop(ctxt); } if (ctxt->record_info) htmlNodeInfoPush(ctxt, &node_info); htmlParserFinishElementParsing(ctxt); return; } /* * Check for an Empty Element from DTD definition */ if ((info != NULL) && (info->empty)) { if ((ctxt->sax != NULL) && (ctxt->sax->endElement != NULL)) ctxt->sax->endElement(ctxt->userData, name); htmlnamePop(ctxt); return; } if (ctxt->record_info) htmlNodeInfoPush(ctxt, &node_info); } CWE ID: CWE-787 Target: 1 Example 2: Code: void WebGL2RenderingContextBase::uniformMatrix4x3fv( const WebGLUniformLocation* location, GLboolean transpose, Vector<GLfloat>& value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix4x3fv", location, transpose, value.data(), value.size(), 12, src_offset, src_length)) return; ContextGL()->UniformMatrix4x3fv( location->Location(), (src_length ? src_length : (value.size() - src_offset)) / 12, transpose, value.data() + src_offset); } 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: virConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID, virConnectDomainEventGenericCallback cb, void *opaque, virFreeCallback freecb) { VIR_DOMAIN_DEBUG(dom, "conn=%p, eventID=%d, cb=%p, opaque=%p, freecb=%p", conn, eventID, cb, opaque, freecb); virResetLastError(); virCheckConnectReturn(conn, -1); if (dom) { virCheckDomainGoto(dom, error); if (dom->conn != conn) { virReportInvalidArg(dom, _("domain '%s' must match connection"), dom->name); goto error; } } virCheckNonNullArgGoto(cb, error); virCheckNonNegativeArgGoto(eventID, error); if (eventID >= VIR_DOMAIN_EVENT_ID_LAST) { virReportInvalidArg(eventID, _("eventID must be less than %d"), VIR_DOMAIN_EVENT_ID_LAST); goto error; } if (conn->driver && conn->driver->connectDomainEventRegisterAny) { int ret; ret = conn->driver->connectDomainEventRegisterAny(conn, dom, eventID, cb, opaque, freecb); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } 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: void DCTStream::init() { jpeg_std_error(&jerr); jerr.error_exit = &exitErrorHandler; src.pub.init_source = str_init_source; src.pub.fill_input_buffer = str_fill_input_buffer; src.pub.skip_input_data = str_skip_input_data; src.pub.resync_to_restart = jpeg_resync_to_restart; src.pub.term_source = str_term_source; src.pub.next_input_byte = NULL; src.str = str; src.index = 0; src.abort = false; current = NULL; limit = NULL; limit = NULL; cinfo.err = &jerr; jpeg_create_decompress(&cinfo); cinfo.src = (jpeg_source_mgr *)&src; row_buffer = NULL; } CWE ID: CWE-20 Target: 1 Example 2: Code: static BOOL update_send_pointer_color(rdpContext* context, const POINTER_COLOR_UPDATE* pointer_color) { wStream* s; rdpRdp* rdp = context->rdp; BOOL ret = FALSE; s = fastpath_update_pdu_init(rdp->fastpath); if (!s) return FALSE; if (!update_write_pointer_color(s, pointer_color)) goto out_fail; ret = fastpath_send_update_pdu(rdp->fastpath, FASTPATH_UPDATETYPE_COLOR, s, FALSE); out_fail: Stream_Release(s); return ret; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: raptor_rss_parse_start(raptor_parser *rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; /* base URI required for RSS */ if(!uri) return 1; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) rss_parser->nspaces_seen[n] = 'N'; /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rss_parser->sax2, uri); return 0; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MediaStreamDevicesController::Accept(bool update_content_setting) { if (content_settings_) content_settings_->OnMediaStreamAllowed(); NotifyUIRequestAccepted(); content::MediaStreamDevices devices; if (microphone_requested_ || webcam_requested_) { switch (request_.request_type) { case content::MEDIA_OPEN_DEVICE: MediaCaptureDevicesDispatcher::GetInstance()->GetRequestedDevice( request_.requested_device_id, request_.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE, request_.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE, &devices); break; case content::MEDIA_DEVICE_ACCESS: case content::MEDIA_GENERATE_STREAM: case content::MEDIA_ENUMERATE_DEVICES: MediaCaptureDevicesDispatcher::GetInstance()-> GetDefaultDevicesForProfile(profile_, microphone_requested_, webcam_requested_, &devices); break; } if (update_content_setting && IsSchemeSecure() && !devices.empty()) SetPermission(true); } scoped_ptr<content::MediaStreamUI> ui; if (!devices.empty()) { ui = MediaCaptureDevicesDispatcher::GetInstance()-> GetMediaStreamCaptureIndicator()->RegisterMediaStream( web_contents_, devices); } content::MediaResponseCallback cb = callback_; callback_.Reset(); cb.Run(devices, ui.Pass()); } CWE ID: CWE-264 Target: 1 Example 2: Code: HistogramType Histogram::GetHistogramType() const { return HISTOGRAM; } 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: status_t ACodec::freeOutputBuffersNotOwnedByComponent() { status_t err = OK; for (size_t i = mBuffers[kPortIndexOutput].size(); i > 0;) { i--; BufferInfo *info = &mBuffers[kPortIndexOutput].editItemAt(i); if (info->mStatus != BufferInfo::OWNED_BY_COMPONENT && info->mStatus != BufferInfo::OWNED_BY_DOWNSTREAM) { status_t err2 = freeBuffer(kPortIndexOutput, i); if (err == OK) { err = err2; } } } return err; } 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: header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 56) ; } ; } /* header_put_le_8byte */ CWE ID: CWE-119 Target: 1 Example 2: Code: void DataReductionProxyIOData::UpdateProxyRequestHeaders( const net::HttpRequestHeaders& headers) { ui_task_runner_->PostTask( FROM_HERE, base::BindOnce(&DataReductionProxyService::SetProxyRequestHeadersOnUI, service_, std::move(headers))); UpdateCustomProxyConfig(); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int handle_symlink(FsContext *fs_ctx, const char *oldpath, V9fsPath *dir_path, const char *name, FsCred *credp) { int fd, dirfd, ret; struct handle_data *data = (struct handle_data *)fs_ctx->private; dirfd = open_by_handle(data->mountfd, dir_path->data, O_PATH); if (dirfd < 0) { return dirfd; } ret = symlinkat(oldpath, dirfd, name); if (!ret) { fd = openat(dirfd, name, O_PATH | O_NOFOLLOW); if (fd < 0) { ret = fd; goto err_out; } ret = fchownat(fd, "", credp->fc_uid, credp->fc_gid, AT_EMPTY_PATH); close(fd); } err_out: close(dirfd); return ret; } 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: unsigned int arpt_do_table(struct sk_buff *skb, const struct nf_hook_state *state, struct xt_table *table) { unsigned int hook = state->hook; static const char nulldevname[IFNAMSIZ] __attribute__((aligned(sizeof(long)))); unsigned int verdict = NF_DROP; const struct arphdr *arp; struct arpt_entry *e, **jumpstack; const char *indev, *outdev; const void *table_base; unsigned int cpu, stackidx = 0; const struct xt_table_info *private; struct xt_action_param acpar; unsigned int addend; if (!pskb_may_pull(skb, arp_hdr_len(skb->dev))) return NF_DROP; indev = state->in ? state->in->name : nulldevname; outdev = state->out ? state->out->name : nulldevname; local_bh_disable(); addend = xt_write_recseq_begin(); private = READ_ONCE(table->private); /* Address dependency. */ cpu = smp_processor_id(); table_base = private->entries; jumpstack = (struct arpt_entry **)private->jumpstack[cpu]; /* No TEE support for arptables, so no need to switch to alternate * stack. All targets that reenter must return absolute verdicts. */ e = get_entry(table_base, private->hook_entry[hook]); acpar.state = state; acpar.hotdrop = false; arp = arp_hdr(skb); do { const struct xt_entry_target *t; struct xt_counters *counter; if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) { e = arpt_next_entry(e); continue; } counter = xt_get_this_cpu_counter(&e->counters); ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1); t = arpt_get_target_c(e); /* Standard target? */ if (!t->u.kernel.target->target) { int v; v = ((struct xt_standard_target *)t)->verdict; if (v < 0) { /* Pop from stack? */ if (v != XT_RETURN) { verdict = (unsigned int)(-v) - 1; break; } if (stackidx == 0) { e = get_entry(table_base, private->underflow[hook]); } else { e = jumpstack[--stackidx]; e = arpt_next_entry(e); } continue; } if (table_base + v != arpt_next_entry(e)) { jumpstack[stackidx++] = e; } e = get_entry(table_base, v); continue; } acpar.target = t->u.kernel.target; acpar.targinfo = t->data; verdict = t->u.kernel.target->target(skb, &acpar); if (verdict == XT_CONTINUE) { /* Target might have changed stuff. */ arp = arp_hdr(skb); e = arpt_next_entry(e); } else { /* Verdict */ break; } } while (!acpar.hotdrop); xt_write_recseq_end(addend); local_bh_enable(); if (acpar.hotdrop) return NF_DROP; else return verdict; } CWE ID: CWE-476 Target: 1 Example 2: Code: void onLinkStatsResults(wifi_request_id id, wifi_iface_stat *iface_stat, int num_radios, wifi_radio_stat *radio_stats) { if (iface_stat != 0) { memcpy(&link_stat, iface_stat, sizeof(wifi_iface_stat)); } else { memset(&link_stat, 0, sizeof(wifi_iface_stat)); } if (num_radios > 0 && radio_stats != 0) { memcpy(&radio_stat, radio_stats, sizeof(wifi_radio_stat)); } else { memset(&radio_stat, 0, sizeof(wifi_radio_stat)); } } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void __cpuinit per_cpu_trap_init(void) { /* Nothing to do for now, VBR initialization later. */ } 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: PHP_FUNCTION(snmp_set_enum_print) { long a1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) { RETURN_FALSE; } netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1); RETURN_TRUE; } CWE ID: CWE-416 Target: 1 Example 2: Code: void ClipboardMessageFilter::OnReadCustomData(ui::ClipboardType clipboard_type, const base::string16& type, base::string16* result) { GetClipboard()->ReadCustomData(clipboard_type, type, result); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: iperf_check_throttle(struct iperf_stream *sp, struct timeval *nowP) { double seconds; uint64_t bits_per_second; if (sp->test->done) return; seconds = timeval_diff(&sp->result->start_time, nowP); bits_per_second = sp->result->bytes_sent * 8 / seconds; if (bits_per_second < sp->test->settings->rate) { sp->green_light = 1; FD_SET(sp->socket, &sp->test->write_set); } else { sp->green_light = 0; FD_CLR(sp->socket, &sp->test->write_set); } } 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: gpk_parse_fileinfo(sc_card_t *card, const u8 *buf, size_t buflen, sc_file_t *file) { const u8 *sp, *end, *next; int i, rc; memset(file, 0, sizeof(*file)); for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE); end = buf + buflen; for (sp = buf; sp + 2 < end; sp = next) { next = sp + 2 + sp[1]; if (next > end) break; if (sp[0] == 0x84) { /* ignore if name is longer than what it should be */ if (sp[1] > sizeof(file->name)) continue; memset(file->name, 0, sizeof(file->name)); memcpy(file->name, sp+2, sp[1]); } else if (sp[0] == 0x85) { unsigned int ac[3], n; file->id = (sp[4] << 8) | sp[5]; file->size = (sp[8] << 8) | sp[9]; file->record_length = sp[7]; /* Map ACLs. Note the third AC byte is * valid of EFs only */ for (n = 0; n < 3; n++) ac[n] = (sp[10+2*n] << 8) | sp[11+2*n]; /* Examine file type */ switch (sp[6] & 7) { case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = sp[6] & 7; ac_to_acl(ac[0], file, SC_AC_OP_UPDATE); ac_to_acl(ac[1], file, SC_AC_OP_WRITE); ac_to_acl(ac[2], file, SC_AC_OP_READ); break; case 0x00: /* 0x38 is DF */ file->type = SC_FILE_TYPE_DF; /* Icky: the GPK uses different ACLs * for creating data files and * 'sensitive' i.e. key files */ ac_to_acl(ac[0], file, SC_AC_OP_LOCK); ac_to_acl(ac[1], file, SC_AC_OP_CREATE); sc_file_add_acl_entry(file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_DELETE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES, SC_AC_NEVER, SC_AC_KEY_REF_NONE); break; } } else if (sp[0] == 0x6f) { /* oops - this is a directory with an IADF. * This happens with the personalized GemSafe cards * for instance. */ file->type = SC_FILE_TYPE_DF; rc = gpk_parse_fci(card, sp + 2, sp[1], file); if (rc < 0) return rc; } } if (file->record_length) file->record_count = file->size / file->record_length; file->magic = SC_FILE_MAGIC; return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: bool smbXcli_req_set_pending(struct tevent_req *req) { struct smbXcli_req_state *state = tevent_req_data(req, struct smbXcli_req_state); struct smbXcli_conn *conn; struct tevent_req **pending; size_t num_pending; conn = state->conn; if (!smbXcli_conn_is_connected(conn)) { return false; } num_pending = talloc_array_length(conn->pending); pending = talloc_realloc(conn, conn->pending, struct tevent_req *, num_pending+1); if (pending == NULL) { return false; } pending[num_pending] = req; conn->pending = pending; tevent_req_set_cleanup_fn(req, smbXcli_req_cleanup); tevent_req_set_cancel_fn(req, smbXcli_req_cancel); if (!smbXcli_conn_receive_next(conn)) { /* * the caller should notify the current request * * And all other pending requests get notified * by smbXcli_conn_disconnect(). */ smbXcli_req_unset_pending(req); smbXcli_conn_disconnect(conn, NT_STATUS_NO_MEMORY); return false; } return true; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int fpga_download(int iobase, int bitrate) { int i, rc; unsigned char *pbits; pbits = get_mcs(bitrate); if (pbits == NULL) return -1; fpga_reset(iobase); for (i = 0; i < YAM_FPGA_SIZE; i++) { if (fpga_write(iobase, pbits[i])) { printk(KERN_ERR "yam: error in write cycle\n"); return -1; /* write... */ } } fpga_write(iobase, 0xFF); rc = inb(MSR(iobase)); /* check DONE signal */ /* Needed for some hardwares */ delay(50); return (rc & MSR_DSR) ? 0 : -1; } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: const BlockEntry* Cluster::GetEntry(const Track* pTrack, long long time_ns) const { assert(pTrack); if (m_pSegment == NULL) // this is the special EOS cluster return pTrack->GetEOS(); #if 0 LoadBlockEntries(); if ((m_entries == NULL) || (m_entries_count <= 0)) return NULL; //return EOS here? const BlockEntry* pResult = pTrack->GetEOS(); BlockEntry** i = m_entries; assert(i); BlockEntry** const j = i + m_entries_count; while (i != j) { const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) continue; if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; pResult = pEntry; } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; } } return pResult; #else const BlockEntry* pResult = pTrack->GetEOS(); long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); assert(status >= 0); if (status > 0) // completely parsed, and no more entries return pResult; if (status < 0) // should never happen return 0; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) { ++index; continue; } if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) // just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; pResult = pEntry; // have a candidate } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; } ++index; } #endif } CWE ID: CWE-20 Target: 1 Example 2: Code: explicit TestOptimizationGuideService( scoped_refptr<base::SingleThreadTaskRunner> io_thread_task_runner) : optimization_guide::OptimizationGuideService(io_thread_task_runner) {} CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void HTMLMediaElement::videoWillBeDrawnToCanvas() const { DCHECK(isHTMLVideoElement()); UseCounter::count(document(), UseCounter::VideoInCanvas); if (m_autoplayUmaHelper->hasSource() && !m_autoplayUmaHelper->isVisible()) UseCounter::count(document(), UseCounter::HiddenAutoplayedVideoInCanvas); } 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: size_t NormalPage::objectPayloadSizeForTesting() { size_t objectPayloadSize = 0; Address headerAddress = payload(); markAsSwept(); ASSERT(headerAddress != payloadEnd()); do { HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(headerAddress); if (!header->isFree()) { ASSERT(header->checkHeader()); objectPayloadSize += header->payloadSize(); } ASSERT(header->size() < blinkPagePayloadSize()); headerAddress += header->size(); ASSERT(headerAddress <= payloadEnd()); } while (headerAddress < payloadEnd()); return objectPayloadSize; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool WebGraphicsContext3DCommandBufferImpl::setParentContext( WebGraphicsContext3D* parent_context) { WebGraphicsContext3DCommandBufferImpl* parent_context_impl = static_cast<WebGraphicsContext3DCommandBufferImpl*>(parent_context); return context_->SetParent( parent_context_impl ? parent_context_impl->context() : 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: DOMArrayBuffer* FileReaderLoader::ArrayBufferResult() { DCHECK_EQ(read_type_, kReadAsArrayBuffer); if (array_buffer_result_) return array_buffer_result_; if (!raw_data_ || error_code_ != FileErrorCode::kOK) return nullptr; DOMArrayBuffer* result = DOMArrayBuffer::Create(raw_data_->ToArrayBuffer()); if (finished_loading_) { array_buffer_result_ = result; AdjustReportedMemoryUsageToV8( -1 * static_cast<int64_t>(raw_data_->ByteLength())); raw_data_.reset(); } return result; } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int userfaultfd_unregister(struct userfaultfd_ctx *ctx, unsigned long arg) { struct mm_struct *mm = ctx->mm; struct vm_area_struct *vma, *prev, *cur; int ret; struct uffdio_range uffdio_unregister; unsigned long new_flags; bool found; unsigned long start, end, vma_end; const void __user *buf = (void __user *)arg; ret = -EFAULT; if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister))) goto out; ret = validate_range(mm, uffdio_unregister.start, uffdio_unregister.len); if (ret) goto out; start = uffdio_unregister.start; end = start + uffdio_unregister.len; ret = -ENOMEM; if (!mmget_not_zero(mm)) goto out; down_write(&mm->mmap_sem); vma = find_vma_prev(mm, start, &prev); if (!vma) goto out_unlock; /* check that there's at least one vma in the range */ ret = -EINVAL; if (vma->vm_start >= end) goto out_unlock; /* * If the first vma contains huge pages, make sure start address * is aligned to huge page size. */ if (is_vm_hugetlb_page(vma)) { unsigned long vma_hpagesize = vma_kernel_pagesize(vma); if (start & (vma_hpagesize - 1)) goto out_unlock; } /* * Search for not compatible vmas. */ found = false; ret = -EINVAL; for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) { cond_resched(); BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^ !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); /* * Check not compatible vmas, not strictly required * here as not compatible vmas cannot have an * userfaultfd_ctx registered on them, but this * provides for more strict behavior to notice * unregistration errors. */ if (!vma_can_userfault(cur)) goto out_unlock; found = true; } BUG_ON(!found); if (vma->vm_start < start) prev = vma; ret = 0; do { cond_resched(); BUG_ON(!vma_can_userfault(vma)); /* * Nothing to do: this vma is already registered into this * userfaultfd and with the right tracking mode too. */ if (!vma->vm_userfaultfd_ctx.ctx) goto skip; if (vma->vm_start > start) start = vma->vm_start; vma_end = min(end, vma->vm_end); if (userfaultfd_missing(vma)) { /* * Wake any concurrent pending userfault while * we unregister, so they will not hang * permanently and it avoids userland to call * UFFDIO_WAKE explicitly. */ struct userfaultfd_wake_range range; range.start = start; range.len = vma_end - start; wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range); } new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP); prev = vma_merge(mm, prev, start, vma_end, new_flags, vma->anon_vma, vma->vm_file, vma->vm_pgoff, vma_policy(vma), NULL_VM_UFFD_CTX); if (prev) { vma = prev; goto next; } if (vma->vm_start < start) { ret = split_vma(mm, vma, start, 1); if (ret) break; } if (vma->vm_end > end) { ret = split_vma(mm, vma, end, 0); if (ret) break; } next: /* * In the vma_merge() successful mprotect-like case 8: * the next vma was merged into the current one and * the current one has not been updated yet. */ vma->vm_flags = new_flags; vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; skip: prev = vma; start = vma->vm_end; vma = vma->vm_next; } while (vma && vma->vm_start < end); out_unlock: up_write(&mm->mmap_sem); mmput(mm); out: return ret; } CWE ID: Target: 1 Example 2: Code: bool RenderFrameImpl::UniqueNameFrameAdapter::IsMainFrame() const { return render_frame_->IsMainFrame(); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline int udp6_csum_init(struct sk_buff *skb, struct udphdr *uh, int proto) { int err; UDP_SKB_CB(skb)->partial_cov = 0; UDP_SKB_CB(skb)->cscov = skb->len; if (proto == IPPROTO_UDPLITE) { err = udplite_checksum_init(skb, uh); if (err) return err; } if (uh->check == 0) { /* RFC 2460 section 8.1 says that we SHOULD log this error. Well, it is reasonable. */ LIMIT_NETDEBUG(KERN_INFO "IPv6: udp checksum is 0\n"); return 1; } if (skb->ip_summed == CHECKSUM_COMPLETE && !csum_ipv6_magic(&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr, skb->len, proto, skb->csum)) skb->ip_summed = CHECKSUM_UNNECESSARY; if (!skb_csum_unnecessary(skb)) skb->csum = ~csum_unfold(csum_ipv6_magic(&ipv6_hdr(skb)->saddr, &ipv6_hdr(skb)->daddr, skb->len, proto, 0)); 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: bool IsBlockedNavigation(net::Error error_code) { switch (error_code) { case net::ERR_BLOCKED_BY_CLIENT: case net::ERR_BLOCKED_BY_RESPONSE: case net::ERR_BLOCKED_BY_XSS_AUDITOR: case net::ERR_UNSAFE_REDIRECT: return true; default: return false; } } CWE ID: CWE-20 Target: 1 Example 2: Code: ClearButtonElement* BaseMultipleFieldsDateAndTimeInputType::clearButtonElement() const { return toClearButtonElement(elementById(ShadowElementNames::clearButton())); } 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: inline HTMLIFrameElement::HTMLIFrameElement(Document& document) : HTMLFrameElementBase(iframeTag, document), did_load_non_empty_document_(false), collapsed_by_client_(false), sandbox_(HTMLIFrameElementSandbox::Create(this)), referrer_policy_(kReferrerPolicyDefault) {} CWE ID: CWE-601 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 ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) { if (current_input_method_.id != new_input_method.id) { previous_input_method_ = current_input_method_; current_input_method_ = new_input_method; if (!input_method::SetCurrentKeyboardLayoutByName( current_input_method_.keyboard_layout)) { LOG(ERROR) << "Failed to change keyboard layout to " << current_input_method_.keyboard_layout; } ObserverListBase<Observer>::Iterator it(observers_); Observer* first_observer = it.GetNext(); if (first_observer) { first_observer->PreferenceUpdateNeeded(this, previous_input_method_, current_input_method_); } } const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_, InputMethodChanged(this, current_input_method_, num_active_input_methods)); } CWE ID: CWE-399 Target: 1 Example 2: Code: static int iov_num_pages(void __user *iov_base, size_t iov_len) { return (PAGE_ALIGN((unsigned long)iov_base + iov_len) - ((unsigned long)iov_base & PAGE_MASK)) >> PAGE_SHIFT; } 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: gfx::Rect BrowserView::GetRootWindowResizerRect() const { if (frame_->IsMaximized() || frame_->IsFullscreen()) return gfx::Rect(); if (IsDownloadShelfVisible()) return gfx::Rect(); gfx::Rect client_rect = contents_split_->bounds(); gfx::Size resize_corner_size = ResizeCorner::GetSize(); int x = client_rect.width() - resize_corner_size.width(); if (base::i18n::IsRTL()) x = 0; return gfx::Rect(x, client_rect.height() - resize_corner_size.height(), resize_corner_size.width(), resize_corner_size.height()); } 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 hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; int err; err = crypto_ahash_export(req, state); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = 1; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; } CWE ID: CWE-476 Target: 1 Example 2: Code: int sco_connect_ind(struct hci_dev *hdev, bdaddr_t *bdaddr, __u8 *flags) { struct sock *sk; int lm = 0; BT_DBG("hdev %s, bdaddr %pMR", hdev->name, bdaddr); /* Find listening sockets */ read_lock(&sco_sk_list.lock); sk_for_each(sk, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; if (!bacmp(&sco_pi(sk)->src, &hdev->bdaddr) || !bacmp(&sco_pi(sk)->src, BDADDR_ANY)) { lm |= HCI_LM_ACCEPT; if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) *flags |= HCI_PROTO_DEFER; break; } } read_unlock(&sco_sk_list.lock); return lm; } 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 fpm_stdio_init_child(struct fpm_worker_pool_s *wp) /* {{{ */ { #ifdef HAVE_SYSLOG_H if (fpm_globals.error_log_fd == ZLOG_SYSLOG) { closelog(); /* ensure to close syslog not to interrupt with PHP syslog code */ } else #endif /* Notice: child cannot use master error_log * because not aware when being reopen * else, should use if (!fpm_use_error_log()) */ if (fpm_globals.error_log_fd > 0) { close(fpm_globals.error_log_fd); } fpm_globals.error_log_fd = -1; zlog_set_fd(-1); if (wp->listening_socket != STDIN_FILENO) { if (0 > dup2(wp->listening_socket, STDIN_FILENO)) { zlog(ZLOG_SYSERROR, "failed to init child stdio: dup2()"); return -1; } } return 0; } /* }}} */ CWE ID: CWE-400 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HTMLCanvasElement::Dispose() { if (PlaceholderFrame()) ReleasePlaceholderFrame(); if (context_) { context_->DetachHost(); context_ = nullptr; } if (canvas2d_bridge_) { canvas2d_bridge_->SetCanvasResourceHost(nullptr); canvas2d_bridge_ = nullptr; } if (gpu_memory_usage_) { DCHECK_GT(global_accelerated_context_count_, 0u); global_accelerated_context_count_--; } global_gpu_memory_usage_ -= gpu_memory_usage_; } CWE ID: CWE-416 Target: 1 Example 2: Code: void GDataCache::CommitDirty(const std::string& resource_id, const std::string& md5, FileOperationType file_operation_type, base::PlatformFileError* error) { AssertOnSequencedWorkerPool(); DCHECK(error); scoped_ptr<CacheEntry> cache_entry = GetCacheEntry(resource_id, std::string()); if (!cache_entry.get() || cache_entry->sub_dir_type == CACHE_TYPE_PINNED) { LOG(WARNING) << "Can't commit dirty a file that wasn't cached: res_id=" << resource_id << ", md5=" << md5; *error = base::PLATFORM_FILE_ERROR_NOT_FOUND; return; } if (!cache_entry->IsDirty()) { LOG(WARNING) << "Can't commit a non-dirty file: res_id=" << resource_id << ", md5=" << md5; *error = base::PLATFORM_FILE_ERROR_INVALID_OPERATION; return; } DCHECK_EQ(CACHE_TYPE_PERSISTENT, cache_entry->sub_dir_type); FilePath symlink_path = GetCacheFilePath(resource_id, std::string(), CACHE_TYPE_OUTGOING, CACHED_FILE_FROM_SERVER); FilePath target_path = GetCacheFilePath(resource_id, md5, cache_entry->sub_dir_type, CACHED_FILE_LOCALLY_MODIFIED); *error = ModifyCacheState(target_path, // source target_path, // destination file_operation_type, symlink_path, true /* create symlink */); } 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 __init xfrm6_tunnel_spi_init(void) { xfrm6_tunnel_spi_kmem = kmem_cache_create("xfrm6_tunnel_spi", sizeof(struct xfrm6_tunnel_spi), 0, SLAB_HWCACHE_ALIGN, NULL); if (!xfrm6_tunnel_spi_kmem) return -ENOMEM; return 0; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void V8RecursionScope::didLeaveScriptContext() { Microtask::performCheckpoint(); V8PerIsolateData::from(m_isolate)->runEndOfScopeTasks(); } CWE ID: CWE-254 Target: 1 Example 2: Code: void ReadPixels( GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) const { DCHECK_GE(x, 0); DCHECK_GE(y, 0); DCHECK_LE(x + width, width_); DCHECK_LE(y + height, height_); for (GLint yy = 0; yy < height; ++yy) { const int8* src = GetPixelAddress(src_pixels_, x, y + yy); const void* dst = ComputePackAlignmentAddress(0, yy, width, pixels); memcpy(const_cast<void*>(dst), src, width * bytes_per_pixel_); } } 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: htmlParseDocTypeDecl(htmlParserCtxtPtr ctxt) { const xmlChar *name; xmlChar *ExternalID = NULL; xmlChar *URI = NULL; /* * We know that '<!DOCTYPE' has been detected. */ SKIP(9); SKIP_BLANKS; /* * Parse the DOCTYPE name. */ name = htmlParseName(ctxt); if (name == NULL) { htmlParseErr(ctxt, XML_ERR_NAME_REQUIRED, "htmlParseDocTypeDecl : no DOCTYPE name !\n", NULL, NULL); } /* * Check that upper(name) == "HTML" !!!!!!!!!!!!! */ SKIP_BLANKS; /* * Check for SystemID and ExternalID */ URI = htmlParseExternalID(ctxt, &ExternalID); SKIP_BLANKS; /* * We should be at the end of the DOCTYPE declaration. */ if (CUR != '>') { htmlParseErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, "DOCTYPE improperly terminated\n", NULL, NULL); /* We shouldn't try to resynchronize ... */ } NEXT; /* * Create or update the document accordingly to the DOCTYPE */ if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); /* * Cleanup, since we don't use all those identifiers */ if (URI != NULL) xmlFree(URI); if (ExternalID != NULL) xmlFree(ExternalID); } 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 PageRequestSummary::UpdateOrAddToOrigins( const GURL& url, const content::mojom::CommonNetworkInfoPtr& network_info) { GURL origin = url.GetOrigin(); if (!origin.is_valid()) return; auto it = origins.find(origin); if (it == origins.end()) { OriginRequestSummary summary; summary.origin = origin; summary.first_occurrence = origins.size(); it = origins.insert({origin, summary}).first; } it->second.always_access_network |= network_info->always_access_network; it->second.accessed_network |= network_info->network_accessed; } CWE ID: CWE-125 Target: 1 Example 2: Code: static inline void flush_slab(struct kmem_cache *s, struct kmem_cache_cpu *c) { stat(c, CPUSLAB_FLUSH); slab_lock(c->page); deactivate_slab(s, c); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WebRequestPermissions::CanExtensionAccessURL( const extensions::InfoMap* extension_info_map, const std::string& extension_id, const GURL& url, bool crosses_incognito, HostPermissionsCheck host_permissions_check) { if (!extension_info_map) return true; const extensions::Extension* extension = extension_info_map->extensions().GetByID(extension_id); if (!extension) return false; if (crosses_incognito && !extension_info_map->CanCrossIncognito(extension)) return false; switch (host_permissions_check) { case DO_NOT_CHECK_HOST: break; case REQUIRE_HOST_PERMISSION: if (!((url.SchemeIs(url::kAboutScheme) || extension->permissions_data()->HasHostPermission(url) || url.GetOrigin() == extension->url()))) { return false; } break; case REQUIRE_ALL_URLS: if (!extension->permissions_data()->HasEffectiveAccessToAllHosts()) return false; break; } return true; } 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: PageInfoUI::IdentityInfo::IdentityInfo() : identity_status(PageInfo::SITE_IDENTITY_STATUS_UNKNOWN), safe_browsing_status(PageInfo::SAFE_BROWSING_STATUS_NONE), connection_status(PageInfo::SITE_CONNECTION_STATUS_UNKNOWN), show_ssl_decision_revoke_button(false), show_change_password_buttons(false) {} CWE ID: CWE-311 Target: 1 Example 2: Code: static void withExecutionContextAndScriptStateWithSpacesMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); TestObjectV8Internal::withExecutionContextAndScriptStateWithSpacesMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int invent_group_ids(struct mount *mnt, bool recurse) { struct mount *p; for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) { if (!p->mnt_group_id && !IS_MNT_SHARED(p)) { int err = mnt_alloc_group_id(p); if (err) { cleanup_group_ids(mnt, p); return err; } } } return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Load_SBit_Png( FT_GlyphSlot slot, FT_Int x_offset, FT_Int y_offset, FT_Int pix_bits, TT_SBit_Metrics metrics, FT_Memory memory, FT_Byte* data, FT_UInt png_len, FT_Bool populate_map_and_metrics ) { FT_Bitmap *map = &slot->bitmap; FT_Error error = FT_Err_Ok; FT_StreamRec stream; png_structp png; png_infop info; png_uint_32 imgWidth, imgHeight; int bitdepth, color_type, interlace; FT_Int i; png_byte* *rows = NULL; /* pacify compiler */ if ( x_offset < 0 || y_offset < 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } if ( !populate_map_and_metrics && ( x_offset + metrics->width > map->width || y_offset + metrics->height > map->rows || pix_bits != 32 || map->pixel_mode != FT_PIXEL_MODE_BGRA ) ) { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_Stream_OpenMemory( &stream, data, png_len ); png = png_create_read_struct( PNG_LIBPNG_VER_STRING, &error, error_callback, warning_callback ); if ( !png ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } info = png_create_info_struct( png ); if ( !info ) { error = FT_THROW( Out_Of_Memory ); png_destroy_read_struct( &png, NULL, NULL ); goto Exit; } if ( ft_setjmp( png_jmpbuf( png ) ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } png_set_read_fn( png, &stream, read_data_from_FT_Stream ); png_read_info( png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( error || ( !populate_map_and_metrics && ( (FT_Int)imgWidth != metrics->width || (FT_Int)imgHeight != metrics->height ) ) ) goto DestroyExit; if ( populate_map_and_metrics ) { FT_Long size; metrics->width = (FT_Int)imgWidth; metrics->height = (FT_Int)imgHeight; map->width = metrics->width; map->rows = metrics->height; map->pixel_mode = FT_PIXEL_MODE_BGRA; map->pitch = map->width * 4; map->num_grays = 256; /* reject too large bitmaps similarly to the rasterizer */ if ( map->rows > 0x7FFF || map->width > 0x7FFF ) { error = FT_THROW( Array_Too_Large ); goto DestroyExit; } size = map->rows * map->pitch; error = ft_glyphslot_alloc_bitmap( slot, size ); if ( error ) goto DestroyExit; } /* convert palette/gray image to rgb */ if ( color_type == PNG_COLOR_TYPE_PALETTE ) png_set_palette_to_rgb( png ); /* expand gray bit depth if needed */ if ( color_type == PNG_COLOR_TYPE_GRAY ) { #if PNG_LIBPNG_VER >= 10209 png_set_expand_gray_1_2_4_to_8( png ); #else png_set_gray_1_2_4_to_8( png ); #endif } /* transform transparency to alpha */ if ( png_get_valid(png, info, PNG_INFO_tRNS ) ) png_set_tRNS_to_alpha( png ); if ( bitdepth == 16 ) png_set_strip_16( png ); if ( bitdepth < 8 ) png_set_packing( png ); /* convert grayscale to RGB */ if ( color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) png_set_gray_to_rgb( png ); if ( interlace != PNG_INTERLACE_NONE ) png_set_interlace_handling( png ); png_set_filler( png, 0xFF, PNG_FILLER_AFTER ); /* recheck header after setting EXPAND options */ png_read_update_info(png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( bitdepth != 8 || !( color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } switch ( color_type ) { default: /* Shouldn't happen, but fall through. */ case PNG_COLOR_TYPE_RGB_ALPHA: png_set_read_user_transform_fn( png, premultiply_data ); break; case PNG_COLOR_TYPE_RGB: /* Humm, this smells. Carry on though. */ png_set_read_user_transform_fn( png, convert_bytes_to_data ); break; } if ( FT_NEW_ARRAY( rows, imgHeight ) ) { error = FT_THROW( Out_Of_Memory ); goto DestroyExit; } for ( i = 0; i < (FT_Int)imgHeight; i++ ) rows[i] = map->buffer + ( y_offset + i ) * map->pitch + x_offset * 4; png_read_image( png, rows ); FT_FREE( rows ); png_read_end( png, info ); DestroyExit: png_destroy_read_struct( &png, &info, NULL ); FT_Stream_Close( &stream ); Exit: return error; } CWE ID: CWE-119 Target: 1 Example 2: Code: message_is_name_owner_changed (FlatpakProxyClient *client, Header *header) { if (header->type == G_DBUS_MESSAGE_TYPE_SIGNAL && g_strcmp0 (header->sender, "org.freedesktop.DBus") == 0 && g_strcmp0 (header->interface, "org.freedesktop.DBus") == 0 && g_strcmp0 (header->member, "NameOwnerChanged") == 0) return TRUE; return FALSE; } CWE ID: CWE-436 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 apply_mailbox_pattern(annotate_state_t *state, const char *pattern, int (*proc)(annotate_state_t *, void *), void *data) { struct apply_rock arock; int r = 0; memset(&arock, 0, sizeof(arock)); arock.state = state; arock.proc = proc; arock.data = data; r = mboxlist_findall(&imapd_namespace, pattern, imapd_userisadmin || imapd_userisproxyadmin, imapd_userid, imapd_authstate, apply_cb, &arock); if (!r && !arock.nseen) r = IMAP_MAILBOX_NONEXISTENT; return r; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void sas_eh_defer_cmd(struct scsi_cmnd *cmd) { struct domain_device *dev = cmd_to_domain_dev(cmd); struct sas_ha_struct *ha = dev->port->ha; struct sas_task *task = TO_SAS_TASK(cmd); if (!dev_is_sata(dev)) { sas_eh_finish_cmd(cmd); return; } /* report the timeout to libata */ sas_end_task(cmd, task); list_move_tail(&cmd->eh_entry, &ha->eh_ata_q); } CWE ID: Target: 1 Example 2: Code: on_window_deletion(void *user_data, Evas_Object *window, void *event_info) { window_close(browser_window_find(window)); } 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: ChromeContentBrowserClient::CreateURLLoaderThrottles( const network::ResourceRequest& request, content::ResourceContext* resource_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) { DCHECK_CURRENTLY_ON(BrowserThread::IO); bool network_service_enabled = base::FeatureList::IsEnabled(network::features::kNetworkService); std::vector<std::unique_ptr<content::URLLoaderThrottle>> result; ProfileIOData* io_data = nullptr; if (safe_browsing_service_ || data_reduction_proxy::params::IsEnabledWithNetworkService()) { io_data = ProfileIOData::FromResourceContext(resource_context); } if (io_data && io_data->data_reduction_proxy_io_data() && data_reduction_proxy::params::IsEnabledWithNetworkService()) { net::HttpRequestHeaders headers; data_reduction_proxy::DataReductionProxyRequestOptions* request_options = io_data->data_reduction_proxy_io_data()->request_options(); request_options->AddPageIDRequestHeader(&headers, request_options->GeneratePageId()); result.push_back(std::make_unique< data_reduction_proxy::DataReductionProxyURLLoaderThrottle>( headers, io_data->data_reduction_proxy_io_data())); } #if defined(SAFE_BROWSING_DB_LOCAL) || defined(SAFE_BROWSING_DB_REMOTE) if (io_data && safe_browsing_service_) { bool matches_enterprise_whitelist = safe_browsing::IsURLWhitelistedByPolicy( request.url, io_data->safe_browsing_whitelist_domains()); if (!matches_enterprise_whitelist && (network_service_enabled || base::FeatureList::IsEnabled( safe_browsing::kCheckByURLLoaderThrottle))) { auto* delegate = GetSafeBrowsingUrlCheckerDelegate(resource_context); if (delegate && !delegate->ShouldSkipRequestCheck( resource_context, request.url, frame_tree_node_id, -1 /* render_process_id */, -1 /* render_frame_id */, request.originated_from_service_worker)) { auto safe_browsing_throttle = safe_browsing::BrowserURLLoaderThrottle::MaybeCreate(delegate, wc_getter); if (safe_browsing_throttle) result.push_back(std::move(safe_browsing_throttle)); } } } #endif // defined(SAFE_BROWSING_DB_LOCAL) || defined(SAFE_BROWSING_DB_REMOTE) if (network_service_enabled) { ChromeNavigationUIData* chrome_navigation_ui_data = static_cast<ChromeNavigationUIData*>(navigation_ui_data); if (chrome_navigation_ui_data && chrome_navigation_ui_data->prerender_mode() != prerender::NO_PRERENDER) { result.push_back(std::make_unique<prerender::PrerenderURLLoaderThrottle>( chrome_navigation_ui_data->prerender_mode(), chrome_navigation_ui_data->prerender_histogram_prefix(), base::BindOnce(GetPrerenderCanceller, wc_getter), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}))); } } if (io_data) { bool is_off_the_record = io_data->IsOffTheRecord(); bool is_signed_in = !is_off_the_record && !io_data->google_services_account_id()->GetValue().empty(); chrome::mojom::DynamicParams dynamic_params = { io_data->force_google_safesearch()->GetValue(), io_data->force_youtube_restrict()->GetValue(), io_data->allowed_domains_for_apps()->GetValue(), variations::VariationsHttpHeaderProvider::GetInstance() ->GetClientDataHeader(is_signed_in)}; result.push_back(std::make_unique<GoogleURLLoaderThrottle>( is_off_the_record, std::move(dynamic_params))); } #if BUILDFLAG(ENABLE_PLUGINS) if (network_service_enabled) { result.push_back( std::make_unique<PluginResponseInterceptorURLLoaderThrottle>( resource_context, request.resource_type, frame_tree_node_id)); } #endif if (network_service_enabled) { auto delegate = std::make_unique<signin::HeaderModificationDelegateImpl>( resource_context); auto signin_throttle = signin::URLLoaderThrottle::MaybeCreate( std::move(delegate), navigation_ui_data, wc_getter); if (signin_throttle) result.push_back(std::move(signin_throttle)); } return result; } 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: raptor_libxml_getEntity(void* user_data, const xmlChar *name) { raptor_sax2* sax2 = (raptor_sax2*)user_data; return libxml2_getEntity(sax2->xc, name); } CWE ID: CWE-200 Target: 1 Example 2: Code: virDomainGetDiskErrors(virDomainPtr dom, virDomainDiskErrorPtr errors, unsigned int maxerrors, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "errors=%p, maxerrors=%u, flags=%x", errors, maxerrors, flags); virResetLastError(); virCheckDomainReturn(dom, -1); if (maxerrors) virCheckNonNullArgGoto(errors, error); else virCheckNullArgGoto(errors, error); if (dom->conn->driver->domainGetDiskErrors) { int ret = dom->conn->driver->domainGetDiskErrors(dom, errors, maxerrors, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } 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 test_unsigned_int_formatting(void) { int i, j; int num_uint_tests; int failed = 0; #if (SIZEOF_INT == 2) i=1; ui_test[i].num = 0xFFFFU; ui_test[i].expected = "65535"; i++; ui_test[i].num = 0xFF00U; ui_test[i].expected = "65280"; i++; ui_test[i].num = 0x00FFU; ui_test[i].expected = "255"; i++; ui_test[i].num = 0xF000U; ui_test[i].expected = "61440"; i++; ui_test[i].num = 0x0F00U; ui_test[i].expected = "3840"; i++; ui_test[i].num = 0x00F0U; ui_test[i].expected = "240"; i++; ui_test[i].num = 0x000FU; ui_test[i].expected = "15"; i++; ui_test[i].num = 0xC000U; ui_test[i].expected = "49152"; i++; ui_test[i].num = 0x0C00U; ui_test[i].expected = "3072"; i++; ui_test[i].num = 0x00C0U; ui_test[i].expected = "192"; i++; ui_test[i].num = 0x000CU; ui_test[i].expected = "12"; i++; ui_test[i].num = 0x0001U; ui_test[i].expected = "1"; i++; ui_test[i].num = 0x0000U; ui_test[i].expected = "0"; num_uint_tests = i; #elif (SIZEOF_INT == 4) i=1; ui_test[i].num = 0xFFFFFFFFU; ui_test[i].expected = "4294967295"; i++; ui_test[i].num = 0xFFFF0000U; ui_test[i].expected = "4294901760"; i++; ui_test[i].num = 0x0000FFFFU; ui_test[i].expected = "65535"; i++; ui_test[i].num = 0xFF000000U; ui_test[i].expected = "4278190080"; i++; ui_test[i].num = 0x00FF0000U; ui_test[i].expected = "16711680"; i++; ui_test[i].num = 0x0000FF00U; ui_test[i].expected = "65280"; i++; ui_test[i].num = 0x000000FFU; ui_test[i].expected = "255"; i++; ui_test[i].num = 0xF0000000U; ui_test[i].expected = "4026531840"; i++; ui_test[i].num = 0x0F000000U; ui_test[i].expected = "251658240"; i++; ui_test[i].num = 0x00F00000U; ui_test[i].expected = "15728640"; i++; ui_test[i].num = 0x000F0000U; ui_test[i].expected = "983040"; i++; ui_test[i].num = 0x0000F000U; ui_test[i].expected = "61440"; i++; ui_test[i].num = 0x00000F00U; ui_test[i].expected = "3840"; i++; ui_test[i].num = 0x000000F0U; ui_test[i].expected = "240"; i++; ui_test[i].num = 0x0000000FU; ui_test[i].expected = "15"; i++; ui_test[i].num = 0xC0000000U; ui_test[i].expected = "3221225472"; i++; ui_test[i].num = 0x0C000000U; ui_test[i].expected = "201326592"; i++; ui_test[i].num = 0x00C00000U; ui_test[i].expected = "12582912"; i++; ui_test[i].num = 0x000C0000U; ui_test[i].expected = "786432"; i++; ui_test[i].num = 0x0000C000U; ui_test[i].expected = "49152"; i++; ui_test[i].num = 0x00000C00U; ui_test[i].expected = "3072"; i++; ui_test[i].num = 0x000000C0U; ui_test[i].expected = "192"; i++; ui_test[i].num = 0x0000000CU; ui_test[i].expected = "12"; i++; ui_test[i].num = 0x00000001U; ui_test[i].expected = "1"; i++; ui_test[i].num = 0x00000000U; ui_test[i].expected = "0"; num_uint_tests = i; #elif (SIZEOF_INT == 8) /* !checksrc! disable LONGLINE all */ i=1; ui_test[i].num = 0xFFFFFFFFFFFFFFFFU; ui_test[i].expected = "18446744073709551615"; i++; ui_test[i].num = 0xFFFFFFFF00000000U; ui_test[i].expected = "18446744069414584320"; i++; ui_test[i].num = 0x00000000FFFFFFFFU; ui_test[i].expected = "4294967295"; i++; ui_test[i].num = 0xFFFF000000000000U; ui_test[i].expected = "18446462598732840960"; i++; ui_test[i].num = 0x0000FFFF00000000U; ui_test[i].expected = "281470681743360"; i++; ui_test[i].num = 0x00000000FFFF0000U; ui_test[i].expected = "4294901760"; i++; ui_test[i].num = 0x000000000000FFFFU; ui_test[i].expected = "65535"; i++; ui_test[i].num = 0xFF00000000000000U; ui_test[i].expected = "18374686479671623680"; i++; ui_test[i].num = 0x00FF000000000000U; ui_test[i].expected = "71776119061217280"; i++; ui_test[i].num = 0x0000FF0000000000U; ui_test[i].expected = "280375465082880"; i++; ui_test[i].num = 0x000000FF00000000U; ui_test[i].expected = "1095216660480"; i++; ui_test[i].num = 0x00000000FF000000U; ui_test[i].expected = "4278190080"; i++; ui_test[i].num = 0x0000000000FF0000U; ui_test[i].expected = "16711680"; i++; ui_test[i].num = 0x000000000000FF00U; ui_test[i].expected = "65280"; i++; ui_test[i].num = 0x00000000000000FFU; ui_test[i].expected = "255"; i++; ui_test[i].num = 0xF000000000000000U; ui_test[i].expected = "17293822569102704640"; i++; ui_test[i].num = 0x0F00000000000000U; ui_test[i].expected = "1080863910568919040"; i++; ui_test[i].num = 0x00F0000000000000U; ui_test[i].expected = "67553994410557440"; i++; ui_test[i].num = 0x000F000000000000U; ui_test[i].expected = "4222124650659840"; i++; ui_test[i].num = 0x0000F00000000000U; ui_test[i].expected = "263882790666240"; i++; ui_test[i].num = 0x00000F0000000000U; ui_test[i].expected = "16492674416640"; i++; ui_test[i].num = 0x000000F000000000U; ui_test[i].expected = "1030792151040"; i++; ui_test[i].num = 0x0000000F00000000U; ui_test[i].expected = "64424509440"; i++; ui_test[i].num = 0x00000000F0000000U; ui_test[i].expected = "4026531840"; i++; ui_test[i].num = 0x000000000F000000U; ui_test[i].expected = "251658240"; i++; ui_test[i].num = 0x0000000000F00000U; ui_test[i].expected = "15728640"; i++; ui_test[i].num = 0x00000000000F0000U; ui_test[i].expected = "983040"; i++; ui_test[i].num = 0x000000000000F000U; ui_test[i].expected = "61440"; i++; ui_test[i].num = 0x0000000000000F00U; ui_test[i].expected = "3840"; i++; ui_test[i].num = 0x00000000000000F0U; ui_test[i].expected = "240"; i++; ui_test[i].num = 0x000000000000000FU; ui_test[i].expected = "15"; i++; ui_test[i].num = 0xC000000000000000U; ui_test[i].expected = "13835058055282163712"; i++; ui_test[i].num = 0x0C00000000000000U; ui_test[i].expected = "864691128455135232"; i++; ui_test[i].num = 0x00C0000000000000U; ui_test[i].expected = "54043195528445952"; i++; ui_test[i].num = 0x000C000000000000U; ui_test[i].expected = "3377699720527872"; i++; ui_test[i].num = 0x0000C00000000000U; ui_test[i].expected = "211106232532992"; i++; ui_test[i].num = 0x00000C0000000000U; ui_test[i].expected = "13194139533312"; i++; ui_test[i].num = 0x000000C000000000U; ui_test[i].expected = "824633720832"; i++; ui_test[i].num = 0x0000000C00000000U; ui_test[i].expected = "51539607552"; i++; ui_test[i].num = 0x00000000C0000000U; ui_test[i].expected = "3221225472"; i++; ui_test[i].num = 0x000000000C000000U; ui_test[i].expected = "201326592"; i++; ui_test[i].num = 0x0000000000C00000U; ui_test[i].expected = "12582912"; i++; ui_test[i].num = 0x00000000000C0000U; ui_test[i].expected = "786432"; i++; ui_test[i].num = 0x000000000000C000U; ui_test[i].expected = "49152"; i++; ui_test[i].num = 0x0000000000000C00U; ui_test[i].expected = "3072"; i++; ui_test[i].num = 0x00000000000000C0U; ui_test[i].expected = "192"; i++; ui_test[i].num = 0x000000000000000CU; ui_test[i].expected = "12"; i++; ui_test[i].num = 0x00000001U; ui_test[i].expected = "1"; i++; ui_test[i].num = 0x00000000U; ui_test[i].expected = "0"; num_uint_tests = i; #endif for(i=1; i<=num_uint_tests; i++) { for(j=0; j<BUFSZ; j++) ui_test[i].result[j] = 'X'; ui_test[i].result[BUFSZ-1] = '\0'; (void)curl_msprintf(ui_test[i].result, "%u", ui_test[i].num); if(memcmp(ui_test[i].result, ui_test[i].expected, strlen(ui_test[i].expected))) { printf("unsigned int test #%.2d: Failed (Expected: %s Got: %s)\n", i, ui_test[i].expected, ui_test[i].result); failed++; } } if(!failed) printf("All curl_mprintf() unsigned int tests OK!\n"); else printf("Some curl_mprintf() unsigned int tests Failed!\n"); return failed; } 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 oz_usb_rx(struct oz_pd *pd, struct oz_elt *elt) { struct oz_usb_hdr *usb_hdr = (struct oz_usb_hdr *)(elt + 1); struct oz_usb_ctx *usb_ctx; spin_lock_bh(&pd->app_lock[OZ_APPID_USB]); usb_ctx = (struct oz_usb_ctx *)pd->app_ctx[OZ_APPID_USB]; if (usb_ctx) oz_usb_get(usb_ctx); spin_unlock_bh(&pd->app_lock[OZ_APPID_USB]); if (usb_ctx == NULL) return; /* Context has gone so nothing to do. */ if (usb_ctx->stopped) goto done; /* If sequence number is non-zero then check it is not a duplicate. * Zero sequence numbers are always accepted. */ if (usb_hdr->elt_seq_num != 0) { if (((usb_ctx->rx_seq_num - usb_hdr->elt_seq_num) & 0x80) == 0) /* Reject duplicate element. */ goto done; } usb_ctx->rx_seq_num = usb_hdr->elt_seq_num; switch (usb_hdr->type) { case OZ_GET_DESC_RSP: { struct oz_get_desc_rsp *body = (struct oz_get_desc_rsp *)usb_hdr; int data_len = elt->length - sizeof(struct oz_get_desc_rsp) + 1; u16 offs = le16_to_cpu(get_unaligned(&body->offset)); u16 total_size = le16_to_cpu(get_unaligned(&body->total_size)); oz_dbg(ON, "USB_REQ_GET_DESCRIPTOR - cnf\n"); oz_hcd_get_desc_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, data_len, offs, total_size); } break; case OZ_SET_CONFIG_RSP: { struct oz_set_config_rsp *body = (struct oz_set_config_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_SET_INTERFACE_RSP: { struct oz_set_interface_rsp *body = (struct oz_set_interface_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, NULL, 0); } break; case OZ_VENDOR_CLASS_RSP: { struct oz_vendor_class_rsp *body = (struct oz_vendor_class_rsp *)usb_hdr; oz_hcd_control_cnf(usb_ctx->hport, body->req_id, body->rcode, body->data, elt->length- sizeof(struct oz_vendor_class_rsp)+1); } break; case OZ_USB_ENDPOINT_DATA: oz_usb_handle_ep_data(usb_ctx, usb_hdr, elt->length); break; } done: oz_usb_put(usb_ctx); } CWE ID: CWE-119 Target: 1 Example 2: Code: JBIG2Bitmap *getBitmap(Guint idx) { return (idx < size) ? bitmaps[idx] : 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: void gitn_del(GF_Box *s) { u32 i; GroupIdToNameBox *ptr = (GroupIdToNameBox *)s; if (ptr == NULL) return; for (i=0; i<ptr->nb_entries; i++) { if (ptr->entries[i].name) gf_free(ptr->entries[i].name); } if (ptr->entries) gf_free(ptr->entries); gf_free(ptr); } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> enabledAtRuntimeMethod1Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.enabledAtRuntimeMethod1"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(int, intArg, V8int::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8int::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->enabledAtRuntimeMethod1(intArg); return v8::Handle<v8::Value>(); } CWE ID: Target: 1 Example 2: Code: static void rdma_umap_priv_init(struct rdma_umap_priv *priv, struct vm_area_struct *vma) { struct ib_uverbs_file *ufile = vma->vm_file->private_data; priv->vma = vma; vma->vm_private_data = priv; vma->vm_ops = &rdma_umap_ops; mutex_lock(&ufile->umap_lock); list_add(&priv->list, &ufile->umaps); mutex_unlock(&ufile->umap_lock); } 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: RenderView* RenderFrameImpl::GetRenderView() { return render_view_; } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ScriptProcessorHandler::Process(size_t frames_to_process) { AudioBus* input_bus = Input(0).Bus(); AudioBus* output_bus = Output(0).Bus(); unsigned double_buffer_index = this->DoubleBufferIndex(); bool is_double_buffer_index_good = double_buffer_index < 2 && double_buffer_index < input_buffers_.size() && double_buffer_index < output_buffers_.size(); DCHECK(is_double_buffer_index_good); if (!is_double_buffer_index_good) return; AudioBuffer* input_buffer = input_buffers_[double_buffer_index].Get(); AudioBuffer* output_buffer = output_buffers_[double_buffer_index].Get(); unsigned number_of_input_channels = internal_input_bus_->NumberOfChannels(); bool buffers_are_good = output_buffer && BufferSize() == output_buffer->length() && buffer_read_write_index_ + frames_to_process <= BufferSize(); if (internal_input_bus_->NumberOfChannels()) buffers_are_good = buffers_are_good && input_buffer && BufferSize() == input_buffer->length(); DCHECK(buffers_are_good); if (!buffers_are_good) return; bool is_frames_to_process_good = frames_to_process && BufferSize() >= frames_to_process && !(BufferSize() % frames_to_process); DCHECK(is_frames_to_process_good); if (!is_frames_to_process_good) return; unsigned number_of_output_channels = output_bus->NumberOfChannels(); bool channels_are_good = (number_of_input_channels == number_of_input_channels_) && (number_of_output_channels == number_of_output_channels_); DCHECK(channels_are_good); if (!channels_are_good) return; for (unsigned i = 0; i < number_of_input_channels; ++i) internal_input_bus_->SetChannelMemory( i, input_buffer->getChannelData(i).View()->Data() + buffer_read_write_index_, frames_to_process); if (number_of_input_channels) internal_input_bus_->CopyFrom(*input_bus); for (unsigned i = 0; i < number_of_output_channels; ++i) { memcpy(output_bus->Channel(i)->MutableData(), output_buffer->getChannelData(i).View()->Data() + buffer_read_write_index_, sizeof(float) * frames_to_process); } buffer_read_write_index_ = (buffer_read_write_index_ + frames_to_process) % BufferSize(); if (!buffer_read_write_index_) { MutexTryLocker try_locker(process_event_lock_); if (!try_locker.Locked()) { output_buffer->Zero(); } else if (Context()->GetExecutionContext()) { if (Context()->HasRealtimeConstraint()) { TaskRunnerHelper::Get(TaskType::kMediaElementEvent, Context()->GetExecutionContext()) ->PostTask(BLINK_FROM_HERE, CrossThreadBind( &ScriptProcessorHandler::FireProcessEvent, CrossThreadUnretained(this), double_buffer_index_)); } else { std::unique_ptr<WaitableEvent> waitable_event = WTF::MakeUnique<WaitableEvent>(); TaskRunnerHelper::Get(TaskType::kMediaElementEvent, Context()->GetExecutionContext()) ->PostTask(BLINK_FROM_HERE, CrossThreadBind( &ScriptProcessorHandler:: FireProcessEventForOfflineAudioContext, CrossThreadUnretained(this), double_buffer_index_, CrossThreadUnretained(waitable_event.get()))); waitable_event->Wait(); } } SwapBuffers(); } } CWE ID: CWE-416 Target: 1 Example 2: Code: void re_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) re_yy_load_buffer_state(yyscanner ); } 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 int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int error = 0; if (sk->sk_state & PPPOX_BOUND) { error = -EIO; goto end; } skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &error); if (error < 0) goto end; m->msg_namelen = 0; if (skb) { total_len = min_t(size_t, total_len, skb->len); error = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len); if (error == 0) { consume_skb(skb); return total_len; } } kfree_skb(skb); end: return error; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DocumentLoader::InstallNewDocument( const KURL& url, Document* owner_document, WebGlobalObjectReusePolicy global_object_reuse_policy, const AtomicString& mime_type, const AtomicString& encoding, InstallNewDocumentReason reason, ParserSynchronizationPolicy parsing_policy, const KURL& overriding_url) { DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive()); DCHECK_EQ(frame_->Tree().ChildCount(), 0u); if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) { GetFrameLoader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedFirstRealLoad); } const SecurityOrigin* previous_security_origin = nullptr; const ContentSecurityPolicy* previous_csp = nullptr; if (frame_->GetDocument()) { previous_security_origin = frame_->GetDocument()->GetSecurityOrigin(); previous_csp = frame_->GetDocument()->GetContentSecurityPolicy(); } if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting) frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_)); if (reason == InstallNewDocumentReason::kNavigation) WillCommitNavigation(); Document* document = frame_->DomWindow()->InstallNewDocument( mime_type, DocumentInit::Create() .WithDocumentLoader(this) .WithURL(url) .WithOwnerDocument(owner_document) .WithNewRegistrationContext() .WithPreviousDocumentCSP(previous_csp), false); if (frame_->IsMainFrame()) frame_->ClearActivation(); if (frame_->HasReceivedUserGestureBeforeNavigation() != had_sticky_activation_) { frame_->SetDocumentHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation( had_sticky_activation_); } if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) { frame_->Tree().ExperimentalSetNulledName(); } if (!overriding_url.IsEmpty()) document->SetBaseURLOverride(overriding_url); DidInstallNewDocument(document, previous_csp); if (reason == InstallNewDocumentReason::kNavigation) DidCommitNavigation(global_object_reuse_policy); if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) { if (document->GetSettings() ->GetForceTouchEventFeatureDetectionForInspector()) { OriginTrialContext::FromOrCreate(document)->AddFeature( "ForceTouchEventFeatureDetectionForInspector"); } OriginTrialContext::AddTokensFromHeader( document, response_.HttpHeaderField(http_names::kOriginTrial)); } bool stale_while_revalidate_enabled = origin_trials::StaleWhileRevalidateEnabled(document); fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled); if (stale_while_revalidate_enabled && !RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag()) UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled); parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding); ScriptableDocumentParser* scriptable_parser = parser_->AsScriptableDocumentParser(); if (scriptable_parser && GetResource()) { scriptable_parser->SetInlineScriptCacheHandler( ToRawResource(GetResource())->InlineScriptCacheHandler()); } WTF::String feature_policy( response_.HttpHeaderField(http_names::kFeaturePolicy)); MergeFeaturesFromOriginPolicy(feature_policy, request_.GetOriginPolicy()); document->ApplyFeaturePolicyFromHeader(feature_policy); GetFrameLoader().DispatchDidClearDocumentOfWindowObject(); } CWE ID: CWE-20 Target: 1 Example 2: Code: static int ipx_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; int val = 0; int len; int rc = -ENOPROTOOPT; lock_sock(sk); if (!(level == SOL_IPX && optname == IPX_TYPE)) goto out; val = ipx_sk(sk)->type; rc = -EFAULT; if (get_user(len, optlen)) goto out; len = min_t(unsigned int, len, sizeof(int)); rc = -EINVAL; if(len < 0) goto out; rc = -EFAULT; if (put_user(len, optlen) || copy_to_user(optval, &val, len)) goto out; rc = 0; out: release_sock(sk); return rc; } 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 FastIdentity16(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register const void* D) { cmsPipeline* Lut = (cmsPipeline*) D; cmsUInt32Number i; for (i=0; i < Lut ->InputChannels; i++) { Out[i] = In[i]; } } 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: TestCompletionCallback() : callback_(base::Bind(&TestCompletionCallback::SetResult, base::Unretained(this))) {} CWE ID: Target: 1 Example 2: Code: static void limitedToOnlyOtherAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); String resultValue = imp->fastGetAttribute(HTMLNames::OtherAttr); if (resultValue.isEmpty()) { ; } else if (equalIgnoringCase(resultValue, "Value1")) { resultValue = "Value1"; } else if (equalIgnoringCase(resultValue, "Value2")) { resultValue = "Value2"; } else { resultValue = ""; } v8SetReturnValueString(info, resultValue, info.GetIsolate()); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Extension::is_content_pack() const { return !content_pack_site_list_.empty(); } CWE ID: CWE-264 Output:
0