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: void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { bool oldHorizontalWritingMode = isHorizontalWritingMode(); RenderBoxModelObject::styleDidChange(diff, oldStyle); RenderStyle* newStyle = style(); if (needsLayout() && oldStyle) { RenderBlock::removePercentHeightDescendantIfNeeded(this); if (isOutOfFlowPositioned() && newStyle->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle->marginBefore() && parent() && !parent()->normalChildNeedsLayout()) parent()->setChildNeedsLayout(); } if (RenderBlock::hasPercentHeightContainerMap() && firstChild() && oldHorizontalWritingMode != isHorizontalWritingMode()) RenderBlock::clearPercentHeightDescendantsFrom(this); if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom() && layer()) { if (int left = layer()->scrollableArea()->scrollXOffset()) { left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom(); layer()->scrollableArea()->scrollToXOffset(left); } if (int top = layer()->scrollableArea()->scrollYOffset()) { top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom(); layer()->scrollableArea()->scrollToYOffset(top); } } if (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer) { RenderObject* parentToInvalidate = parent(); for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) { parentToInvalidate->invalidateBackgroundObscurationStatus(); parentToInvalidate = parentToInvalidate->parent(); } } if (isDocumentElement() || isBody()) document().view()->recalculateScrollbarOverlayStyle(); updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle); updateGridPositionAfterStyleChange(oldStyle); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int xts_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst, struct scatterlist *src, unsigned int nbytes) { struct camellia_xts_ctx *ctx = crypto_blkcipher_ctx(desc->tfm); return glue_xts_crypt_128bit(&camellia_enc_xts, desc, dst, src, nbytes, XTS_TWEAK_CAST(camellia_enc_blk), &ctx->tweak_ctx, &ctx->crypt_ctx); } 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: SPL_METHOD(SplObjectStorage, detach) { zval *obj; spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "o", &obj) == FAILURE) { return; } spl_object_storage_detach(intern, getThis(), obj TSRMLS_CC); zend_hash_internal_pointer_reset_ex(&intern->storage, &intern->pos); intern->index = 0; } /* }}} */ /* {{{ proto string SplObjectStorage::getHash($object) 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: make_size_image(png_store* PNG_CONST ps, png_byte PNG_CONST colour_type, png_byte PNG_CONST bit_depth, int PNG_CONST interlace_type, png_uint_32 PNG_CONST w, png_uint_32 PNG_CONST h, int PNG_CONST do_interlace) { context(ps, fault); /* At present libpng does not support the write of an interlaced image unless * PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the code here * does the pixel interlace itself, so: */ check_interlace_type(interlace_type); Try { png_infop pi; png_structp pp; unsigned int pixel_size; /* Make a name and get an appropriate id for the store: */ char name[FILE_NAME_SIZE]; PNG_CONST png_uint_32 id = FILEID(colour_type, bit_depth, 0/*palette*/, interlace_type, w, h, do_interlace); standard_name_from_id(name, sizeof name, 0, id); pp = set_store_for_write(ps, &pi, name); /* In the event of a problem return control to the Catch statement below * to do the clean up - it is not possible to 'return' directly from a Try * block. */ if (pp == NULL) Throw ps; png_set_IHDR(pp, pi, w, h, bit_depth, colour_type, interlace_type, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); #ifdef PNG_TEXT_SUPPORTED { static char key[] = "image name"; /* must be writeable */ size_t pos; png_text text; char copy[FILE_NAME_SIZE]; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; /* Yuck: the text must be writable! */ pos = safecat(copy, sizeof copy, 0, ps->wname); text.text = copy; text.text_length = pos; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif if (colour_type == 3) /* palette */ init_standard_palette(ps, pp, pi, 1U << bit_depth, 0/*do tRNS*/); png_write_info(pp, pi); /* Calculate the bit size, divide by 8 to get the byte size - this won't * overflow because we know the w values are all small enough even for * a system where 'unsigned int' is only 16 bits. */ pixel_size = bit_size(pp, colour_type, bit_depth); if (png_get_rowbytes(pp, pi) != ((w * pixel_size) + 7) / 8) png_error(pp, "row size incorrect"); else { int npasses = npasses_from_interlace_type(pp, interlace_type); png_uint_32 y; int pass; # ifdef PNG_WRITE_FILTER_SUPPORTED int nfilter = PNG_FILTER_VALUE_LAST; # endif png_byte image[16][SIZE_ROWMAX]; /* To help consistent error detection make the parts of this buffer * that aren't set below all '1': */ memset(image, 0xff, sizeof image); if (!do_interlace && npasses != png_set_interlace_handling(pp)) png_error(pp, "write: png_set_interlace_handling failed"); /* Prepare the whole image first to avoid making it 7 times: */ for (y=0; y<h; ++y) size_row(image[y], w * pixel_size, y); for (pass=0; pass<npasses; ++pass) { /* The following two are for checking the macros: */ PNG_CONST png_uint_32 wPass = PNG_PASS_COLS(w, pass); /* If do_interlace is set we don't call png_write_row for every * row because some of them are empty. In fact, for a 1x1 image, * most of them are empty! */ for (y=0; y<h; ++y) { png_const_bytep row = image[y]; png_byte tempRow[SIZE_ROWMAX]; /* If do_interlace *and* the image is interlaced we * need a reduced interlace row; this may be reduced * to empty. */ if (do_interlace && interlace_type == PNG_INTERLACE_ADAM7) { /* The row must not be written if it doesn't exist, notice * that there are two conditions here, either the row isn't * ever in the pass or the row would be but isn't wide * enough to contribute any pixels. In fact the wPass test * can be used to skip the whole y loop in this case. */ if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && wPass > 0) { /* Set to all 1's for error detection (libpng tends to * set unset things to 0). */ memset(tempRow, 0xff, sizeof tempRow); interlace_row(tempRow, row, pixel_size, w, pass); row = tempRow; } else continue; } # ifdef PNG_WRITE_FILTER_SUPPORTED /* Only get to here if the row has some pixels in it, set the * filters to 'all' for the very first row and thereafter to a * single filter. It isn't well documented, but png_set_filter * does accept a filter number (per the spec) as well as a bit * mask. * * The apparent wackiness of decrementing nfilter rather than * incrementing is so that Paeth gets used in all images bigger * than 1 row - it's the tricky one. */ png_set_filter(pp, 0/*method*/, nfilter >= PNG_FILTER_VALUE_LAST ? PNG_ALL_FILTERS : nfilter); if (nfilter-- == 0) nfilter = PNG_FILTER_VALUE_LAST-1; # endif png_write_row(pp, row); } } } #ifdef PNG_TEXT_SUPPORTED { static char key[] = "end marker"; static char comment[] = "end"; png_text text; /* Use a compressed text string to test the correct interaction of text * compression and IDAT compression. */ text.compression = TEXT_COMPRESSION; text.key = key; text.text = comment; text.text_length = (sizeof comment)-1; text.itxt_length = 0; text.lang = 0; text.lang_key = 0; png_set_text(pp, pi, &text, 1); } #endif png_write_end(pp, pi); /* And store this under the appropriate id, then clean up. */ store_storefile(ps, id); store_write_reset(ps); } Catch(fault) { /* Use the png_store returned by the exception. This may help the compiler * because 'ps' is not used in this branch of the setjmp. Note that fault * and ps will always be the same value. */ store_write_reset(fault); } } CWE ID: Target: 1 Example 2: Code: void DocumentLoader::mainReceivedError(const ResourceError& error) { ASSERT(!error.isNull()); if (m_applicationCacheHost->maybeLoadFallbackForMainError(request(), error)) return; if (m_identifierForLoadWithoutResourceLoader) { ASSERT(!mainResourceLoader()); frameLoader()->client()->dispatchDidFailLoading(this, m_identifierForLoadWithoutResourceLoader, error); } #if !USE(CF) ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading()); #endif m_applicationCacheHost->failedLoadingMainResource(); if (!frameLoader()) return; setMainDocumentError(error); clearMainResourceLoader(); frameLoader()->receivedMainResourceError(error); } 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: check_file_permissions(i_ctx_t *i_ctx_p, const char *fname, int len, gx_io_device *iodev, const char *permitgroup) { char fname_reduced[gp_file_name_sizeof]; uint rlen = sizeof(fname_reduced); if (gp_file_name_reduce(fname, len, fname_reduced, &rlen) != gp_combine_success) return gs_error_invalidaccess; /* fail if we couldn't reduce */ return check_file_permissions_reduced(i_ctx_p, fname_reduced, rlen, iodev, permitgroup); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int snd_compress_check_input(struct snd_compr_params *params) { /* first let's check the buffer parameter's */ if (params->buffer.fragment_size == 0 || params->buffer.fragments > SIZE_MAX / params->buffer.fragment_size) return -EINVAL; /* now codec parameters */ if (params->codec.id == 0 || params->codec.id > SND_AUDIOCODEC_MAX) return -EINVAL; if (params->codec.ch_in == 0 || params->codec.ch_out == 0) return -EINVAL; return 0; } CWE ID: Target: 1 Example 2: Code: ecryptfs_write_metadata_to_xattr(struct dentry *ecryptfs_dentry, char *page_virt, size_t size) { int rc; rc = ecryptfs_setxattr(ecryptfs_dentry, ECRYPTFS_XATTR_NAME, page_virt, size, 0); return rc; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void StreamingProcessor::releaseRecordingFrame(const sp<IMemory>& mem) { ATRACE_CALL(); status_t res; Mutex::Autolock m(mMutex); ssize_t offset; size_t size; sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); if (heap->getHeapID() != mRecordingHeap->mHeap->getHeapID()) { ALOGW("%s: Camera %d: Mismatched heap ID, ignoring release " "(got %x, expected %x)", __FUNCTION__, mId, heap->getHeapID(), mRecordingHeap->mHeap->getHeapID()); return; } VideoNativeMetadata *payload = reinterpret_cast<VideoNativeMetadata*>( (uint8_t*)heap->getBase() + offset); if (payload->eType != kMetadataBufferTypeANWBuffer) { ALOGE("%s: Camera %d: Recording frame type invalid (got %x, expected %x)", __FUNCTION__, mId, payload->eType, kMetadataBufferTypeANWBuffer); return; } size_t itemIndex; for (itemIndex = 0; itemIndex < mRecordingBuffers.size(); itemIndex++) { const BufferItem item = mRecordingBuffers[itemIndex]; if (item.mBuf != BufferItemConsumer::INVALID_BUFFER_SLOT && item.mGraphicBuffer->getNativeBuffer() == payload->pBuffer) { break; } } if (itemIndex == mRecordingBuffers.size()) { ALOGE("%s: Camera %d: Can't find returned ANW Buffer %p in list of " "outstanding buffers", __FUNCTION__, mId, payload->pBuffer); return; } ALOGVV("%s: Camera %d: Freeing returned ANW buffer %p index %d", __FUNCTION__, mId, payload->pBuffer, itemIndex); res = mRecordingConsumer->releaseBuffer(mRecordingBuffers[itemIndex]); if (res != OK) { ALOGE("%s: Camera %d: Unable to free recording frame " "(Returned ANW buffer: %p): %s (%d)", __FUNCTION__, mId, payload->pBuffer, strerror(-res), res); return; } mRecordingBuffers.replaceAt(itemIndex); mRecordingHeapFree++; ALOGV_IF(mRecordingHeapFree == mRecordingHeapCount, "%s: Camera %d: All %d recording buffers returned", __FUNCTION__, mId, mRecordingHeapCount); } 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 void* lookupOpenGLFunctionAddress(const char* functionName, bool* success = 0) { if (success && !*success) return 0; void* target = getProcAddress(functionName); if (target) return target; String fullFunctionName(functionName); fullFunctionName.append("ARB"); target = getProcAddress(fullFunctionName.utf8().data()); if (target) return target; fullFunctionName = functionName; fullFunctionName.append("EXT"); target = getProcAddress(fullFunctionName.utf8().data()); #if defined(GL_ES_VERSION_2_0) fullFunctionName = functionName; fullFunctionName.append("ANGLE"); target = getProcAddress(fullFunctionName.utf8().data()); fullFunctionName = functionName; fullFunctionName.append("APPLE"); target = getProcAddress(fullFunctionName.utf8().data()); #endif if (!target && success) *success = false; return target; } CWE ID: Target: 1 Example 2: Code: tracing_cpumask_write(struct file *filp, const char __user *ubuf, size_t count, loff_t *ppos) { struct trace_array *tr = file_inode(filp)->i_private; cpumask_var_t tracing_cpumask_new; int err, cpu; if (!alloc_cpumask_var(&tracing_cpumask_new, GFP_KERNEL)) return -ENOMEM; err = cpumask_parse_user(ubuf, count, tracing_cpumask_new); if (err) goto err_unlock; local_irq_disable(); arch_spin_lock(&tr->max_lock); for_each_tracing_cpu(cpu) { /* * Increase/decrease the disabled counter if we are * about to flip a bit in the cpumask: */ if (cpumask_test_cpu(cpu, tr->tracing_cpumask) && !cpumask_test_cpu(cpu, tracing_cpumask_new)) { atomic_inc(&per_cpu_ptr(tr->trace_buffer.data, cpu)->disabled); ring_buffer_record_disable_cpu(tr->trace_buffer.buffer, cpu); } if (!cpumask_test_cpu(cpu, tr->tracing_cpumask) && cpumask_test_cpu(cpu, tracing_cpumask_new)) { atomic_dec(&per_cpu_ptr(tr->trace_buffer.data, cpu)->disabled); ring_buffer_record_enable_cpu(tr->trace_buffer.buffer, cpu); } } arch_spin_unlock(&tr->max_lock); local_irq_enable(); cpumask_copy(tr->tracing_cpumask, tracing_cpumask_new); free_cpumask_var(tracing_cpumask_new); return count; err_unlock: free_cpumask_var(tracing_cpumask_new); return err; } 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 UnwrapAndVerifyMojoHandle(mojo::ScopedSharedBufferHandle buffer_handle, size_t expected_size, bool expected_read_only_flag) { base::SharedMemoryHandle memory_handle; size_t memory_size = 0; bool read_only_flag = false; const MojoResult result = mojo::UnwrapSharedMemoryHandle(std::move(buffer_handle), &memory_handle, &memory_size, &read_only_flag); EXPECT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(expected_size, memory_size); EXPECT_EQ(expected_read_only_flag, read_only_flag); } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void perf_callchain_user_64(struct perf_callchain_entry *entry, struct pt_regs *regs) { unsigned long sp, next_sp; unsigned long next_ip; unsigned long lr; long level = 0; struct signal_frame_64 __user *sigframe; unsigned long __user *fp, *uregs; next_ip = perf_instruction_pointer(regs); lr = regs->link; sp = regs->gpr[1]; perf_callchain_store(entry, next_ip); for (;;) { fp = (unsigned long __user *) sp; if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp)) return; if (level > 0 && read_user_stack_64(&fp[2], &next_ip)) return; /* * Note: the next_sp - sp >= signal frame size check * is true when next_sp < sp, which can happen when * transitioning from an alternate signal stack to the * normal stack. */ if (next_sp - sp >= sizeof(struct signal_frame_64) && (is_sigreturn_64_address(next_ip, sp) || (level <= 1 && is_sigreturn_64_address(lr, sp))) && sane_signal_64_frame(sp)) { /* * This looks like an signal frame */ sigframe = (struct signal_frame_64 __user *) sp; uregs = sigframe->uc.uc_mcontext.gp_regs; if (read_user_stack_64(&uregs[PT_NIP], &next_ip) || read_user_stack_64(&uregs[PT_LNK], &lr) || read_user_stack_64(&uregs[PT_R1], &sp)) return; level = 0; perf_callchain_store(entry, PERF_CONTEXT_USER); perf_callchain_store(entry, next_ip); continue; } if (level == 0) next_ip = lr; perf_callchain_store(entry, next_ip); ++level; sp = next_sp; } } CWE ID: CWE-399 Target: 1 Example 2: Code: int pseudo_get_sec_session_info( char const *starter_reconnect_session_info, MyString &reconnect_session_id, MyString &reconnect_session_info, MyString &reconnect_session_key, char const *starter_filetrans_session_info, MyString &filetrans_session_id, MyString &filetrans_session_info, MyString &filetrans_session_key) { RemoteResource *remote; if (parallelMasterResource == NULL) { remote = thisRemoteResource; } else { remote = parallelMasterResource; } bool rc = remote->getSecSessionInfo( starter_reconnect_session_info, reconnect_session_id, reconnect_session_info, reconnect_session_key, starter_filetrans_session_info, filetrans_session_id, filetrans_session_info, filetrans_session_key); if( !rc ) { return -1; } return 1; } CWE ID: CWE-134 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void local_socket_close_locked(asocket* s) { D("entered local_socket_close_locked. LS(%d) fd=%d", s->id, s->fd); if (s->peer) { D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd); /* Note: it's important to call shutdown before disconnecting from * the peer, this ensures that remote sockets can still get the id * of the local socket they're connected to, to send a CLOSE() * protocol event. */ if (s->peer->shutdown) { s->peer->shutdown(s->peer); } s->peer->peer = 0; if (s->peer->close == local_socket_close) { local_socket_close_locked(s->peer); } else { s->peer->close(s->peer); } s->peer = 0; } /* If we are already closing, or if there are no ** pending packets, destroy immediately */ if (s->closing || s->has_write_error || s->pkt_first == NULL) { int id = s->id; local_socket_destroy(s); D("LS(%d): closed", id); return; } /* otherwise, put on the closing list */ D("LS(%d): closing", s->id); s->closing = 1; fdevent_del(&s->fde, FDE_READ); remove_socket(s); D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd); insert_local_socket(s, &local_socket_closing_list); CHECK_EQ(FDE_WRITE, s->fde.state & FDE_WRITE); } 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: int create_user_ns(struct cred *new) { struct user_namespace *ns, *parent_ns = new->user_ns; kuid_t owner = new->euid; kgid_t group = new->egid; int ret; /* The creator needs a mapping in the parent user namespace * or else we won't be able to reasonably tell userspace who * created a user_namespace. */ if (!kuid_has_mapping(parent_ns, owner) || !kgid_has_mapping(parent_ns, group)) return -EPERM; ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL); if (!ns) return -ENOMEM; ret = proc_alloc_inum(&ns->proc_inum); if (ret) { kmem_cache_free(user_ns_cachep, ns); return ret; } atomic_set(&ns->count, 1); /* Leave the new->user_ns reference with the new user namespace. */ ns->parent = parent_ns; ns->owner = owner; ns->group = group; set_cred_user_ns(new, ns); return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: void FrameView::removeSlowRepaintObject() { ASSERT(m_slowRepaintObjectCount > 0); m_slowRepaintObjectCount--; if (!m_slowRepaintObjectCount) { if (Page* page = m_frame->page()) { if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator()) scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this); } } } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void v9fs_device_unrealize_common(V9fsState *s, Error **errp) { g_free(s->ctx.fs_root); g_free(s->tag); } 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 TIFF_MetaHandler::ProcessXMP() { this->processedXMP = true; // Make sure we only come through here once. bool found; bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0); if ( readOnly ) { this->psirMgr = new PSIR_MemoryReader(); this->iptcMgr = new IPTC_Reader(); } else { this->psirMgr = new PSIR_FileWriter(); this->iptcMgr = new IPTC_Writer(); // ! Parse it later. } TIFF_Manager & tiff = this->tiffMgr; // Give the compiler help in recognizing non-aliases. PSIR_Manager & psir = *this->psirMgr; IPTC_Manager & iptc = *this->iptcMgr; TIFF_Manager::TagInfo psirInfo; bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo ); if ( havePSIR ) { // ! Do the Photoshop 6 integration before other legacy analysis. psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen ); PSIR_Manager::ImgRsrcInfo buriedExif; found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif ); if ( found ) { tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen ); if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif ); } } TIFF_Manager::TagInfo iptcInfo; bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); // The TIFF IPTC tag. int iptcDigestState = kDigestMatches; if ( haveIPTC ) { bool haveDigest = false; PSIR_Manager::ImgRsrcInfo digestInfo; if ( havePSIR ) haveDigest = psir.GetImgRsrc ( kPSIR_IPTCDigest, &digestInfo ); if ( digestInfo.dataLen != 16 ) haveDigest = false; if ( ! haveDigest ) { iptcDigestState = kDigestMissing; } else { iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, iptcInfo.dataLen, digestInfo.dataPtr ); if ( (iptcDigestState == kDigestDiffers) && (kTIFF_TypeSizes[iptcInfo.type] > 1) ) { XMP_Uns8 * endPtr = (XMP_Uns8*)iptcInfo.dataPtr + iptcInfo.dataLen - 1; XMP_Uns8 * minPtr = endPtr - kTIFF_TypeSizes[iptcInfo.type] + 1; while ( (endPtr >= minPtr) && (*endPtr == 0) ) --endPtr; iptcDigestState = PhotoDataUtils::CheckIPTCDigest ( iptcInfo.dataPtr, unpaddedLen, digestInfo.dataPtr ); } } } XMP_OptionBits options = k2XMP_FileHadExif; // TIFF files are presumed to have Exif legacy. if ( haveIPTC ) options |= k2XMP_FileHadIPTC; if ( this->containsXMP ) options |= k2XMP_FileHadXMP; bool haveXMP = false; if ( ! this->xmpPacket.empty() ) { XMP_Assert ( this->containsXMP ); XMP_StringPtr packetStr = this->xmpPacket.c_str(); XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size(); try { this->xmpObj.ParseFromBuffer ( packetStr, packetLen ); } catch ( ... ) { /* Ignore parsing failures, someday we hope to get partial XMP back. */ } haveXMP = true; } if ( haveIPTC && (! haveXMP) && (iptcDigestState == kDigestMatches) ) iptcDigestState = kDigestMissing; bool parseIPTC = (iptcDigestState != kDigestMatches) || (! readOnly); if ( parseIPTC ) iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); ImportPhotoData ( tiff, iptc, psir, iptcDigestState, &this->xmpObj, options ); this->containsXMP = true; // Assume we now have something in the XMP. } // TIFF_MetaHandler::ProcessXMP CWE ID: CWE-125 Target: 1 Example 2: Code: static inline struct task_group *css_tg(struct cgroup_subsys_state *css) { return css ? container_of(css, struct task_group, css) : 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: connection_ap_handshake_process_socks(entry_connection_t *conn) { socks_request_t *socks; int sockshere; const or_options_t *options = get_options(); int had_reply = 0; connection_t *base_conn = ENTRY_TO_CONN(conn); tor_assert(conn); tor_assert(base_conn->type == CONN_TYPE_AP); tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT); tor_assert(conn->socks_request); socks = conn->socks_request; log_debug(LD_APP,"entered."); sockshere = fetch_from_buf_socks(base_conn->inbuf, socks, options->TestSocks, options->SafeSocks); if (socks->replylen) { had_reply = 1; connection_write_to_buf((const char*)socks->reply, socks->replylen, base_conn); socks->replylen = 0; if (sockshere == -1) { /* An invalid request just got a reply, no additional * one is necessary. */ socks->has_finished = 1; } } if (sockshere == 0) { log_debug(LD_APP,"socks handshake not all here yet."); return 0; } else if (sockshere == -1) { if (!had_reply) { log_warn(LD_APP,"Fetching socks handshake failed. Closing."); connection_ap_handshake_socks_reply(conn, NULL, 0, END_STREAM_REASON_SOCKSPROTOCOL); } connection_mark_unattached_ap(conn, END_STREAM_REASON_SOCKSPROTOCOL | END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED); return -1; } /* else socks handshake is done, continue processing */ if (SOCKS_COMMAND_IS_CONNECT(socks->command)) control_event_stream_status(conn, STREAM_EVENT_NEW, 0); else control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0); return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL); } 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: WORD32 ih264d_create(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { ih264d_create_op_t *ps_create_op; WORD32 ret; ps_create_op = (ih264d_create_op_t *)pv_api_op; ps_create_op->s_ivd_create_op_t.u4_error_code = 0; ret = ih264d_allocate_static_bufs(&dec_hdl, pv_api_ip, pv_api_op); /* If allocation of some buffer fails, then free buffers allocated till then */ if((IV_FAIL == ret) && (NULL != dec_hdl)) { ih264d_free_static_bufs(dec_hdl); ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED; ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR; return IV_FAIL; } return IV_SUCCESS; } CWE ID: CWE-770 Target: 1 Example 2: Code: void OxideQQuickWebView::setCanTemporarilyRunInsecureContent(bool allow) { Q_D(OxideQQuickWebView); if (!d->proxy_) { return; } d->proxy_->setCanTemporarilyRunInsecureContent(allow); } 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: const base::Optional<gfx::Size>& RenderFrameHostImpl::GetFrameSize() { return frame_size_; } CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int bmdma_prepare_buf(IDEDMA *dma, int is_write) { BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma); IDEState *s = bmdma_active_if(bm); uint32_t size; } prd; CWE ID: CWE-399 Target: 1 Example 2: Code: format_UNROLL_XLATE(const struct ofpact_unroll_xlate *a, struct ds *s) { ds_put_format(s, "%sunroll_xlate(%s%stable=%s%"PRIu8 ", %scookie=%s%"PRIu64"%s)%s", colors.paren, colors.end, colors.special, colors.end, a->rule_table_id, colors.param, colors.end, ntohll(a->rule_cookie), colors.paren, colors.end); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int vfs_open(const struct path *path, struct file *file, const struct cred *cred) { struct dentry *dentry = path->dentry; struct inode *inode = dentry->d_inode; file->f_path = *path; if (dentry->d_flags & DCACHE_OP_SELECT_INODE) { inode = dentry->d_op->d_select_inode(dentry, file->f_flags); if (IS_ERR(inode)) return PTR_ERR(inode); } return do_dentry_open(file, inode, NULL, cred); } CWE ID: CWE-284 Target: 1 Example 2: Code: vmnc_handle_hextile_rectangle (GstVMncDec * dec, struct RfbRectangle *rect, const guint8 * data, int len, gboolean decode) { int tilesx = GST_ROUND_UP_16 (rect->width) / 16; int tilesy = GST_ROUND_UP_16 (rect->height) / 16; int x, y, z; int off = 0; int subrects; int coloured; int width, height; guint32 fg = 0, bg = 0, colour; guint8 flags; for (y = 0; y < tilesy; y++) { if (y == tilesy - 1) height = rect->height - (tilesy - 1) * 16; else height = 16; for (x = 0; x < tilesx; x++) { if (x == tilesx - 1) width = rect->width - (tilesx - 1) * 16; else width = 16; if (off >= len) { return ERROR_INSUFFICIENT_DATA; } flags = data[off++]; if (flags & 0x1) { if (off + width * height * dec->format.bytes_per_pixel > len) { return ERROR_INSUFFICIENT_DATA; } if (decode) render_raw_tile (dec, data + off, rect->x + x * 16, rect->y + y * 16, width, height); off += width * height * dec->format.bytes_per_pixel; } else { if (flags & 0x2) { READ_PIXEL (bg, data, off, len) } if (flags & 0x4) { READ_PIXEL (fg, data, off, len) } subrects = 0; if (flags & 0x8) { if (off >= len) { return ERROR_INSUFFICIENT_DATA; } subrects = data[off++]; } /* Paint background colour on entire tile */ if (decode) render_subrect (dec, rect->x + x * 16, rect->y + y * 16, width, height, bg); coloured = flags & 0x10; for (z = 0; z < subrects; z++) { if (coloured) { READ_PIXEL (colour, data, off, len); } else colour = fg; if (off + 2 > len) return ERROR_INSUFFICIENT_DATA; { int off_x = (data[off] & 0xf0) >> 4; int off_y = (data[off] & 0x0f); int w = ((data[off + 1] & 0xf0) >> 4) + 1; int h = (data[off + 1] & 0x0f) + 1; off += 2; /* Ensure we don't have out of bounds coordinates */ if (off_x + w > width || off_y + h > height) { GST_WARNING_OBJECT (dec, "Subrect out of bounds: %d-%d x %d-%d " "extends outside %dx%d", off_x, w, off_y, h, width, height); return ERROR_INVALID; } if (decode) render_subrect (dec, rect->x + x * 16 + off_x, rect->y + y * 16 + off_y, w, h, colour); } } } } } return off; } 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: GDataEntry* GDataFile::FromDocumentEntry( GDataDirectory* parent, DocumentEntry* doc, GDataDirectoryService* directory_service) { DCHECK(doc->is_hosted_document() || doc->is_file()); GDataFile* file = new GDataFile(parent, directory_service); file->title_ = UTF16ToUTF8(doc->title()); if (doc->is_file()) { file->file_info_.size = doc->file_size(); file->file_md5_ = doc->file_md5(); const Link* upload_link = doc->GetLinkByType(Link::RESUMABLE_EDIT_MEDIA); if (upload_link) file->upload_url_ = upload_link->href(); } else { file->document_extension_ = doc->GetHostedDocumentExtension(); file->file_info_.size = 0; } file->kind_ = doc->kind(); const Link* edit_link = doc->GetLinkByType(Link::EDIT); if (edit_link) file->edit_url_ = edit_link->href(); file->content_url_ = doc->content_url(); file->content_mime_type_ = doc->content_mime_type(); file->resource_id_ = doc->resource_id(); file->is_hosted_document_ = doc->is_hosted_document(); file->file_info_.last_modified = doc->updated_time(); file->file_info_.last_accessed = doc->updated_time(); file->file_info_.creation_time = doc->published_time(); file->deleted_ = doc->deleted(); const Link* parent_link = doc->GetLinkByType(Link::PARENT); if (parent_link) file->parent_resource_id_ = ExtractResourceId(parent_link->href()); file->SetBaseNameFromTitle(); const Link* thumbnail_link = doc->GetLinkByType(Link::THUMBNAIL); if (thumbnail_link) file->thumbnail_url_ = thumbnail_link->href(); const Link* alternate_link = doc->GetLinkByType(Link::ALTERNATE); if (alternate_link) file->alternate_url_ = alternate_link->href(); return file; } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void UrlFetcherDownloader::OnNetworkFetcherComplete(base::FilePath file_path, int net_error, int64_t content_size) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); const base::TimeTicks download_end_time(base::TimeTicks::Now()); const base::TimeDelta download_time = download_end_time >= download_start_time_ ? download_end_time - download_start_time_ : base::TimeDelta(); int error = -1; if (!file_path.empty() && response_code_ == 200) { DCHECK_EQ(0, net_error); error = 0; } else if (response_code_ != -1) { error = response_code_; } else { error = net_error; } const bool is_handled = error == 0 || IsHttpServerError(error); Result result; result.error = error; if (!error) { result.response = file_path; } DownloadMetrics download_metrics; download_metrics.url = url(); download_metrics.downloader = DownloadMetrics::kUrlFetcher; download_metrics.error = error; download_metrics.downloaded_bytes = error ? -1 : content_size; download_metrics.total_bytes = total_bytes_; download_metrics.download_time_ms = download_time.InMilliseconds(); VLOG(1) << "Downloaded " << content_size << " bytes in " << download_time.InMilliseconds() << "ms from " << url().spec() << " to " << result.response.value(); if (error && !download_dir_.empty()) { base::PostTask(FROM_HERE, kTaskTraits, base::BindOnce(IgnoreResult(&base::DeleteFileRecursively), download_dir_)); } main_task_runner()->PostTask( FROM_HERE, base::BindOnce(&UrlFetcherDownloader::OnDownloadComplete, base::Unretained(this), is_handled, result, download_metrics)); } CWE ID: CWE-20 Target: 1 Example 2: Code: opj_image_t* tgatoimage(const char *filename, opj_cparameters_t *parameters) { FILE *f; opj_image_t *image; unsigned int image_width, image_height, pixel_bit_depth; unsigned int x, y; int flip_image = 0; opj_image_cmptparm_t cmptparm[4]; /* maximum 4 components */ int numcomps; OPJ_COLOR_SPACE color_space; OPJ_BOOL mono ; OPJ_BOOL save_alpha; int subsampling_dx, subsampling_dy; int i; f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Failed to open %s for reading !!\n", filename); return 0; } if (!tga_readheader(f, &pixel_bit_depth, &image_width, &image_height, &flip_image)) { fclose(f); return NULL; } /* We currently only support 24 & 32 bit tga's ... */ if (!((pixel_bit_depth == 24) || (pixel_bit_depth == 32))) { fclose(f); return NULL; } /* initialize image components */ memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t)); mono = (pixel_bit_depth == 8) || (pixel_bit_depth == 16); /* Mono with & without alpha. */ save_alpha = (pixel_bit_depth == 16) || (pixel_bit_depth == 32); /* Mono with alpha, or RGB with alpha */ if (mono) { color_space = OPJ_CLRSPC_GRAY; numcomps = save_alpha ? 2 : 1; } else { numcomps = save_alpha ? 4 : 3; color_space = OPJ_CLRSPC_SRGB; } /* If the declared file size is > 10 MB, check that the file is big */ /* enough to avoid excessive memory allocations */ if (image_height != 0 && image_width > 10000000U / image_height / (OPJ_UINT32)numcomps) { char ch; OPJ_UINT64 expected_file_size = (OPJ_UINT64)image_width * image_height * (OPJ_UINT32)numcomps; long curpos = ftell(f); if (expected_file_size > (OPJ_UINT64)INT_MAX) { expected_file_size = (OPJ_UINT64)INT_MAX; } fseek(f, (long)expected_file_size - 1, SEEK_SET); if (fread(&ch, 1, 1, f) != 1) { fclose(f); return NULL; } fseek(f, curpos, SEEK_SET); } subsampling_dx = parameters->subsampling_dx; subsampling_dy = parameters->subsampling_dy; for (i = 0; i < numcomps; i++) { cmptparm[i].prec = 8; cmptparm[i].bpp = 8; cmptparm[i].sgnd = 0; cmptparm[i].dx = (OPJ_UINT32)subsampling_dx; cmptparm[i].dy = (OPJ_UINT32)subsampling_dy; cmptparm[i].w = image_width; cmptparm[i].h = image_height; } /* create the image */ image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm[0], color_space); if (!image) { fclose(f); return NULL; } /* set image offset and reference grid */ image->x0 = (OPJ_UINT32)parameters->image_offset_x0; image->y0 = (OPJ_UINT32)parameters->image_offset_y0; image->x1 = !image->x0 ? (OPJ_UINT32)(image_width - 1) * (OPJ_UINT32)subsampling_dx + 1 : image->x0 + (OPJ_UINT32)(image_width - 1) * (OPJ_UINT32)subsampling_dx + 1; image->y1 = !image->y0 ? (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1 : image->y0 + (OPJ_UINT32)(image_height - 1) * (OPJ_UINT32)subsampling_dy + 1; /* set image data */ for (y = 0; y < image_height; y++) { int index; if (flip_image) { index = (int)((image_height - y - 1) * image_width); } else { index = (int)(y * image_width); } if (numcomps == 3) { for (x = 0; x < image_width; x++) { unsigned char r, g, b; if (!fread(&b, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&g, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&r, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } image->comps[0].data[index] = r; image->comps[1].data[index] = g; image->comps[2].data[index] = b; index++; } } else if (numcomps == 4) { for (x = 0; x < image_width; x++) { unsigned char r, g, b, a; if (!fread(&b, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&g, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&r, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } if (!fread(&a, 1, 1, f)) { fprintf(stderr, "\nError: fread return a number of element different from the expected.\n"); opj_image_destroy(image); fclose(f); return NULL; } image->comps[0].data[index] = r; image->comps[1].data[index] = g; image->comps[2].data[index] = b; image->comps[3].data[index] = a; index++; } } else { fprintf(stderr, "Currently unsupported bit depth : %s\n", filename); } } fclose(f); return image; } 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 HTMLSelectElement::remove(HTMLOptionElement* option) { if (option->ownerSelectElement() != this) return; option->remove(IGNORE_EXCEPTION); } 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: image_transform_png_set_scale_16_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(colour_type) this->next = *that; *that = this; return bit_depth > 8; } CWE ID: Target: 1 Example 2: Code: static int megasas_dcmd_cfg_read(MegasasState *s, MegasasCmd *cmd) { uint8_t data[4096] = { 0 }; struct mfi_config_data *info; int num_pd_disks = 0, array_offset, ld_offset; BusChild *kid; if (cmd->iov_size > 4096) { return MFI_STAT_INVALID_PARAMETER; } QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { num_pd_disks++; } info = (struct mfi_config_data *)&data; /* * Array mapping: * - One array per SCSI device * - One logical drive per SCSI device * spanning the entire device */ info->array_count = num_pd_disks; info->array_size = sizeof(struct mfi_array) * num_pd_disks; info->log_drv_count = num_pd_disks; info->log_drv_size = sizeof(struct mfi_ld_config) * num_pd_disks; info->spares_count = 0; info->spares_size = sizeof(struct mfi_spare); info->size = sizeof(struct mfi_config_data) + info->array_size + info->log_drv_size; if (info->size > 4096) { return MFI_STAT_INVALID_PARAMETER; } array_offset = sizeof(struct mfi_config_data); ld_offset = array_offset + sizeof(struct mfi_array) * num_pd_disks; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = SCSI_DEVICE(kid->child); uint16_t sdev_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); struct mfi_array *array; struct mfi_ld_config *ld; uint64_t pd_size; int i; array = (struct mfi_array *)(data + array_offset); blk_get_geometry(sdev->conf.blk, &pd_size); array->size = cpu_to_le64(pd_size); array->num_drives = 1; array->array_ref = cpu_to_le16(sdev_id); array->pd[0].ref.v.device_id = cpu_to_le16(sdev_id); array->pd[0].ref.v.seq_num = 0; array->pd[0].fw_state = MFI_PD_STATE_ONLINE; array->pd[0].encl.pd = 0xFF; array->pd[0].encl.slot = (sdev->id & 0xFF); for (i = 1; i < MFI_MAX_ROW_SIZE; i++) { array->pd[i].ref.v.device_id = 0xFFFF; array->pd[i].ref.v.seq_num = 0; array->pd[i].fw_state = MFI_PD_STATE_UNCONFIGURED_GOOD; array->pd[i].encl.pd = 0xFF; array->pd[i].encl.slot = 0xFF; } array_offset += sizeof(struct mfi_array); ld = (struct mfi_ld_config *)(data + ld_offset); memset(ld, 0, sizeof(struct mfi_ld_config)); ld->properties.ld.v.target_id = sdev->id; ld->properties.default_cache_policy = MR_LD_CACHE_READ_AHEAD | MR_LD_CACHE_READ_ADAPTIVE; ld->properties.current_cache_policy = MR_LD_CACHE_READ_AHEAD | MR_LD_CACHE_READ_ADAPTIVE; ld->params.state = MFI_LD_STATE_OPTIMAL; ld->params.stripe_size = 3; ld->params.num_drives = 1; ld->params.span_depth = 1; ld->params.is_consistent = 1; ld->span[0].start_block = 0; ld->span[0].num_blocks = cpu_to_le64(pd_size); ld->span[0].array_ref = cpu_to_le16(sdev_id); ld_offset += sizeof(struct mfi_ld_config); } cmd->iov_size -= dma_buf_read((uint8_t *)data, info->size, &cmd->qsg); return MFI_STAT_OK; } 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: R_API ut64 r_bin_java_bootstrap_methods_attr_calc_size(RBinJavaAttrInfo *attr) { RListIter *iter, *iter_tmp; RBinJavaBootStrapMethod *bsm = NULL; ut64 size = 0; if (attr) { size += 6; size += 2; r_list_foreach_safe (attr->info.bootstrap_methods_attr.bootstrap_methods, iter, iter_tmp, bsm) { if (bsm) { size += r_bin_java_bootstrap_method_calc_size (bsm); } else { } } } return size; } 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: entry_guard_obeys_restriction(const entry_guard_t *guard, const entry_guard_restriction_t *rst) { tor_assert(guard); if (! rst) return 1; // No restriction? No problem. return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN); } CWE ID: CWE-200 Target: 1 Example 2: Code: static int gup_pud_range(p4d_t p4d, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { unsigned long next; pud_t *pudp; pudp = pud_offset(&p4d, addr); do { pud_t pud = READ_ONCE(*pudp); next = pud_addr_end(addr, end); if (pud_none(pud)) return 0; if (unlikely(pud_huge(pud))) { if (!gup_huge_pud(pud, pudp, addr, next, write, pages, nr)) return 0; } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) { if (!gup_huge_pd(__hugepd(pud_val(pud)), addr, PUD_SHIFT, next, write, pages, nr)) return 0; } else if (!gup_pmd_range(pud, addr, next, write, pages, nr)) return 0; } while (pudp++, addr = next, addr != end); return 1; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int null_hash_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { 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: static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, void *hba_private) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); SCSIRequest *req; SCSIDiskReq *r; req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private); r = DO_UPCAST(SCSIDiskReq, req, req); r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE); return req; } CWE ID: CWE-119 Target: 1 Example 2: Code: rio_timer (unsigned long data) { struct net_device *dev = (struct net_device *)data; struct netdev_private *np = netdev_priv(dev); unsigned int entry; int next_tick = 1*HZ; unsigned long flags; spin_lock_irqsave(&np->rx_lock, flags); /* Recover rx ring exhausted error */ if (np->cur_rx - np->old_rx >= RX_RING_SIZE) { printk(KERN_INFO "Try to recover rx ring exhausted...\n"); /* Re-allocate skbuffs to fill the descriptor ring */ for (; np->cur_rx - np->old_rx > 0; np->old_rx++) { struct sk_buff *skb; entry = np->old_rx % RX_RING_SIZE; /* Dropped packets don't need to re-allocate */ if (np->rx_skbuff[entry] == NULL) { skb = netdev_alloc_skb_ip_align(dev, np->rx_buf_sz); if (skb == NULL) { np->rx_ring[entry].fraginfo = 0; printk (KERN_INFO "%s: Still unable to re-allocate Rx skbuff.#%d\n", dev->name, entry); break; } np->rx_skbuff[entry] = skb; np->rx_ring[entry].fraginfo = cpu_to_le64 (pci_map_single (np->pdev, skb->data, np->rx_buf_sz, PCI_DMA_FROMDEVICE)); } np->rx_ring[entry].fraginfo |= cpu_to_le64((u64)np->rx_buf_sz << 48); np->rx_ring[entry].status = 0; } /* end for */ } /* end if */ spin_unlock_irqrestore (&np->rx_lock, flags); np->timer.expires = jiffies + next_tick; add_timer(&np->timer); } 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 region16_union_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { const RECTANGLE_16* srcExtents; RECTANGLE_16* dstExtents; const RECTANGLE_16* currentBand, *endSrcRect, *nextBand; REGION16_DATA* newItems = NULL; RECTANGLE_16* dstRect = NULL; UINT32 usedRects, srcNbRects; UINT16 topInterBand; assert(src); assert(src->data); assert(dst); srcExtents = region16_extents(src); dstExtents = region16_extents_noconst(dst); if (!region16_n_rects(src)) { /* source is empty, so the union is rect */ dst->extents = *rect; dst->data = allocateRegion(1); if (!dst->data) return FALSE; dstRect = region16_rects_noconst(dst); dstRect->top = rect->top; dstRect->left = rect->left; dstRect->right = rect->right; dstRect->bottom = rect->bottom; return TRUE; } newItems = allocateRegion((1 + region16_n_rects(src)) * 4); if (!newItems) return FALSE; dstRect = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; /* adds the piece of rect that is on the top of src */ if (rect->top < srcExtents->top) { dstRect->top = rect->top; dstRect->left = rect->left; dstRect->right = rect->right; dstRect->bottom = MIN(srcExtents->top, rect->bottom); usedRects++; dstRect++; } /* treat possibly overlapping region */ currentBand = region16_rects(src, &srcNbRects); endSrcRect = currentBand + srcNbRects; while (currentBand < endSrcRect) { if ((currentBand->bottom <= rect->top) || (rect->bottom <= currentBand->top) || rectangle_contained_in_band(currentBand, endSrcRect, rect)) { /* no overlap between rect and the band, rect is totally below or totally above * the current band, or rect is already covered by an item of the band. * let's copy all the rectangles from this band +----+ | | rect (case 1) +----+ ================= band of srcRect ================= +----+ | | rect (case 2) +----+ */ region16_copy_band_with_union(dstRect, currentBand, endSrcRect, currentBand->top, currentBand->bottom, NULL, &usedRects, &nextBand, &dstRect); topInterBand = rect->top; } else { /* rect overlaps the band: | | | | ====^=================| |==| |=========================== band | top split | | | | v | 1 | | 2 | ^ | | | | +----+ +----+ | merge zone | | | | | | | 4 | v +----+ | | | | +----+ ^ | | | 3 | | bottom split | | | | ====v=========================| |==| |=================== | | | | possible cases: 1) no top split, merge zone then a bottom split. The band will be splitted in two 2) not band split, only the merge zone, band merged with rect but not splitted 3) a top split, the merge zone and no bottom split. The band will be split in two 4) a top split, the merge zone and also a bottom split. The band will be splitted in 3, but the coalesce algorithm may merge the created bands */ UINT16 mergeTop = currentBand->top; UINT16 mergeBottom = currentBand->bottom; /* test if we need a top split, case 3 and 4 */ if (rect->top > currentBand->top) { region16_copy_band_with_union(dstRect, currentBand, endSrcRect, currentBand->top, rect->top, NULL, &usedRects, &nextBand, &dstRect); mergeTop = rect->top; } /* do the merge zone (all cases) */ if (rect->bottom < currentBand->bottom) mergeBottom = rect->bottom; region16_copy_band_with_union(dstRect, currentBand, endSrcRect, mergeTop, mergeBottom, rect, &usedRects, &nextBand, &dstRect); /* test if we need a bottom split, case 1 and 4 */ if (rect->bottom < currentBand->bottom) { region16_copy_band_with_union(dstRect, currentBand, endSrcRect, mergeBottom, currentBand->bottom, NULL, &usedRects, &nextBand, &dstRect); } topInterBand = currentBand->bottom; } /* test if a piece of rect should be inserted as a new band between * the current band and the next one. band n and n+1 shouldn't touch. * * ============================================================== * band n * +------+ +------+ * ===========| rect |====================| |=============== * | | +------+ | | * +------+ | rect | | rect | * +------+ | | * =======================================| |================ * +------+ band n+1 * =============================================================== * */ if ((nextBand < endSrcRect) && (nextBand->top != currentBand->bottom) && (rect->bottom > currentBand->bottom) && (rect->top < nextBand->top)) { dstRect->right = rect->right; dstRect->left = rect->left; dstRect->top = topInterBand; dstRect->bottom = MIN(nextBand->top, rect->bottom); dstRect++; usedRects++; } currentBand = nextBand; } /* adds the piece of rect that is below src */ if (srcExtents->bottom < rect->bottom) { dstRect->top = MAX(srcExtents->bottom, rect->top); dstRect->left = rect->left; dstRect->right = rect->right; dstRect->bottom = rect->bottom; usedRects++; dstRect++; } if ((src == dst) && (src->data->size > 0) && (src->data != &empty_region)) free(src->data); dstExtents->top = MIN(rect->top, srcExtents->top); dstExtents->left = MIN(rect->left, srcExtents->left); dstExtents->bottom = MAX(rect->bottom, srcExtents->bottom); dstExtents->right = MAX(rect->right, srcExtents->right); newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); dst->data = realloc(newItems, newItems->size); if (!dst->data) { free(newItems); return FALSE; } dst->data->nbRects = usedRects; return region16_simplify_bands(dst); } CWE ID: CWE-772 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: image_transform_png_set_expand_16_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_expand_16(pp); this->next->set(this->next, that, pp, pi); } CWE ID: Target: 1 Example 2: Code: ssize_t iov_iter_get_pages_alloc(struct iov_iter *i, struct page ***pages, size_t maxsize, size_t *start) { struct page **p; if (maxsize > i->count) maxsize = i->count; if (unlikely(i->type & ITER_PIPE)) return pipe_get_pages_alloc(i, pages, maxsize, start); iterate_all_kinds(i, maxsize, v, ({ unsigned long addr = (unsigned long)v.iov_base; size_t len = v.iov_len + (*start = addr & (PAGE_SIZE - 1)); int n; int res; addr &= ~(PAGE_SIZE - 1); n = DIV_ROUND_UP(len, PAGE_SIZE); p = get_pages_array(n); if (!p) return -ENOMEM; res = get_user_pages_fast(addr, n, (i->type & WRITE) != WRITE, p); if (unlikely(res < 0)) { kvfree(p); return res; } *pages = p; return (res == n ? len : res * PAGE_SIZE) - *start; 0;}),({ /* can't be more than PAGE_SIZE */ *start = v.bv_offset; *pages = p = get_pages_array(1); if (!p) return -ENOMEM; get_page(*p = v.bv_page); return v.bv_len; }),({ return -EFAULT; }) ) return 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 show_state_filter(unsigned long state_filter) { struct task_struct *g, *p; #if BITS_PER_LONG == 32 printk(KERN_INFO " task PC stack pid father\n"); #else printk(KERN_INFO " task PC stack pid father\n"); #endif read_lock(&tasklist_lock); do_each_thread(g, p) { /* * reset the NMI-timeout, listing all files on a slow * console might take a lot of time: */ touch_nmi_watchdog(); if (!state_filter || (p->state & state_filter)) sched_show_task(p); } while_each_thread(g, p); touch_all_softlockup_watchdogs(); #ifdef CONFIG_SCHED_DEBUG sysrq_sched_debug_show(); #endif read_unlock(&tasklist_lock); /* * Only show locks if all tasks are dumped: */ if (!state_filter) debug_show_all_locks(); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int rpc_type_of_NPPVariable(int variable) { int type; switch (variable) { case NPPVpluginNameString: case NPPVpluginDescriptionString: case NPPVformValue: // byte values of 0 does not appear in the UTF-8 encoding but for U+0000 type = RPC_TYPE_STRING; break; case NPPVpluginWindowSize: case NPPVpluginTimerInterval: type = RPC_TYPE_INT32; break; case NPPVpluginNeedsXEmbed: case NPPVpluginWindowBool: case NPPVpluginTransparentBool: case NPPVjavascriptPushCallerBool: case NPPVpluginKeepLibraryInMemory: type = RPC_TYPE_BOOLEAN; break; case NPPVpluginScriptableNPObject: type = RPC_TYPE_NP_OBJECT; break; default: type = RPC_ERROR_GENERIC; break; } return type; } CWE ID: CWE-264 Target: 1 Example 2: Code: static u64 mmu_spte_get_lockless(u64 *sptep) { return __get_spte_lockless(sptep); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data) { usb_conv_info_t *usb_conv_info; usb_ms_conv_info_t *usb_ms_conv_info; proto_tree *tree; proto_item *ti; guint32 signature=0; int offset=0; gboolean is_request; itl_nexus_t *itl; itlq_nexus_t *itlq; /* Reject the packet if data is NULL */ if (data == NULL) return 0; usb_conv_info = (usb_conv_info_t *)data; /* verify that we do have a usb_ms_conv_info */ usb_ms_conv_info=(usb_ms_conv_info_t *)usb_conv_info->class_data; if(!usb_ms_conv_info){ usb_ms_conv_info=wmem_new(wmem_file_scope(), usb_ms_conv_info_t); usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope()); usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope()); usb_conv_info->class_data=usb_ms_conv_info; } is_request=(pinfo->srcport==NO_ENDPOINT); col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS"); col_clear(pinfo->cinfo, COL_INFO); ti = proto_tree_add_protocol_format(parent_tree, proto_usb_ms, tvb, 0, -1, "USB Mass Storage"); tree = proto_item_add_subtree(ti, ett_usb_ms); signature=tvb_get_letohl(tvb, offset); /* * SCSI CDB inside CBW */ if(is_request&&(signature==0x43425355)&&(tvb_reported_length(tvb)==31)){ tvbuff_t *cdb_tvb; int cdbrlen, cdblen; guint8 lun, flags; guint32 datalen; /* dCBWSignature */ proto_tree_add_item(tree, hf_usb_ms_dCBWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCBWTag */ proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCBWDataTransferLength */ proto_tree_add_item(tree, hf_usb_ms_dCBWDataTransferLength, tvb, offset, 4, ENC_LITTLE_ENDIAN); datalen=tvb_get_letohl(tvb, offset); offset+=4; /* dCBWFlags */ proto_tree_add_item(tree, hf_usb_ms_dCBWFlags, tvb, offset, 1, ENC_LITTLE_ENDIAN); flags=tvb_get_guint8(tvb, offset); offset+=1; /* dCBWLUN */ proto_tree_add_item(tree, hf_usb_ms_dCBWTarget, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(tree, hf_usb_ms_dCBWLUN, tvb, offset, 1, ENC_LITTLE_ENDIAN); lun=tvb_get_guint8(tvb, offset)&0x0f; offset+=1; /* make sure we have a ITL structure for this LUN */ itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, lun); if(!itl){ itl=wmem_new(wmem_file_scope(), itl_nexus_t); itl->cmdset=0xff; itl->conversation=NULL; wmem_tree_insert32(usb_ms_conv_info->itl, lun, itl); } /* make sure we have an ITLQ structure for this LUN/transaction */ itlq=(itlq_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ itlq=wmem_new(wmem_file_scope(), itlq_nexus_t); itlq->lun=lun; itlq->scsi_opcode=0xffff; itlq->task_flags=0; if(datalen){ if(flags&0x80){ itlq->task_flags|=SCSI_DATA_READ; } else { itlq->task_flags|=SCSI_DATA_WRITE; } } itlq->data_length=datalen; itlq->bidir_data_length=0; itlq->fc_time=pinfo->abs_ts; itlq->first_exchange_frame=pinfo->num; itlq->last_exchange_frame=0; itlq->flags=0; itlq->alloc_len=0; itlq->extra_data=NULL; wmem_tree_insert32(usb_ms_conv_info->itlq, pinfo->num, itlq); } /* dCBWCBLength */ proto_tree_add_item(tree, hf_usb_ms_dCBWCBLength, tvb, offset, 1, ENC_LITTLE_ENDIAN); cdbrlen=tvb_get_guint8(tvb, offset)&0x1f; offset+=1; cdblen=cdbrlen; if(cdblen>tvb_captured_length_remaining(tvb, offset)){ cdblen=tvb_captured_length_remaining(tvb, offset); } if(cdblen){ cdb_tvb=tvb_new_subset(tvb, offset, cdblen, cdbrlen); dissect_scsi_cdb(cdb_tvb, pinfo, parent_tree, SCSI_DEV_UNKNOWN, itlq, itl); } return tvb_captured_length(tvb); } /* * SCSI RESPONSE inside CSW */ if((!is_request)&&(signature==0x53425355)&&(tvb_reported_length(tvb)==13)){ guint8 status; /* dCSWSignature */ proto_tree_add_item(tree, hf_usb_ms_dCSWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWTag */ proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWDataResidue */ proto_tree_add_item(tree, hf_usb_ms_dCSWDataResidue, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset+=4; /* dCSWStatus */ proto_tree_add_item(tree, hf_usb_ms_dCSWStatus, tvb, offset, 1, ENC_LITTLE_ENDIAN); status=tvb_get_guint8(tvb, offset); /*offset+=1;*/ itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ return tvb_captured_length(tvb); } itlq->last_exchange_frame=pinfo->num; itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun); if(!itl){ return tvb_captured_length(tvb); } if(!status){ dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0); } else { /* just send "check condition" */ dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0x02); } return tvb_captured_length(tvb); } /* * Ok it was neither CDB not STATUS so just assume it is either data in/out */ itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num); if(!itlq){ return tvb_captured_length(tvb); } itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun); if(!itl){ return tvb_captured_length(tvb); } dissect_scsi_payload(tvb, pinfo, parent_tree, is_request, itlq, itl, 0); return tvb_captured_length(tvb); } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Chapters::Display::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) // ChapterString ID { status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) // ChapterLanguage ID { status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) // ChapterCountry ID { status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderFrameHostImpl::ExecuteJavaScriptForTests( const base::string16& javascript) { Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_, javascript, 0, false, false)); } 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 RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg, X509_ALGOR **pmaskHash) { const unsigned char *p; int plen; RSA_PSS_PARAMS *pss; *pmaskHash = NULL; if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE) return NULL; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen); if (!pss) return NULL; *pmaskHash = rsa_mgf1_decode(pss->maskGenAlgorithm); return pss; } 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: IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) { int i; int ret = 0; DefragInit(); /* * Build the packets. */ int id = 1; Packet *packets[17]; memset(packets, 0x00, sizeof(packets)); /* * Original fragments. */ /* A*24 at 0. */ packets[0] = IPV6BuildTestPacket(id, 0, 1, 'A', 24); /* B*15 at 32. */ packets[1] = IPV6BuildTestPacket(id, 32 >> 3, 1, 'B', 16); /* C*24 at 48. */ packets[2] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'C', 24); /* D*8 at 80. */ packets[3] = IPV6BuildTestPacket(id, 80 >> 3, 1, 'D', 8); /* E*16 at 104. */ packets[4] = IPV6BuildTestPacket(id, 104 >> 3, 1, 'E', 16); /* F*24 at 120. */ packets[5] = IPV6BuildTestPacket(id, 120 >> 3, 1, 'F', 24); /* G*16 at 144. */ packets[6] = IPV6BuildTestPacket(id, 144 >> 3, 1, 'G', 16); /* H*16 at 160. */ packets[7] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'H', 16); /* I*8 at 176. */ packets[8] = IPV6BuildTestPacket(id, 176 >> 3, 1, 'I', 8); /* * Overlapping subsequent fragments. */ /* J*32 at 8. */ packets[9] = IPV6BuildTestPacket(id, 8 >> 3, 1, 'J', 32); /* K*24 at 48. */ packets[10] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'K', 24); /* L*24 at 72. */ packets[11] = IPV6BuildTestPacket(id, 72 >> 3, 1, 'L', 24); /* M*24 at 96. */ packets[12] = IPV6BuildTestPacket(id, 96 >> 3, 1, 'M', 24); /* N*8 at 128. */ packets[13] = IPV6BuildTestPacket(id, 128 >> 3, 1, 'N', 8); /* O*8 at 152. */ packets[14] = IPV6BuildTestPacket(id, 152 >> 3, 1, 'O', 8); /* P*8 at 160. */ packets[15] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'P', 8); /* Q*16 at 176. */ packets[16] = IPV6BuildTestPacket(id, 176 >> 3, 0, 'Q', 16); default_policy = policy; /* Send all but the last. */ for (i = 0; i < 9; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { goto end; } } int overlap = 0; for (; i < 16; i++) { Packet *tp = Defrag(NULL, NULL, packets[i], NULL); if (tp != NULL) { SCFree(tp); goto end; } if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { overlap++; } } if (!overlap) goto end; /* And now the last one. */ Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL); if (reassembled == NULL) goto end; if (memcmp(GET_PKT_DATA(reassembled) + 40, expected, expected_len) != 0) goto end; if (IPV6_GET_PLEN(reassembled) != 192) goto end; SCFree(reassembled); /* Make sure all frags were returned to the pool. */ if (defrag_context->frag_pool->outstanding != 0) { printf("defrag_context->frag_pool->outstanding %u: ", defrag_context->frag_pool->outstanding); goto end; } ret = 1; end: for (i = 0; i < 17; i++) { SCFree(packets[i]); } DefragDestroy(); return ret; } CWE ID: CWE-358 Target: 1 Example 2: Code: static void __balance_callback(struct rq *rq) { struct callback_head *head, *next; void (*func)(struct rq *rq); unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); head = rq->balance_callback; rq->balance_callback = NULL; while (head) { func = (void (*)(struct rq *))head->func; next = head->next; head->next = NULL; head = next; func(rq); } raw_spin_unlock_irqrestore(&rq->lock, flags); } 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 HTMLSelectElement::accessKeySetSelectedIndex(int index) { if (!focused()) accessKeyAction(false); const Vector<HTMLElement*>& items = listItems(); int listIndex = optionToListIndex(index); if (listIndex >= 0) { HTMLElement* element = items[listIndex]; if (element->hasTagName(optionTag)) { if (toHTMLOptionElement(element)->selected()) toHTMLOptionElement(element)->setSelectedState(false); else selectOption(index, DispatchChangeEvent | UserDriven); } } if (usesMenuList()) dispatchChangeEventForMenuList(); else listBoxOnChange(); scrollToSelection(); } 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: TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc, uint32_t flags, uaddr_t uaddr, size_t len) { uaddr_t a; size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE, CORE_MMU_USER_PARAM_SIZE); if (ADD_OVERFLOW(uaddr, len, &a)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (flags & TEE_MEMORY_ACCESS_SECURE)) return TEE_ERROR_ACCESS_DENIED; /* * Rely on TA private memory test to check if address range is private * to TA or not. */ if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) && !tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len)) return TEE_ERROR_ACCESS_DENIED; for (a = uaddr; a < (uaddr + len); a += addr_incr) { uint32_t attr; TEE_Result res; res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr); if (res != TEE_SUCCESS) return res; if ((flags & TEE_MEMORY_ACCESS_NONSECURE) && (attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_SECURE) && !(attr & TEE_MATTR_SECURE)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW)) return TEE_ERROR_ACCESS_DENIED; if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR)) return TEE_ERROR_ACCESS_DENIED; } return TEE_SUCCESS; } CWE ID: CWE-20 Target: 1 Example 2: Code: static int tty_tiocgicount(struct tty_struct *tty, void __user *arg) { int retval = -EINVAL; struct serial_icounter_struct icount; memset(&icount, 0, sizeof(icount)); if (tty->ops->get_icount) retval = tty->ops->get_icount(tty, &icount); if (retval != 0) return retval; if (copy_to_user(arg, &icount, sizeof(icount))) return -EFAULT; return 0; } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int RenderBox::scrollWidth() const { if (hasOverflowClip()) return layer()->scrollWidth(); if (style()->isLeftToRightDirection()) return max(clientWidth(), maxXLayoutOverflow() - borderLeft()); return clientWidth() - min(0, minXLayoutOverflow() - borderLeft()); } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { if (!render_frame_created_) return false; ScopedActiveURL scoped_active_url(this); bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; if (delegate_->OnMessageReceived(this, msg)) return true; RenderFrameProxyHost* proxy = frame_tree_node_->render_manager()->GetProxyToParent(); if (proxy && proxy->cross_process_frame_connector() && proxy->cross_process_frame_connector()->OnMessageReceived(msg)) return true; handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole, OnDidAddMessageToConsole) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse, OnVisualStateResponse) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog, OnRunJavaScriptDialog) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies, OnDidAddContentSecurityPolicies) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy, OnDidChangeFramePolicy) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties, OnDidChangeFrameOwnerProperties) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust) IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent, OnForwardResourceTimingToParent) IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse, OnTextSurroundingSelectionResponse) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult, OnAccessibilityFindInPageResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult, OnAccessibilityChildFrameHitTestResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse, OnAccessibilitySnapshotResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged, OnSuddenTerminationDisablerChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress, OnDidChangeLoadProgress) IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState, OnUpdateUserActivationState) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation, OnSetHasReceivedUserGestureBeforeNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking, OnSetNeedsOcclusionTracking); IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame, OnScrollRectToVisibleInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame, OnBubbleLogicalScrollInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess, OnRenderFallbackContentInParentProcess) #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) #endif IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken, OnRequestOverlayRoutingToken) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow) IPC_END_MESSAGE_MAP() return handled; } CWE ID: CWE-416 Target: 1 Example 2: Code: ScopedPixelUnpackState::~ScopedPixelUnpackState() { state_->RestoreUnpackState(); } 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 kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, struct list_head *invalid_list) { return __kvm_sync_page(vcpu, sp, invalid_list, 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: ServiceWorkerContainer* NavigatorServiceWorker::serviceWorker(Navigator& navigator, ExceptionState& exceptionState) { return NavigatorServiceWorker::from(navigator).serviceWorker(exceptionState); } CWE ID: CWE-264 Target: 1 Example 2: Code: wait_for_refresh(int offset, const char *prefix, int msec) { int lpc = msec / 1000; struct timespec sleept = { 1, 0 }; if (as_console == FALSE) { timer_id = g_timeout_add(msec, mon_timer_popped, NULL); return; } crm_notice("%sRefresh in %ds...", prefix ? prefix : "", lpc); while (lpc > 0) { #if CURSES_ENABLED move(offset, 0); /* printw("%sRefresh in \033[01;32m%ds\033[00m...", prefix?prefix:"", lpc); */ printw("%sRefresh in %ds...\n", prefix ? prefix : "", lpc); clrtoeol(); refresh(); #endif lpc--; if (lpc == 0) { timer_id = g_timeout_add(1000, mon_timer_popped, NULL); } else { if (nanosleep(&sleept, NULL) != 0) { return; } } } } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void flush_tlb_page(struct vm_area_struct *vma, unsigned long start) { struct mm_struct *mm = vma->vm_mm; preempt_disable(); if (current->active_mm == mm) { if (current->mm) __flush_tlb_one(start); else leave_mm(smp_processor_id()); } if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids) flush_tlb_others(mm_cpumask(mm), mm, start, 0UL); preempt_enable(); } 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: juniper_ggsn_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ggsn_header { uint8_t svc_id; uint8_t flags_len; uint8_t proto; uint8_t flags; uint8_t vlan_id[2]; uint8_t res[2]; }; const struct juniper_ggsn_header *gh; l2info.pictype = DLT_JUNIPER_GGSN; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; gh = (struct juniper_ggsn_header *)&l2info.cookie; if (ndo->ndo_eflag) { ND_PRINT((ndo, "proto %s (%u), vlan %u: ", tok2str(juniper_protocol_values,"Unknown",gh->proto), gh->proto, EXTRACT_16BITS(&gh->vlan_id[0]))); } switch (gh->proto) { case JUNIPER_PROTO_IPV4: ip_print(ndo, p, l2info.length); break; case JUNIPER_PROTO_IPV6: ip6_print(ndo, p, l2info.length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto)); } return l2info.header_len; } CWE ID: CWE-125 Target: 1 Example 2: Code: abort_sasl(struct Client *data) { if(data->localClient->sasl_out == 0 || data->localClient->sasl_complete) return; data->localClient->sasl_out = data->localClient->sasl_complete = 0; ServerStats.is_sbad++; if(!IsClosing(data)) sendto_one(data, form_str(ERR_SASLABORTED), me.name, EmptyString(data->name) ? "*" : data->name); if(*data->localClient->sasl_agent) { struct Client *agent_p = find_id(data->localClient->sasl_agent); if(agent_p) { sendto_one(agent_p, ":%s ENCAP %s SASL %s %s D A", me.id, agent_p->servptr->name, data->id, agent_p->id); return; } } sendto_server(NULL, NULL, CAP_TS6|CAP_ENCAP, NOCAPS, ":%s ENCAP * SASL %s * D A", me.id, data->id); } CWE ID: CWE-285 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: blink::WebFrameWidget* RenderViewImpl::GetWebFrameWidget() { return frame_widget_; } 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: png_zalloc(voidpf png_ptr, uInt items, uInt size) { png_voidp ptr; png_structp p=(png_structp)png_ptr; png_uint_32 save_flags=p->flags; png_uint_32 num_bytes; if (png_ptr == NULL) return (NULL); if (items > PNG_UINT_32_MAX/size) { png_warning (p, "Potential overflow in png_zalloc()"); return (NULL); } num_bytes = (png_uint_32)items * size; p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK; ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes); p->flags=save_flags; #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO) if (ptr == NULL) return ((voidpf)ptr); if (num_bytes > (png_uint_32)0x8000L) { png_memset(ptr, 0, (png_size_t)0x8000L); png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0, (png_size_t)(num_bytes - (png_uint_32)0x8000L)); } else { png_memset(ptr, 0, (png_size_t)num_bytes); } #endif return ((voidpf)ptr); } CWE ID: CWE-119 Target: 1 Example 2: Code: DOMDataStoreHandle::DOMDataStoreHandle(bool initialize) : m_store(adoptPtr(!initialize ? 0 : new ScopedDOMDataStore())) { if (m_store) V8PerIsolateData::current()->registerDOMDataStore(m_store.get()); } 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 copy_fields(const FieldMatchContext *fm, AVFrame *dst, const AVFrame *src, int field) { int plane; for (plane = 0; plane < 4 && src->data[plane]; plane++) av_image_copy_plane(dst->data[plane] + field*dst->linesize[plane], dst->linesize[plane] << 1, src->data[plane] + field*src->linesize[plane], src->linesize[plane] << 1, get_width(fm, src, plane), get_height(fm, src, plane) / 2); } 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: gss_init_sec_context (minor_status, claimant_cred_handle, context_handle, target_name, req_mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec) OM_uint32 * minor_status; gss_cred_id_t claimant_cred_handle; gss_ctx_id_t * context_handle; gss_name_t target_name; gss_OID req_mech_type; OM_uint32 req_flags; OM_uint32 time_req; gss_channel_bindings_t input_chan_bindings; gss_buffer_t input_token; gss_OID * actual_mech_type; gss_buffer_t output_token; OM_uint32 * ret_flags; OM_uint32 * time_rec; { OM_uint32 status, temp_minor_status; gss_union_name_t union_name; gss_union_cred_t union_cred; gss_name_t internal_name; gss_union_ctx_id_t union_ctx_id; gss_OID selected_mech; gss_mechanism mech; gss_cred_id_t input_cred_handle; status = val_init_sec_ctx_args(minor_status, claimant_cred_handle, context_handle, target_name, req_mech_type, req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (status != GSS_S_COMPLETE) return (status); status = gssint_select_mech_type(minor_status, req_mech_type, &selected_mech); if (status != GSS_S_COMPLETE) return (status); union_name = (gss_union_name_t)target_name; /* * obtain the gss mechanism information for the requested * mechanism. If mech_type is NULL, set it to the resultant * mechanism */ mech = gssint_get_mechanism(selected_mech); if (mech == NULL) return (GSS_S_BAD_MECH); if (mech->gss_init_sec_context == NULL) return (GSS_S_UNAVAILABLE); /* * If target_name is mechanism_specific, then it must match the * mech_type that we're about to use. Otherwise, do an import on * the external_name form of the target name. */ if (union_name->mech_type && g_OID_equal(union_name->mech_type, selected_mech)) { internal_name = union_name->mech_name; } else { if ((status = gssint_import_internal_name(minor_status, selected_mech, union_name, &internal_name)) != GSS_S_COMPLETE) return (status); } /* * if context_handle is GSS_C_NO_CONTEXT, allocate a union context * descriptor to hold the mech type information as well as the * underlying mechanism context handle. Otherwise, cast the * value of *context_handle to the union context variable. */ if(*context_handle == GSS_C_NO_CONTEXT) { status = GSS_S_FAILURE; union_ctx_id = (gss_union_ctx_id_t) malloc(sizeof(gss_union_ctx_id_desc)); if (union_ctx_id == NULL) goto end; if (generic_gss_copy_oid(&temp_minor_status, selected_mech, &union_ctx_id->mech_type) != GSS_S_COMPLETE) { free(union_ctx_id); goto end; } /* copy the supplied context handle */ union_ctx_id->internal_ctx_id = GSS_C_NO_CONTEXT; } else union_ctx_id = (gss_union_ctx_id_t)*context_handle; /* * get the appropriate cred handle from the union cred struct. * defaults to GSS_C_NO_CREDENTIAL if there is no cred, which will * use the default credential. */ union_cred = (gss_union_cred_t) claimant_cred_handle; input_cred_handle = gssint_get_mechanism_cred(union_cred, selected_mech); /* * now call the approprate underlying mechanism routine */ status = mech->gss_init_sec_context( minor_status, input_cred_handle, &union_ctx_id->internal_ctx_id, internal_name, gssint_get_public_oid(selected_mech), req_flags, time_req, input_chan_bindings, input_token, actual_mech_type, output_token, ret_flags, time_rec); if (status != GSS_S_COMPLETE && status != GSS_S_CONTINUE_NEEDED) { /* * The spec says the preferred method is to delete all context info on * the first call to init, and on all subsequent calls make the caller * responsible for calling gss_delete_sec_context. However, if the * mechanism decided to delete the internal context, we should also * delete the union context. */ map_error(minor_status, mech); if (union_ctx_id->internal_ctx_id == GSS_C_NO_CONTEXT) *context_handle = GSS_C_NO_CONTEXT; if (*context_handle == GSS_C_NO_CONTEXT) { free(union_ctx_id->mech_type->elements); free(union_ctx_id->mech_type); free(union_ctx_id); } } else if (*context_handle == GSS_C_NO_CONTEXT) { union_ctx_id->loopback = union_ctx_id; *context_handle = (gss_ctx_id_t)union_ctx_id; } end: if (union_name->mech_name == NULL || union_name->mech_name != internal_name) { (void) gssint_release_internal_name(&temp_minor_status, selected_mech, &internal_name); } return(status); } CWE ID: CWE-415 Target: 1 Example 2: Code: static __u32 hash( const char* name) { __u32 h = 0; __u32 g; while(*name) { h = (h<<4) + *name++; if ((g = (h & 0xf0000000))) h ^=g>>24; h &=~g; } return h; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void run(const char* source_path, const char* label, uid_t uid, gid_t gid, userid_t userid, bool multi_user, bool full_write) { struct fuse_global global; struct fuse fuse_default; struct fuse fuse_read; struct fuse fuse_write; struct fuse_handler handler_default; struct fuse_handler handler_read; struct fuse_handler handler_write; pthread_t thread_default; pthread_t thread_read; pthread_t thread_write; memset(&global, 0, sizeof(global)); memset(&fuse_default, 0, sizeof(fuse_default)); memset(&fuse_read, 0, sizeof(fuse_read)); memset(&fuse_write, 0, sizeof(fuse_write)); memset(&handler_default, 0, sizeof(handler_default)); memset(&handler_read, 0, sizeof(handler_read)); memset(&handler_write, 0, sizeof(handler_write)); pthread_mutex_init(&global.lock, NULL); global.package_to_appid = hashmapCreate(256, str_hash, str_icase_equals); global.uid = uid; global.gid = gid; global.multi_user = multi_user; global.next_generation = 0; global.inode_ctr = 1; memset(&global.root, 0, sizeof(global.root)); global.root.nid = FUSE_ROOT_ID; /* 1 */ global.root.refcount = 2; global.root.namelen = strlen(source_path); global.root.name = strdup(source_path); global.root.userid = userid; global.root.uid = AID_ROOT; global.root.under_android = false; strcpy(global.source_path, source_path); if (multi_user) { global.root.perm = PERM_PRE_ROOT; snprintf(global.obb_path, sizeof(global.obb_path), "%s/obb", source_path); } else { global.root.perm = PERM_ROOT; snprintf(global.obb_path, sizeof(global.obb_path), "%s/Android/obb", source_path); } fuse_default.global = &global; fuse_read.global = &global; fuse_write.global = &global; global.fuse_default = &fuse_default; global.fuse_read = &fuse_read; global.fuse_write = &fuse_write; snprintf(fuse_default.dest_path, PATH_MAX, "/mnt/runtime/default/%s", label); snprintf(fuse_read.dest_path, PATH_MAX, "/mnt/runtime/read/%s", label); snprintf(fuse_write.dest_path, PATH_MAX, "/mnt/runtime/write/%s", label); handler_default.fuse = &fuse_default; handler_read.fuse = &fuse_read; handler_write.fuse = &fuse_write; handler_default.token = 0; handler_read.token = 1; handler_write.token = 2; umask(0); if (multi_user) { /* Multi-user storage is fully isolated per user, so "other" * permissions are completely masked off. */ if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006) || fuse_setup(&fuse_read, AID_EVERYBODY, 0027) || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0027)) { ERROR("failed to fuse_setup\n"); exit(1); } } else { /* Physical storage is readable by all users on device, but * the Android directories are masked off to a single user * deep inside attr_from_stat(). */ if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006) || fuse_setup(&fuse_read, AID_EVERYBODY, full_write ? 0027 : 0022) || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0022)) { ERROR("failed to fuse_setup\n"); exit(1); } } /* Drop privs */ if (setgroups(sizeof(kGroups) / sizeof(kGroups[0]), kGroups) < 0) { ERROR("cannot setgroups: %s\n", strerror(errno)); exit(1); } if (setgid(gid) < 0) { ERROR("cannot setgid: %s\n", strerror(errno)); exit(1); } if (setuid(uid) < 0) { ERROR("cannot setuid: %s\n", strerror(errno)); exit(1); } if (multi_user) { fs_prepare_dir(global.obb_path, 0775, uid, gid); } if (pthread_create(&thread_default, NULL, start_handler, &handler_default) || pthread_create(&thread_read, NULL, start_handler, &handler_read) || pthread_create(&thread_write, NULL, start_handler, &handler_write)) { ERROR("failed to pthread_create\n"); exit(1); } watch_package_list(&global); ERROR("terminated prematurely\n"); exit(1); } 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: bool TextAutosizer::processSubtree(RenderObject* layoutRoot) { if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->printing() || !m_document->page()) return false; Frame* mainFrame = m_document->page()->mainFrame(); TextAutosizingWindowInfo windowInfo; windowInfo.windowSize = m_document->settings()->textAutosizingWindowSizeOverride(); if (windowInfo.windowSize.isEmpty()) { bool includeScrollbars = !InspectorInstrumentation::shouldApplyScreenWidthOverride(mainFrame); windowInfo.windowSize = mainFrame->view()->visibleContentRect(includeScrollbars).size(); // FIXME: Check that this is always in logical (density-independent) pixels (see wkbug.com/87440). } windowInfo.minLayoutSize = mainFrame->view()->layoutSize(); for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->parent()) { if (!frame->view()->isInChildFrameWithFrameFlattening()) windowInfo.minLayoutSize = windowInfo.minLayoutSize.shrunkTo(frame->view()->layoutSize()); } RenderBlock* container = layoutRoot->isRenderBlock() ? toRenderBlock(layoutRoot) : layoutRoot->containingBlock(); while (container && !isAutosizingContainer(container)) container = container->containingBlock(); RenderBlock* cluster = container; while (cluster && (!isAutosizingContainer(cluster) || !isAutosizingCluster(cluster))) cluster = cluster->containingBlock(); processCluster(cluster, container, layoutRoot, windowInfo); return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: PrintingContext::Result PrintingContextCairo::NewPage() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } 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 ResourceFetcher::StartLoad(Resource* resource) { DCHECK(resource); DCHECK(resource->StillNeedsLoad()); ResourceRequest request(resource->GetResourceRequest()); ResourceLoader* loader = nullptr; { Resource::RevalidationStartForbiddenScope revalidation_start_forbidden_scope(resource); ScriptForbiddenIfMainThreadScope script_forbidden_scope; if (!Context().ShouldLoadNewResource(resource->GetType()) && IsMainThread()) { GetMemoryCache()->Remove(resource); return false; } ResourceResponse response; blink::probe::PlatformSendRequest probe(&Context(), resource->Identifier(), request, response, resource->Options().initiator_info); Context().DispatchWillSendRequest(resource->Identifier(), request, response, resource->Options().initiator_info); SecurityOrigin* source_origin = Context().GetSecurityOrigin(); if (source_origin && source_origin->HasSuborigin()) request.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kNone); resource->SetResourceRequest(request); loader = ResourceLoader::Create(this, scheduler_, resource); if (resource->ShouldBlockLoadEvent()) loaders_.insert(loader); else non_blocking_loaders_.insert(loader); StorePerformanceTimingInitiatorInformation(resource); resource->SetFetcherSecurityOrigin(source_origin); Resource::ProhibitAddRemoveClientInScope prohibit_add_remove_client_in_scope(resource); resource->NotifyStartLoad(); } loader->Start(); return true; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ReadUserLogState::SetState( const ReadUserLog::FileState &state ) { const ReadUserLogFileState::FileState *istate; if ( !convertState(state, istate) ) { return false; } if ( strcmp( istate->m_signature, FileStateSignature ) ) { m_init_error = true; return false; } if ( istate->m_version != FILESTATE_VERSION ) { m_init_error = true; return false; } m_base_path = istate->m_base_path; m_max_rotations = istate->m_max_rotations; Rotation( istate->m_rotation, false, true ); m_log_type = istate->m_log_type; m_uniq_id = istate->m_uniq_id; m_sequence = istate->m_sequence; m_stat_buf.st_ino = istate->m_inode; m_stat_buf.st_ctime = istate->m_ctime; m_stat_buf.st_size = istate->m_size.asint; m_stat_valid = true; m_offset = istate->m_offset.asint; m_event_num = istate->m_event_num.asint; m_log_position = istate->m_log_position.asint; m_log_record = istate->m_log_record.asint; m_update_time = istate->m_update_time; m_initialized = true; MyString str; GetStateString( str, "Restored reader state" ); dprintf( D_FULLDEBUG, str.Value() ); return true; } CWE ID: CWE-134 Target: 1 Example 2: Code: int FS_LoadStack( void ) { return fs_loadStack; } CWE ID: CWE-269 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track) { uint8_t buf[7] = { 0 }; int ret; if ((ret = mov_write_dvc1_structs(track, buf)) < 0) return ret; avio_wb32(pb, track->vos_len + 8 + sizeof(buf)); ffio_wfourcc(pb, "dvc1"); avio_write(pb, buf, sizeof(buf)); avio_write(pb, track->vos_data, track->vos_len); return 0; } CWE ID: CWE-369 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: parse_cosine_rec_hdr(struct wtap_pkthdr *phdr, const char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec, pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return -1; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return -1; } yy = mm = dd = hr = min = sec = csec = 0; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error; return pkt_len; } CWE ID: CWE-119 Target: 1 Example 2: Code: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_BROWSER_CLOSED: delete this; return; default: NOTREACHED(); break; } } 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 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); bool masked; if (vmx->loaded_vmcs->nmi_known_unmasked) return false; masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI; vmx->loaded_vmcs->nmi_known_unmasked = !masked; return masked; } 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: DocumentInit& DocumentInit::WithPreviousDocumentCSP( const ContentSecurityPolicy* previous_csp) { DCHECK(!previous_csp_); previous_csp_ = previous_csp; return *this; } CWE ID: CWE-20 Target: 1 Example 2: Code: static void fill_tgid_exit(struct task_struct *tsk) { unsigned long flags; spin_lock_irqsave(&tsk->sighand->siglock, flags); if (!tsk->signal->stats) goto ret; /* * Each accounting subsystem calls its functions here to * accumalate its per-task stats for tsk, into the per-tgid structure * * per-task-foo(tsk->signal->stats, tsk); */ delayacct_add_tsk(tsk->signal->stats, tsk); ret: spin_unlock_irqrestore(&tsk->sighand->siglock, flags); return; } 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: State(WebContents* a_dst_contents, int a_dst_index, TabStripModelObserverAction a_action) : src_contents(NULL), dst_contents(a_dst_contents), src_index(-1), dst_index(a_dst_index), user_gesture(false), foreground(false), action(a_action) { } 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 cg_open(const char *path, struct fuse_file_info *fi) { const char *cgroup; char *fpath = NULL, *path1, *path2, * cgdir = NULL, *controller; struct cgfs_files *k = NULL; struct file_info *file_info; struct fuse_context *fc = fuse_get_context(); int ret; if (!fc) return -EIO; controller = pick_controller_from_path(fc, path); if (!controller) return -EIO; cgroup = find_cgroup_in_path(path); if (!cgroup) return -EINVAL; get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { path1 = "/"; path2 = cgdir; } else { path1 = cgdir; path2 = fpath; } k = cgfs_get_key(controller, path1, path2); if (!k) { ret = -EINVAL; goto out; } free_key(k); if (!fc_may_access(fc, controller, path1, path2, fi->flags)) { ret = -EACCES; goto out; } /* we'll free this at cg_release */ file_info = malloc(sizeof(*file_info)); if (!file_info) { ret = -ENOMEM; goto out; } file_info->controller = must_copy_string(controller); file_info->cgroup = must_copy_string(path1); file_info->file = must_copy_string(path2); file_info->type = LXC_TYPE_CGFILE; file_info->buf = NULL; file_info->buflen = 0; fi->fh = (unsigned long)file_info; ret = 0; out: free(cgdir); return ret; } CWE ID: CWE-264 Target: 1 Example 2: Code: GLuint GLES2Implementation::GetProgramResourceIndex( GLuint program, GLenum program_interface, const char* name) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glGetProgramResourceIndex(" << program << ", " << program_interface << ", " << name << ")"); TRACE_EVENT0("gpu", "GLES2::GetProgramResourceIndex"); GLuint index = share_group_->program_info_manager()->GetProgramResourceIndex( this, program, program_interface, name); GPU_CLIENT_LOG("returned " << index); CheckGLError(); return index; } 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 l2tp_ip6_recv(struct sk_buff *skb) { struct sock *sk; u32 session_id; u32 tunnel_id; unsigned char *ptr, *optr; struct l2tp_session *session; struct l2tp_tunnel *tunnel = NULL; int length; /* Point to L2TP header */ optr = ptr = skb->data; if (!pskb_may_pull(skb, 4)) goto discard; session_id = ntohl(*((__be32 *) ptr)); ptr += 4; /* RFC3931: L2TP/IP packets have the first 4 bytes containing * the session_id. If it is 0, the packet is a L2TP control * frame and the session_id value can be discarded. */ if (session_id == 0) { __skb_pull(skb, 4); goto pass_up; } /* Ok, this is a data packet. Lookup the session. */ session = l2tp_session_find(&init_net, NULL, session_id); if (session == NULL) goto discard; tunnel = session->tunnel; if (tunnel == NULL) goto discard; /* Trace packet contents, if enabled */ if (tunnel->debug & L2TP_MSG_DATA) { length = min(32u, skb->len); if (!pskb_may_pull(skb, length)) goto discard; pr_debug("%s: ip recv\n", tunnel->name); print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, ptr, length); } l2tp_recv_common(session, skb, ptr, optr, 0, skb->len, tunnel->recv_payload_hook); return 0; pass_up: /* Get the tunnel_id from the L2TP header */ if (!pskb_may_pull(skb, 12)) goto discard; if ((skb->data[0] & 0xc0) != 0xc0) goto discard; tunnel_id = ntohl(*(__be32 *) &skb->data[4]); tunnel = l2tp_tunnel_find(&init_net, tunnel_id); if (tunnel != NULL) sk = tunnel->sock; else { struct ipv6hdr *iph = ipv6_hdr(skb); read_lock_bh(&l2tp_ip6_lock); sk = __l2tp_ip6_bind_lookup(&init_net, &iph->daddr, 0, tunnel_id); read_unlock_bh(&l2tp_ip6_lock); } if (sk == NULL) goto discard; sock_hold(sk); if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_put; nf_reset(skb); return sk_receive_skb(sk, skb, 1); discard_put: sock_put(sk); discard: kfree_skb(skb); return 0; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32, unsigned int size_left, enum compat_mwt type, struct ebt_entries_buf_state *state, const void *base) { int growth = 0; char *buf; if (size_left == 0) return 0; buf = (char *) match32; while (size_left >= sizeof(*match32)) { struct ebt_entry_match *match_kern; int ret; match_kern = (struct ebt_entry_match *) state->buf_kern_start; if (match_kern) { char *tmp; tmp = state->buf_kern_start + state->buf_kern_offset; match_kern = (struct ebt_entry_match *) tmp; } ret = ebt_buf_add(state, buf, sizeof(*match32)); if (ret < 0) return ret; size_left -= sizeof(*match32); /* add padding before match->data (if any) */ ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize()); if (ret < 0) return ret; if (match32->match_size > size_left) return -EINVAL; size_left -= match32->match_size; ret = compat_mtw_from_user(match32, type, state, base); if (ret < 0) return ret; if (WARN_ON(ret < match32->match_size)) return -EINVAL; growth += ret - match32->match_size; growth += ebt_compat_entry_padsize(); buf += sizeof(*match32); buf += match32->match_size; if (match_kern) match_kern->match_size = ret; WARN_ON(type == EBT_COMPAT_TARGET && size_left); match32 = (struct compat_ebt_entry_mwt *) buf; } return growth; } CWE ID: CWE-787 Target: 1 Example 2: Code: void Gfx::opSetFillCMYKColor(Object args[], int numArgs) { GfxColor color; int i; if (textHaveCSPattern && drawText) { GBool needFill = out->deviceHasTextClip(state); out->endTextObject(state); if (needFill) { doPatternFill(gTrue); } out->restoreState(state); } state->setFillPattern(NULL); state->setFillColorSpace(new GfxDeviceCMYKColorSpace()); out->updateFillColorSpace(state); for (i = 0; i < 4; ++i) { color.c[i] = dblToCol(args[i].getNum()); } state->setFillColor(&color); out->updateFillColor(state); if (textHaveCSPattern) { out->beginTextObject(state); out->updateRender(state); out->updateTextMat(state); out->updateTextPos(state); textHaveCSPattern = gFalse; } } 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: GURL DevToolsWindow::GetDevToolsURL(Profile* profile, const GURL& base_url, bool shared_worker_frontend, bool v8_only_frontend, const std::string& remote_frontend, bool can_dock, const std::string& panel) { if (base_url.SchemeIs("data")) return base_url; std::string frontend_url( !remote_frontend.empty() ? remote_frontend : base_url.is_empty() ? chrome::kChromeUIDevToolsURL : base_url.spec()); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&")); if (shared_worker_frontend) url_string += "&isSharedWorker=true"; if (v8_only_frontend) url_string += "&v8only=true"; if (remote_frontend.size()) { url_string += "&remoteFrontend=true"; } else { url_string += "&remoteBase=" + DevToolsUI::GetRemoteBaseURL().spec(); } if (can_dock) url_string += "&can_dock=true"; if (panel.size()) url_string += "&panel=" + panel; return DevToolsUI::SanitizeFrontendURL(GURL(url_string)); } 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 Image *ReadNULLImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickPixelPacket background; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; ssize_t 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); image=AcquireImage(image_info); if (image->columns == 0) image->columns=1; if (image->rows == 0) image->rows=1; image->matte=MagickTrue; GetMagickPixelPacket(image,&background); background.opacity=(MagickRealType) TransparentOpacity; if (image->colorspace == CMYKColorspace) ConvertRGBToCMYK(&background); for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelPacket(image,&background,q,indexes); q++; indexes++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(GetFirstImageInList(image)); } CWE ID: CWE-119 Target: 1 Example 2: Code: virtual ~TestTarget() { } 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 dvb_usbv2_device_power_ctrl(struct dvb_usb_device *d, int onoff) { int ret; if (onoff) d->powered++; else d->powered--; if (d->powered == 0 || (onoff && d->powered == 1)) { /* when switching from 1 to 0 or from 0 to 1 */ dev_dbg(&d->udev->dev, "%s: power=%d\n", __func__, onoff); if (d->props->power_ctrl) { ret = d->props->power_ctrl(d, onoff); if (ret < 0) goto err; } } return 0; err: dev_dbg(&d->udev->dev, "%s: failed=%d\n", __func__, ret); return ret; } 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: OMX_ERRORTYPE SimpleSoftOMXComponent::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *defParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (defParams->nPortIndex >= mPorts.size() || defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) { return OMX_ErrorUndefined; } const PortInfo *port = &mPorts.itemAt(defParams->nPortIndex); memcpy(defParams, &port->mDef, sizeof(port->mDef)); return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } } CWE ID: CWE-119 Target: 1 Example 2: Code: static ssize_t aio_fdsync(struct kiocb *iocb) { struct file *file = iocb->ki_filp; ssize_t ret = -EINVAL; if (file->f_op->aio_fsync) ret = file->f_op->aio_fsync(iocb, 1); 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: static uint32_t vmsvga_index_read(void *opaque, uint32_t address) { struct vmsvga_state_s *s = opaque; return s->index; } 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: BOOL transport_connect_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->layer == TRANSPORT_LAYER_TSG) return TRUE; if (!transport_connect_tls(transport)) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { if (!connectErrorCode) connectErrorCode = AUTHENTICATIONERROR; fprintf(stderr, "Authentication failure, check credentials.\n" "If credentials are valid, the NTLMSSP implementation may be to blame.\n"); credssp_free(transport->credssp); return FALSE; } credssp_free(transport->credssp); return TRUE; } CWE ID: CWE-476 Target: 1 Example 2: Code: void big_key_describe(const struct key *key, struct seq_file *m) { unsigned long datalen = key->type_data.x[1]; seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, ": %lu [%s]", datalen, datalen > BIG_KEY_FILE_THRESHOLD ? "file" : "buff"); } 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 spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zval *arg1; zend_error_handling error_handling; if (!file_path || !file_path_len) { #if defined(PHP_WIN32) zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path"); if (file_path && !use_copy) { efree(file_path); } #else if (file_path && !use_copy) { efree(file_path); } file_path_len = 1; file_path = "/"; #endif return NULL; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); return intern; } /* }}} */ 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 Chapters::Edition::ExpandAtomsArray() { if (m_atoms_size > m_atoms_count) return true; // nothing else to do const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; Atom* const atoms = new (std::nothrow) Atom[size]; if (atoms == NULL) return false; for (int idx = 0; idx < m_atoms_count; ++idx) { m_atoms[idx].ShallowCopy(atoms[idx]); } delete[] m_atoms; m_atoms = atoms; m_atoms_size = size; return true; } CWE ID: CWE-119 Target: 1 Example 2: Code: void netdev_bonding_info_change(struct net_device *dev, struct netdev_bonding_info *bonding_info) { struct netdev_notifier_bonding_info info; memcpy(&info.bonding_info, bonding_info, sizeof(struct netdev_bonding_info)); call_netdevice_notifiers_info(NETDEV_BONDING_INFO, dev, &info.info); } 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: void RTCSessionDescriptionRequestImpl::requestSucceeded(PassRefPtr<RTCSessionDescriptionDescriptor> descriptor) { if (m_successCallback) { RefPtr<RTCSessionDescription> sessionDescription = RTCSessionDescription::create(descriptor); m_successCallback->handleEvent(sessionDescription.get()); } clear(); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: handle_ppp(netdissect_options *ndo, u_int proto, const u_char *p, int length) { if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */ ppp_hdlc(ndo, p - 1, length); return; } switch (proto) { case PPP_LCP: /* fall through */ case PPP_IPCP: case PPP_OSICP: case PPP_MPLSCP: case PPP_IPV6CP: case PPP_CCP: case PPP_BACP: handle_ctrl_proto(ndo, proto, p, length); break; case PPP_ML: handle_mlppp(ndo, p, length); break; case PPP_CHAP: handle_chap(ndo, p, length); break; case PPP_PAP: handle_pap(ndo, p, length); break; case PPP_BAP: /* XXX: not yet completed */ handle_bap(ndo, p, length); break; case ETHERTYPE_IP: /*XXX*/ case PPP_VJNC: case PPP_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: /*XXX*/ case PPP_IPV6: ip6_print(ndo, p, length); break; case ETHERTYPE_IPX: /*XXX*/ case PPP_IPX: ipx_print(ndo, p, length); break; case PPP_OSI: isoclns_print(ndo, p, length, length); break; case PPP_MPLS_UCAST: case PPP_MPLS_MCAST: mpls_print(ndo, p, length); break; case PPP_COMP: ND_PRINT((ndo, "compressed PPP data")); break; default: ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto))); print_unknown_data(ndo, p, "\n\t", length); break; } } CWE ID: CWE-125 Target: 1 Example 2: Code: HWND RenderWidgetHostViewAura::GetHostWindowHWND() const { aura::WindowTreeHost* host = window_->GetHost(); return host ? host->GetAcceleratedWidget() : nullptr; } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: path_mountpoint(struct nameidata *nd, unsigned flags, struct path *path) { const char *s = path_init(nd, flags); int err; if (IS_ERR(s)) return PTR_ERR(s); while (!(err = link_path_walk(s, nd)) && (err = mountpoint_last(nd, path)) > 0) { s = trailing_symlink(nd); if (IS_ERR(s)) { err = PTR_ERR(s); break; } } terminate_walk(nd); return err; } 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: long Tracks::Parse() { assert(m_trackEntries == NULL); assert(m_trackEntriesEnd == NULL); const long long stop = m_start + m_size; IMkvReader* const pReader = m_pSegment->m_pReader; int count = 0; long long pos = m_start; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x2E) // TrackEntry ID ++count; pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); if (count <= 0) return 0; // success m_trackEntries = new (std::nothrow) Track* [count]; if (m_trackEntries == NULL) return -1; m_trackEntriesEnd = m_trackEntries; pos = m_start; while (pos < stop) { const long long element_start = pos; long long id, payload_size; const long status = ParseElementHeader(pReader, pos, stop, id, payload_size); if (status < 0) // error return status; if (payload_size == 0) // weird continue; const long long payload_stop = pos + payload_size; assert(payload_stop <= stop); // checked in ParseElement const long long element_size = payload_stop - element_start; if (id == 0x2E) { // TrackEntry ID Track*& pTrack = *m_trackEntriesEnd; pTrack = NULL; const long status = ParseTrackEntry(pos, payload_size, element_start, element_size, pTrack); if (status) return status; if (pTrack) ++m_trackEntriesEnd; } pos = payload_stop; assert(pos <= stop); } assert(pos == stop); return 0; // success } CWE ID: CWE-20 Target: 1 Example 2: Code: NOINLINE void ResetThread_FILE() { volatile int inhibit_comdat = __LINE__; ALLOW_UNUSED_LOCAL(inhibit_comdat); BrowserThreadImpl::StopRedirectionOfThreadID(BrowserThread::FILE); } CWE ID: CWE-310 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static uint32_t select_lease_time(struct dhcp_packet *packet) { uint32_t lease_time_sec = server_config.max_lease_sec; uint8_t *lease_time_opt = udhcp_get_option(packet, DHCP_LEASE_TIME); if (lease_time_opt) { move_from_unaligned32(lease_time_sec, lease_time_opt); lease_time_sec = ntohl(lease_time_sec); if (lease_time_sec > server_config.max_lease_sec) lease_time_sec = server_config.max_lease_sec; if (lease_time_sec < server_config.min_lease_sec) lease_time_sec = server_config.min_lease_sec; } return lease_time_sec; } 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: __u32 secure_tcp_sequence_number(__be32 saddr, __be32 daddr, __be16 sport, __be16 dport) { __u32 seq; __u32 hash[4]; struct keydata *keyptr = get_keyptr(); /* * Pick a unique starting offset for each TCP connection endpoints * (saddr, daddr, sport, dport). * Note that the words are placed into the starting vector, which is * then mixed with a partial MD4 over random data. */ hash[0] = (__force u32)saddr; hash[1] = (__force u32)daddr; hash[2] = ((__force u16)sport << 16) + (__force u16)dport; hash[3] = keyptr->secret[11]; seq = half_md4_transform(hash, keyptr->secret) & HASH_MASK; seq += keyptr->count; /* * As close as possible to RFC 793, which * suggests using a 250 kHz clock. * Further reading shows this assumes 2 Mb/s networks. * For 10 Mb/s Ethernet, a 1 MHz clock is appropriate. * For 10 Gb/s Ethernet, a 1 GHz clock should be ok, but * we also need to limit the resolution so that the u32 seq * overlaps less than one time per MSL (2 minutes). * Choosing a clock of 64 ns period is OK. (period of 274 s) */ seq += ktime_to_ns(ktime_get_real()) >> 6; return seq; } CWE ID: Target: 1 Example 2: Code: bool ParamTraits<LogData>::Read(const Message* m, PickleIterator* iter, param_type* r) { return ReadParam(m, iter, &r->channel) && ReadParam(m, iter, &r->routing_id) && ReadParam(m, iter, &r->type) && ReadParam(m, iter, &r->flags) && ReadParam(m, iter, &r->sent) && ReadParam(m, iter, &r->receive) && ReadParam(m, iter, &r->dispatch) && ReadParam(m, iter, &r->message_name) && ReadParam(m, iter, &r->params); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int main(int argc, char **argv) { const char *test_name = NULL; bool skip_sanity_suite = false; for (int i = 1; i < argc; ++i) { if (!strcmp("--help", argv[i])) { print_usage(argv[0]); return 0; } if (!strcmp("--insanity", argv[i])) { skip_sanity_suite = true; continue; } if (!is_valid(argv[i])) { printf("Error: invalid test name.\n"); print_usage(argv[0]); return -1; } if (test_name != NULL) { printf("Error: invalid arguments.\n"); print_usage(argv[0]); return -1; } test_name = argv[i]; } if (is_shell_running()) { printf("Run 'adb shell stop' before running %s.\n", argv[0]); return -1; } config_t *config = config_new(CONFIG_FILE_PATH); if (!config) { printf("Error: unable to open stack config file.\n"); print_usage(argv[0]); return -1; } for (const config_section_node_t *node = config_section_begin(config); node != config_section_end(config); node = config_section_next(node)) { const char *name = config_section_name(node); if (config_has_key(config, name, "LinkKey") && string_to_bdaddr(name, &bt_remote_bdaddr)) { break; } } config_free(config); if (bdaddr_is_empty(&bt_remote_bdaddr)) { printf("Error: unable to find paired device in config file.\n"); print_usage(argv[0]); return -1; } if (!hal_open(callbacks_get_adapter_struct())) { printf("Unable to open Bluetooth HAL.\n"); return 1; } if (!btsocket_init()) { printf("Unable to initialize Bluetooth sockets.\n"); return 2; } if (!pan_init()) { printf("Unable to initialize PAN.\n"); return 3; } if (!gatt_init()) { printf("Unable to initialize GATT.\n"); return 4; } watchdog_running = true; pthread_create(&watchdog_thread, NULL, watchdog_fn, NULL); static const char *DEFAULT = "\x1b[0m"; static const char *GREEN = "\x1b[0;32m"; static const char *RED = "\x1b[0;31m"; if (!isatty(fileno(stdout))) { DEFAULT = GREEN = RED = ""; } int pass = 0; int fail = 0; int case_num = 0; if (!skip_sanity_suite) { for (size_t i = 0; i < sanity_suite_size; ++i) { if (!test_name || !strcmp(test_name, sanity_suite[i].function_name)) { callbacks_init(); if (sanity_suite[i].function()) { printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, sanity_suite[i].function_name, GREEN, DEFAULT); ++pass; } else { printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, sanity_suite[i].function_name, RED, DEFAULT); ++fail; } callbacks_cleanup(); ++watchdog_id; } } } if (fail) { printf("\n%sSanity suite failed with %d errors.%s\n", RED, fail, DEFAULT); hal_close(); return 4; } for (size_t i = 0; i < test_suite_size; ++i) { if (!test_name || !strcmp(test_name, test_suite[i].function_name)) { callbacks_init(); CALL_AND_WAIT(bt_interface->enable(), adapter_state_changed); if (test_suite[i].function()) { printf("[%4d] %-64s [%sPASS%s]\n", ++case_num, test_suite[i].function_name, GREEN, DEFAULT); ++pass; } else { printf("[%4d] %-64s [%sFAIL%s]\n", ++case_num, test_suite[i].function_name, RED, DEFAULT); ++fail; } CALL_AND_WAIT(bt_interface->disable(), adapter_state_changed); callbacks_cleanup(); ++watchdog_id; } } printf("\n"); if (fail) { printf("%d/%d tests failed. See above for failed test cases.\n", fail, sanity_suite_size + test_suite_size); } else { printf("All tests passed!\n"); } watchdog_running = false; pthread_join(watchdog_thread, NULL); hal_close(); return 0; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int hci_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct hci_ufilter uf; struct sock *sk = sock->sk; int len, opt, err = 0; BT_DBG("sk %p, opt %d", sk, optname); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) { err = -EINVAL; goto done; } switch (optname) { case HCI_DATA_DIR: if (hci_pi(sk)->cmsg_mask & HCI_CMSG_DIR) opt = 1; else opt = 0; if (put_user(opt, optval)) err = -EFAULT; break; case HCI_TIME_STAMP: if (hci_pi(sk)->cmsg_mask & HCI_CMSG_TSTAMP) opt = 1; else opt = 0; if (put_user(opt, optval)) err = -EFAULT; break; case HCI_FILTER: { struct hci_filter *f = &hci_pi(sk)->filter; uf.type_mask = f->type_mask; uf.opcode = f->opcode; uf.event_mask[0] = *((u32 *) f->event_mask + 0); uf.event_mask[1] = *((u32 *) f->event_mask + 1); } len = min_t(unsigned int, len, sizeof(uf)); if (copy_to_user(optval, &uf, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } done: release_sock(sk); return err; } CWE ID: CWE-200 Target: 1 Example 2: Code: static char *get_object_name(struct fsck_options *options, struct object *obj) { if (!options->object_names) return NULL; return lookup_decoration(options->object_names, obj); } 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 rtnl_phys_port_name_fill(struct sk_buff *skb, struct net_device *dev) { char name[IFNAMSIZ]; int err; err = dev_get_phys_port_name(dev, name, sizeof(name)); if (err) { if (err == -EOPNOTSUPP) return 0; return err; } if (nla_put(skb, IFLA_PHYS_PORT_NAME, strlen(name), name)) return -EMSGSIZE; return 0; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BlobDataHandle::~BlobDataHandle() { ThreadableBlobRegistry::unregisterBlobURL(m_internalURL); } CWE ID: Target: 1 Example 2: Code: void OnShowCreatedWindow(int pending_widget_routing_id, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture) { content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::BindOnce(&PendingWidgetMessageFilter::OnReceivedRoutingIDOnUI, this, pending_widget_routing_id)); } CWE ID: CWE-285 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 ip_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { int err; err = do_ip_getsockopt(sk, level, optname, optval, optlen, 0); #ifdef CONFIG_NETFILTER /* we need to exclude all possible ENOPROTOOPTs except default case */ if (err == -ENOPROTOOPT && optname != IP_PKTOPTIONS && !ip_mroute_opt(optname)) { int len; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); err = nf_getsockopt(sk, PF_INET, optname, optval, &len); release_sock(sk); if (err >= 0) err = put_user(len, optlen); return err; } #endif return err; } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: parserep(netdissect_options *ndo, register const struct sunrpc_msg *rp, register u_int length) { register const uint32_t *dp; u_int len; enum sunrpc_accept_stat astat; /* * Portability note: * Here we find the address of the ar_verf credentials. * Originally, this calculation was * dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf * On the wire, the rp_acpt field starts immediately after * the (32 bit) rp_stat field. However, rp_acpt (which is a * "struct accepted_reply") contains a "struct opaque_auth", * whose internal representation contains a pointer, so on a * 64-bit machine the compiler inserts 32 bits of padding * before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use * the internal representation to parse the on-the-wire * representation. Instead, we skip past the rp_stat field, * which is an "enum" and so occupies one 32-bit word. */ dp = ((const uint32_t *)&rp->rm_reply) + 1; ND_TCHECK(dp[1]); len = EXTRACT_32BITS(&dp[1]); if (len >= length) return (NULL); /* * skip past the ar_verf credentials. */ dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t); ND_TCHECK2(dp[0], 0); /* * now we can check the ar_stat field */ astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp); if (astat != SUNRPC_SUCCESS) { ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat))); nfserr = 1; /* suppress trunc string */ return (NULL); } /* successful return */ ND_TCHECK2(*dp, sizeof(astat)); return ((const uint32_t *) (sizeof(astat) + ((const char *)dp))); trunc: return (0); } CWE ID: CWE-125 Target: 1 Example 2: Code: static void usbip_dump_request_type(__u8 rt) { switch (rt & USB_RECIP_MASK) { case USB_RECIP_DEVICE: pr_debug("DEVICE"); break; case USB_RECIP_INTERFACE: pr_debug("INTERF"); break; case USB_RECIP_ENDPOINT: pr_debug("ENDPOI"); break; case USB_RECIP_OTHER: pr_debug("OTHER "); break; default: pr_debug("------"); break; } } 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: bson_iter_init_find_case (bson_iter_t *iter, /* INOUT */ const bson_t *bson, /* IN */ const char *key) /* IN */ { BSON_ASSERT (iter); BSON_ASSERT (bson); BSON_ASSERT (key); return bson_iter_init (iter, bson) && bson_iter_find_case (iter, key); } 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: brcmf_cfg80211_mgmt_tx(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_mgmt_tx_params *params, u64 *cookie) { struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy); struct ieee80211_channel *chan = params->chan; const u8 *buf = params->buf; size_t len = params->len; const struct ieee80211_mgmt *mgmt; struct brcmf_cfg80211_vif *vif; s32 err = 0; s32 ie_offset; s32 ie_len; struct brcmf_fil_action_frame_le *action_frame; struct brcmf_fil_af_params_le *af_params; bool ack; s32 chan_nr; u32 freq; brcmf_dbg(TRACE, "Enter\n"); *cookie = 0; mgmt = (const struct ieee80211_mgmt *)buf; if (!ieee80211_is_mgmt(mgmt->frame_control)) { brcmf_err("Driver only allows MGMT packet type\n"); return -EPERM; } vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev); if (ieee80211_is_probe_resp(mgmt->frame_control)) { /* Right now the only reason to get a probe response */ /* is for p2p listen response or for p2p GO from */ /* wpa_supplicant. Unfortunately the probe is send */ /* on primary ndev, while dongle wants it on the p2p */ /* vif. Since this is only reason for a probe */ /* response to be sent, the vif is taken from cfg. */ /* If ever desired to send proberesp for non p2p */ /* response then data should be checked for */ /* "DIRECT-". Note in future supplicant will take */ /* dedicated p2p wdev to do this and then this 'hack'*/ /* is not needed anymore. */ ie_offset = DOT11_MGMT_HDR_LEN + DOT11_BCN_PRB_FIXED_LEN; ie_len = len - ie_offset; if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif) vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif; err = brcmf_vif_set_mgmt_ie(vif, BRCMF_VNDR_IE_PRBRSP_FLAG, &buf[ie_offset], ie_len); cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, true, GFP_KERNEL); } else if (ieee80211_is_action(mgmt->frame_control)) { af_params = kzalloc(sizeof(*af_params), GFP_KERNEL); if (af_params == NULL) { brcmf_err("unable to allocate frame\n"); err = -ENOMEM; goto exit; } action_frame = &af_params->action_frame; /* Add the packet Id */ action_frame->packet_id = cpu_to_le32(*cookie); /* Add BSSID */ memcpy(&action_frame->da[0], &mgmt->da[0], ETH_ALEN); memcpy(&af_params->bssid[0], &mgmt->bssid[0], ETH_ALEN); /* Add the length exepted for 802.11 header */ action_frame->len = cpu_to_le16(len - DOT11_MGMT_HDR_LEN); /* Add the channel. Use the one specified as parameter if any or * the current one (got from the firmware) otherwise */ if (chan) freq = chan->center_freq; else brcmf_fil_cmd_int_get(vif->ifp, BRCMF_C_GET_CHANNEL, &freq); chan_nr = ieee80211_frequency_to_channel(freq); af_params->channel = cpu_to_le32(chan_nr); memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN], le16_to_cpu(action_frame->len)); brcmf_dbg(TRACE, "Action frame, cookie=%lld, len=%d, freq=%d\n", *cookie, le16_to_cpu(action_frame->len), freq); ack = brcmf_p2p_send_action_frame(cfg, cfg_to_ndev(cfg), af_params); cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, ack, GFP_KERNEL); kfree(af_params); } else { brcmf_dbg(TRACE, "Unhandled, fc=%04x!!\n", mgmt->frame_control); brcmf_dbg_hex_dump(true, buf, len, "payload, len=%zu\n", len); } exit: return err; } CWE ID: CWE-119 Target: 1 Example 2: Code: static int vhost_scsi_shutdown_session(struct se_session *se_sess) { return 0; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ManifestChangeNotifier::DidChangeManifest() { if (weak_factory_.HasWeakPtrs()) return; if (!render_frame()->GetWebFrame()->IsLoading()) { render_frame() ->GetTaskRunner(blink::TaskType::kUnspecedLoading) ->PostTask(FROM_HERE, base::BindOnce(&ManifestChangeNotifier::ReportManifestChange, weak_factory_.GetWeakPtr())); return; } ReportManifestChange(); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool AppCacheDatabase::FindEntry(int64_t cache_id, const GURL& url, EntryRecord* record) { DCHECK(record); if (!LazyOpen(kDontCreate)) return false; static const char kSql[] = "SELECT cache_id, url, flags, response_id, response_size FROM Entries" " WHERE cache_id = ? AND url = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, cache_id); statement.BindString(1, url.spec()); if (!statement.Step()) return false; ReadEntryRecord(statement, record); DCHECK(record->cache_id == cache_id); DCHECK(record->url == url); return true; } CWE ID: CWE-200 Target: 1 Example 2: Code: xfs_buf_get_uncached( struct xfs_buftarg *target, size_t numblks, int flags) { unsigned long page_count; int error, i; struct xfs_buf *bp; DEFINE_SINGLE_BUF_MAP(map, XFS_BUF_DADDR_NULL, numblks); bp = _xfs_buf_alloc(target, &map, 1, 0); if (unlikely(bp == NULL)) goto fail; page_count = PAGE_ALIGN(numblks << BBSHIFT) >> PAGE_SHIFT; error = _xfs_buf_get_pages(bp, page_count, 0); if (error) goto fail_free_buf; for (i = 0; i < page_count; i++) { bp->b_pages[i] = alloc_page(xb_to_gfp(flags)); if (!bp->b_pages[i]) goto fail_free_mem; } bp->b_flags |= _XBF_PAGES; error = _xfs_buf_map_pages(bp, 0); if (unlikely(error)) { xfs_warn(target->bt_mount, "%s: failed to map pages\n", __func__); goto fail_free_mem; } trace_xfs_buf_get_uncached(bp, _RET_IP_); return bp; fail_free_mem: while (--i >= 0) __free_page(bp->b_pages[i]); _xfs_buf_free_pages(bp); fail_free_buf: xfs_buf_free_maps(bp); kmem_zone_free(xfs_buf_zone, bp); fail: return NULL; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WebContents* PrintPreviewDialogController::CreatePrintPreviewDialog( WebContents* initiator) { base::AutoReset<bool> auto_reset(&is_creating_print_preview_dialog_, true); ConstrainedWebDialogDelegate* web_dialog_delegate = ShowConstrainedWebDialog(initiator->GetBrowserContext(), new PrintPreviewDialogDelegate(initiator), initiator); WebContents* preview_dialog = web_dialog_delegate->GetWebContents(); GURL print_url(chrome::kChromeUIPrintURL); content::HostZoomMap::Get(preview_dialog->GetSiteInstance()) ->SetZoomLevelForHostAndScheme(print_url.scheme(), print_url.host(), 0); PrintViewManager::CreateForWebContents(preview_dialog); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( preview_dialog); preview_dialog_map_[preview_dialog] = initiator; waiting_for_new_preview_page_ = true; task_manager::WebContentsTags::CreateForPrintingContents(preview_dialog); AddObservers(initiator); AddObservers(preview_dialog); return preview_dialog; } CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; FlipContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; AVFrame *out; uint8_t *inrow, *outrow; int i, j, plane, step; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); /* copy palette if required */ if (av_pix_fmt_desc_get(inlink->format)->flags & AV_PIX_FMT_FLAG_PAL) memcpy(out->data[1], in->data[1], AVPALETTE_SIZE); for (plane = 0; plane < 4 && in->data[plane]; plane++) { const int width = (plane == 1 || plane == 2) ? FF_CEIL_RSHIFT(inlink->w, s->hsub) : inlink->w; const int height = (plane == 1 || plane == 2) ? FF_CEIL_RSHIFT(inlink->h, s->vsub) : inlink->h; step = s->max_step[plane]; outrow = out->data[plane]; inrow = in ->data[plane] + (width - 1) * step; for (i = 0; i < height; i++) { switch (step) { case 1: for (j = 0; j < width; j++) outrow[j] = inrow[-j]; break; case 2: { uint16_t *outrow16 = (uint16_t *)outrow; uint16_t * inrow16 = (uint16_t *) inrow; for (j = 0; j < width; j++) outrow16[j] = inrow16[-j]; } break; case 3: { uint8_t *in = inrow; uint8_t *out = outrow; for (j = 0; j < width; j++, out += 3, in -= 3) { int32_t v = AV_RB24(in); AV_WB24(out, v); } } break; case 4: { uint32_t *outrow32 = (uint32_t *)outrow; uint32_t * inrow32 = (uint32_t *) inrow; for (j = 0; j < width; j++) outrow32[j] = inrow32[-j]; } break; default: for (j = 0; j < width; j++) memcpy(outrow + j*step, inrow - j*step, step); } inrow += in ->linesize[plane]; outrow += out->linesize[plane]; } } av_frame_free(&in); return ff_filter_frame(outlink, out); } CWE ID: CWE-119 Target: 1 Example 2: Code: void qeth_tx_timeout(struct net_device *dev) { struct qeth_card *card; card = dev->ml_priv; QETH_CARD_TEXT(card, 4, "txtimeo"); card->stats.tx_errors++; qeth_schedule_recovery(card); } 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: nfs4_callback_svc(void *vrqstp) { int err; struct svc_rqst *rqstp = vrqstp; set_freezable(); while (!kthread_should_stop()) { /* * Listen for a request on the socket */ err = svc_recv(rqstp, MAX_SCHEDULE_TIMEOUT); if (err == -EAGAIN || err == -EINTR) continue; svc_process(rqstp); } return 0; } CWE ID: CWE-404 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx) { struct srp_tsk_mgmt *srp_tsk; struct se_cmd *cmd; struct se_session *sess = ch->sess; uint64_t unpacked_lun; uint32_t tag = 0; int tcm_tmr; int rc; BUG_ON(!send_ioctx); srp_tsk = recv_ioctx->ioctx.buf; cmd = &send_ioctx->cmd; pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld" " cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func, srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess); srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT); send_ioctx->cmd.tag = srp_tsk->tag; tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func); if (tcm_tmr < 0) { send_ioctx->cmd.se_tmr_req->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED; goto fail; } unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun, sizeof(srp_tsk->lun)); if (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) { rc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag); if (rc < 0) { send_ioctx->cmd.se_tmr_req->response = TMR_TASK_DOES_NOT_EXIST; goto fail; } tag = srp_tsk->task_tag; } rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun, srp_tsk, tcm_tmr, GFP_KERNEL, tag, TARGET_SCF_ACK_KREF); if (rc != 0) { send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED; goto fail; } return; fail: transport_send_check_condition_and_sense(cmd, 0, 0); // XXX: } CWE ID: CWE-476 Target: 1 Example 2: Code: WebURLRequest CreateURLRequestForNavigation( const CommonNavigationParams& common_params, const RequestNavigationParams& request_params, std::unique_ptr<NavigationResponseOverrideParameters> response_override, bool is_view_source_mode_enabled) { const GURL navigation_url = !request_params.original_url.is_empty() ? request_params.original_url : common_params.url; const std::string navigation_method = !request_params.original_method.empty() ? request_params.original_method : common_params.method; WebURLRequest request(navigation_url); request.SetHTTPMethod(WebString::FromUTF8(navigation_method)); if (is_view_source_mode_enabled) request.SetCacheMode(blink::mojom::FetchCacheMode::kForceCache); WebString web_referrer; if (common_params.referrer.url.is_valid()) { web_referrer = WebSecurityPolicy::GenerateReferrerHeader( common_params.referrer.policy, common_params.url, WebString::FromUTF8(common_params.referrer.url.spec())); request.SetHTTPReferrer(web_referrer, common_params.referrer.policy); if (!web_referrer.IsEmpty()) { request.SetHTTPOriginIfNeeded( WebSecurityOrigin(url::Origin::Create(common_params.referrer.url))); } } if (common_params.post_data) { request.SetHTTPBody(GetWebHTTPBodyForRequestBody(*common_params.post_data)); if (!request_params.post_content_type.empty()) { request.AddHTTPHeaderField( WebString::FromASCII(net::HttpRequestHeaders::kContentType), WebString::FromASCII(request_params.post_content_type)); } } if (!web_referrer.IsEmpty() || common_params.referrer.policy != network::mojom::ReferrerPolicy::kDefault) { request.SetHTTPReferrer(web_referrer, common_params.referrer.policy); } request.SetPreviewsState( static_cast<WebURLRequest::PreviewsState>(common_params.previews_state)); request.SetOriginPolicy(WebString::FromUTF8(common_params.origin_policy)); if (common_params.initiator_origin) request.SetRequestorOrigin(common_params.initiator_origin.value()); auto extra_data = std::make_unique<RequestExtraData>(); extra_data->set_navigation_response_override(std::move(response_override)); extra_data->set_navigation_initiated_by_renderer( request_params.nav_entry_id == 0); request.SetExtraData(std::move(extra_data)); request.SetWasDiscarded(request_params.was_discarded); return request; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ZEND_API int ZEND_FASTCALL zend_hash_rehash(HashTable *ht) { Bucket *p; uint32_t nIndex, i; IS_CONSISTENT(ht); if (UNEXPECTED(ht->nNumOfElements == 0)) { if (ht->u.flags & HASH_FLAG_INITIALIZED) { ht->nNumUsed = 0; HT_HASH_RESET(ht); } return SUCCESS; } HT_HASH_RESET(ht); i = 0; p = ht->arData; if (ht->nNumUsed == ht->nNumOfElements) { do { nIndex = p->h | ht->nTableMask; Z_NEXT(p->val) = HT_HASH(ht, nIndex); HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(i); p++; } while (++i < ht->nNumUsed); } else { do { if (UNEXPECTED(Z_TYPE(p->val) == IS_UNDEF)) { uint32_t j = i; Bucket *q = p; if (EXPECTED(ht->u.v.nIteratorsCount == 0)) { while (++i < ht->nNumUsed) { p++; if (EXPECTED(Z_TYPE_INFO(p->val) != IS_UNDEF)) { ZVAL_COPY_VALUE(&q->val, &p->val); q->h = p->h; nIndex = q->h | ht->nTableMask; q->key = p->key; Z_NEXT(q->val) = HT_HASH(ht, nIndex); HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(j); if (UNEXPECTED(ht->nInternalPointer == i)) { ht->nInternalPointer = j; } q++; j++; } } } else { uint32_t iter_pos = zend_hash_iterators_lower_pos(ht, 0); while (++i < ht->nNumUsed) { p++; if (EXPECTED(Z_TYPE_INFO(p->val) != IS_UNDEF)) { ZVAL_COPY_VALUE(&q->val, &p->val); q->h = p->h; nIndex = q->h | ht->nTableMask; q->key = p->key; Z_NEXT(q->val) = HT_HASH(ht, nIndex); HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(j); if (UNEXPECTED(ht->nInternalPointer == i)) { ht->nInternalPointer = j; } if (UNEXPECTED(i == iter_pos)) { zend_hash_iterators_update(ht, i, j); iter_pos = zend_hash_iterators_lower_pos(ht, iter_pos + 1); } q++; j++; } } } ht->nNumUsed = j; break; } nIndex = p->h | ht->nTableMask; Z_NEXT(p->val) = HT_HASH(ht, nIndex); HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(i); p++; } while (++i < ht->nNumUsed); } return SUCCESS; } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Response StorageHandler::TrackCacheStorageForOrigin(const std::string& origin) { if (!process_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&CacheStorageObserver::TrackOriginOnIOThread, base::Unretained(GetCacheStorageObserver()), url::Origin::Create(origin_url))); return Response::OK(); } CWE ID: CWE-20 Target: 1 Example 2: Code: bool PhotoDataUtils::IsValueDifferent ( const IPTC_Manager & newIPTC, const IPTC_Manager & oldIPTC, XMP_Uns8 id ) { IPTC_Manager::DataSetInfo newInfo; size_t newCount = newIPTC.GetDataSet ( id, &newInfo ); if ( newCount == 0 ) return false; // Ignore missing new IPTC values. IPTC_Manager::DataSetInfo oldInfo; size_t oldCount = oldIPTC.GetDataSet ( id, &oldInfo ); if ( oldCount == 0 ) return true; // Missing old IPTC values differ. if ( newCount != oldCount ) return true; std::string oldStr, newStr; for ( newCount = 0; newCount < oldCount; ++newCount ) { if ( ignoreLocalText & (! newIPTC.UsingUTF8()) ) { // Check to see if the new value should be ignored. (void) newIPTC.GetDataSet ( id, &newInfo, newCount ); if ( ! ReconcileUtils::IsASCII ( newInfo.dataPtr, newInfo.dataLen ) ) continue; } (void) newIPTC.GetDataSet_UTF8 ( id, &newStr, newCount ); (void) oldIPTC.GetDataSet_UTF8 ( id, &oldStr, newCount ); if ( newStr.size() == 0 ) continue; // Ignore empty new IPTC. if ( newStr != oldStr ) break; } return ( newCount != oldCount ); // Not different if all values matched. } // PhotoDataUtils::IsValueDifferent 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: virtual ~SpellCheckClient() { } 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: file_ms_alloc(int flags) { struct magic_set *ms; size_t i, len; if ((ms = CAST(struct magic_set *, calloc((size_t)1, sizeof(struct magic_set)))) == NULL) return NULL; if (magic_setflags(ms, flags) == -1) { errno = EINVAL; goto free; } ms->o.buf = ms->o.pbuf = NULL; len = (ms->c.len = 10) * sizeof(*ms->c.li); if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL) goto free; ms->event_flags = 0; ms->error = -1; for (i = 0; i < MAGIC_SETS; i++) ms->mlist[i] = NULL; ms->file = "unknown"; ms->line = 0; ms->indir_max = FILE_INDIR_MAX; ms->name_max = FILE_NAME_MAX; ms->elf_shnum_max = FILE_ELF_SHNUM_MAX; ms->elf_phnum_max = FILE_ELF_PHNUM_MAX; return ms; free: free(ms); return NULL; } CWE ID: CWE-399 Target: 1 Example 2: Code: status_t Camera3Device::deleteStream(int id) { ATRACE_CALL(); Mutex::Autolock il(mInterfaceLock); Mutex::Autolock l(mLock); status_t res; ALOGV("%s: Camera %d: Deleting stream %d", __FUNCTION__, mId, id); if (mStatus == STATUS_ACTIVE) { ALOGV("%s: Camera %d: Device not idle", __FUNCTION__, mId); return -EBUSY; } sp<Camera3StreamInterface> deletedStream; ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id); if (mInputStream != NULL && id == mInputStream->getId()) { deletedStream = mInputStream; mInputStream.clear(); } else { if (outputStreamIdx == NAME_NOT_FOUND) { CLOGE("Stream %d does not exist", id); return BAD_VALUE; } } if (outputStreamIdx != NAME_NOT_FOUND) { deletedStream = mOutputStreams.editValueAt(outputStreamIdx); mOutputStreams.removeItem(id); } res = deletedStream->disconnect(); if (res != OK) { SET_ERR_L("Can't disconnect deleted stream %d", id); } mDeletedStreams.add(deletedStream); mNeedConfig = true; return res; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int indexedbasecolor(i_ctx_t * i_ctx_p, ref *space, int base, int *stage, int *cont, int *stack_depth) { int code; if (*stage == 0) { /* Usefully /Indexed can't be the base of any other space, so we know * the current space in the graphics state is this one. */ gs_color_space *pcs; pcs = gs_currentcolorspace(igs); /* Update the counters */ *stage = 1; *cont = 1; /* Indexed spaces can have *either* a procedure or a string for the * lookup. */ if (pcs->params.indexed.use_proc) { es_ptr ep = ++esp; ref proc; /* We have a procedure, set up the continuation to run the * lookup procedure. (The index is already on the operand stack) */ check_estack(1); code = array_get(imemory, space, 3, &proc); if (code < 0) return code; *ep = proc; /* lookup proc */ return o_push_estack; } else { int i, index; os_ptr op = osp; unsigned char *ptr = (unsigned char *)pcs->params.indexed.lookup.table.data; *stage = 0; /* We have a string, start by retrieving the index from the op stack */ /* Make sure its an integer! */ if (!r_has_type(op, t_integer)) return_error (gs_error_typecheck); index = op->value.intval; /* And remove it from the stack. */ pop(1); op = osp; /* Make sure we have enough space on the op stack to hold * one value for each component of the alternate space */ push(pcs->params.indexed.n_comps); op -= pcs->params.indexed.n_comps - 1; /* Move along the lookup table, one byte for each component , the * number of times required to get to the lookup for this index */ ptr += index * pcs->params.indexed.n_comps; /* For all the components of the alternate space, push the value * of the component on the stack. The value is given by the byte * from the lookup table divided by 255 to give a value between * 0 and 1. */ for (i = 0; i < pcs->params.indexed.n_comps; i++, op++) { float rval = (*ptr++) / 255.0; make_real(op, rval); } return 0; } } else { *stage = 0; *cont = 1; return 0; } } CWE ID: CWE-704 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ssize_t MPEG4DataSource::readAt(off64_t offset, void *data, size_t size) { Mutex::Autolock autoLock(mLock); if (offset >= mCachedOffset && offset + size <= mCachedOffset + mCachedSize) { memcpy(data, &mCache[offset - mCachedOffset], size); return size; } return mSource->readAt(offset, data, size); } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderViewImpl::OnUpdatedFrameTree( int process_id, int route_id, const std::string& frame_tree) { DCHECK(false); if (!is_swapped_out_) return; base::DictionaryValue* frames = NULL; scoped_ptr<base::Value> tree(base::JSONReader::Read(frame_tree)); if (tree.get() && tree->IsType(base::Value::TYPE_DICTIONARY)) tree->GetAsDictionary(&frames); updating_frame_tree_ = true; active_frame_id_map_.clear(); target_process_id_ = process_id; target_routing_id_ = route_id; CreateFrameTree(webview()->mainFrame(), frames); updating_frame_tree_ = false; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static v8::Handle<v8::Value> overloadedMethod2Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.overloadedMethod2"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); if (args.Length() <= 1) { imp->overloadedMethod(objArg); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined))); imp->overloadedMethod(objArg, intArg); return v8::Handle<v8::Value>(); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool FrameSelection::IsHandleVisible() const { return GetSelectionInDOMTree().IsHandleVisible(); } CWE ID: CWE-119 Target: 1 Example 2: Code: PHP_FUNCTION(pg_lo_open) { zval *pgsql_link = NULL; long oid_long; char *oid_string, *end_ptr, *mode_string; int oid_strlen, mode_strlen; PGconn *pgsql; Oid oid; int id = -1, pgsql_mode=0, pgsql_lofd; int create=0; pgLofp *pgsql_lofp; int argc = ZEND_NUM_ARGS(); /* accept string type since Oid is unsigned int */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC, "ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) { if (oid_long <= InvalidOid) { php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; id = PGG(default_link); CHECK_DEFAULT_LINK(id); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments"); RETURN_FALSE; } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); /* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of faster to type. Unfortunately, doesn't behave the same way as fopen()... (Jouni) */ if (strchr(mode_string, 'r') == mode_string) { pgsql_mode |= INV_READ; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_WRITE; } } if (strchr(mode_string, 'w') == mode_string) { pgsql_mode |= INV_WRITE; create = 1; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_READ; } } pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp)); if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (create) { if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } else { if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (lo_unlink(pgsql, oid) == -1) { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP"); RETURN_FALSE; } efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object"); RETURN_FALSE; } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; Z_LVAL_P(return_value) = zend_list_insert(pgsql_lofp, le_lofp TSRMLS_CC); Z_TYPE_P(return_value) = IS_LONG; } } } else { efree(pgsql_lofp); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object"); RETURN_FALSE; } } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp); } } 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: tcpmss_mangle_packet(struct sk_buff *skb, const struct xt_action_param *par, unsigned int family, unsigned int tcphoff, unsigned int minlen) { const struct xt_tcpmss_info *info = par->targinfo; struct tcphdr *tcph; int len, tcp_hdrlen; unsigned int i; __be16 oldval; u16 newmss; u8 *opt; /* This is a fragment, no TCP header is available */ if (par->fragoff != 0) return 0; if (!skb_make_writable(skb, skb->len)) return -1; len = skb->len - tcphoff; if (len < (int)sizeof(struct tcphdr)) return -1; tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff); tcp_hdrlen = tcph->doff * 4; if (len < tcp_hdrlen) return -1; if (info->mss == XT_TCPMSS_CLAMP_PMTU) { struct net *net = xt_net(par); unsigned int in_mtu = tcpmss_reverse_mtu(net, skb, family); unsigned int min_mtu = min(dst_mtu(skb_dst(skb)), in_mtu); if (min_mtu <= minlen) { net_err_ratelimited("unknown or invalid path-MTU (%u)\n", min_mtu); return -1; } newmss = min_mtu - minlen; } else newmss = info->mss; opt = (u_int8_t *)tcph; for (i = sizeof(struct tcphdr); i <= tcp_hdrlen - TCPOLEN_MSS; i += optlen(opt, i)) { if (opt[i] == TCPOPT_MSS && opt[i+1] == TCPOLEN_MSS) { u_int16_t oldmss; oldmss = (opt[i+2] << 8) | opt[i+3]; /* Never increase MSS, even when setting it, as * doing so results in problems for hosts that rely * on MSS being set correctly. */ if (oldmss <= newmss) return 0; opt[i+2] = (newmss & 0xff00) >> 8; opt[i+3] = newmss & 0x00ff; inet_proto_csum_replace2(&tcph->check, skb, htons(oldmss), htons(newmss), false); return 0; } } /* There is data after the header so the option can't be added * without moving it, and doing so may make the SYN packet * itself too large. Accept the packet unmodified instead. */ if (len > tcp_hdrlen) return 0; /* * MSS Option not found ?! add it.. */ if (skb_tailroom(skb) < TCPOLEN_MSS) { if (pskb_expand_head(skb, 0, TCPOLEN_MSS - skb_tailroom(skb), GFP_ATOMIC)) return -1; tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff); } skb_put(skb, TCPOLEN_MSS); /* * IPv4: RFC 1122 states "If an MSS option is not received at * connection setup, TCP MUST assume a default send MSS of 536". * IPv6: RFC 2460 states IPv6 has a minimum MTU of 1280 and a minimum * length IPv6 header of 60, ergo the default MSS value is 1220 * Since no MSS was provided, we must use the default values */ if (xt_family(par) == NFPROTO_IPV4) newmss = min(newmss, (u16)536); else newmss = min(newmss, (u16)1220); opt = (u_int8_t *)tcph + sizeof(struct tcphdr); memmove(opt + TCPOLEN_MSS, opt, len - sizeof(struct tcphdr)); inet_proto_csum_replace2(&tcph->check, skb, htons(len), htons(len + TCPOLEN_MSS), true); opt[0] = TCPOPT_MSS; opt[1] = TCPOLEN_MSS; opt[2] = (newmss & 0xff00) >> 8; opt[3] = newmss & 0x00ff; inet_proto_csum_replace4(&tcph->check, skb, 0, *((__be32 *)opt), false); oldval = ((__be16 *)tcph)[6]; tcph->doff += TCPOLEN_MSS/4; inet_proto_csum_replace2(&tcph->check, skb, oldval, ((__be16 *)tcph)[6], false); return TCPOLEN_MSS; } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main(int argc, char **argv) { int frame_cnt = 0; FILE *outfile = NULL; vpx_codec_ctx_t codec; const VpxInterface *decoder = NULL; VpxVideoReader *reader = NULL; const VpxVideoInfo *info = NULL; int n = 0; int m = 0; int is_range = 0; char *nptr = NULL; exec_name = argv[0]; if (argc != 4) die("Invalid number of arguments."); reader = vpx_video_reader_open(argv[1]); if (!reader) die("Failed to open %s for reading.", argv[1]); if (!(outfile = fopen(argv[2], "wb"))) die("Failed to open %s for writing.", argv[2]); n = strtol(argv[3], &nptr, 0); m = strtol(nptr + 1, NULL, 0); is_range = (*nptr == '-'); if (!n || !m || (*nptr != '-' && *nptr != '/')) die("Couldn't parse pattern %s.\n", argv[3]); info = vpx_video_reader_get_info(reader); decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc); if (!decoder) die("Unknown input codec."); printf("Using %s\n", vpx_codec_iface_name(decoder->interface())); if (vpx_codec_dec_init(&codec, decoder->interface(), NULL, 0)) die_codec(&codec, "Failed to initialize decoder."); while (vpx_video_reader_read_frame(reader)) { vpx_codec_iter_t iter = NULL; vpx_image_t *img = NULL; size_t frame_size = 0; int skip; const unsigned char *frame = vpx_video_reader_get_frame(reader, &frame_size); if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0)) die_codec(&codec, "Failed to decode frame."); ++frame_cnt; skip = (is_range && frame_cnt >= n && frame_cnt <= m) || (!is_range && m - (frame_cnt - 1) % m <= n); if (!skip) { putc('.', stdout); while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL) vpx_img_write(img, outfile); } else { putc('X', stdout); } fflush(stdout); } printf("Processed %d frames.\n", frame_cnt); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n", info->frame_width, info->frame_height, argv[2]); vpx_video_reader_close(reader); fclose(outfile); return EXIT_SUCCESS; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool WebGLRenderingContextBase::ContextCreatedOnCompatibleAdapter( const XRDevice* device) { return true; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: process_setstat(u_int32_t id) { Attrib a; char *name; int r, status = SSH2_FX_OK; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug("request %u: setstat name \"%s\"", id, name); if (a.flags & SSH2_FILEXFER_ATTR_SIZE) { logit("set \"%s\" size %llu", name, (unsigned long long)a.size); r = truncate(name, a.size); if (r == -1) status = errno_to_portable(errno); } if (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) { logit("set \"%s\" mode %04o", name, a.perm); r = chmod(name, a.perm & 07777); if (r == -1) status = errno_to_portable(errno); } if (a.flags & SSH2_FILEXFER_ATTR_ACMODTIME) { char buf[64]; time_t t = a.mtime; strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S", localtime(&t)); logit("set \"%s\" modtime %s", name, buf); r = utimes(name, attrib_to_tv(&a)); if (r == -1) status = errno_to_portable(errno); } if (a.flags & SSH2_FILEXFER_ATTR_UIDGID) { logit("set \"%s\" owner %lu group %lu", name, (u_long)a.uid, (u_long)a.gid); r = chown(name, a.uid, a.gid); if (r == -1) status = errno_to_portable(errno); } send_status(id, status); free(name); } CWE ID: CWE-269 Output:
0
Here are some example code snippets. Analyze the following 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 Track::GetNumber() const { return m_info.number; } CWE ID: CWE-119 Target: 1 Example 2: Code: get_line_from_string(char **lines, int *line_len) { int i; char *z = *lines; if( z[0] == '\0' ) return NULL; for (i=0; z[i]; i++) { if (z[i] == '\n') { if (i > 0 && z[i-1]=='\r') { z[i-1] = '\0'; } else { z[i] = '\0'; } i++; break; } } /* advance lines on */ *lines = &z[i]; *line_len -= i; return z; } CWE ID: CWE-22 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 SoftMPEG2::setDecodeArgs( ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op, OMX_BUFFERHEADERTYPE *inHeader, OMX_BUFFERHEADERTYPE *outHeader, size_t timeStampIx) { size_t sizeY = outputBufferWidth() * outputBufferHeight(); size_t sizeUV; uint8_t *pBuf; ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE; /* When in flush and after EOS with zero byte input, * inHeader is set to zero. Hence check for non-null */ if (inHeader) { ps_dec_ip->u4_ts = timeStampIx; ps_dec_ip->pv_stream_buffer = inHeader->pBuffer + inHeader->nOffset; ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen; } else { ps_dec_ip->u4_ts = 0; ps_dec_ip->pv_stream_buffer = NULL; ps_dec_ip->u4_num_Bytes = 0; } if (outHeader) { pBuf = outHeader->pBuffer; } else { pBuf = mFlushOutBuffer; } sizeUV = sizeY / 4; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; ps_dec_ip->s_out_buffer.u4_num_bufs = 3; return; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) { if (external_popup_menu_ == NULL) return; blink::WebScopedUserGesture gesture(frame_); external_popup_menu_->DidSelectItem(selected_index); external_popup_menu_.reset(); } CWE ID: CWE-416 Target: 1 Example 2: Code: static void testInterfaceEmptyArrayAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValue(info, v8Array(imp->testInterfaceEmptyArrayAttribute(), 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 VaapiVideoDecodeAccelerator::Initialize(const Config& config, Client* client) { DCHECK(task_runner_->BelongsToCurrentThread()); if (config.is_encrypted()) { NOTREACHED() << "Encrypted streams are not supported for this VDA"; return false; } switch (config.output_mode) { case Config::OutputMode::ALLOCATE: output_format_ = vaapi_picture_factory_->GetBufferFormatForAllocateMode(); break; case Config::OutputMode::IMPORT: output_format_ = vaapi_picture_factory_->GetBufferFormatForImportMode(); break; default: NOTREACHED() << "Only ALLOCATE and IMPORT OutputModes are supported"; return false; } client_ptr_factory_.reset(new base::WeakPtrFactory<Client>(client)); client_ = client_ptr_factory_->GetWeakPtr(); VideoCodecProfile profile = config.profile; base::AutoLock auto_lock(lock_); DCHECK_EQ(state_, kUninitialized); VLOGF(2) << "Initializing VAVDA, profile: " << GetProfileName(profile); vaapi_wrapper_ = VaapiWrapper::CreateForVideoCodec( VaapiWrapper::kDecode, profile, base::Bind(&ReportToUMA, VAAPI_ERROR)); if (!vaapi_wrapper_.get()) { VLOGF(1) << "Failed initializing VAAPI for profile " << GetProfileName(profile); return false; } if (profile >= H264PROFILE_MIN && profile <= H264PROFILE_MAX) { h264_accelerator_.reset( new VaapiH264Accelerator(this, vaapi_wrapper_.get())); decoder_.reset(new H264Decoder(h264_accelerator_.get())); } else if (profile >= VP8PROFILE_MIN && profile <= VP8PROFILE_MAX) { vp8_accelerator_.reset(new VaapiVP8Accelerator(this, vaapi_wrapper_.get())); decoder_.reset(new VP8Decoder(vp8_accelerator_.get())); } else if (profile >= VP9PROFILE_MIN && profile <= VP9PROFILE_MAX) { vp9_accelerator_.reset(new VaapiVP9Accelerator(this, vaapi_wrapper_.get())); decoder_.reset(new VP9Decoder(vp9_accelerator_.get())); } else { VLOGF(1) << "Unsupported profile " << GetProfileName(profile); return false; } profile_ = profile; CHECK(decoder_thread_.Start()); decoder_thread_task_runner_ = decoder_thread_.task_runner(); state_ = kIdle; output_mode_ = config.output_mode; return true; } 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: BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; if (im == NULL) { return; } if (!gdImageTrueColor(im)) { gd_error("Paletter image not supported by webp"); return; } if (quality == -1) { quality = 80; } if (overflow2(gdImageSX(im), 4)) { return; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out); if (out_size == 0) { gd_error("gd-webp encoding failed"); goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); } CWE ID: CWE-415 Target: 1 Example 2: Code: PHP_MINIT_FUNCTION(pgsql) { REGISTER_INI_ENTRIES(); le_link = zend_register_list_destructors_ex(_close_pgsql_link, NULL, "pgsql link", module_number); le_plink = zend_register_list_destructors_ex(NULL, _close_pgsql_plink, "pgsql link persistent", module_number); le_result = zend_register_list_destructors_ex(_free_result, NULL, "pgsql result", module_number); le_lofp = zend_register_list_destructors_ex(_free_ptr, NULL, "pgsql large object", module_number); le_string = zend_register_list_destructors_ex(_free_ptr, NULL, "pgsql string", module_number); #if HAVE_PG_CONFIG_H /* PG_VERSION - libpq version */ REGISTER_STRING_CONSTANT("PGSQL_LIBPQ_VERSION", PG_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("PGSQL_LIBPQ_VERSION_STR", PG_VERSION_STR, CONST_CS | CONST_PERSISTENT); #endif /* For connection option */ REGISTER_LONG_CONSTANT("PGSQL_CONNECT_FORCE_NEW", PGSQL_CONNECT_FORCE_NEW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECT_ASYNC", PGSQL_CONNECT_ASYNC, CONST_CS | CONST_PERSISTENT); /* For pg_fetch_array() */ REGISTER_LONG_CONSTANT("PGSQL_ASSOC", PGSQL_ASSOC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_NUM", PGSQL_NUM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_BOTH", PGSQL_BOTH, CONST_CS | CONST_PERSISTENT); /* For pg_connection_status() */ REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_BAD", CONNECTION_BAD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_OK", CONNECTION_OK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_STARTED", CONNECTION_STARTED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_MADE", CONNECTION_MADE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_AWAITING_RESPONSE", CONNECTION_AWAITING_RESPONSE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_AUTH_OK", CONNECTION_AUTH_OK, CONST_CS | CONST_PERSISTENT); #ifdef CONNECTION_SSL_STARTUP REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_SSL_STARTUP", CONNECTION_SSL_STARTUP, CONST_CS | CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_SETENV", CONNECTION_SETENV, CONST_CS | CONST_PERSISTENT); /* For pg_connect_poll() */ REGISTER_LONG_CONSTANT("PGSQL_POLLING_FAILED", PGRES_POLLING_FAILED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_POLLING_READING", PGRES_POLLING_READING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_POLLING_WRITING", PGRES_POLLING_WRITING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_POLLING_OK", PGRES_POLLING_OK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_POLLING_ACTIVE", PGRES_POLLING_ACTIVE, CONST_CS | CONST_PERSISTENT); #if HAVE_PGTRANSACTIONSTATUS /* For pg_transaction_status() */ REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_IDLE", PQTRANS_IDLE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_ACTIVE", PQTRANS_ACTIVE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_INTRANS", PQTRANS_INTRANS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_INERROR", PQTRANS_INERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_UNKNOWN", PQTRANS_UNKNOWN, CONST_CS | CONST_PERSISTENT); #endif #if HAVE_PQSETERRORVERBOSITY /* For pg_set_error_verbosity() */ REGISTER_LONG_CONSTANT("PGSQL_ERRORS_TERSE", PQERRORS_TERSE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_ERRORS_DEFAULT", PQERRORS_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_ERRORS_VERBOSE", PQERRORS_VERBOSE, CONST_CS | CONST_PERSISTENT); #endif /* For lo_seek() */ REGISTER_LONG_CONSTANT("PGSQL_SEEK_SET", SEEK_SET, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_SEEK_CUR", SEEK_CUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_SEEK_END", SEEK_END, CONST_CS | CONST_PERSISTENT); /* For pg_result_status() return value type */ REGISTER_LONG_CONSTANT("PGSQL_STATUS_LONG", PGSQL_STATUS_LONG, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_STATUS_STRING", PGSQL_STATUS_STRING, CONST_CS | CONST_PERSISTENT); /* For pg_result_status() return value */ REGISTER_LONG_CONSTANT("PGSQL_EMPTY_QUERY", PGRES_EMPTY_QUERY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_COMMAND_OK", PGRES_COMMAND_OK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TUPLES_OK", PGRES_TUPLES_OK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_COPY_OUT", PGRES_COPY_OUT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_COPY_IN", PGRES_COPY_IN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_BAD_RESPONSE", PGRES_BAD_RESPONSE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_NONFATAL_ERROR", PGRES_NONFATAL_ERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_FATAL_ERROR", PGRES_FATAL_ERROR, CONST_CS | CONST_PERSISTENT); #if HAVE_PQRESULTERRORFIELD /* For pg_result_error_field() field codes */ REGISTER_LONG_CONSTANT("PGSQL_DIAG_SEVERITY", PG_DIAG_SEVERITY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_SQLSTATE", PG_DIAG_SQLSTATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_PRIMARY", PG_DIAG_MESSAGE_PRIMARY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_DETAIL", PG_DIAG_MESSAGE_DETAIL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_HINT", PG_DIAG_MESSAGE_HINT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_STATEMENT_POSITION", PG_DIAG_STATEMENT_POSITION, CONST_CS | CONST_PERSISTENT); #ifdef PG_DIAG_INTERNAL_POSITION REGISTER_LONG_CONSTANT("PGSQL_DIAG_INTERNAL_POSITION", PG_DIAG_INTERNAL_POSITION, CONST_CS | CONST_PERSISTENT); #endif #ifdef PG_DIAG_INTERNAL_QUERY REGISTER_LONG_CONSTANT("PGSQL_DIAG_INTERNAL_QUERY", PG_DIAG_INTERNAL_QUERY, CONST_CS | CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("PGSQL_DIAG_CONTEXT", PG_DIAG_CONTEXT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_FILE", PG_DIAG_SOURCE_FILE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_LINE", PG_DIAG_SOURCE_LINE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_FUNCTION", PG_DIAG_SOURCE_FUNCTION, CONST_CS | CONST_PERSISTENT); #endif /* pg_convert options */ REGISTER_LONG_CONSTANT("PGSQL_CONV_IGNORE_DEFAULT", PGSQL_CONV_IGNORE_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONV_FORCE_NULL", PGSQL_CONV_FORCE_NULL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONV_IGNORE_NOT_NULL", PGSQL_CONV_IGNORE_NOT_NULL, CONST_CS | CONST_PERSISTENT); /* pg_insert/update/delete/select options */ REGISTER_LONG_CONSTANT("PGSQL_DML_ESCAPE", PGSQL_DML_ESCAPE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DML_NO_CONV", PGSQL_DML_NO_CONV, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DML_EXEC", PGSQL_DML_EXEC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DML_ASYNC", PGSQL_DML_ASYNC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DML_STRING", PGSQL_DML_STRING, CONST_CS | CONST_PERSISTENT); return SUCCESS; } 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: error::Error GLES2DecoderPassthroughImpl::DoLockDiscardableTextureCHROMIUM( GLuint texture_id) { if (!group_->passthrough_discardable_manager()->LockTexture(texture_id, group_.get())) { InsertError(GL_INVALID_VALUE, "Texture ID not initialized"); return error::kNoError; } return error::kNoError; } 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 TabCountChangeObserver::TabDetachedAt(TabContents* contents, int index) { CheckTabCount(); } CWE ID: CWE-20 Target: 1 Example 2: Code: bool HTMLFormElement::checkValidityWithoutDispatchingEvents() { return !checkInvalidControlsAndCollectUnhandled(0, HTMLFormControlElement::CheckValidityDispatchEventsNone); } 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: xps_load_sfnt_name(xps_font_t *font, char *namep) { byte *namedata; int offset, length; /*int format;*/ int count, stringoffset; int found; int i, k; found = 0; strcpy(namep, "Unknown"); offset = xps_find_sfnt_table(font, "name", &length); if (offset < 0 || length < 6) { gs_warn("cannot find name table"); return; } /* validate the offset, and the data for the two * values we're about to read */ if (offset + 6 > font->length) { gs_warn("name table byte offset invalid"); return; } namedata = font->data + offset; /*format = u16(namedata + 0);*/ count = u16(namedata + 2); stringoffset = u16(namedata + 4); if (stringoffset + offset > font->length || offset + 6 + count * 12 > font->length) { gs_warn("name table invalid"); return; } if (length < 6 + (count * 12)) { gs_warn("name table too short"); return; } for (i = 0; i < count; i++) { byte *record = namedata + 6 + i * 12; int pid = u16(record + 0); int eid = u16(record + 2); int langid = u16(record + 4); int nameid = u16(record + 6); length = u16(record + 8); offset = u16(record + 10); /* Full font name or postscript name */ if (nameid == 4 || nameid == 6) { if (found < 3) { memcpy(namep, namedata + stringoffset + offset, length); namep[length] = 0; found = 3; } } if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */ { if (found < 2) { unsigned char *s = namedata + stringoffset + offset; int n = length / 2; for (k = 0; k < n; k ++) { int c = u16(s + k * 2); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 2; } } if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */ { if (found < 1) { unsigned char *s = namedata + stringoffset + offset; int n = length / 4; for (k = 0; k < n; k ++) { int c = u32(s + k * 4); namep[k] = isprint(c) ? c : '?'; } namep[k] = 0; found = 1; } } } } 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 perform_gamma_transform_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) { unsigned int i, j; for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j) if (i != j) { gamma_transform_test(pm, colour_type, bit_depth, palette_number, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/, pm->use_input_precision, 0 /*do not scale16*/); if (fail(pm)) return; } } } CWE ID: Target: 1 Example 2: Code: static int csnmp_config(oconfig_item_t *ci) { call_snmp_init_once(); for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *child = ci->children + i; if (strcasecmp("Data", child->key) == 0) csnmp_config_add_data(child); else if (strcasecmp("Host", child->key) == 0) csnmp_config_add_host(child); else { WARNING("snmp plugin: Ignoring unknown config option `%s'.", child->key); } } /* for (ci->children) */ return (0); } /* int csnmp_config */ 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: SiteProcessMap* GetSiteProcessMapForBrowserContext(BrowserContext* context) { DCHECK(context); SiteProcessMap* map = static_cast<SiteProcessMap*>( context->GetUserData(kSiteProcessMapKeyName)); if (!map) { map = new SiteProcessMap(); context->SetUserData(kSiteProcessMapKeyName, base::WrapUnique(map)); } return map; } 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 RenderThreadImpl::EnsureWebKitInitialized() { if (webkit_platform_support_) return; webkit_platform_support_.reset(new RendererWebKitPlatformSupportImpl); blink::initialize(webkit_platform_support_.get()); main_thread_compositor_task_runner_ = make_scoped_refptr(new SchedulerProxyTaskRunner< &blink::WebSchedulerProxy::postCompositorTask>()); v8::Isolate* isolate = blink::mainThreadIsolate(); isolate->SetCounterFunction(base::StatsTable::FindLocation); isolate->SetCreateHistogramFunction(CreateHistogram); isolate->SetAddHistogramSampleFunction(AddHistogramSample); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); bool enable = !command_line.HasSwitch(switches::kDisableThreadedCompositing); if (enable) { #if defined(OS_ANDROID) if (SynchronousCompositorFactory* factory = SynchronousCompositorFactory::GetInstance()) compositor_message_loop_proxy_ = factory->GetCompositorMessageLoop(); #endif if (!compositor_message_loop_proxy_.get()) { compositor_thread_.reset(new base::Thread("Compositor")); compositor_thread_->Start(); #if defined(OS_ANDROID) compositor_thread_->SetPriority(base::kThreadPriority_Display); #endif compositor_message_loop_proxy_ = compositor_thread_->message_loop_proxy(); compositor_message_loop_proxy_->PostTask( FROM_HERE, base::Bind(base::IgnoreResult(&ThreadRestrictions::SetIOAllowed), false)); } InputHandlerManagerClient* input_handler_manager_client = NULL; #if defined(OS_ANDROID) if (SynchronousCompositorFactory* factory = SynchronousCompositorFactory::GetInstance()) { input_handler_manager_client = factory->GetInputHandlerManagerClient(); } #endif if (!input_handler_manager_client) { input_event_filter_ = new InputEventFilter(this, main_thread_compositor_task_runner_, compositor_message_loop_proxy_); AddFilter(input_event_filter_.get()); input_handler_manager_client = input_event_filter_.get(); } input_handler_manager_.reset( new InputHandlerManager(compositor_message_loop_proxy_, input_handler_manager_client)); } scoped_refptr<base::MessageLoopProxy> output_surface_loop; if (enable) output_surface_loop = compositor_message_loop_proxy_; else output_surface_loop = base::MessageLoopProxy::current(); compositor_output_surface_filter_ = CompositorOutputSurface::CreateFilter(output_surface_loop.get()); AddFilter(compositor_output_surface_filter_.get()); RenderThreadImpl::RegisterSchemes(); EnableBlinkPlatformLogChannels( command_line.GetSwitchValueASCII(switches::kBlinkPlatformLogChannels)); SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line); if (!media::IsMediaLibraryInitialized()) { WebRuntimeFeatures::enableWebAudio(false); } FOR_EACH_OBSERVER(RenderProcessObserver, observers_, WebKitInitialized()); devtools_agent_message_filter_ = new DevToolsAgentFilter(); AddFilter(devtools_agent_message_filter_.get()); if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) ScheduleIdleHandler(kLongIdleHandlerDelayMs); cc_blink::SetSharedMemoryAllocationFunction(AllocateSharedMemoryFunction); if (!command_line.HasSwitch(switches::kEnableDeferredImageDecoding) && !is_impl_side_painting_enabled_) SkGraphics::SetImageCacheByteLimit(0u); SkGraphics::SetImageCacheSingleAllocationByteLimit( kImageCacheSingleAllocationByteLimit); if (command_line.HasSwitch(switches::kMemoryMetrics)) { memory_observer_.reset(new MemoryObserver()); message_loop()->AddTaskObserver(memory_observer_.get()); } } CWE ID: Target: 1 Example 2: Code: static void nr_set_lockdep_one(struct net_device *dev, struct netdev_queue *txq, void *_unused) { lockdep_set_class(&txq->_xmit_lock, &nr_netdev_xmit_lock_key); } 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 ram_save_complete(QEMUFile *f, void *opaque) { qemu_mutex_lock_ramlist(); migration_bitmap_sync(); ram_control_before_iterate(f, RAM_CONTROL_FINISH); /* try transferring iterative blocks of memory */ /* flush all remaining blocks regardless of rate limiting */ while (true) { int bytes_sent; bytes_sent = ram_find_and_save_block(f, true); /* no more blocks to sent */ if (bytes_sent == 0) { break; } bytes_transferred += bytes_sent; } ram_control_after_iterate(f, RAM_CONTROL_FINISH); migration_end(); qemu_mutex_unlock_ramlist(); qemu_put_be64(f, RAM_SAVE_FLAG_EOS); 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: ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) { int totlen; uint32_t t; if (p[0] & 0x80) totlen = 4; else totlen = 4 + EXTRACT_16BITS(&p[2]); if (ep < p + totlen) { ND_PRINT((ndo,"[|attr]")); return ep + 1; } ND_PRINT((ndo,"(")); t = EXTRACT_16BITS(&p[0]) & 0x7fff; ND_PRINT((ndo,"type=#%d ", t)); if (p[0] & 0x80) { ND_PRINT((ndo,"value=")); t = p[2]; rawprint(ndo, (const uint8_t *)&p[2], 2); } else { ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2]))); rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); } ND_PRINT((ndo,")")); return p + totlen; } CWE ID: CWE-125 Target: 1 Example 2: Code: std::string RenderFrameDevToolsAgentHost::GetTitle() { DevToolsManager* manager = DevToolsManager::GetInstance(); if (manager->delegate() && web_contents()) { std::string title = manager->delegate()->GetTargetTitle(web_contents()); if (!title.empty()) return title; } if (IsChildFrame() && frame_host_) return frame_host_->GetLastCommittedURL().spec(); if (web_contents()) return base::UTF16ToUTF8(web_contents()->GetTitle()); return GetURL().spec(); } 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: long BlockGroup::Parse() { const long status = m_block.Parse(m_pCluster); if (status) return status; m_block.SetKey((m_prev > 0) && (m_next <= 0)); return 0; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); } CWE ID: CWE-119 Target: 1 Example 2: Code: void ShowInterstitial(const char* url) { new TestOfflineLoadPage(contents(), GURL(url), this); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce) { long datalen; datalen = parse_iv2((*p) + 2, p); (*p) += 2; if (datalen < 0 || (*p) + datalen >= max) { zend_error(E_WARNING, "Insufficient data for unserializing - %ld required, %ld present", datalen, (long)(max - (*p))); return 0; } if (ce->unserialize == NULL) { zend_error(E_WARNING, "Class %s has no unserializer", ce->name); object_init_ex(*rval, ce); } else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash TSRMLS_CC) != SUCCESS) { return 0; } (*p) += datalen; return finish_nested_data(UNSERIALIZE_PASSTHRU); } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static unsigned long randomize_stack_top(unsigned long stack_top) { unsigned int random_variable = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { random_variable = get_random_int() & STACK_RND_MASK; random_variable <<= PAGE_SHIFT; } #ifdef CONFIG_STACK_GROWSUP return PAGE_ALIGN(stack_top) + random_variable; #else return PAGE_ALIGN(stack_top) - random_variable; #endif } CWE ID: CWE-264 Target: 1 Example 2: Code: static void __exit nvmet_fc_exit_module(void) { /* sanity check - all lports should be removed */ if (!list_empty(&nvmet_fc_target_list)) pr_warn("%s: targetport list not empty\n", __func__); nvmet_unregister_transport(&nvmet_fc_tgt_fcp_ops); ida_destroy(&nvmet_fc_tgtport_cnt); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AXARIAGridCell::isAriaColumnHeader() const { const AtomicString& role = getAttribute(HTMLNames::roleAttr); return equalIgnoringCase(role, "columnheader"); } CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void xacct_add_tsk(struct taskstats *stats, struct task_struct *p) { /* convert pages-jiffies to Mbyte-usec */ stats->coremem = jiffies_to_usecs(p->acct_rss_mem1) * PAGE_SIZE / MB; stats->virtmem = jiffies_to_usecs(p->acct_vm_mem1) * PAGE_SIZE / MB; if (p->mm) { /* adjust to KB unit */ stats->hiwater_rss = p->mm->hiwater_rss * PAGE_SIZE / KB; stats->hiwater_vm = p->mm->hiwater_vm * PAGE_SIZE / KB; } stats->read_char = p->rchar; stats->write_char = p->wchar; stats->read_syscalls = p->syscr; stats->write_syscalls = p->syscw; } CWE ID: CWE-399 Target: 1 Example 2: Code: PluginDataRemover* PluginDataRemover::Create(BrowserContext* browser_context) { return new PluginDataRemoverImpl(browser_context); } 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 tcp_v4_err(struct sk_buff *icmp_skb, u32 info) { const struct iphdr *iph = (const struct iphdr *)icmp_skb->data; struct tcphdr *th = (struct tcphdr *)(icmp_skb->data + (iph->ihl << 2)); struct inet_connection_sock *icsk; struct tcp_sock *tp; struct inet_sock *inet; const int type = icmp_hdr(icmp_skb)->type; const int code = icmp_hdr(icmp_skb)->code; struct sock *sk; struct sk_buff *skb; __u32 seq; __u32 remaining; int err; struct net *net = dev_net(icmp_skb->dev); if (icmp_skb->len < (iph->ihl << 2) + 8) { ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS); return; } sk = inet_lookup(net, &tcp_hashinfo, iph->daddr, th->dest, iph->saddr, th->source, inet_iif(icmp_skb)); if (!sk) { ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS); return; } if (sk->sk_state == TCP_TIME_WAIT) { inet_twsk_put(inet_twsk(sk)); return; } bh_lock_sock(sk); /* If too many ICMPs get dropped on busy * servers this needs to be solved differently. */ if (sock_owned_by_user(sk)) NET_INC_STATS_BH(net, LINUX_MIB_LOCKDROPPEDICMPS); if (sk->sk_state == TCP_CLOSE) goto out; if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) { NET_INC_STATS_BH(net, LINUX_MIB_TCPMINTTLDROP); goto out; } icsk = inet_csk(sk); tp = tcp_sk(sk); seq = ntohl(th->seq); if (sk->sk_state != TCP_LISTEN && !between(seq, tp->snd_una, tp->snd_nxt)) { NET_INC_STATS_BH(net, LINUX_MIB_OUTOFWINDOWICMPS); goto out; } switch (type) { case ICMP_SOURCE_QUENCH: /* Just silently ignore these. */ goto out; case ICMP_PARAMETERPROB: err = EPROTO; break; case ICMP_DEST_UNREACH: if (code > NR_ICMP_UNREACH) goto out; if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */ if (!sock_owned_by_user(sk)) do_pmtu_discovery(sk, iph, info); goto out; } err = icmp_err_convert[code].errno; /* check if icmp_skb allows revert of backoff * (see draft-zimmermann-tcp-lcd) */ if (code != ICMP_NET_UNREACH && code != ICMP_HOST_UNREACH) break; if (seq != tp->snd_una || !icsk->icsk_retransmits || !icsk->icsk_backoff) break; if (sock_owned_by_user(sk)) break; icsk->icsk_backoff--; inet_csk(sk)->icsk_rto = __tcp_set_rto(tp) << icsk->icsk_backoff; tcp_bound_rto(sk); skb = tcp_write_queue_head(sk); BUG_ON(!skb); remaining = icsk->icsk_rto - min(icsk->icsk_rto, tcp_time_stamp - TCP_SKB_CB(skb)->when); if (remaining) { inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, remaining, TCP_RTO_MAX); } else { /* RTO revert clocked out retransmission. * Will retransmit now */ tcp_retransmit_timer(sk); } break; case ICMP_TIME_EXCEEDED: err = EHOSTUNREACH; break; default: goto out; } switch (sk->sk_state) { struct request_sock *req, **prev; case TCP_LISTEN: if (sock_owned_by_user(sk)) goto out; req = inet_csk_search_req(sk, &prev, th->dest, iph->daddr, iph->saddr); if (!req) goto out; /* ICMPs are not backlogged, hence we cannot get an established socket here. */ WARN_ON(req->sk); if (seq != tcp_rsk(req)->snt_isn) { NET_INC_STATS_BH(net, LINUX_MIB_OUTOFWINDOWICMPS); goto out; } /* * Still in SYN_RECV, just remove it silently. * There is no good way to pass the error to the newly * created socket, and POSIX does not want network * errors returned from accept(). */ inet_csk_reqsk_queue_drop(sk, req, prev); goto out; case TCP_SYN_SENT: case TCP_SYN_RECV: /* Cannot happen. It can f.e. if SYNs crossed. */ if (!sock_owned_by_user(sk)) { sk->sk_err = err; sk->sk_error_report(sk); tcp_done(sk); } else { sk->sk_err_soft = err; } goto out; } /* If we've already connected we will keep trying * until we time out, or the user gives up. * * rfc1122 4.2.3.9 allows to consider as hard errors * only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too, * but it is obsoleted by pmtu discovery). * * Note, that in modern internet, where routing is unreliable * and in each dark corner broken firewalls sit, sending random * errors ordered by their masters even this two messages finally lose * their original sense (even Linux sends invalid PORT_UNREACHs) * * Now we are in compliance with RFCs. * --ANK (980905) */ inet = inet_sk(sk); if (!sock_owned_by_user(sk) && inet->recverr) { sk->sk_err = err; sk->sk_error_report(sk); } else { /* Only an error on timeout */ sk->sk_err_soft = err; } out: bh_unlock_sock(sk); sock_put(sk); } 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: int32 CommandBufferProxyImpl::RegisterTransferBuffer( base::SharedMemory* shared_memory, size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer( route_id_, shared_memory->handle(), // Returns FileDescriptor with auto_close off. size, id_request, &id))) { return -1; } return id; } CWE ID: Target: 1 Example 2: Code: void SimulateTab() { ui::KeyEvent pressed_tab(ui::ET_KEY_PRESSED, ui::VKEY_TAB, ui::EF_NONE); media_controls_view_->GetFocusManager()->OnKeyEvent(pressed_tab); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu, struct kvm_lapic *apic) { bool pending; int vector; /* * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host * and KVM_PV_EOI_ENABLED in guest memory as follows: * * KVM_APIC_PV_EOI_PENDING is unset: * -> host disabled PV EOI. * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set: * -> host enabled PV EOI, guest did not execute EOI yet. * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset: * -> host enabled PV EOI, guest executed EOI. */ BUG_ON(!pv_eoi_enabled(vcpu)); pending = pv_eoi_get_pending(vcpu); /* * Clear pending bit in any case: it will be set again on vmentry. * While this might not be ideal from performance point of view, * this makes sure pv eoi is only enabled when we know it's safe. */ pv_eoi_clr_pending(vcpu); if (pending) return; vector = apic_set_eoi(apic); trace_kvm_pv_eoi(apic, vector); } 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: pdf_load_xobject(fz_context *ctx, pdf_document *doc, pdf_obj *dict) { pdf_xobject *form; if ((form = pdf_find_item(ctx, pdf_drop_xobject_imp, dict)) != NULL) return form; form->iteration = 0; /* Store item immediately, to avoid possible recursion if objects refer back to this one */ pdf_store_item(ctx, dict, form, pdf_xobject_size(form)); form->obj = pdf_keep_obj(ctx, dict); return form; } CWE ID: CWE-20 Target: 1 Example 2: Code: UWORD8 ih264d_is_end_of_pic(UWORD16 u2_frame_num, UWORD8 u1_nal_ref_idc, pocstruct_t *ps_cur_poc, pocstruct_t *ps_prev_poc, dec_slice_params_t * ps_prev_slice, /*!< Previous slice parameters*/ UWORD8 u1_pic_order_cnt_type, UWORD8 u1_nal_unit_type, UWORD32 u4_idr_pic_id, UWORD8 u1_field_pic_flag, UWORD8 u1_bottom_field_flag) { WORD8 i1_is_end_of_pic; WORD8 a, b, c, d, e, f, g, h; a = b = c = d = e = f = g = h = 0; a = (ps_prev_slice->u2_frame_num != u2_frame_num); b = (ps_prev_slice->u1_field_pic_flag != u1_field_pic_flag); if(u1_field_pic_flag && ps_prev_slice->u1_field_pic_flag) c = (u1_bottom_field_flag != ps_prev_slice->u1_bottom_field_flag); d = (u1_nal_ref_idc == 0 && ps_prev_slice->u1_nal_ref_idc != 0) || (u1_nal_ref_idc != 0 && ps_prev_slice->u1_nal_ref_idc == 0); if(!a) { if((u1_pic_order_cnt_type == 0) && (ps_prev_slice->u1_pic_order_cnt_type == 0)) { e = ((ps_cur_poc->i4_pic_order_cnt_lsb != ps_prev_poc->i4_pic_order_cnt_lsb) || (ps_cur_poc->i4_delta_pic_order_cnt_bottom != ps_prev_poc->i4_delta_pic_order_cnt_bottom)); } if((u1_pic_order_cnt_type == 1) && (ps_prev_slice->u1_pic_order_cnt_type == 1)) { f = ((ps_cur_poc->i4_delta_pic_order_cnt[0] != ps_prev_poc->i4_delta_pic_order_cnt[0]) || (ps_cur_poc->i4_delta_pic_order_cnt[1] != ps_prev_poc->i4_delta_pic_order_cnt[1])); } } if((u1_nal_unit_type == IDR_SLICE_NAL) && (ps_prev_slice->u1_nal_unit_type == IDR_SLICE_NAL)) { g = (u4_idr_pic_id != ps_prev_slice->u4_idr_pic_id); } if((u1_nal_unit_type == IDR_SLICE_NAL) && (ps_prev_slice->u1_nal_unit_type != IDR_SLICE_NAL)) { h = 1; } i1_is_end_of_pic = a + b + c + d + e + f + g + h; return (i1_is_end_of_pic); } 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 afiucv_hs_callback_synack(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); struct af_iucv_trans_hdr *trans_hdr = (struct af_iucv_trans_hdr *)skb->data; if (!iucv) goto out; if (sk->sk_state != IUCV_BOUND) goto out; bh_lock_sock(sk); iucv->msglimit_peer = trans_hdr->window; sk->sk_state = IUCV_CONNECTED; sk->sk_state_change(sk); bh_unlock_sock(sk); out: kfree_skb(skb); return NET_RX_SUCCESS; } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { struct bpf_verifier_state *cur = env->cur_state; struct bpf_verifier_stack_elem *elem; int err; elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); if (!elem) goto err; elem->insn_idx = insn_idx; elem->prev_insn_idx = prev_insn_idx; elem->next = env->head; env->head = elem; env->stack_size++; err = copy_verifier_state(&elem->st, cur); if (err) goto err; if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { verbose(env, "BPF program is too complex\n"); goto err; } return &elem->st; err: free_verifier_state(env->cur_state, true); env->cur_state = NULL; /* pop all elements and return */ while (!pop_stack(env, NULL, NULL)); return NULL; } CWE ID: CWE-189 Target: 1 Example 2: Code: OVS_REQUIRES(ofproto_mutex) { if (group_collection_n(groups) > 0) { if (group_collection_n(groups) == 1) { ovsrcu_postpone(remove_group_rcu, group_collection_groups(groups)[0]); group_collection_init(groups); } else { ovsrcu_postpone(remove_groups_rcu, group_collection_detach(groups)); } } } CWE ID: CWE-617 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: v8::Handle<v8::Value> V8TestObj::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); if (args.Length() <= 0 || !args[0]->IsFunction()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); RefPtr<TestCallback> testCallback = V8TestCallback::create(args[0], getScriptExecutionContext()); RefPtr<TestObj> impl = TestObj::create(testCallback); v8::Handle<v8::Object> wrapper = args.Holder(); V8DOMWrapper::setDOMWrapper(wrapper, &info, impl.get()); V8DOMWrapper::setJSWrapperForDOMObject(impl.release(), v8::Persistent<v8::Object>::New(wrapper), args.GetIsolate()); return args.Holder(); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: nvmet_fc_find_target_queue(struct nvmet_fc_tgtport *tgtport, u64 connection_id) { struct nvmet_fc_tgt_assoc *assoc; struct nvmet_fc_tgt_queue *queue; u64 association_id = nvmet_fc_getassociationid(connection_id); u16 qid = nvmet_fc_getqueueid(connection_id); unsigned long flags; spin_lock_irqsave(&tgtport->lock, flags); list_for_each_entry(assoc, &tgtport->assoc_list, a_list) { if (association_id == assoc->association_id) { queue = assoc->queues[qid]; if (queue && (!atomic_read(&queue->connected) || !nvmet_fc_tgt_q_get(queue))) queue = NULL; spin_unlock_irqrestore(&tgtport->lock, flags); return queue; } } spin_unlock_irqrestore(&tgtport->lock, flags); return NULL; } CWE ID: CWE-119 Target: 1 Example 2: Code: ScriptPromise ReadableStream::cancel(ScriptState* scriptState, ScriptValue reason) { if (m_reader) return ScriptPromise::reject(scriptState, V8ThrowException::createTypeError(scriptState->isolate(), "this stream is locked to a ReadableStreamReader")); setIsDisturbed(); if (m_state == Closed) return ScriptPromise::castUndefined(scriptState); if (m_state == Errored) return ScriptPromise::rejectWithDOMException(scriptState, m_exception); return cancelInternal(scriptState, reason); } 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: image_transform_png_set_background_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* Check for tRNS first: */ if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE) image_pixel_add_alpha(that, &display->this); /* This is only necessary if the alpha value is less than 1. */ if (that->alphaf < 1) { /* Now we do the background calculation without any gamma correction. */ if (that->alphaf <= 0) { that->redf = data.redf; that->greenf = data.greenf; that->bluef = data.bluef; that->rede = data.rede; that->greene = data.greene; that->bluee = data.bluee; that->red_sBIT= data.red_sBIT; that->green_sBIT= data.green_sBIT; that->blue_sBIT= data.blue_sBIT; } else /* 0 < alpha < 1 */ { double alf = 1 - that->alphaf; that->redf = that->redf * that->alphaf + data.redf * alf; that->rede = that->rede * that->alphaf + data.rede * alf + DBL_EPSILON; that->greenf = that->greenf * that->alphaf + data.greenf * alf; that->greene = that->greene * that->alphaf + data.greene * alf + DBL_EPSILON; that->bluef = that->bluef * that->alphaf + data.bluef * alf; that->bluee = that->bluee * that->alphaf + data.bluee * alf + DBL_EPSILON; } /* Remove the alpha type and set the alpha (not in that order.) */ that->alphaf = 1; that->alphae = 0; if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) that->colour_type = PNG_COLOR_TYPE_RGB; else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) that->colour_type = PNG_COLOR_TYPE_GRAY; /* PNG_COLOR_TYPE_PALETTE is not changed */ } this->next->mod(this->next, that, pp, display); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool Cues::Find(long long time_ns, const Track* pTrack, const CuePoint*& pCP, const CuePoint::TrackPosition*& pTP) const { assert(time_ns >= 0); assert(pTrack); #if 0 LoadCuePoint(); //establish invariant assert(m_cue_points); assert(m_count > 0); CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count + m_preload_count; CuePoint** j = jj; pCP = *i; assert(pCP); if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL); } IMkvReader* const pReader = m_pSegment->m_pReader; while (i < j) { CuePoint** const k = i + (j - i) / 2; assert(k < jj); CuePoint* const pCP = *k; assert(pCP); pCP->Load(pReader); const long long t = pCP->GetTime(m_pSegment); if (t <= time_ns) i = k + 1; else j = k; assert(i <= j); } assert(i == j); assert(i <= jj); assert(i > ii); pCP = *--i; assert(pCP); assert(pCP->GetTime(m_pSegment) <= time_ns); #else if (m_cue_points == NULL) return false; if (m_count == 0) return false; CuePoint** const ii = m_cue_points; CuePoint** i = ii; CuePoint** const jj = ii + m_count; CuePoint** j = jj; pCP = *i; assert(pCP); if (time_ns <= pCP->GetTime(m_pSegment)) { pTP = pCP->Find(pTrack); return (pTP != NULL); } while (i < j) { CuePoint** const k = i + (j - i) / 2; assert(k < jj); CuePoint* const pCP = *k; assert(pCP); const long long t = pCP->GetTime(m_pSegment); if (t <= time_ns) i = k + 1; else j = k; assert(i <= j); } assert(i == j); assert(i <= jj); assert(i > ii); pCP = *--i; assert(pCP); assert(pCP->GetTime(m_pSegment) <= time_ns); #endif pTP = pCP->Find(pTrack); return (pTP != NULL); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void nonpaging_new_cr3(struct kvm_vcpu *vcpu) { mmu_free_roots(vcpu); } 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 FragmentPaintPropertyTreeBuilder::UpdatePaintOffsetTranslation( const base::Optional<IntPoint>& paint_offset_translation) { DCHECK(properties_); if (paint_offset_translation) { TransformPaintPropertyNode::State state; state.matrix.Translate(paint_offset_translation->X(), paint_offset_translation->Y()); state.flattens_inherited_transform = context_.current.should_flatten_inherited_transform; if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled() || RuntimeEnabledFeatures::BlinkGenPropertyTreesEnabled()) state.rendering_context_id = context_.current.rendering_context_id; OnUpdate(properties_->UpdatePaintOffsetTranslation( context_.current.transform, std::move(state))); context_.current.transform = properties_->PaintOffsetTranslation(); if (object_.IsLayoutView()) { context_.absolute_position.transform = properties_->PaintOffsetTranslation(); context_.fixed_position.transform = properties_->PaintOffsetTranslation(); } } else { OnClear(properties_->ClearPaintOffsetTranslation()); } } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } CWE ID: CWE-369 Target: 1 Example 2: Code: int Element::offsetLeft() { document()->updateLayoutIgnorePendingStylesheets(); if (RenderBoxModelObject* renderer = renderBoxModelObject()) return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer); return 0; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int mem_resize(jas_stream_memobj_t *m, int bufsize) { unsigned char *buf; assert(m->buf_); assert(bufsize >= 0); if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char)))) { return -1; } m->buf_ = buf; m->bufsize_ = bufsize; return 0; } CWE ID: CWE-415 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int validation_gamma(int argc, char **argv) { double gamma[9] = { 2.2, 1.8, 1.52, 1.45, 1., 1/1.45, 1/1.52, 1/1.8, 1/2.2 }; double maxerr; int i, silent=0, onlygamma=0; /* Silence the output with -s, just test the gamma functions with -g: */ while (--argc > 0) if (strcmp(*++argv, "-s") == 0) silent = 1; else if (strcmp(*argv, "-g") == 0) onlygamma = 1; else { fprintf(stderr, "unknown argument %s\n", *argv); return 1; } if (!onlygamma) { /* First validate the log functions: */ maxerr = 0; for (i=0; i<256; ++i) { double correct = -log(i/255.)/log(2.)*65536; double error = png_log8bit(i) - correct; if (i != 0 && fabs(error) > maxerr) maxerr = fabs(error); if (i == 0 && png_log8bit(i) != 0xffffffff || i != 0 && png_log8bit(i) != floor(correct+.5)) { fprintf(stderr, "8 bit log error: %d: got %u, expected %f\n", i, png_log8bit(i), correct); } } if (!silent) printf("maximum 8 bit log error = %f\n", maxerr); maxerr = 0; for (i=0; i<65536; ++i) { double correct = -log(i/65535.)/log(2.)*65536; double error = png_log16bit(i) - correct; if (i != 0 && fabs(error) > maxerr) maxerr = fabs(error); if (i == 0 && png_log16bit(i) != 0xffffffff || i != 0 && png_log16bit(i) != floor(correct+.5)) { if (error > .68) /* By experiment error is less than .68 */ { fprintf(stderr, "16 bit log error: %d: got %u, expected %f" " error: %f\n", i, png_log16bit(i), correct, error); } } } if (!silent) printf("maximum 16 bit log error = %f\n", maxerr); /* Now exponentiations. */ maxerr = 0; for (i=0; i<=0xfffff; ++i) { double correct = exp(-i/65536. * log(2.)) * (65536. * 65536); double error = png_exp(i) - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (fabs(error) > 1883) /* By experiment. */ { fprintf(stderr, "32 bit exp error: %d: got %u, expected %f" " error: %f\n", i, png_exp(i), correct, error); } } if (!silent) printf("maximum 32 bit exp error = %f\n", maxerr); maxerr = 0; for (i=0; i<=0xfffff; ++i) { double correct = exp(-i/65536. * log(2.)) * 255; double error = png_exp8bit(i) - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (fabs(error) > .50002) /* By experiment */ { fprintf(stderr, "8 bit exp error: %d: got %u, expected %f" " error: %f\n", i, png_exp8bit(i), correct, error); } } if (!silent) printf("maximum 8 bit exp error = %f\n", maxerr); maxerr = 0; for (i=0; i<=0xfffff; ++i) { double correct = exp(-i/65536. * log(2.)) * 65535; double error = png_exp16bit(i) - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (fabs(error) > .524) /* By experiment */ { fprintf(stderr, "16 bit exp error: %d: got %u, expected %f" " error: %f\n", i, png_exp16bit(i), correct, error); } } if (!silent) printf("maximum 16 bit exp error = %f\n", maxerr); } /* !onlygamma */ /* Test the overall gamma correction. */ for (i=0; i<9; ++i) { unsigned j; double g = gamma[i]; png_fixed_point gfp = floor(g * PNG_FP_1 + .5); if (!silent) printf("Test gamma %f\n", g); maxerr = 0; for (j=0; j<256; ++j) { double correct = pow(j/255., g) * 255; png_byte out = png_gamma_8bit_correct(j, gfp); double error = out - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (out != floor(correct+.5)) { fprintf(stderr, "8bit %d ^ %f: got %d expected %f error %f\n", j, g, out, correct, error); } } if (!silent) printf("gamma %f: maximum 8 bit error %f\n", g, maxerr); maxerr = 0; for (j=0; j<65536; ++j) { double correct = pow(j/65535., g) * 65535; png_uint_16 out = png_gamma_16bit_correct(j, gfp); double error = out - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (fabs(error) > 1.62) { fprintf(stderr, "16bit %d ^ %f: got %d expected %f error %f\n", j, g, out, correct, error); } } if (!silent) printf("gamma %f: maximum 16 bit error %f\n", g, maxerr); } return 0; } CWE ID: Target: 1 Example 2: Code: static void cleanup_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root, int err) { struct btrfs_transaction *cur_trans = trans->transaction; WARN_ON(trans->use_count > 1); btrfs_abort_transaction(trans, root, err); spin_lock(&root->fs_info->trans_lock); list_del_init(&cur_trans->list); if (cur_trans == root->fs_info->running_transaction) { root->fs_info->running_transaction = NULL; root->fs_info->trans_no_join = 0; } spin_unlock(&root->fs_info->trans_lock); btrfs_cleanup_one_transaction(trans->transaction, root); put_transaction(cur_trans); put_transaction(cur_trans); trace_btrfs_transaction_commit(root); btrfs_scrub_continue(root); if (current->journal_info == trans) current->journal_info = NULL; kmem_cache_free(btrfs_trans_handle_cachep, trans); } CWE ID: CWE-310 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline int check_pmd_range(struct vm_area_struct *vma, pud_t *pud, unsigned long addr, unsigned long end, const nodemask_t *nodes, unsigned long flags, void *private) { pmd_t *pmd; unsigned long next; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); split_huge_page_pmd(vma->vm_mm, pmd); if (pmd_none_or_clear_bad(pmd)) continue; if (check_pte_range(vma, pmd, addr, next, nodes, flags, private)) return -EIO; } while (pmd++, addr = next, addr != end); return 0; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sgi_clock_get(clockid_t clockid, struct timespec *tp) { u64 nsec; nsec = rtc_time() * sgi_clock_period + sgi_clock_offset.tv_nsec; tp->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tp->tv_nsec) + sgi_clock_offset.tv_sec; return 0; }; CWE ID: CWE-189 Target: 1 Example 2: Code: std::unique_ptr<WebContents> WebContents::CreateWithSessionStorage( const WebContents::CreateParams& params, const SessionStorageNamespaceMap& session_storage_namespace_map) { std::unique_ptr<WebContentsImpl> new_contents( new WebContentsImpl(params.browser_context)); RenderFrameHostImpl* opener_rfh = FindOpenerRFH(params); FrameTreeNode* opener = nullptr; if (opener_rfh) opener = opener_rfh->frame_tree_node(); new_contents->SetOpenerForNewContents(opener, params.opener_suppressed); for (SessionStorageNamespaceMap::const_iterator it = session_storage_namespace_map.begin(); it != session_storage_namespace_map.end(); ++it) { new_contents->GetController() .SetSessionStorageNamespace(it->first, it->second.get()); } if (params.guest_delegate) { BrowserPluginGuest::Create(new_contents.get(), params.guest_delegate); } new_contents->Init(params); return new_contents; } 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: bool asn1_write_OctetString(struct asn1_data *data, const void *p, size_t length) { asn1_push_tag(data, ASN1_OCTET_STRING); asn1_write(data, p, length); asn1_pop_tag(data); return !data->has_error; } 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 handle_packet(unsigned char *data, int data_len) { struct mt_mactelnet_hdr pkthdr; /* Minimal size checks (pings are not supported here) */ if (data_len < MT_HEADER_LEN){ return -1; } parse_packet(data, &pkthdr); /* We only care about packets with correct sessionkey */ if (pkthdr.seskey != sessionkey) { return -1; } /* Handle data packets */ if (pkthdr.ptype == MT_PTYPE_DATA) { struct mt_packet odata; struct mt_mactelnet_control_hdr cpkt; int success = 0; /* Always transmit ACKNOWLEDGE packets in response to DATA packets */ init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, pkthdr.counter + (data_len - MT_HEADER_LEN)); send_udp(&odata, 0); /* Accept first packet, and all packets greater than incounter, and if counter has wrapped around. */ if (pkthdr.counter > incounter || (incounter - pkthdr.counter) > 65535) { incounter = pkthdr.counter; } else { /* Ignore double or old packets */ return -1; } /* Parse controlpacket data */ success = parse_control_packet(data + MT_HEADER_LEN, data_len - MT_HEADER_LEN, &cpkt); while (success) { /* If we receive pass_salt, transmit auth data back */ if (cpkt.cptype == MT_CPTYPE_PASSSALT) { memcpy(pass_salt, cpkt.data, cpkt.length); send_auth(username, password); } /* If the (remaining) data did not have a control-packet magic byte sequence, the data is raw terminal data to be outputted to the terminal. */ else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) { fwrite((const void *)cpkt.data, 1, cpkt.length, stdout); } /* END_AUTH means that the user/password negotiation is done, and after this point terminal data may arrive, so we set up the terminal to raw mode. */ else if (cpkt.cptype == MT_CPTYPE_END_AUTH) { /* we have entered "terminal mode" */ terminal_mode = 1; if (is_a_tty) { /* stop input buffering at all levels. Give full control of terminal to RouterOS */ raw_term(); setvbuf(stdin, (char*)NULL, _IONBF, 0); /* Add resize signal handler */ signal(SIGWINCH, sig_winch); } } /* Parse next controlpacket */ success = parse_control_packet(NULL, 0, &cpkt); } } else if (pkthdr.ptype == MT_PTYPE_ACK) { /* Handled elsewhere */ } /* The server wants to terminate the connection, we have to oblige */ else if (pkthdr.ptype == MT_PTYPE_END) { struct mt_packet odata; /* Acknowledge the disconnection by sending a END packet in return */ init_packet(&odata, MT_PTYPE_END, srcmac, dstmac, pkthdr.seskey, 0); send_udp(&odata, 0); if (!quiet_mode) { fprintf(stderr, _("Connection closed.\n")); } /* exit */ running = 0; } else { fprintf(stderr, _("Unhandeled packet type: %d received from server %s\n"), pkthdr.ptype, ether_ntoa((struct ether_addr *)dstmac)); return -1; } return pkthdr.ptype; } CWE ID: CWE-119 Target: 1 Example 2: Code: BGD_DECLARE(gdImagePtr) gdImageClone (gdImagePtr src) { gdImagePtr dst; register int i, x; if (src->trueColor) { dst = gdImageCreateTrueColor(src->sx , src->sy); } else { dst = gdImageCreate(src->sx , src->sy); } if (dst == NULL) { return NULL; } if (src->trueColor == 0) { dst->colorsTotal = src->colorsTotal; for (i = 0; i < gdMaxColors; i++) { dst->red[i] = src->red[i]; dst->green[i] = src->green[i]; dst->blue[i] = src->blue[i]; dst->alpha[i] = src->alpha[i]; dst->open[i] = src->open[i]; } for (i = 0; i < src->sy; i++) { for (x = 0; x < src->sx; x++) { dst->pixels[i][x] = src->pixels[i][x]; } } } else { for (i = 0; i < src->sy; i++) { for (x = 0; x < src->sx; x++) { dst->tpixels[i][x] = src->tpixels[i][x]; } } } if (src->styleLength > 0) { dst->styleLength = src->styleLength; dst->stylePos = src->stylePos; for (i = 0; i < src->styleLength; i++) { dst->style[i] = src->style[i]; } } dst->interlace = src->interlace; dst->alphaBlendingFlag = src->alphaBlendingFlag; dst->saveAlphaFlag = src->saveAlphaFlag; dst->AA = src->AA; dst->AA_color = src->AA_color; dst->AA_dont_blend = src->AA_dont_blend; dst->cx1 = src->cx1; dst->cy1 = src->cy1; dst->cx2 = src->cx2; dst->cy2 = src->cy2; dst->res_x = src->res_x; dst->res_y = src->res_x; dst->paletteQuantizationMethod = src->paletteQuantizationMethod; dst->paletteQuantizationSpeed = src->paletteQuantizationSpeed; dst->paletteQuantizationMinQuality = src->paletteQuantizationMinQuality; dst->paletteQuantizationMinQuality = src->paletteQuantizationMinQuality; dst->interpolation_id = src->interpolation_id; dst->interpolation = src->interpolation; if (src->brush) { dst->brush = gdImageClone(src->brush); } if (src->tile) { dst->tile = gdImageClone(src->tile); } if (src->style) { gdImageSetStyle(dst, src->style, src->styleLength); } for (i = 0; i < gdMaxColors; i++) { dst->brushColorMap[i] = src->brushColorMap[i]; dst->tileColorMap[i] = src->tileColorMap[i]; } if (src->polyAllocated > 0) { dst->polyAllocated = src->polyAllocated; for (i = 0; i < src->polyAllocated; i++) { dst->polyInts[i] = src->polyInts[i]; } } return dst; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool RenderThreadImpl::OnControlMessageReceived(const IPC::Message& msg) { ObserverListBase<RenderProcessObserver>::Iterator it(observers_); RenderProcessObserver* observer; while ((observer = it.GetNext()) != NULL) { if (observer->OnControlMessageReceived(msg)) return true; } if (appcache_dispatcher_->OnMessageReceived(msg) || dom_storage_dispatcher_->OnMessageReceived(msg) || embedded_worker_dispatcher_->OnMessageReceived(msg)) { return true; } bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderThreadImpl, msg) IPC_MESSAGE_HANDLER(FrameMsg_NewFrame, OnCreateNewFrame) IPC_MESSAGE_HANDLER(FrameMsg_NewFrameProxy, OnCreateNewFrameProxy) IPC_MESSAGE_HANDLER(ViewMsg_SetZoomLevelForCurrentURL, OnSetZoomLevelForCurrentURL) IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView) IPC_MESSAGE_HANDLER(ViewMsg_NetworkTypeChanged, OnNetworkTypeChanged) IPC_MESSAGE_HANDLER(ViewMsg_TempCrashWithData, OnTempCrashWithData) IPC_MESSAGE_HANDLER(WorkerProcessMsg_CreateWorker, OnCreateNewSharedWorker) IPC_MESSAGE_HANDLER(ViewMsg_TimezoneChange, OnUpdateTimezone) #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(ViewMsg_SetWebKitSharedTimersSuspended, OnSetWebKitSharedTimersSuspended) #endif #if defined(OS_MACOSX) IPC_MESSAGE_HANDLER(ViewMsg_UpdateScrollbarTheme, OnUpdateScrollbarTheme) #endif #if defined(ENABLE_PLUGINS) IPC_MESSAGE_HANDLER(ViewMsg_PurgePluginListCache, OnPurgePluginListCache) #endif IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } 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: virtual void ResetModel() { last_pts_ = 0; bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz; frame_number_ = 0; first_drop_ = 0; bits_total_ = 0; duration_ = 0.0; } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderView::OnDelete() { if (!webview()) return; webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Delete")); } 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 WebContentsImpl::ClearFocusedElement() { if (auto* frame = GetFocusedFrame()) frame->ClearFocusedElement(); } 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 AutoFillMetrics::Log(QualityMetric metric) const { DCHECK(metric < NUM_QUALITY_METRICS); UMA_HISTOGRAM_ENUMERATION("AutoFill.Quality", metric, NUM_QUALITY_METRICS); } CWE ID: CWE-399 Target: 1 Example 2: Code: bool Document::setFocusedNode(PassRefPtr<Node> prpNewFocusedNode, FocusDirection direction) { RefPtr<Node> newFocusedNode = prpNewFocusedNode; if (newFocusedNode && (newFocusedNode->document() != this)) return true; if (m_focusedNode == newFocusedNode) return true; if (m_inPageCache) return false; bool focusChangeBlocked = false; RefPtr<Node> oldFocusedNode = m_focusedNode; m_focusedNode = 0; if (oldFocusedNode) { ASSERT(!oldFocusedNode->inDetach()); if (oldFocusedNode->active()) oldFocusedNode->setActive(false); oldFocusedNode->setFocus(false); if (oldFocusedNode->isElementNode()) { Element* element = toElement(oldFocusedNode.get()); if (element->wasChangedSinceLastFormControlChangeEvent()) element->dispatchFormControlChangeEvent(); } oldFocusedNode->dispatchBlurEvent(newFocusedNode); if (m_focusedNode) { focusChangeBlocked = true; newFocusedNode = 0; } oldFocusedNode->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedNode); // DOM level 3 name for the bubbling blur event. oldFocusedNode->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedNode); // DOM level 2 name for compatibility. if (m_focusedNode) { focusChangeBlocked = true; newFocusedNode = 0; } if (oldFocusedNode == this && oldFocusedNode->hasOneRef()) return true; if (oldFocusedNode->isRootEditableElement()) frame()->editor()->didEndEditing(); if (view()) { Widget* oldWidget = widgetForNode(oldFocusedNode.get()); if (oldWidget) oldWidget->setFocus(false); else view()->setFocus(false); } } if (newFocusedNode && (newFocusedNode->isPluginElement() || newFocusedNode->isFocusable())) { if (newFocusedNode->isRootEditableElement() && !acceptsEditingFocus(newFocusedNode.get())) { focusChangeBlocked = true; goto SetFocusedNodeDone; } m_focusedNode = newFocusedNode; m_focusedNode->dispatchFocusEvent(oldFocusedNode, direction); if (m_focusedNode != newFocusedNode) { focusChangeBlocked = true; goto SetFocusedNodeDone; } m_focusedNode->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedNode); // DOM level 3 bubbling focus event. if (m_focusedNode != newFocusedNode) { focusChangeBlocked = true; goto SetFocusedNodeDone; } m_focusedNode->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedNode); // DOM level 2 for compatibility. if (m_focusedNode != newFocusedNode) { focusChangeBlocked = true; goto SetFocusedNodeDone; } m_focusedNode->setFocus(true); if (m_focusedNode->isRootEditableElement()) frame()->editor()->didBeginEditing(); if (view()) { Widget* focusWidget = widgetForNode(m_focusedNode.get()); if (focusWidget) { updateLayout(); focusWidget = widgetForNode(m_focusedNode.get()); } if (focusWidget) focusWidget->setFocus(true); else view()->setFocus(true); } } if (!focusChangeBlocked && m_focusedNode) { if (AXObjectCache* cache = axObjectCache()) cache->handleFocusedUIElementChanged(oldFocusedNode.get(), newFocusedNode.get()); } if (!focusChangeBlocked) page()->chrome()->focusedNodeChanged(m_focusedNode.get()); SetFocusedNodeDone: updateStyleIfNeeded(); return !focusChangeBlocked; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void a2dp_open_ctrl_path(struct a2dp_stream_common *common) { int i; /* retry logic to catch any timing variations on control channel */ for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) { /* connect control channel if not already connected */ if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0) { /* success, now check if stack is ready */ if (check_a2dp_ready(common) == 0) break; ERROR("error : a2dp not ready, wait 250 ms and retry"); usleep(250000); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; } /* ctrl channel not ready, wait a bit */ usleep(250000); } } 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: bool AXObject::isLiveRegion() const { const AtomicString& liveRegion = liveRegionStatus(); return equalIgnoringCase(liveRegion, "polite") || equalIgnoringCase(liveRegion, "assertive"); } CWE ID: CWE-254 Target: 1 Example 2: Code: static int mxf_parse_handle_partition_or_eof(MXFContext *mxf) { return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1; } CWE ID: CWE-834 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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::SlideAnimation* GetBackgroundViewAnimationForWindow( int grid_index, aura::Window* window) { return GetWindowItemForWindow(grid_index, window) ->GetBackgroundViewAnimation(); } 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 GDataFileSystem::OnSearch(const SearchCallback& callback, GetDocumentsParams* params, GDataFileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error != GDATA_FILE_OK) { if (!callback.is_null()) callback.Run(error, GURL(), scoped_ptr<std::vector<SearchResultInfo> >()); return; } std::vector<SearchResultInfo>* results(new std::vector<SearchResultInfo>()); DCHECK_EQ(1u, params->feed_list->size()); DocumentFeed* feed = params->feed_list->at(0); GURL next_feed; feed->GetNextFeedURL(&next_feed); if (feed->entries().empty()) { scoped_ptr<std::vector<SearchResultInfo> > result_vec(results); if (!callback.is_null()) callback.Run(error, next_feed, result_vec.Pass()); return; } for (size_t i = 0; i < feed->entries().size(); ++i) { DocumentEntry* doc = const_cast<DocumentEntry*>(feed->entries()[i]); scoped_ptr<GDataEntry> entry( GDataEntry::FromDocumentEntry(NULL, doc, directory_service_.get())); if (!entry.get()) continue; DCHECK_EQ(doc->resource_id(), entry->resource_id()); DCHECK(!entry->is_deleted()); std::string entry_resource_id = entry->resource_id(); if (entry->AsGDataFile()) { scoped_ptr<GDataFile> entry_as_file(entry.release()->AsGDataFile()); directory_service_->RefreshFile(entry_as_file.Pass()); DCHECK(!entry.get()); } directory_service_->GetEntryByResourceIdAsync(entry_resource_id, base::Bind(&AddEntryToSearchResults, results, callback, base::Bind(&GDataFileSystem::CheckForUpdates, ui_weak_ptr_), error, i+1 == feed->entries().size(), next_feed)); } } CWE ID: CWE-399 Target: 1 Example 2: Code: static int cine_read_probe(AVProbeData *p) { int HeaderSize; if (p->buf[0] == 'C' && p->buf[1] == 'I' && // Type (HeaderSize = AV_RL16(p->buf + 2)) >= 0x2C && // HeaderSize AV_RL16(p->buf + 4) <= CC_UNINT && // Compression AV_RL16(p->buf + 6) <= 1 && // Version AV_RL32(p->buf + 20) && // ImageCount AV_RL32(p->buf + 24) >= HeaderSize && // OffImageHeader AV_RL32(p->buf + 28) >= HeaderSize && // OffSetup AV_RL32(p->buf + 32) >= HeaderSize) // OffImageOffsets return AVPROBE_SCORE_MAX; return 0; } CWE ID: CWE-834 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 WaitUntilSatisfied() { if (!was_observed_) message_loop_runner_->Run(); if (observer_.IsObserving(render_widget_)) observer_.Remove(render_widget_); return !did_fail_; } 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: OMX_ERRORTYPE SoftAACEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.aac", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mBitRate = aacParams->nBitRate; mNumChannels = aacParams->nChannels; mSampleRate = aacParams->nSampleRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: GF_Err audio_sample_entry_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s; e = gf_isom_box_write_header(s, bs); if (e) return e; gf_isom_audio_sample_entry_write((GF_AudioSampleEntryBox*)s, bs); if (ptr->esd) { e = gf_isom_box_write((GF_Box *)ptr->esd, bs); if (e) return e; } if (ptr->cfg_3gpp) { e = gf_isom_box_write((GF_Box *)ptr->cfg_3gpp, bs); if (e) return e; } if (ptr->cfg_ac3) { e = gf_isom_box_write((GF_Box *)ptr->cfg_ac3, bs); if (e) return e; } return gf_isom_box_array_write(s, ptr->protections, bs); } 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: String AXLayoutObject::textAlternative(bool recursive, bool inAriaLabelledByTraversal, AXObjectSet& visited, AXNameFrom& nameFrom, AXRelatedObjectVector* relatedObjects, NameSources* nameSources) const { if (m_layoutObject) { String textAlternative; bool foundTextAlternative = false; if (m_layoutObject->isBR()) { textAlternative = String("\n"); foundTextAlternative = true; } else if (m_layoutObject->isText() && (!recursive || !m_layoutObject->isCounter())) { LayoutText* layoutText = toLayoutText(m_layoutObject); String result = layoutText->plainText(); if (!result.isEmpty() || layoutText->isAllCollapsibleWhitespace()) textAlternative = result; else textAlternative = layoutText->text(); foundTextAlternative = true; } else if (m_layoutObject->isListMarker() && !recursive) { textAlternative = toLayoutListMarker(m_layoutObject)->text(); foundTextAlternative = true; } if (foundTextAlternative) { nameFrom = AXNameFromContents; if (nameSources) { nameSources->push_back(NameSource(false)); nameSources->back().type = nameFrom; nameSources->back().text = textAlternative; } return textAlternative; } } return AXNodeObject::textAlternative(recursive, inAriaLabelledByTraversal, visited, nameFrom, relatedObjects, nameSources); } CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int decode_bit_string(const u8 * inbuf, size_t inlen, void *outbuf, size_t outlen, int invert) { const u8 *in = inbuf; u8 *out = (u8 *) outbuf; int zero_bits = *in & 0x07; size_t octets_left = inlen - 1; int i, count = 0; memset(outbuf, 0, outlen); in++; if (outlen < octets_left) return SC_ERROR_BUFFER_TOO_SMALL; if (inlen < 1) return SC_ERROR_INVALID_ASN1_OBJECT; while (octets_left) { /* 1st octet of input: ABCDEFGH, where A is the MSB */ /* 1st octet of output: HGFEDCBA, where A is the LSB */ /* first bit in bit string is the LSB in first resulting octet */ int bits_to_go; *out = 0; if (octets_left == 1) bits_to_go = 8 - zero_bits; else bits_to_go = 8; if (invert) for (i = 0; i < bits_to_go; i++) { *out |= ((*in >> (7 - i)) & 1) << i; } else { *out = *in; } out++; in++; octets_left--; count++; } return (count * 8) - zero_bits; } CWE ID: CWE-119 Target: 1 Example 2: Code: void CE_CharToWide(char *str, unsigned short *w_str) { MultiByteToWideChar(CP_ACP, 0, str, -1, w_str, GF_MAX_PATH); } 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 BrowserEventRouter::TabUpdated(WebContents* contents, bool did_navigate) { TabEntry* entry = GetTabEntry(contents); DictionaryValue* changed_properties = NULL; DCHECK(entry); if (did_navigate) changed_properties = entry->DidNavigate(contents); else changed_properties = entry->UpdateLoadState(contents); if (changed_properties) DispatchTabUpdatedEvent(contents, changed_properties); } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void perform_gamma_scale16_tests(png_modifier *pm) { # ifndef PNG_MAX_GAMMA_8 # define PNG_MAX_GAMMA_8 11 # endif # define SBIT_16_TO_8 PNG_MAX_GAMMA_8 /* Include the alpha cases here. Note that sbit matches the internal value * used by the library - otherwise we will get spurious errors from the * internal sbit style approximation. * * The threshold test is here because otherwise the 16 to 8 conversion will * proceed *without* gamma correction, and the tests above will fail (but not * by much) - this could be fixed, it only appears with the -g option. */ unsigned int i, j; for (i=0; i<pm->ngamma_tests; ++i) { for (j=0; j<pm->ngamma_tests; ++j) { if (i != j && fabs(pm->gammas[j]/pm->gammas[i]-1) >= PNG_GAMMA_THRESHOLD) { gamma_transform_test(pm, 0, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 2, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 4, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; gamma_transform_test(pm, 6, 16, 0, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], SBIT_16_TO_8, pm->use_input_precision_16to8, 1 /*scale16*/); if (fail(pm)) return; } } } } CWE ID: Target: 1 Example 2: Code: Element* FrameSelection::RootEditableElementOrDocumentElement() const { Element* selection_root = ComputeVisibleSelectionInDOMTreeDeprecated().RootEditableElement(); return selection_root ? selection_root : GetDocument().documentElement(); } 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 RTCPeerConnectionHandlerChromium::setLocalDescription(PassRefPtr<RTCVoidRequest> request, PassRefPtr<RTCSessionDescriptionDescriptor> sessionDescription) { if (!m_webHandler) return; m_webHandler->setLocalDescription(request, sessionDescription); } 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: grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, struct grub_ext4_extent_header *ext_block, grub_uint32_t fileblock) { struct grub_ext4_extent_idx *index; while (1) { int i; grub_disk_addr_t block; index = (struct grub_ext4_extent_idx *) (ext_block + 1); if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC) return 0; if (ext_block->depth == 0) return ext_block; for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++) { if (fileblock < grub_le_to_cpu32(index[i].block)) break; } if (--i < 0) return 0; block = grub_le_to_cpu16 (index[i].leaf_hi); block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); if (grub_disk_read (data->disk, block << LOG2_EXT2_BLOCK_SIZE (data), 0, EXT2_BLOCK_SIZE(data), buf)) return 0; ext_block = (struct grub_ext4_extent_header *) buf; } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void fatal_jpeg_error (j_common_ptr cinfo) { jmpbuf_wrapper *jmpbufw; char buffer[JMSG_LENGTH_MAX]; (*cinfo->err->format_message)(cinfo, buffer); gd_error_ex(GD_WARNING, "gd-jpeg: JPEG library reports unrecoverable error: %s", buffer); jmpbufw = (jmpbuf_wrapper *) cinfo->client_data; jpeg_destroy (cinfo); if (jmpbufw != 0) { longjmp (jmpbufw->jmpbuf, 1); gd_error_ex(GD_ERROR, "gd-jpeg: EXTREMELY fatal error: longjmp returned control; terminating"); } else { gd_error_ex(GD_ERROR, "gd-jpeg: EXTREMELY fatal error: jmpbuf unrecoverable; terminating"); } exit (99); } 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: status_t OMXNodeInstance::getConfig( OMX_INDEXTYPE index, void *params, size_t /* size */) { Mutex::Autolock autoLock(mLock); OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; if (err != OMX_ErrorNoMore) { CLOG_IF_ERROR(getConfig, err, "%s(%#x)", asString(extIndex), index); } return StatusFromOMXError(err); } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: GF_Err gf_sm_load_init(GF_SceneLoader *load) { GF_Err e = GF_NOT_SUPPORTED; char *ext, szExt[50]; /*we need at least a scene graph*/ if (!load || (!load->ctx && !load->scene_graph) #ifndef GPAC_DISABLE_ISOM || (!load->fileName && !load->isom && !(load->flags & GF_SM_LOAD_FOR_PLAYBACK) ) #endif ) return GF_BAD_PARAM; if (!load->type) { #ifndef GPAC_DISABLE_ISOM if (load->isom) { load->type = GF_SM_LOAD_MP4; } else #endif { ext = (char *)strrchr(load->fileName, '.'); if (!ext) return GF_NOT_SUPPORTED; if (!stricmp(ext, ".gz")) { char *anext; ext[0] = 0; anext = (char *)strrchr(load->fileName, '.'); ext[0] = '.'; ext = anext; } strcpy(szExt, &ext[1]); strlwr(szExt); if (strstr(szExt, "bt")) load->type = GF_SM_LOAD_BT; else if (strstr(szExt, "wrl")) load->type = GF_SM_LOAD_VRML; else if (strstr(szExt, "x3dv")) load->type = GF_SM_LOAD_X3DV; #ifndef GPAC_DISABLE_LOADER_XMT else if (strstr(szExt, "xmt") || strstr(szExt, "xmta")) load->type = GF_SM_LOAD_XMTA; else if (strstr(szExt, "x3d")) load->type = GF_SM_LOAD_X3D; #endif else if (strstr(szExt, "swf")) load->type = GF_SM_LOAD_SWF; else if (strstr(szExt, "mov")) load->type = GF_SM_LOAD_QT; else if (strstr(szExt, "svg")) load->type = GF_SM_LOAD_SVG; else if (strstr(szExt, "xsr")) load->type = GF_SM_LOAD_XSR; else if (strstr(szExt, "xbl")) load->type = GF_SM_LOAD_XBL; else if (strstr(szExt, "xml")) { char *rtype = gf_xml_get_root_type(load->fileName, &e); if (rtype) { if (!strcmp(rtype, "SAFSession")) load->type = GF_SM_LOAD_XSR; else if (!strcmp(rtype, "XMT-A")) load->type = GF_SM_LOAD_XMTA; else if (!strcmp(rtype, "X3D")) load->type = GF_SM_LOAD_X3D; else if (!strcmp(rtype, "bindings")) load->type = GF_SM_LOAD_XBL; gf_free(rtype); } } } } if (!load->type) return e; if (!load->scene_graph) load->scene_graph = load->ctx->scene_graph; switch (load->type) { #ifndef GPAC_DISABLE_LOADER_BT case GF_SM_LOAD_BT: case GF_SM_LOAD_VRML: case GF_SM_LOAD_X3DV: return gf_sm_load_init_bt(load); #endif #ifndef GPAC_DISABLE_LOADER_XMT case GF_SM_LOAD_XMTA: case GF_SM_LOAD_X3D: return gf_sm_load_init_xmt(load); #endif #ifndef GPAC_DISABLE_SVG case GF_SM_LOAD_SVG: case GF_SM_LOAD_XSR: case GF_SM_LOAD_DIMS: return gf_sm_load_init_svg(load); case GF_SM_LOAD_XBL: e = gf_sm_load_init_xbl(load); load->process = gf_sm_load_run_xbl; load->done = gf_sm_load_done_xbl; return e; #endif #ifndef GPAC_DISABLE_SWF_IMPORT case GF_SM_LOAD_SWF: return gf_sm_load_init_swf(load); #endif #ifndef GPAC_DISABLE_LOADER_ISOM case GF_SM_LOAD_MP4: return gf_sm_load_init_isom(load); #endif #ifndef GPAC_DISABLE_QTVR case GF_SM_LOAD_QT: return gf_sm_load_init_qt(load); #endif default: return GF_NOT_SUPPORTED; } return GF_NOT_SUPPORTED; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void withScriptStateObjMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); ScriptState* currentState = ScriptState::current(); if (!currentState) return; ScriptState& state = *currentState; RefPtr<TestObject> result = imp->withScriptStateObj(&state); if (state.hadException()) { v8::Local<v8::Value> exception = state.exception(); state.clearException(); throwError(exception, info.GetIsolate()); return; } v8SetReturnValue(info, result.release()); } 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 php_handler(request_rec *r) { php_struct * volatile ctx; void *conf; apr_bucket_brigade * volatile brigade; apr_bucket *bucket; apr_status_t rv; request_rec * volatile parent_req = NULL; TSRMLS_FETCH(); #define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC); conf = ap_get_module_config(r->per_dir_config, &php5_module); /* apply_config() needs r in some cases, so allocate server_context early */ ctx = SG(server_context); if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) { normal: ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx)); /* register a cleanup so we clear out the SG(server_context) * after each request. Note: We pass in the pointer to the * server_context in case this is handled by a different thread. */ apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null); ctx->r = r; ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */ } else { parent_req = ctx->r; ctx->r = r; } apply_config(conf); if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) { /* Check for xbithack in this case. */ if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) { PHPAP_INI_OFF; return DECLINED; } } /* Give a 404 if PATH_INFO is used but is explicitly disabled in * the configuration; default behaviour is to accept. */ if (r->used_path_info == AP_REQ_REJECT_PATH_INFO && r->path_info && r->path_info[0]) { PHPAP_INI_OFF; return HTTP_NOT_FOUND; } /* handle situations where user turns the engine off */ if (!AP2(engine)) { PHPAP_INI_OFF; return DECLINED; } if (r->finfo.filetype == 0) { php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC); PHPAP_INI_OFF; return HTTP_NOT_FOUND; } if (r->finfo.filetype == APR_DIR) { php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC); PHPAP_INI_OFF; return HTTP_FORBIDDEN; } /* Setup the CGI variables if this is the main request */ if (r->main == NULL || /* .. or if the sub-request environment differs from the main-request. */ r->subprocess_env != r->main->subprocess_env ) { /* setup standard CGI variables */ ap_add_common_vars(r); ap_add_cgi_vars(r); } zend_first_try { if (ctx == NULL) { brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc); ctx = SG(server_context); ctx->brigade = brigade; if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) { zend_bailout(); } } else { if (!parent_req) { parent_req = ctx->r; } if (parent_req && parent_req->handler && strcmp(parent_req->handler, PHP_MAGIC_TYPE) && strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(parent_req->handler, PHP_SCRIPT)) { if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) { zend_bailout(); } } /* * check if coming due to ErrorDocument * We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs * during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting * PHP instance to handle the request rather then creating a new one. */ if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) { parent_req = NULL; goto normal; } ctx->r = r; brigade = ctx->brigade; } if (AP2(last_modified)) { ap_update_mtime(r, r->finfo.mtime); ap_set_last_modified(r); } /* Determine if we need to parse the file or show the source */ if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) { zend_syntax_highlighter_ini syntax_highlighter_ini; php_get_highlight_struct(&syntax_highlighter_ini); highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC); } else { zend_file_handle zfd; zfd.type = ZEND_HANDLE_FILENAME; zfd.filename = (char *) r->filename; zfd.free_filename = 0; zfd.opened_path = NULL; if (!parent_req) { php_execute_script(&zfd TSRMLS_CC); } else { zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd); } apr_table_set(r->notes, "mod_php_memory_usage", apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC))); } } zend_end_try(); if (!parent_req) { php_apache_request_dtor(r TSRMLS_CC); ctx->request_processed = 1; bucket = apr_bucket_eos_create(r->connection->bucket_alloc); APR_BRIGADE_INSERT_TAIL(brigade, bucket); rv = ap_pass_brigade(r->output_filters, brigade); if (rv != APR_SUCCESS || r->connection->aborted) { zend_first_try { php_handle_aborted_connection(); } zend_end_try(); } apr_brigade_cleanup(brigade); apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup); } else { ctx->r = parent_req; } return OK; } 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: SPL_METHOD(SplFileObject, hasChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool SplFileObject::getChildren() CWE ID: CWE-190 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoReleaseShaderCompiler() { api()->glReleaseShaderCompilerFn(); return error::kNoError; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: const char* menu_cache_app_get_exec( MenuCacheApp* app ) { return app->exec; } 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: uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); return MP4buffer; } } return NULL; } CWE ID: CWE-787 Target: 1 Example 2: Code: void ATSParser::Stream::signalEOS(status_t finalResult) { if (mSource != NULL) { mSource->signalEOS(finalResult); } mEOSReached = true; flush(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: static inline bool is_invalid_opcode(u32 intr_info) { return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK | INTR_INFO_VALID_MASK)) == (INTR_TYPE_HARD_EXCEPTION | UD_VECTOR | INTR_INFO_VALID_MASK); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, "\r\n"); line; line = strtok(NULL, "\r\n")) { if (!strncmp(line, "export ", 7)) continue; val = strchr(line, '='); if (!val) { printf("invalid configuration line\n"); break; } *val++ = '\0'; if (!strcmp(line, "JSON_INDENT")) conf.indent = atoi(val); if (!strcmp(line, "JSON_COMPACT")) conf.compact = atoi(val); if (!strcmp(line, "JSON_ENSURE_ASCII")) conf.ensure_ascii = atoi(val); if (!strcmp(line, "JSON_PRESERVE_ORDER")) conf.preserve_order = atoi(val); if (!strcmp(line, "JSON_SORT_KEYS")) conf.sort_keys = atoi(val); if (!strcmp(line, "STRIP")) conf.strip = atoi(val); } free(buffer); } CWE ID: CWE-310 Target: 1 Example 2: Code: int SpeechRecognitionManagerImpl::CreateSession( const SpeechRecognitionSessionConfig& config) { DCHECK_CURRENTLY_ON(BrowserThread::IO); const int session_id = GetNextSessionID(); DCHECK(!SessionExists(session_id)); auto session = std::make_unique<Session>(); session->id = session_id; session->config = config; session->context = config.initial_context; #if !defined(OS_ANDROID) SpeechRecognitionEngine::Config remote_engine_config; remote_engine_config.language = config.language; remote_engine_config.grammars = config.grammars; remote_engine_config.audio_sample_rate = SpeechRecognizerImpl::kAudioSampleRate; remote_engine_config.audio_num_bits_per_sample = SpeechRecognizerImpl::kNumBitsPerAudioSample; remote_engine_config.filter_profanities = config.filter_profanities; remote_engine_config.continuous = config.continuous; remote_engine_config.interim_results = config.interim_results; remote_engine_config.max_hypotheses = config.max_hypotheses; remote_engine_config.origin_url = config.origin.Serialize(); remote_engine_config.auth_token = config.auth_token; remote_engine_config.auth_scope = config.auth_scope; remote_engine_config.preamble = config.preamble; SpeechRecognitionEngine* google_remote_engine = new SpeechRecognitionEngine( config.shared_url_loader_factory, config.accept_language); google_remote_engine->SetConfig(remote_engine_config); session->recognizer = new SpeechRecognizerImpl( this, audio_system_, session_id, config.continuous, config.interim_results, google_remote_engine); #else session->recognizer = new SpeechRecognizerImplAndroid(this, session_id); #endif sessions_[session_id] = std::move(session); base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI}) ->PostTask( FROM_HERE, base::BindOnce(&SpeechRecognitionManagerImpl::FrameDeletionObserver:: CreateObserverForSession, base::Unretained(frame_deletion_observer_.get()), config.initial_context.render_process_id, config.initial_context.render_frame_id, session_id)); return session_id; } 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 dns_hostname_validation(const char *string, char **err) { const char *c, *d; int i; if (strlen(string) > DNS_MAX_NAME_SIZE) { if (err) *err = DNS_TOO_LONG_FQDN; return 0; } c = string; while (*c) { d = c; i = 0; while (*d != '.' && *d && i <= DNS_MAX_LABEL_SIZE) { i++; if (!((*d == '-') || (*d == '_') || ((*d >= 'a') && (*d <= 'z')) || ((*d >= 'A') && (*d <= 'Z')) || ((*d >= '0') && (*d <= '9')))) { if (err) *err = DNS_INVALID_CHARACTER; return 0; } d++; } if ((i >= DNS_MAX_LABEL_SIZE) && (d[i] != '.')) { if (err) *err = DNS_LABEL_TOO_LONG; return 0; } if (*d == '\0') goto out; c = ++d; } out: return 1; } 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 rndis_set_response(USBNetState *s, rndis_set_msg_type *buf, unsigned int length) { rndis_set_cmplt_type *resp = rndis_queue_response(s, sizeof(rndis_set_cmplt_type)); uint32_t bufoffs, buflen; int ret; if (!resp) return USB_RET_STALL; bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8; buflen = le32_to_cpu(buf->InformationBufferLength); if (bufoffs + buflen > length) return USB_RET_STALL; ret = ndis_set(s, le32_to_cpu(buf->OID), bufoffs + (uint8_t *) buf, buflen); resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type)); if (ret < 0) { /* OID not supported */ resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED); return 0; } resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS); return 0; } CWE ID: CWE-189 Target: 1 Example 2: Code: static HB_Error Load_Mark2Array( HB_Mark2Array* m2a, HB_UShort num_classes, HB_Stream stream ) { HB_Error error; HB_UShort m, n, count; HB_UInt cur_offset, new_offset, base_offset; HB_Mark2Record *m2r; HB_Anchor *m2an, *m2ans; base_offset = FILE_Pos(); if ( ACCESS_Frame( 2L ) ) return error; count = m2a->Mark2Count = GET_UShort(); FORGET_Frame(); m2a->Mark2Record = NULL; if ( ALLOC_ARRAY( m2a->Mark2Record, count, HB_Mark2Record ) ) return error; m2r = m2a->Mark2Record; m2ans = NULL; if ( ALLOC_ARRAY( m2ans, count * num_classes, HB_Anchor ) ) goto Fail; for ( m = 0; m < count; m++ ) { m2an = m2r[m].Mark2Anchor = m2ans + m * num_classes; for ( n = 0; n < num_classes; n++ ) { if ( ACCESS_Frame( 2L ) ) goto Fail; new_offset = GET_UShort() + base_offset; FORGET_Frame(); if (new_offset == base_offset) { /* Anchor table not provided. Skip loading. * Some versions of FreeSans hit this. */ m2an[n].PosFormat = 0; continue; } cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = Load_Anchor( &m2an[n], stream ) ) != HB_Err_Ok ) goto Fail; (void)FILE_Seek( cur_offset ); } } return HB_Err_Ok; Fail: FREE( m2ans ); FREE( m2r ); return error; } 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: hook_print (struct t_weechat_plugin *plugin, struct t_gui_buffer *buffer, const char *tags, const char *message, int strip_colors, t_hook_callback_print *callback, void *callback_data) { struct t_hook *new_hook; struct t_hook_print *new_hook_print; if (!callback) return NULL; new_hook = malloc (sizeof (*new_hook)); if (!new_hook) return NULL; new_hook_print = malloc (sizeof (*new_hook_print)); if (!new_hook_print) { rc = (int) (HOOK_CONNECT(ptr_hook, gnutls_cb)) (ptr_hook->callback_data, tls_session, req_ca, nreq, pk_algos, pk_algos_len, answer); break; } ptr_hook = ptr_hook->next_hook; new_hook->hook_data = new_hook_print; new_hook_print->callback = callback; new_hook_print->buffer = buffer; if (tags) { new_hook_print->tags_array = string_split (tags, ",", 0, 0, &new_hook_print->tags_count); } else { new_hook_print->tags_count = 0; new_hook_print->tags_array = NULL; } new_hook_print->message = (message) ? strdup (message) : NULL; new_hook_print->strip_colors = strip_colors; hook_add_to_list (new_hook); return new_hook; } 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: base::string16 GetAppForProtocolUsingRegistry(const GURL& url) { base::string16 command_to_launch; base::string16 cmd_key_path = base::ASCIIToUTF16(url.scheme()); base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS && !command_to_launch.empty()) { return command_to_launch; } cmd_key_path = base::ASCIIToUTF16(url.scheme() + "\\shell\\open\\command"); base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); return command_line.GetProgram().BaseName().value(); } return base::string16(); } CWE ID: CWE-20 Target: 1 Example 2: Code: static void *fb_seq_next(struct seq_file *m, void *v, loff_t *pos) { (*pos)++; return (*pos < FB_MAX) ? pos : NULL; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(locale_get_display_name) { get_icu_disp_value_src_php( DISP_NAME , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p\n", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err("Underflows must be unconditional and " "use the STANDARD target with " "ACCEPT/DROP\n"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: void OxideQQuickWebViewPrivate::setLocationBarAnimated(bool animated) { if (!proxy_) { construct_props_->location_bar_animated = animated; } else { proxy_->setLocationBarAnimated(animated); } } 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: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet( icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;" "[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;" "[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;" "[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;" "ұ > y; [χҳӽӿ] > x;" "ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;" "[зӡ] > 3"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } 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: virtual void TreeNodesRemoved(TreeModel* model, TreeModelNode* parent, int start, int count) { removed_count_++; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void fuse_request_init(struct fuse_req *req, struct page **pages, struct fuse_page_desc *page_descs, unsigned npages) { INIT_LIST_HEAD(&req->list); INIT_LIST_HEAD(&req->intr_entry); init_waitqueue_head(&req->waitq); refcount_set(&req->count, 1); req->pages = pages; req->page_descs = page_descs; req->max_pages = npages; __set_bit(FR_PENDING, &req->flags); } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(mcrypt_create_iv) { char *iv; long source = RANDOM; long size; int n = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &size, &source) == FAILURE) { return; } if (size <= 0 || size >= INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create an IV with a size of less than 1 or greater than %d", INT_MAX); RETURN_FALSE; } iv = ecalloc(size + 1, 1); if (source == RANDOM || source == URANDOM) { #if PHP_WIN32 /* random/urandom equivalent on Windows */ BYTE *iv_b = (BYTE *) iv; if (php_win32_get_random_bytes(iv_b, (size_t) size) == FAILURE){ efree(iv); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data"); RETURN_FALSE; } n = size; #else int *fd = &MCG(fd[source]); size_t read_bytes = 0; if (*fd < 0) { *fd = open(source == RANDOM ? "/dev/random" : "/dev/urandom", O_RDONLY); if (*fd < 0) { efree(iv); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot open source device"); RETURN_FALSE; } } while (read_bytes < size) { n = read(*fd, iv + read_bytes, size - read_bytes); if (n < 0) { break; } read_bytes += n; } n = read_bytes; if (n < size) { efree(iv); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data"); RETURN_FALSE; } #endif } else { n = size; while (size) { iv[--size] = (char) (255.0 * php_rand(TSRMLS_C) / RAND_MAX); } } RETURN_STRINGL(iv, n, 0); } 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: AudioOutputAuthorizationHandlerTest() { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kUseFakeDeviceForMediaStream); thread_bundle_ = base::MakeUnique<TestBrowserThreadBundle>( TestBrowserThreadBundle::Options::REAL_IO_THREAD); audio_thread_ = base::MakeUnique<AudioManagerThread>(); audio_manager_.reset(new media::FakeAudioManager( audio_thread_->task_runner(), audio_thread_->worker_task_runner(), &log_factory_)); media_stream_manager_ = base::MakeUnique<MediaStreamManager>(audio_manager_.get()); SyncWithAllThreads(); } CWE ID: Target: 1 Example 2: Code: ImageManager* image_manager() { return group_->image_manager(); } 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: FileReaderLoader::~FileReaderLoader() { Cleanup(); UnadjustReportedMemoryUsageToV8(); } 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 ChromeNetworkDelegate::AccumulateContentLength( int64 received_content_length, int64 original_content_length, bool via_data_reduction_proxy) { DCHECK_GE(received_content_length, 0); DCHECK_GE(original_content_length, 0); StoreAccumulatedContentLength(received_content_length, original_content_length, via_data_reduction_proxy); received_content_length_ += received_content_length; original_content_length_ += original_content_length; } CWE ID: CWE-416 Target: 1 Example 2: Code: static void des_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src) { struct des_sparc64_ctx *ctx = crypto_tfm_ctx(tfm); const u64 *K = ctx->decrypt_expkey; des_sparc64_crypt(K, (const u64 *) src, (u64 *) dst); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool set_off_slab_cache(struct kmem_cache *cachep, size_t size, unsigned long flags) { size_t left; cachep->num = 0; /* * Always use on-slab management when SLAB_NOLEAKTRACE * to avoid recursive calls into kmemleak. */ if (flags & SLAB_NOLEAKTRACE) return false; /* * Size is large, assume best to place the slab management obj * off-slab (should allow better packing of objs). */ left = calculate_slab_order(cachep, size, flags | CFLGS_OFF_SLAB); if (!cachep->num) return false; /* * If the slab has been placed off-slab, and we have enough space then * move it on-slab. This is at the expense of any extra colouring. */ if (left >= cachep->num * sizeof(freelist_idx_t)) return false; cachep->colour = left / cachep->colour_off; return true; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int fpga_reset(void) { if (!check_boco2()) { /* we do not have BOCO2, this is not really used */ return 0; } printf("PCIe reset through GPIO7: "); /* apply PCIe reset via GPIO */ kw_gpio_set_valid(KM_PEX_RST_GPIO_PIN, 1); kw_gpio_direction_output(KM_PEX_RST_GPIO_PIN, 1); kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 0); udelay(1000*10); kw_gpio_set_value(KM_PEX_RST_GPIO_PIN, 1); printf(" done\n"); return 0; } CWE ID: CWE-787 Target: 1 Example 2: Code: v8::Handle<v8::Value> V8WebGLRenderingContext::getSupportedExtensionsCallback(const v8::Arguments& args) { INC_STATS("DOM.WebGLRenderingContext.getSupportedExtensionsCallback()"); WebGLRenderingContext* imp = V8WebGLRenderingContext::toNative(args.Holder()); if (imp->isContextLost()) return v8::Null(); Vector<String> value = imp->getSupportedExtensions(); v8::Local<v8::Array> array = v8::Array::New(value.size()); for (size_t ii = 0; ii < value.size(); ++ii) array->Set(v8::Integer::New(ii), v8::String::New(fromWebCoreString(value[ii]), value[ii].length())); return array; } 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 TabStrip::ChangeTabGroup(int model_index, base::Optional<int> old_group, base::Optional<int> new_group) { if (new_group.has_value() && !group_headers_[new_group.value()]) { const TabGroupData* group_data = controller_->GetDataForGroup(new_group.value()); auto header = std::make_unique<TabGroupHeader>(group_data->title()); header->set_owned_by_client(); AddChildView(header.get()); group_headers_[new_group.value()] = std::move(header); } if (old_group.has_value() && controller_->ListTabsInGroup(old_group.value()).size() == 0) { group_headers_.erase(old_group.value()); } UpdateIdealBounds(); AnimateToIdealBounds(); } 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: bool PaymentRequest::SatisfiesSkipUIConstraints() const { return base::FeatureList::IsEnabled(features::kWebPaymentsSingleAppUiSkip) && base::FeatureList::IsEnabled(::features::kServiceWorkerPaymentApps) && is_show_user_gesture_ && state()->is_get_all_instruments_finished() && state()->available_instruments().size() == 1 && spec()->stringified_method_data().size() == 1 && !spec()->request_shipping() && !spec()->request_payer_name() && !spec()->request_payer_phone() && !spec()->request_payer_email() && spec()->url_payment_method_identifiers().size() == 1; } CWE ID: CWE-189 Target: 1 Example 2: Code: static int futex_wait_setup(u32 __user *uaddr, u32 val, int fshared, struct futex_q *q, struct futex_hash_bucket **hb) { u32 uval; int ret; /* * Access the page AFTER the hash-bucket is locked. * Order is important: * * Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val); * Userspace waker: if (cond(var)) { var = new; futex_wake(&var); } * * The basic logical guarantee of a futex is that it blocks ONLY * if cond(var) is known to be true at the time of blocking, for * any cond. If we queued after testing *uaddr, that would open * a race condition where we could block indefinitely with * cond(var) false, which would violate the guarantee. * * A consequence is that futex_wait() can return zero and absorb * a wakeup when *uaddr != val on entry to the syscall. This is * rare, but normal. */ retry: q->key = FUTEX_KEY_INIT; ret = get_futex_key(uaddr, fshared, &q->key); if (unlikely(ret != 0)) return ret; retry_private: *hb = queue_lock(q); ret = get_futex_value_locked(&uval, uaddr); if (ret) { queue_unlock(q, *hb); ret = get_user(uval, uaddr); if (ret) goto out; if (!fshared) goto retry_private; put_futex_key(fshared, &q->key); goto retry; } if (uval != val) { queue_unlock(q, *hb); ret = -EWOULDBLOCK; } out: if (ret) put_futex_key(fshared, &q->key); 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: void RendererSchedulerImpl::ResumeTimersForAndroidWebView() { main_thread_only().pause_timers_for_webview = false; UpdatePolicy(); } 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: png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { png_size_t copy = output_size - count; if ((png_size_t) avail < copy) copy = (png_size_t) avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = "Buffer error in compressed datastream in %s chunk"; break; case Z_DATA_ERROR: msg = "Data error in compressed datastream in %s chunk"; break; default: msg = "Incomplete compressed datastream in %s chunk"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = "Damaged compressed datastream in chunk other than IDAT"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } } CWE ID: CWE-119 Target: 1 Example 2: Code: PHP_FUNCTION(openssl_pkey_new) { struct php_x509_request req; zval * args = NULL; zval *data; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a!", &args) == FAILURE) { return; } RETVAL_FALSE; if (args && Z_TYPE_P(args) == IS_ARRAY) { EVP_PKEY *pkey; if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "rsa", sizeof("rsa")-1)) != NULL && Z_TYPE_P(data) == IS_ARRAY) { pkey = EVP_PKEY_new(); if (pkey) { RSA *rsa = RSA_new(); if (rsa) { if (php_openssl_pkey_init_and_assign_rsa(pkey, rsa, data)) { RETURN_RES(zend_register_resource(pkey, le_key)); } RSA_free(rsa); } else { php_openssl_store_errors(); } EVP_PKEY_free(pkey); } else { php_openssl_store_errors(); } RETURN_FALSE; } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "dsa", sizeof("dsa") - 1)) != NULL && Z_TYPE_P(data) == IS_ARRAY) { pkey = EVP_PKEY_new(); if (pkey) { DSA *dsa = DSA_new(); if (dsa) { if (php_openssl_pkey_init_dsa(dsa, data)) { if (EVP_PKEY_assign_DSA(pkey, dsa)) { RETURN_RES(zend_register_resource(pkey, le_key)); } else { php_openssl_store_errors(); } } DSA_free(dsa); } else { php_openssl_store_errors(); } EVP_PKEY_free(pkey); } else { php_openssl_store_errors(); } RETURN_FALSE; } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "dh", sizeof("dh") - 1)) != NULL && Z_TYPE_P(data) == IS_ARRAY) { pkey = EVP_PKEY_new(); if (pkey) { DH *dh = DH_new(); if (dh) { if (php_openssl_pkey_init_dh(dh, data)) { if (EVP_PKEY_assign_DH(pkey, dh)) { ZVAL_COPY_VALUE(return_value, zend_list_insert(pkey, le_key)); return; } else { php_openssl_store_errors(); } } DH_free(dh); } else { php_openssl_store_errors(); } EVP_PKEY_free(pkey); } else { php_openssl_store_errors(); } RETURN_FALSE; #ifdef HAVE_EVP_PKEY_EC } else if ((data = zend_hash_str_find(Z_ARRVAL_P(args), "ec", sizeof("ec") - 1)) != NULL && Z_TYPE_P(data) == IS_ARRAY) { EC_KEY *eckey = NULL; EC_GROUP *group = NULL; EC_POINT *pnt = NULL; const BIGNUM *d; pkey = EVP_PKEY_new(); if (pkey) { eckey = EC_KEY_new(); if (eckey) { EC_GROUP *group = NULL; zval *bn; zval *x; zval *y; if ((bn = zend_hash_str_find(Z_ARRVAL_P(data), "curve_name", sizeof("curve_name") - 1)) != NULL && Z_TYPE_P(bn) == IS_STRING) { int nid = OBJ_sn2nid(Z_STRVAL_P(bn)); if (nid != NID_undef) { group = EC_GROUP_new_by_curve_name(nid); if (!group) { php_openssl_store_errors(); goto clean_exit; } EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE); EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED); if (!EC_KEY_set_group(eckey, group)) { php_openssl_store_errors(); goto clean_exit; } } } if (group == NULL) { php_error_docref(NULL, E_WARNING, "Unknown curve_name"); goto clean_exit; } if ((bn = zend_hash_str_find(Z_ARRVAL_P(data), "d", sizeof("d") - 1)) != NULL && Z_TYPE_P(bn) == IS_STRING) { d = BN_bin2bn((unsigned char*) Z_STRVAL_P(bn), Z_STRLEN_P(bn), NULL); if (!EC_KEY_set_private_key(eckey, d)) { php_openssl_store_errors(); goto clean_exit; } pnt = EC_POINT_new(group); if (!pnt || !EC_POINT_mul(group, pnt, d, NULL, NULL, NULL)) { php_openssl_store_errors(); goto clean_exit; } } else if ((x = zend_hash_str_find(Z_ARRVAL_P(data), "x", sizeof("x") - 1)) != NULL && Z_TYPE_P(x) == IS_STRING && (y = zend_hash_str_find(Z_ARRVAL_P(data), "y", sizeof("y") - 1)) != NULL && Z_TYPE_P(y) == IS_STRING) { pnt = EC_POINT_new(group); if (pnt == NULL) { php_openssl_store_errors(); goto clean_exit; } if (!EC_POINT_set_affine_coordinates_GFp( group, pnt, BN_bin2bn((unsigned char*) Z_STRVAL_P(x), Z_STRLEN_P(x), NULL), BN_bin2bn((unsigned char*) Z_STRVAL_P(y), Z_STRLEN_P(y), NULL), NULL)) { php_openssl_store_errors(); goto clean_exit; } } if (pnt != NULL) { if (!EC_KEY_set_public_key(eckey, pnt)) { php_openssl_store_errors(); goto clean_exit; } EC_POINT_free(pnt); pnt = NULL; } if (!EC_KEY_check_key(eckey)) { PHP_OPENSSL_RAND_ADD_TIME(); EC_KEY_generate_key(eckey); php_openssl_store_errors(); } if (EC_KEY_check_key(eckey) && EVP_PKEY_assign_EC_KEY(pkey, eckey)) { EC_GROUP_free(group); RETURN_RES(zend_register_resource(pkey, le_key)); } else { php_openssl_store_errors(); } } else { php_openssl_store_errors(); } } else { php_openssl_store_errors(); } clean_exit: if (pnt != NULL) { EC_POINT_free(pnt); } if (group != NULL) { EC_GROUP_free(group); } if (eckey != NULL) { EC_KEY_free(eckey); } if (pkey != NULL) { EVP_PKEY_free(pkey); } RETURN_FALSE; #endif } } PHP_SSL_REQ_INIT(&req); if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) { if (php_openssl_generate_private_key(&req)) { /* pass back a key resource */ RETVAL_RES(zend_register_resource(req.priv_key, le_key)); /* make sure the cleanup code doesn't zap it! */ req.priv_key = NULL; } } PHP_SSL_REQ_DISPOSE(&req); } CWE ID: CWE-754 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 reactor_status_t run_reactor(reactor_t *reactor, int iterations) { assert(reactor != NULL); reactor->run_thread = pthread_self(); reactor->is_running = true; struct epoll_event events[MAX_EVENTS]; for (int i = 0; iterations == 0 || i < iterations; ++i) { pthread_mutex_lock(&reactor->list_lock); list_clear(reactor->invalidation_list); pthread_mutex_unlock(&reactor->list_lock); int ret; do { ret = epoll_wait(reactor->epoll_fd, events, MAX_EVENTS, -1); } while (ret == -1 && errno == EINTR); if (ret == -1) { LOG_ERROR("%s error in epoll_wait: %s", __func__, strerror(errno)); reactor->is_running = false; return REACTOR_STATUS_ERROR; } for (int j = 0; j < ret; ++j) { if (events[j].data.ptr == NULL) { eventfd_t value; eventfd_read(reactor->event_fd, &value); reactor->is_running = false; return REACTOR_STATUS_STOP; } reactor_object_t *object = (reactor_object_t *)events[j].data.ptr; pthread_mutex_lock(&reactor->list_lock); if (list_contains(reactor->invalidation_list, object)) { pthread_mutex_unlock(&reactor->list_lock); continue; } pthread_mutex_lock(&object->lock); pthread_mutex_unlock(&reactor->list_lock); reactor->object_removed = false; if (events[j].events & (EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR) && object->read_ready) object->read_ready(object->context); if (!reactor->object_removed && events[j].events & EPOLLOUT && object->write_ready) object->write_ready(object->context); pthread_mutex_unlock(&object->lock); if (reactor->object_removed) { pthread_mutex_destroy(&object->lock); osi_free(object); } } } reactor->is_running = false; return REACTOR_STATUS_DONE; } 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: alloc_limit_failure (char *fn_name, size_t size) { fprintf (stderr, "%s: Maximum allocation size exceeded " "(maxsize = %lu; size = %lu).\n", fn_name, (unsigned long)alloc_limit, (unsigned long)size); } CWE ID: CWE-190 Target: 1 Example 2: Code: static int decode_attr_symlink_support(struct xdr_stream *xdr, uint32_t *bitmap, uint32_t *res) { __be32 *p; *res = 0; if (unlikely(bitmap[0] & (FATTR4_WORD0_SYMLINK_SUPPORT - 1U))) return -EIO; if (likely(bitmap[0] & FATTR4_WORD0_SYMLINK_SUPPORT)) { p = xdr_inline_decode(xdr, 4); if (unlikely(!p)) goto out_overflow; *res = be32_to_cpup(p); bitmap[0] &= ~FATTR4_WORD0_SYMLINK_SUPPORT; } dprintk("%s: symlink support=%s\n", __func__, *res == 0 ? "false" : "true"); return 0; out_overflow: print_overflow_msg(__func__, xdr); return -EIO; } 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: long mkvparser::ParseElementHeader( IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume length of size if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; //success } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int cg_opendir(const char *path, struct fuse_file_info *fi) { struct fuse_context *fc = fuse_get_context(); const char *cgroup; struct file_info *dir_info; char *controller = NULL; if (!fc) return -EIO; if (strcmp(path, "/cgroup") == 0) { cgroup = NULL; controller = NULL; } else { controller = pick_controller_from_path(fc, path); if (!controller) return -EIO; cgroup = find_cgroup_in_path(path); if (!cgroup) { /* this is just /cgroup/controller, return its contents */ cgroup = "/"; } } if (cgroup && !fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) { return -EACCES; } /* we'll free this at cg_releasedir */ dir_info = malloc(sizeof(*dir_info)); if (!dir_info) return -ENOMEM; dir_info->controller = must_copy_string(controller); dir_info->cgroup = must_copy_string(cgroup); dir_info->type = LXC_TYPE_CGDIR; dir_info->buf = NULL; dir_info->file = NULL; dir_info->buflen = 0; fi->fh = (unsigned long)dir_info; return 0; } CWE ID: CWE-264 Target: 1 Example 2: Code: xmlCleanSpecialAttrCallback(void *payload, void *data, const xmlChar *fullname, const xmlChar *fullattr, const xmlChar *unused ATTRIBUTE_UNUSED) { xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) data; if (((long) payload) == XML_ATTRIBUTE_CDATA) { xmlHashRemoveEntry2(ctxt->attsSpecial, fullname, fullattr, NULL); } } CWE ID: CWE-611 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst)); tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_mask(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_mask(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) { tcp_v6_restore_cb(newnp->pktoptions); skb_set_owner_r(newnp->pktoptions, newsk); } } } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: tcp_listendrop(sk); return 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: void ChromeMockRenderThread::OnDidGetPrintedPagesCount( int cookie, int number_pages) { if (printer_.get()) printer_->SetPrintedPagesCount(cookie, number_pages); } CWE ID: CWE-200 Target: 1 Example 2: Code: static struct dentry *start_creating(const char *name, struct dentry *parent) { struct dentry *dentry; int error; pr_debug("debugfs: creating file '%s'\n",name); if (IS_ERR(parent)) return parent; error = simple_pin_fs(&debug_fs_type, &debugfs_mount, &debugfs_mount_count); if (error) return ERR_PTR(error); /* If the parent is not specified, we create it in the root. * We need the root dentry to do this, which is in the super * block. A pointer to that is in the struct vfsmount that we * have around. */ if (!parent) parent = debugfs_mount->mnt_root; inode_lock(d_inode(parent)); dentry = lookup_one_len(name, parent, strlen(name)); if (!IS_ERR(dentry) && d_really_is_positive(dentry)) { dput(dentry); dentry = ERR_PTR(-EEXIST); } if (IS_ERR(dentry)) { inode_unlock(d_inode(parent)); simple_release_fs(&debugfs_mount, &debugfs_mount_count); } return dentry; } 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 void markPointer(Visitor* visitor, HeapObjectHeader* header) { ASSERT(header->checkHeader()); const GCInfo* gcInfo = ThreadHeap::gcInfo(header->gcInfoIndex()); if (gcInfo->hasVTable() && !vTableInitialized(header->payload())) { visitor->markHeaderNoTracing(header); ASSERT(isUninitializedMemory(header->payload(), header->payloadSize())); } else { visitor->markHeader(header, gcInfo->m_trace); } } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int handle_vmread(struct kvm_vcpu *vcpu) { unsigned long field; u64 field_value; unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION); u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); gva_t gva = 0; if (!nested_vmx_check_permission(vcpu)) return 1; if (!nested_vmx_check_vmcs12(vcpu)) return kvm_skip_emulated_instruction(vcpu); /* Decode instruction info and find the field to read */ field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf)); /* Read the field, zero-extended to a u64 field_value */ if (vmcs12_read_any(vcpu, field, &field_value) < 0) { nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT); return kvm_skip_emulated_instruction(vcpu); } /* * Now copy part of this value to register or memory, as requested. * Note that the number of bits actually copied is 32 or 64 depending * on the guest's mode (32 or 64 bit), not on the given field's length. */ if (vmx_instruction_info & (1u << 10)) { kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf), field_value); } else { if (get_vmx_mem_address(vcpu, exit_qualification, vmx_instruction_info, true, &gva)) return 1; /* _system ok, as hardware has verified cpl=0 */ kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva, &field_value, (is_long_mode(vcpu) ? 8 : 4), NULL); } nested_vmx_succeed(vcpu); return kvm_skip_emulated_instruction(vcpu); } CWE ID: Target: 1 Example 2: Code: dwarf_elf_object_relocate_a_section(void* obj_in, Dwarf_Half section_index, Dwarf_Debug dbg, int* error) { int res = DW_DLV_ERROR; dwarf_elf_object_access_internals_t*obj = 0; struct Dwarf_Section_s * relocatablesec = 0; if (section_index == 0) { return DW_DLV_NO_ENTRY; } obj = (dwarf_elf_object_access_internals_t*)obj_in; /* The section to relocate must already be loaded into memory. */ res = find_section_to_relocate(dbg, section_index,&relocatablesec,error); if (res != DW_DLV_OK) { return res; } /* Sun and possibly others do not always set sh_link in .debug_* sections. So we cannot do full consistency checks. */ if (relocatablesec->dss_reloc_index == 0 ) { /* Something is wrong. */ *error = DW_DLE_RELOC_SECTION_MISSING_INDEX; return DW_DLV_ERROR; } /* Now load the relocations themselves. */ res = dwarf_elf_object_access_load_section(obj_in, relocatablesec->dss_reloc_index, &relocatablesec->dss_reloc_data, error); if (res != DW_DLV_OK) { return res; } /* Now get the symtab. */ if (!obj->symtab) { obj->symtab = &dbg->de_elf_symtab; obj->strtab = &dbg->de_elf_strtab; } if (obj->symtab->dss_index != relocatablesec->dss_reloc_link) { /* Something is wrong. */ *error = DW_DLE_RELOC_MISMATCH_RELOC_INDEX; return DW_DLV_ERROR; } if (obj->strtab->dss_index != obj->symtab->dss_link) { /* Something is wrong. */ *error = DW_DLE_RELOC_MISMATCH_STRTAB_INDEX; return DW_DLV_ERROR; } if (!obj->symtab->dss_data) { /* Now load the symtab */ res = dwarf_elf_object_access_load_section(obj_in, obj->symtab->dss_index, &obj->symtab->dss_data, error); if (res != DW_DLV_OK) { return res; } } if (!obj->strtab->dss_data) { /* Now load the strtab */ res = dwarf_elf_object_access_load_section(obj_in, obj->strtab->dss_index, &obj->strtab->dss_data,error); if (res != DW_DLV_OK){ return res; } } /* We have all the data we need in memory. */ res = loop_through_relocations(dbg,obj,relocatablesec,error); return res; } 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 MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } CWE ID: CWE-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 *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) { if (len > outHeader->nAllocLen) { ALOGE("memset buffer too small: got %lu, expected %zu", (unsigned long)outHeader->nAllocLen, len); android_errorWriteLog(0x534e4554, "29422022"); notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL); mSignalledError = true; return NULL; } return memset(outHeader->pBuffer, c, len); } CWE ID: CWE-264 Target: 1 Example 2: Code: reportProcessingInstruction(XML_Parser parser, const ENCODING *enc, const char *start, const char *end) { const XML_Char *target; XML_Char *data; const char *tem; if (!parser->m_processingInstructionHandler) { if (parser->m_defaultHandler) reportDefault(parser, enc, start, end); return 1; } start += enc->minBytesPerChar * 2; tem = start + XmlNameLength(enc, start); target = poolStoreString(&parser->m_tempPool, enc, start, tem); if (!target) return 0; poolFinish(&parser->m_tempPool); data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem), end - enc->minBytesPerChar*2); if (!data) return 0; normalizeLines(data); parser->m_processingInstructionHandler(parser->m_handlerArg, target, data); poolClear(&parser->m_tempPool); return 1; } CWE ID: CWE-611 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 RunScrollbarThumbDragLatencyTest() { #if !defined(OS_ANDROID) blink::WebFloatPoint scrollbar_thumb(795, 30); blink::WebMouseEvent mouse_down = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseDown, scrollbar_thumb.x, scrollbar_thumb.y, 0); mouse_down.button = blink::WebMouseEvent::Button::kLeft; mouse_down.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_down); blink::WebMouseEvent mouse_move = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseMove, scrollbar_thumb.x, scrollbar_thumb.y + 10, 0); mouse_move.button = blink::WebMouseEvent::Button::kLeft; mouse_move.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_move); RunUntilInputProcessed(GetWidgetHost()); mouse_move.SetPositionInWidget(scrollbar_thumb.x, scrollbar_thumb.y + 20); mouse_move.SetPositionInScreen(scrollbar_thumb.x, scrollbar_thumb.y + 20); GetWidgetHost()->ForwardMouseEvent(mouse_move); RunUntilInputProcessed(GetWidgetHost()); blink::WebMouseEvent mouse_up = SyntheticWebMouseEventBuilder::Build( blink::WebInputEvent::kMouseUp, scrollbar_thumb.x, scrollbar_thumb.y + 20, 0); mouse_up.button = blink::WebMouseEvent::Button::kLeft; mouse_up.SetTimeStamp(base::TimeTicks::Now()); GetWidgetHost()->ForwardMouseEvent(mouse_up); RunUntilInputProcessed(GetWidgetHost()); FetchHistogramsFromChildProcesses(); const std::string scroll_types[] = {"ScrollBegin", "ScrollUpdate"}; for (const std::string& scroll_type : scroll_types) { EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.TimeToScrollUpdateSwapBegin4")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.RendererSwapToBrowserNotified2")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.BrowserNotifiedToBeforeGpuSwap2")); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.GpuSwap2")); std::string thread_name = DoesScrollbarScrollOnMainThread() ? "Main" : "Impl"; EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.TimeToHandled2_" + thread_name)); EXPECT_TRUE(VerifyRecordedSamplesForHistogram( 1, "Event.Latency." + scroll_type + ".Scrollbar.HandledToRendererSwap2_" + thread_name)); } #endif // !defined(OS_ANDROID) } CWE ID: CWE-281 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: GesturePoint::GesturePoint() : first_touch_time_(0.0), last_touch_time_(0.0), last_tap_time_(0.0), velocity_calculator_(kBufferedPoints) { } CWE ID: CWE-20 Target: 1 Example 2: Code: static ssize_t ap_functions_show(struct device *dev, struct device_attribute *attr, char *buf) { struct ap_device *ap_dev = to_ap_dev(dev); return snprintf(buf, PAGE_SIZE, "0x%08X\n", ap_dev->functions); } 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 UsbDeviceImpl::OpenInterface(int interface_id, const OpenCallback& callback) { chromeos::PermissionBrokerClient* client = chromeos::DBusThreadManager::Get()->GetPermissionBrokerClient(); DCHECK(client) << "Could not get permission broker client."; client->RequestPathAccess( device_path_, interface_id, base::Bind(&UsbDeviceImpl::OnPathAccessRequestComplete, this, callback)); } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction) { FDrive *cur_drv = get_cur_drv(fdctrl); if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x80) { /* Command parameters done */ if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x40) { fdctrl->fifo[0] = fdctrl->fifo[1]; fdctrl->fifo[2] = 0; fdctrl->fifo[3] = 0; } } else if (fdctrl->data_len > 7) { /* ERROR */ fdctrl->fifo[0] = 0x80 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl); fdctrl_set_fifo(fdctrl, 1); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void ConvertDoubleToURational(double value, unsigned int *numerator, unsigned int *denominator) { float2urat(value, 0xFFFFFFFFU, numerator, denominator); } 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 Browser::OpenTabpose() { #if defined(OS_MACOSX) UserMetrics::RecordAction(UserMetricsAction("OpenTabpose"), profile_); window()->OpenTabpose(); #else NOTREACHED(); #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: void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan) { if (paintingDisabled()) return; m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle()))); m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, angleSpan); } CWE ID: CWE-399 Target: 1 Example 2: Code: static int prdt_tbl_entry_size(const AHCI_SG *tbl) { return (le32_to_cpu(tbl->flags_size) & AHCI_PRDT_SIZE_MASK) + 1; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes) { if (likely(i->nr_segs == 1)) { i->iov_offset += bytes; } else { const struct iovec *iov = i->iov; size_t base = i->iov_offset; while (bytes) { int copy = min(bytes, iov->iov_len - base); bytes -= copy; base += copy; if (iov->iov_len == base) { iov++; base = 0; } } i->iov = iov; i->iov_offset = base; } } 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 RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmGlobalEntry *ptr = NULL; int buflen = bin->buf->length; if (sec->payload_data + 32 > buflen) { return NULL; } if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) { return ret; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) { goto beach; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) { goto beach; } if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } r_list_append (ret, ptr); r++; } return ret; beach: free (ptr); return ret; } CWE ID: CWE-125 Target: 1 Example 2: Code: void MediaPlayerService::AudioOutput::setMinBufferCount() { char value[PROPERTY_VALUE_MAX]; if (property_get("ro.kernel.qemu", value, 0)) { mIsOnEmulator = true; mMinBufferCount = 12; // to prevent systematic buffer underrun for emulator } } 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: rpl_dio_printopt(netdissect_options *ndo, const struct rpl_dio_genoption *opt, u_int length) { if(length < RPL_DIO_GENOPTION_LEN) return; length -= RPL_DIO_GENOPTION_LEN; ND_TCHECK(opt->rpl_dio_len); while((opt->rpl_dio_type == RPL_OPT_PAD0 && (const u_char *)opt < ndo->ndo_snapend) || ND_TTEST2(*opt,(opt->rpl_dio_len+2))) { unsigned int optlen = opt->rpl_dio_len+2; if(opt->rpl_dio_type == RPL_OPT_PAD0) { optlen = 1; ND_PRINT((ndo, " opt:pad0")); } else { ND_PRINT((ndo, " opt:%s len:%u ", tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type), optlen)); if(ndo->ndo_vflag > 2) { unsigned int paylen = opt->rpl_dio_len; if(paylen > length) paylen = length; hex_print(ndo, " ", ((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */ paylen); } } opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen); length -= optlen; } return; trunc: ND_PRINT((ndo," [|truncated]")); return; } 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: status_t OMXNodeInstance::emptyBuffer( OMX::buffer_id buffer, OMX_U32 rangeOffset, OMX_U32 rangeLength, OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) { Mutex::Autolock autoLock(mLock); OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer); BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */); sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */); if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource && backup->capacity() >= sizeof(VideoNativeMetadata) && codec->capacity() >= sizeof(VideoGrallocMetadata) && ((VideoNativeMetadata *)backup->base())->eType == kMetadataBufferTypeANWBuffer) { VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base(); VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base(); CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p", backupMeta.pBuffer, backupMeta.pBuffer->handle); codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL; codecMeta.eType = kMetadataBufferTypeGrallocSource; header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0; header->nOffset = 0; } else { if (rangeOffset > header->nAllocLen || rangeLength > header->nAllocLen - rangeOffset) { CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd)); if (fenceFd >= 0) { ::close(fenceFd); } return BAD_VALUE; } header->nFilledLen = rangeLength; header->nOffset = rangeOffset; buffer_meta->CopyToOMX(header); } return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd); } CWE ID: CWE-119 Target: 1 Example 2: Code: void ndisc_send_na(struct net_device *dev, struct neighbour *neigh, const struct in6_addr *daddr, const struct in6_addr *solicited_addr, bool router, bool solicited, bool override, bool inc_opt) { struct sk_buff *skb; struct in6_addr tmpaddr; struct inet6_ifaddr *ifp; const struct in6_addr *src_addr; struct nd_msg *msg; int optlen = 0; /* for anycast or proxy, solicited_addr != src_addr */ ifp = ipv6_get_ifaddr(dev_net(dev), solicited_addr, dev, 1); if (ifp) { src_addr = solicited_addr; if (ifp->flags & IFA_F_OPTIMISTIC) override = false; inc_opt |= ifp->idev->cnf.force_tllao; in6_ifa_put(ifp); } else { if (ipv6_dev_get_saddr(dev_net(dev), dev, daddr, inet6_sk(dev_net(dev)->ipv6.ndisc_sk)->srcprefs, &tmpaddr)) return; src_addr = &tmpaddr; } if (!dev->addr_len) inc_opt = 0; if (inc_opt) optlen += ndisc_opt_addr_space(dev); skb = ndisc_alloc_skb(dev, sizeof(*msg) + optlen); if (!skb) return; msg = (struct nd_msg *)skb_put(skb, sizeof(*msg)); *msg = (struct nd_msg) { .icmph = { .icmp6_type = NDISC_NEIGHBOUR_ADVERTISEMENT, .icmp6_router = router, .icmp6_solicited = solicited, .icmp6_override = override, }, .target = *solicited_addr, }; if (inc_opt) ndisc_fill_addr_option(skb, ND_OPT_TARGET_LL_ADDR, dev->dev_addr); ndisc_send_skb(skb, daddr, src_addr); } CWE ID: CWE-17 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, pgprot_t prot) { struct mm_struct *mm = vma->vm_mm; int retval; pte_t *pte, entry; spinlock_t *ptl; retval = -ENOMEM; pte = get_locked_pte(mm, addr, &ptl); if (!pte) goto out; retval = -EBUSY; if (!pte_none(*pte)) goto out_unlock; /* Ok, finally just insert the thing.. */ entry = pte_mkspecial(pfn_pte(pfn, prot)); set_pte_at(mm, addr, pte, entry); update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */ retval = 0; out_unlock: pte_unmap_unlock(pte, ptl); out: return retval; } 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 cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np) { struct platform_device *pdev = cqspi->pdev; struct device *dev = &pdev->dev; struct cqspi_flash_pdata *f_pdata; struct spi_nor *nor; struct mtd_info *mtd; unsigned int cs; int i, ret; /* Get flash device data */ for_each_available_child_of_node(dev->of_node, np) { if (of_property_read_u32(np, "reg", &cs)) { dev_err(dev, "Couldn't determine chip select.\n"); goto err; } if (cs > CQSPI_MAX_CHIPSELECT) { dev_err(dev, "Chip select %d out of range.\n", cs); goto err; } f_pdata = &cqspi->f_pdata[cs]; f_pdata->cqspi = cqspi; f_pdata->cs = cs; ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np); if (ret) goto err; nor = &f_pdata->nor; mtd = &nor->mtd; mtd->priv = nor; nor->dev = dev; spi_nor_set_flash_node(nor, np); nor->priv = f_pdata; nor->read_reg = cqspi_read_reg; nor->write_reg = cqspi_write_reg; nor->read = cqspi_read; nor->write = cqspi_write; nor->erase = cqspi_erase; nor->prepare = cqspi_prep; nor->unprepare = cqspi_unprep; mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d", dev_name(dev), cs); if (!mtd->name) { ret = -ENOMEM; goto err; } ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD); if (ret) goto err; ret = mtd_device_register(mtd, NULL, 0); if (ret) goto err; f_pdata->registered = true; } return 0; err: for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++) if (cqspi->f_pdata[i].registered) mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd); return ret; } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline MagickBooleanType IsAuthenticPixelCache( const CacheInfo *restrict cache_info,const NexusInfo *restrict nexus_info) { MagickBooleanType status; MagickOffsetType offset; /* Does nexus pixels point directly to in-core cache pixels or is it buffered? */ if (cache_info->type == PingCache) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; status=nexus_info->pixels == (cache_info->pixels+offset) ? MagickTrue : MagickFalse; return(status); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __jfs_set_acl(tid_t tid, struct inode *inode, int type, struct posix_acl *acl) { char *ea_name; int rc; int size = 0; char *value = NULL; switch (type) { case ACL_TYPE_ACCESS: ea_name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { rc = posix_acl_equiv_mode(acl, &inode->i_mode); if (rc < 0) return rc; inode->i_ctime = CURRENT_TIME; mark_inode_dirty(inode); if (rc == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: ea_name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: return -EINVAL; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_KERNEL); if (!value) return -ENOMEM; rc = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (rc < 0) goto out; } rc = __jfs_setxattr(tid, inode, ea_name, value, size, 0); out: kfree(value); if (!rc) set_cached_acl(inode, type, acl); return rc; } CWE ID: CWE-285 Output:
1