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: mountpoint_last(struct nameidata *nd, struct path *path) { int error = 0; struct dentry *dentry; struct dentry *dir = nd->path.dentry; /* If we're in rcuwalk, drop out of it to handle last component */ if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL)) { error = -ECHILD; goto out; } } nd->flags &= ~LOOKUP_PARENT; if (unlikely(nd->last_type != LAST_NORM)) { error = handle_dots(nd, nd->last_type); if (error) goto out; dentry = dget(nd->path.dentry); goto done; } mutex_lock(&dir->d_inode->i_mutex); dentry = d_lookup(dir, &nd->last); if (!dentry) { /* * No cached dentry. Mounted dentries are pinned in the cache, * so that means that this dentry is probably a symlink or the * path doesn't actually point to a mounted dentry. */ dentry = d_alloc(dir, &nd->last); if (!dentry) { error = -ENOMEM; mutex_unlock(&dir->d_inode->i_mutex); goto out; } dentry = lookup_real(dir->d_inode, dentry, nd->flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); goto out; } } mutex_unlock(&dir->d_inode->i_mutex); done: if (!dentry->d_inode || d_is_negative(dentry)) { error = -ENOENT; dput(dentry); goto out; } path->dentry = dentry; path->mnt = mntget(nd->path.mnt); if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW)) return 1; follow_mount(path); error = 0; out: terminate_walk(nd); return error; } CWE ID: CWE-59 Target: 1 Example 2: Code: static int php_check_dots(const char *element, int n) { while (n-- > 0) if (element[n] != '.') break; return (n != -1); } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int cms_kari_set1_pkey(CMS_ContentInfo *cms, CMS_RecipientInfo *ri, EVP_PKEY *pk, X509 *cert) { int i; STACK_OF(CMS_RecipientEncryptedKey) *reks; CMS_RecipientEncryptedKey *rek; reks = CMS_RecipientInfo_kari_get0_reks(ri); for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) { int rv; rek = sk_CMS_RecipientEncryptedKey_value(reks, i); if (cert != NULL && CMS_RecipientEncryptedKey_cert_cmp(rek, cert)) continue; CMS_RecipientInfo_kari_set0_pkey(ri, pk); rv = CMS_RecipientInfo_kari_decrypt(cms, ri, rek); CMS_RecipientInfo_kari_set0_pkey(ri, NULL); if (rv > 0) return 1; return cert == NULL ? 0 : -1; } return 0; } CWE ID: CWE-311 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index, IncludePrivacySensitiveFields include_privacy_sensitive_fields) { if (!tab_strip) ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index); DictionaryValue* result = new DictionaryValue(); bool is_loading = contents->IsLoading(); result->SetInteger(keys::kIdKey, GetTabId(contents)); result->SetInteger(keys::kIndexKey, tab_index); result->SetInteger(keys::kWindowIdKey, GetWindowIdOfTab(contents)); result->SetString(keys::kStatusKey, GetTabStatusText(is_loading)); result->SetBoolean(keys::kActiveKey, tab_strip && tab_index == tab_strip->active_index()); result->SetBoolean(keys::kSelectedKey, tab_strip && tab_index == tab_strip->active_index()); result->SetBoolean(keys::kHighlightedKey, tab_strip && tab_strip->IsTabSelected(tab_index)); result->SetBoolean(keys::kPinnedKey, tab_strip && tab_strip->IsTabPinned(tab_index)); result->SetBoolean(keys::kIncognitoKey, contents->GetBrowserContext()->IsOffTheRecord()); if (include_privacy_sensitive_fields == INCLUDE_PRIVACY_SENSITIVE_FIELDS) { result->SetString(keys::kUrlKey, contents->GetURL().spec()); result->SetString(keys::kTitleKey, contents->GetTitle()); if (!is_loading) { NavigationEntry* entry = contents->GetController().GetActiveEntry(); if (entry && entry->GetFavicon().valid) result->SetString(keys::kFaviconUrlKey, entry->GetFavicon().url.spec()); } } if (tab_strip) { WebContents* opener = tab_strip->GetOpenerOfWebContentsAt(tab_index); if (opener) result->SetInteger(keys::kOpenerTabIdKey, GetTabId(opener)); } return result; } CWE ID: CWE-264 Target: 1 Example 2: Code: void WebContentsImpl::AttachInterstitialPage( InterstitialPageImpl* interstitial_page) { DCHECK(interstitial_page); render_manager_.set_interstitial_page(interstitial_page); FOR_EACH_OBSERVER(WebContentsObserver, observers_, DidAttachInterstitialPage()); } 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 TestPlaybackRate(double playback_rate, int buffer_size_in_frames, int total_frames_requested) { int initial_bytes_enqueued = bytes_enqueued_; int initial_bytes_buffered = algorithm_.bytes_buffered(); algorithm_.SetPlaybackRate(static_cast<float>(playback_rate)); scoped_array<uint8> buffer( new uint8[buffer_size_in_frames * algorithm_.bytes_per_frame()]); if (playback_rate == 0.0) { int frames_written = algorithm_.FillBuffer(buffer.get(), buffer_size_in_frames); EXPECT_EQ(0, frames_written); return; } int frames_remaining = total_frames_requested; while (frames_remaining > 0) { int frames_requested = std::min(buffer_size_in_frames, frames_remaining); int frames_written = algorithm_.FillBuffer(buffer.get(), frames_requested); CHECK_GT(frames_written, 0); CheckFakeData(buffer.get(), frames_written, playback_rate); frames_remaining -= frames_written; } int bytes_requested = total_frames_requested * algorithm_.bytes_per_frame(); int bytes_consumed = ComputeConsumedBytes(initial_bytes_enqueued, initial_bytes_buffered); if (playback_rate == 1.0) { EXPECT_EQ(bytes_requested, bytes_consumed); return; } static const double kMaxAcceptableDelta = 0.01; double actual_playback_rate = 1.0 * bytes_consumed / bytes_requested; double delta = std::abs(1.0 - (actual_playback_rate / playback_rate)); EXPECT_LE(delta, kMaxAcceptableDelta); } 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: unix_client_connect(hsm_com_client_hdl_t *hdl) { int fd, len; struct sockaddr_un unix_addr; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { return HSM_COM_ERROR; } memset(&unix_addr,0,sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; if(strlen(hdl->c_path) >= sizeof(unix_addr.sun_path)) { close(fd); return HSM_COM_PATH_ERR; } snprintf(unix_addr.sun_path, sizeof(unix_addr.sun_path), "%s", hdl->c_path); len = SUN_LEN(&unix_addr); unlink(unix_addr.sun_path); if(bind(fd, (struct sockaddr *)&unix_addr, len) < 0) { unlink(hdl->c_path); close(fd); return HSM_COM_BIND_ERR; } if(chmod(unix_addr.sun_path, S_IRWXU) < 0) { unlink(hdl->c_path); close(fd); return HSM_COM_CHMOD_ERR; } memset(&unix_addr,0,sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; strncpy(unix_addr.sun_path, hdl->s_path, sizeof(unix_addr.sun_path)); unix_addr.sun_path[sizeof(unix_addr.sun_path)-1] = 0; len = SUN_LEN(&unix_addr); if (connect(fd, (struct sockaddr *) &unix_addr, len) < 0) { unlink(hdl->c_path); close(fd); return HSM_COM_CONX_ERR; } hdl->client_fd = fd; hdl->client_state = HSM_COM_C_STATE_CT; if(unix_sck_send_conn(hdl, 2) != HSM_COM_OK) { hdl->client_state = HSM_COM_C_STATE_IN; return HSM_COM_SEND_ERR; } return HSM_COM_OK; } CWE ID: CWE-362 Target: 1 Example 2: Code: bool WebLocalFrameImpl::IsCommandEnabled(const WebString& name) const { DCHECK(GetFrame()); return GetFrame()->GetEditor().CreateCommand(name).IsEnabled(); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(openssl_random_pseudo_bytes) { long buffer_length; unsigned char *buffer = NULL; zval *zstrong_result_returned = NULL; int strong_result = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) { return; return; } if (buffer_length <= 0) { RETURN_FALSE; } if (zstrong_result_returned) { zval_dtor(zstrong_result_returned); ZVAL_BOOL(zstrong_result_returned, 0); } buffer = emalloc(buffer_length + 1); #ifdef PHP_WIN32 strong_result = 1; /* random/urandom equivalent on Windows */ if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) { efree(buffer); if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) { efree(buffer); if (zstrong_result_returned) { RETURN_FALSE; } #else if ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) { efree(buffer); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, 0); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, 0); } RETURN_FALSE; } #endif RETVAL_STRINGL((char *)buffer, buffer_length, 0); if (zstrong_result_returned) { ZVAL_BOOL(zstrong_result_returned, strong_result); } } /* }}} */ CWE ID: CWE-310 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void InsertRow(unsigned char *p,ssize_t y,Image *image, int bpp) { ExceptionInfo *exception; int bit; ssize_t x; register PixelPacket *q; IndexPacket index; register IndexPacket *indexes; exception=(&image->exception); switch (bpp) { case 1: /* Convert bitmap scanline. */ { 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-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } p++; } if (!SyncAuthenticPixels(image,exception)) break; break; } case 2: /* Convert PseudoColor scanline. */ { 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-1); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x3); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 4: /* Convert PseudoColor scanline. */ { 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-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; index=ConstrainColormapIndex(image,(*p) & 0x0f); SetPixelIndex(indexes+x+1,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; break; } case 8: /* Convert PseudoColor scanline. */ { 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++) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } break; case 24: /* Convert DirectColor scanline. */ q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } if (!SyncAuthenticPixels(image,exception)) break; break; } } CWE ID: CWE-787 Target: 1 Example 2: Code: void LoginDisplayHostWebUI::OnStartUserAdding() { DisableKeyboardOverscroll(); restore_path_ = RESTORE_ADD_USER_INTO_SESSION; if (features::IsAshInBrowserProcess()) finalize_animation_type_ = ANIMATION_ADD_USER; MultiUserWindowManager* window_manager = MultiUserWindowManager::GetInstance(); if (window_manager) window_manager->AddObserver(this); VLOG(1) << "Login WebUI >> user adding"; if (!login_window_) LoadURL(GURL(kUserAddingURL)); login_view_->set_should_emit_login_prompt_visible(false); if (features::IsAshInBrowserProcess()) { aura::Window* lock_container = ash::Shell::GetContainer( ash::Shell::GetPrimaryRootWindow(), ash::kShellWindowId_LockScreenContainersContainer); lock_container->layer()->SetOpacity(1.0); } else { NOTIMPLEMENTED(); } CreateExistingUserController(); if (!signin_screen_controller_.get()) { signin_screen_controller_.reset(new SignInScreenController(GetOobeUI())); } SetOobeProgressBarVisible(oobe_progress_bar_visible_ = false); SetStatusAreaVisible(true); existing_user_controller_->Init( user_manager::UserManager::Get()->GetUsersAllowedForMultiProfile()); CHECK(login_display_); GetOobeUI()->ShowSigninScreen(LoginScreenContext(), login_display_.get(), login_display_.get()); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual void notifyNeedPage(void* page) { #if USE(MADV_FREE_FOR_JIT_MEMORY) UNUSED_PARAM(page); #else m_reservation.commit(page, pageSize()); #endif } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { const unsigned char *pixels; Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image colormap. */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) ReadBlobStream(image,(size_t) (-(ssize_t) length) & 0x01, GetQuantumPixels(quantum_info),&count); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } CWE ID: CWE-772 Target: 1 Example 2: Code: e1000_receive(NetClientState *nc, const uint8_t *buf, size_t size) { E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque; struct e1000_rx_desc desc; dma_addr_t base; unsigned int n, rdt; uint32_t rdh_start; uint16_t vlan_special = 0; uint8_t vlan_status = 0, vlan_offset = 0; uint8_t min_buf[MIN_BUF_SIZE]; size_t desc_offset; size_t desc_size; size_t total_size; if (!(s->mac_reg[RCTL] & E1000_RCTL_EN)) return -1; /* Pad to minimum Ethernet frame length */ if (size < sizeof(min_buf)) { memcpy(min_buf, buf, size); memset(&min_buf[size], 0, sizeof(min_buf) - size); buf = min_buf; size = sizeof(min_buf); } size = sizeof(min_buf); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void timer_enter_running(Timer *t) { _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; r = manager_add_job(UNIT(t)->manager, JOB_START, UNIT_TRIGGER(UNIT(t)), JOB_REPLACE, true, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, 0); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, TIMER_FAILURE_RESOURCES); } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void usage_exit() { fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile>\n", exec_name); exit(EXIT_FAILURE); } CWE ID: CWE-119 Target: 1 Example 2: Code: Read(gfx::mojom::BufferUsageAndFormatDataView data, gfx::BufferUsageAndFormat* out) { return data.ReadUsage(&out->usage) && data.ReadFormat(&out->format); } 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 TabContentsContainerGtk::DetachTab(TabContents* tab) { gfx::NativeView widget = tab->web_contents()->GetNativeView(); if (widget) { GtkWidget* parent = gtk_widget_get_parent(widget); if (parent) { DCHECK_EQ(parent, expanded_); gtk_container_remove(GTK_CONTAINER(expanded_), widget); } } } 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: std::string DataUseUserData::GetServiceNameAsString(ServiceName service_name) { switch (service_name) { case SUGGESTIONS: return "Suggestions"; case NOT_TAGGED: return "NotTagged"; case TRANSLATE: return "Translate"; case SYNC: return "Sync"; case OMNIBOX: return "Omnibox"; case INVALIDATION: return "Invalidation"; case RAPPOR: return "Rappor"; case VARIATIONS: return "Variations"; case UMA: return "UMA"; case DOMAIN_RELIABILITY: return "DomainReliability"; case PROFILE_DOWNLOADER: return "ProfileDownloader"; case GOOGLE_URL_TRACKER: return "GoogleURLTracker"; case AUTOFILL: return "Autofill"; case POLICY: return "Policy"; case SPELL_CHECKER: return "SpellChecker"; case NTP_SNIPPETS: return "NTPSnippets"; case SAFE_BROWSING: return "SafeBrowsing"; case DATA_REDUCTION_PROXY: return "DataReductionProxy"; case PRECACHE: return "Precache"; case NTP_TILES: return "NTPTiles"; case FEEDBACK_UPLOADER: return "FeedbackUploader"; case TRACING_UPLOADER: return "TracingUploader"; case DOM_DISTILLER: return "DOMDistiller"; case CLOUD_PRINT: return "CloudPrint"; case SEARCH_PROVIDER_LOGOS: return "SearchProviderLogos"; case UPDATE_CLIENT: return "UpdateClient"; case GCM_DRIVER: return "GCMDriver"; case WEB_HISTORY_SERVICE: return "WebHistoryService"; case NETWORK_TIME_TRACKER: return "NetworkTimeTracker"; case SUPERVISED_USER: return "SupervisedUser"; case IMAGE_FETCHER_UNTAGGED: return "ImageFetcherUntagged"; case GAIA: return "GAIA"; } return "INVALID"; } CWE ID: CWE-190 Target: 1 Example 2: Code: static int l2tp_ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; __be32 *transhdr = NULL; int err = 0; skb = skb_peek(&sk->sk_write_queue); if (skb == NULL) goto out; transhdr = (__be32 *)skb_transport_header(skb); *transhdr = 0; err = ip6_push_pending_frames(sk); out: return err; } 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: _gd2PutHeader (gdImagePtr im, gdIOCtx * out, int cs, int fmt, int cx, int cy) { int i; /* Send the gd2 id, to verify file format. */ for (i = 0; i < 4; i++) { gdPutC ((unsigned char) (GD2_ID[i]), out); }; /* */ /* We put the version info first, so future versions can easily change header info. */ /* */ gdPutWord (GD2_VERS, out); gdPutWord (im->sx, out); gdPutWord (im->sy, out); gdPutWord (cs, out); gdPutWord (fmt, out); gdPutWord (cx, out); gdPutWord (cy, out); } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto, int depth _U_) { const struct ikev1_pl_t *p; struct ikev1_pl_t t; const u_char *cp; const char *idstr; const struct attrmap *map; size_t nmap; const u_char *ep2; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T))); p = (const struct ikev1_pl_t *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&t, ext, sizeof(t)); switch (proto) { case 1: idstr = STR_OR_ID(t.t_id, ikev1_p_map); map = oakley_t_map; nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); break; case 2: idstr = STR_OR_ID(t.t_id, ah_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 3: idstr = STR_OR_ID(t.t_id, esp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; case 4: idstr = STR_OR_ID(t.t_id, ipcomp_p_map); map = ipsec_t_map; nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]); break; default: idstr = NULL; map = NULL; nmap = 0; break; } if (idstr) ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr)); else ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id)); cp = (const u_char *)(p + 1); ep2 = (const u_char *)p + item_len; while (cp < ep && cp < ep2) { if (map && nmap) { cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, map, nmap); } else cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); } if (ep < ep2) ND_PRINT((ndo,"...")); return cp; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T))); return NULL; } CWE ID: CWE-125 Target: 1 Example 2: Code: qtdemux_tree_get_child_by_type (GNode * node, guint32 fourcc) { GNode *child; guint8 *buffer; guint32 child_fourcc; for (child = g_node_first_child (node); child; child = g_node_next_sibling (child)) { buffer = (guint8 *) child->data; child_fourcc = QT_FOURCC (buffer + 4); if (child_fourcc == fourcc) { return child; } } return NULL; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: pim_print(netdissect_options *ndo, register const u_char *bp, register u_int len, const u_char *bp2) { register const u_char *ep; register const struct pim *pim = (const struct pim *)bp; ep = (const u_char *)ndo->ndo_snapend; if (bp >= ep) return; #ifdef notyet /* currently we see only version and type */ ND_TCHECK(pim->pim_rsv); #endif switch (PIM_VER(pim->pim_typever)) { case 2: if (!ndo->ndo_vflag) { ND_PRINT((ndo, "PIMv%u, %s, length %u", PIM_VER(pim->pim_typever), tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)), len)); return; } else { ND_PRINT((ndo, "PIMv%u, length %u\n\t%s", PIM_VER(pim->pim_typever), len, tok2str(pimv2_type_values,"Unknown Type",PIM_TYPE(pim->pim_typever)))); pimv2_print(ndo, bp, len, bp2); } break; default: ND_PRINT((ndo, "PIMv%u, length %u", PIM_VER(pim->pim_typever), len)); break; } 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: MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum) { size_t extent; if (CheckMemoryOverflow(count,quantum) != MagickFalse) return((void *) NULL); extent=count*quantum; return(AcquireMagickMemory(extent)); } CWE ID: CWE-119 Target: 1 Example 2: Code: void ACodec::signalFlush() { ALOGV("[%s] signalFlush", mComponentName.c_str()); (new AMessage(kWhatFlush, this))->post(); } 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 GetURLRowForAutocompleteMatch(Profile* profile, const AutocompleteMatch& match, history::URLRow* url_row) { DCHECK(url_row); HistoryService* history_service = profile->GetHistoryService(Profile::EXPLICIT_ACCESS); if (!history_service) return false; history::URLDatabase* url_db = history_service->InMemoryDatabase(); return url_db && (url_db->GetRowForURL(match.destination_url, url_row) != 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: cJSON *cJSON_CreateObject( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_Object; return item; } CWE ID: CWE-119 Target: 1 Example 2: Code: static long region_chg(struct resv_map *resv, long f, long t) { struct list_head *head = &resv->regions; struct file_region *rg, *nrg = NULL; long chg = 0; retry: spin_lock(&resv->lock); retry_locked: resv->adds_in_progress++; /* * Check for sufficient descriptors in the cache to accommodate * the number of in progress add operations. */ if (resv->adds_in_progress > resv->region_cache_count) { struct file_region *trg; VM_BUG_ON(resv->adds_in_progress - resv->region_cache_count > 1); /* Must drop lock to allocate a new descriptor. */ resv->adds_in_progress--; spin_unlock(&resv->lock); trg = kmalloc(sizeof(*trg), GFP_KERNEL); if (!trg) { kfree(nrg); return -ENOMEM; } spin_lock(&resv->lock); list_add(&trg->link, &resv->region_cache); resv->region_cache_count++; goto retry_locked; } /* Locate the region we are before or in. */ list_for_each_entry(rg, head, link) if (f <= rg->to) break; /* If we are below the current region then a new region is required. * Subtle, allocate a new region at the position but make it zero * size such that we can guarantee to record the reservation. */ if (&rg->link == head || t < rg->from) { if (!nrg) { resv->adds_in_progress--; spin_unlock(&resv->lock); nrg = kmalloc(sizeof(*nrg), GFP_KERNEL); if (!nrg) return -ENOMEM; nrg->from = f; nrg->to = f; INIT_LIST_HEAD(&nrg->link); goto retry; } list_add(&nrg->link, rg->link.prev); chg = t - f; goto out_nrg; } /* Round our left edge to the current segment if it encloses us. */ if (f > rg->from) f = rg->from; chg = t - f; /* Check for and consume any regions we now overlap with. */ list_for_each_entry(rg, rg->link.prev, link) { if (&rg->link == head) break; if (rg->from > t) goto out; /* We overlap with this area, if it extends further than * us then we must extend ourselves. Account for its * existing reservation. */ if (rg->to > t) { chg += rg->to - t; t = rg->to; } chg -= rg->to - rg->from; } out: spin_unlock(&resv->lock); /* We already know we raced and no longer need the new region */ kfree(nrg); return chg; out_nrg: spin_unlock(&resv->lock); return chg; } 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 ib_ucm_open(struct inode *inode, struct file *filp) { struct ib_ucm_file *file; file = kmalloc(sizeof(*file), GFP_KERNEL); if (!file) return -ENOMEM; INIT_LIST_HEAD(&file->events); INIT_LIST_HEAD(&file->ctxs); init_waitqueue_head(&file->poll_wait); mutex_init(&file->file_mutex); filp->private_data = file; file->filp = filp; file->device = container_of(inode->i_cdev, struct ib_ucm_device, cdev); return nonseekable_open(inode, filp); } 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: ChromeContentBrowserClient::CreateThrottlesForNavigation( content::NavigationHandle* handle) { std::vector<std::unique_ptr<content::NavigationThrottle>> throttles; if (handle->IsInMainFrame()) { throttles.push_back( page_load_metrics::MetricsNavigationThrottle::Create(handle)); } #if BUILDFLAG(ENABLE_PLUGINS) std::unique_ptr<content::NavigationThrottle> flash_url_throttle = FlashDownloadInterception::MaybeCreateThrottleFor(handle); if (flash_url_throttle) throttles.push_back(std::move(flash_url_throttle)); #endif #if BUILDFLAG(ENABLE_SUPERVISED_USERS) std::unique_ptr<content::NavigationThrottle> supervised_user_throttle = SupervisedUserNavigationThrottle::MaybeCreateThrottleFor(handle); if (supervised_user_throttle) throttles.push_back(std::move(supervised_user_throttle)); #endif #if defined(OS_ANDROID) prerender::PrerenderContents* prerender_contents = prerender::PrerenderContents::FromWebContents(handle->GetWebContents()); if (!prerender_contents && handle->IsInMainFrame()) { throttles.push_back( navigation_interception::InterceptNavigationDelegate::CreateThrottleFor( handle)); } throttles.push_back(InterceptOMADownloadNavigationThrottle::Create(handle)); #elif BUILDFLAG(ENABLE_EXTENSIONS) if (handle->IsInMainFrame()) { auto url_to_app_throttle = PlatformAppNavigationRedirector::MaybeCreateThrottleFor(handle); if (url_to_app_throttle) throttles.push_back(std::move(url_to_app_throttle)); } if (base::FeatureList::IsEnabled(features::kDesktopPWAWindowing)) { if (base::FeatureList::IsEnabled(features::kDesktopPWAsLinkCapturing)) { auto bookmark_app_experimental_throttle = extensions::BookmarkAppExperimentalNavigationThrottle:: MaybeCreateThrottleFor(handle); if (bookmark_app_experimental_throttle) throttles.push_back(std::move(bookmark_app_experimental_throttle)); } else if (!base::FeatureList::IsEnabled( features::kDesktopPWAsStayInWindow)) { auto bookmark_app_throttle = extensions::BookmarkAppNavigationThrottle::MaybeCreateThrottleFor( handle); if (bookmark_app_throttle) throttles.push_back(std::move(bookmark_app_throttle)); } } if (base::FeatureList::IsEnabled( features::kMimeHandlerViewInCrossProcessFrame)) { auto plugin_frame_attach_throttle = extensions::ExtensionsGuestViewMessageFilter::MaybeCreateThrottle( handle); if (plugin_frame_attach_throttle) throttles.push_back(std::move(plugin_frame_attach_throttle)); } #endif #if defined(OS_CHROMEOS) if (handle->IsInMainFrame()) { if (merge_session_throttling_utils::ShouldAttachNavigationThrottle() && !merge_session_throttling_utils::AreAllSessionMergedAlready() && handle->GetURL().SchemeIsHTTPOrHTTPS()) { throttles.push_back(MergeSessionNavigationThrottle::Create(handle)); } auto url_to_apps_throttle = chromeos::AppsNavigationThrottle::MaybeCreate(handle); if (url_to_apps_throttle) throttles.push_back(std::move(url_to_apps_throttle)); } #endif #if BUILDFLAG(ENABLE_EXTENSIONS) throttles.push_back( std::make_unique<extensions::ExtensionNavigationThrottle>(handle)); std::unique_ptr<content::NavigationThrottle> user_script_throttle = extensions::ExtensionsBrowserClient::Get() ->GetUserScriptListener() ->CreateNavigationThrottle(handle); if (user_script_throttle) throttles.push_back(std::move(user_script_throttle)); #endif #if BUILDFLAG(ENABLE_SUPERVISED_USERS) std::unique_ptr<content::NavigationThrottle> supervised_user_nav_throttle = SupervisedUserGoogleAuthNavigationThrottle::MaybeCreate(handle); if (supervised_user_nav_throttle) throttles.push_back(std::move(supervised_user_nav_throttle)); #endif content::WebContents* web_contents = handle->GetWebContents(); if (auto* subresource_filter_client = ChromeSubresourceFilterClient::FromWebContents(web_contents)) { subresource_filter_client->MaybeAppendNavigationThrottles(handle, &throttles); } #if !defined(OS_ANDROID) std::unique_ptr<content::NavigationThrottle> background_tab_navigation_throttle = resource_coordinator:: BackgroundTabNavigationThrottle::MaybeCreateThrottleFor(handle); if (background_tab_navigation_throttle) throttles.push_back(std::move(background_tab_navigation_throttle)); #endif #if defined(SAFE_BROWSING_DB_LOCAL) std::unique_ptr<content::NavigationThrottle> password_protection_navigation_throttle = safe_browsing::MaybeCreateNavigationThrottle(handle); if (password_protection_navigation_throttle) { throttles.push_back(std::move(password_protection_navigation_throttle)); } #endif std::unique_ptr<content::NavigationThrottle> pdf_iframe_throttle = PDFIFrameNavigationThrottle::MaybeCreateThrottleFor(handle); if (pdf_iframe_throttle) throttles.push_back(std::move(pdf_iframe_throttle)); std::unique_ptr<content::NavigationThrottle> tab_under_throttle = TabUnderNavigationThrottle::MaybeCreate(handle); if (tab_under_throttle) throttles.push_back(std::move(tab_under_throttle)); throttles.push_back(std::make_unique<PolicyBlacklistNavigationThrottle>( handle, handle->GetWebContents()->GetBrowserContext())); if (base::FeatureList::IsEnabled(features::kSSLCommittedInterstitials)) { throttles.push_back(std::make_unique<SSLErrorNavigationThrottle>( handle, std::make_unique<CertificateReportingServiceCertReporter>(web_contents), base::Bind(&SSLErrorHandler::HandleSSLError))); } std::unique_ptr<content::NavigationThrottle> https_upgrade_timing_throttle = TypedNavigationTimingThrottle::MaybeCreateThrottleFor(handle); if (https_upgrade_timing_throttle) throttles.push_back(std::move(https_upgrade_timing_throttle)); #if !defined(OS_ANDROID) std::unique_ptr<content::NavigationThrottle> devtools_throttle = DevToolsWindow::MaybeCreateNavigationThrottle(handle); if (devtools_throttle) throttles.push_back(std::move(devtools_throttle)); std::unique_ptr<content::NavigationThrottle> new_tab_page_throttle = NewTabPageNavigationThrottle::MaybeCreateThrottleFor(handle); if (new_tab_page_throttle) throttles.push_back(std::move(new_tab_page_throttle)); std::unique_ptr<content::NavigationThrottle> google_password_manager_throttle = GooglePasswordManagerNavigationThrottle::MaybeCreateThrottleFor( handle); if (google_password_manager_throttle) throttles.push_back(std::move(google_password_manager_throttle)); #endif std::unique_ptr<content::NavigationThrottle> previews_lite_page_throttle = PreviewsLitePageDecider::MaybeCreateThrottleFor(handle); if (previews_lite_page_throttle) throttles.push_back(std::move(previews_lite_page_throttle)); if (base::FeatureList::IsEnabled(safe_browsing::kCommittedSBInterstitials)) { throttles.push_back( std::make_unique<safe_browsing::SafeBrowsingNavigationThrottle>( handle)); } #if defined(OS_WIN) || defined(OS_MACOSX) || \ (defined(OS_LINUX) && !defined(OS_CHROMEOS)) std::unique_ptr<content::NavigationThrottle> browser_switcher_throttle = browser_switcher::BrowserSwitcherNavigationThrottle :: MaybeCreateThrottleFor(handle); if (browser_switcher_throttle) throttles.push_back(std::move(browser_switcher_throttle)); #endif return throttles; } CWE ID: CWE-362 Target: 1 Example 2: Code: static void cssAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); TestObjectPythonV8Internal::cssAttributeAttributeSetter(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void AwContents::InvokeGeolocationCallback(JNIEnv* env, jobject obj, jboolean value, jstring origin) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (pending_geolocation_prompts_.empty()) return; GURL callback_origin(base::android::ConvertJavaStringToUTF16(env, origin)); if (callback_origin.GetOrigin() == pending_geolocation_prompts_.front().first) { pending_geolocation_prompts_.front().second.Run(value); pending_geolocation_prompts_.pop_front(); if (!pending_geolocation_prompts_.empty()) { ShowGeolocationPromptHelper(java_ref_, pending_geolocation_prompts_.front().first); } } } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: WebRunnerMainDelegate::CreateContentBrowserClient() { DCHECK(!browser_client_); browser_client_ = std::make_unique<WebRunnerContentBrowserClient>( std::move(context_channel_)); return browser_client_.get(); } CWE ID: CWE-264 Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoGetShaderInfoLog( GLuint shader, std::string* infolog) { CheckErrorCallbackState(); GLuint service_id = GetShaderServiceID(shader, resources_); GLint info_log_len = 0; api()->glGetShaderivFn(service_id, GL_INFO_LOG_LENGTH, &info_log_len); if (CheckErrorCallbackState()) { return error::kNoError; } std::vector<char> buffer(info_log_len, 0); GLsizei length = 0; api()->glGetShaderInfoLogFn(service_id, info_log_len, &length, buffer.data()); DCHECK(length <= info_log_len); *infolog = length > 0 ? std::string(buffer.data(), length) : std::string(); 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: star_get_sparse_info (struct tar_sparse_file *file) { size_t i; union block *h = current_header; int ext_p; enum oldgnu_add_status rc = add_ok; file->stat_info->sparse_map_avail = 0; if (h->star_in_header.prefix[0] == '\0' && h->star_in_header.sp[0].offset[10] != '\0') { /* Old star format */ for (i = 0; i < SPARSES_IN_STAR_HEADER; i++) { rc = oldgnu_add_sparse (file, &h->star_in_header.sp[i]); if (rc != add_ok) break; } ext_p = h->star_in_header.isextended; } else ext_p = 1; for (; rc == add_ok && ext_p; ext_p = h->star_ext_header.isextended) { h = find_next_block (); if (!h) { ERROR ((0, 0, _("Unexpected EOF in archive"))); return false; } set_next_block_after (h); for (i = 0; i < SPARSES_IN_STAR_EXT_HEADER && rc == add_ok; i++) rc = oldgnu_add_sparse (file, &h->star_ext_header.sp[i]); file->dumped_size += BLOCKSIZE; } if (rc == add_fail) { ERROR ((0, 0, _("%s: invalid sparse archive member"), file->stat_info->orig_file_name)); return false; } return true; } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __init ipgre_init(void) { int err; printk(KERN_INFO "GRE over IPv4 tunneling driver\n"); if (inet_add_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) { printk(KERN_INFO "ipgre init: can't add protocol\n"); return -EAGAIN; } err = register_pernet_device(&ipgre_net_ops); if (err < 0) goto gen_device_failed; err = rtnl_link_register(&ipgre_link_ops); if (err < 0) goto rtnl_link_failed; err = rtnl_link_register(&ipgre_tap_ops); if (err < 0) goto tap_ops_failed; out: return err; tap_ops_failed: rtnl_link_unregister(&ipgre_link_ops); rtnl_link_failed: unregister_pernet_device(&ipgre_net_ops); gen_device_failed: inet_del_protocol(&ipgre_protocol, IPPROTO_GRE); goto out; } CWE ID: Target: 1 Example 2: Code: static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { double result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+ c1*x^2+c2*x+c3). */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel+parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { double amplitude, bias, frequency, phase; /* Sinusoid: frequency, phase, amplitude, bias. */ frequency=(number_parameters >= 1) ? parameters[0] : 1.0; phase=(number_parameters >= 2) ? parameters[1] : 0.0; amplitude=(number_parameters >= 3) ? parameters[2] : 0.5; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (QuantumRange*(amplitude*sin((double) (2.0* MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias)); break; } case ArcsinFunction: { double bias, center, range, width; /* Arcsin (peged at range limits for invalid results): width, center, range, and bias. */ width=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=2.0/width*(QuantumScale*pixel-center); if ( result <= -1.0 ) result=bias-range/2.0; else if (result >= 1.0) result=bias+range/2.0; else result=(double) (range/MagickPI*asin((double) result)+bias); result*=QuantumRange; break; } case ArctanFunction: { double center, bias, range, slope; /* Arctan: slope, center, range, and bias. */ slope=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (MagickPI*slope*(QuantumScale*pixel-center)); result=(double) (QuantumRange*(range/MagickPI*atan((double) result)+bias)); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } 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: node_addrs_changed(node_t *node) { node->last_reachable = node->last_reachable6 = 0; node->country = -1; } 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: unsigned char *base64decode(const char *buf, size_t *size) { if (!buf || !size) return NULL; size_t len = (*size > 0) ? *size : strlen(buf); if (len <= 0) return NULL; unsigned char *outbuf = (unsigned char*)malloc((len/4)*3+3); const char *ptr = buf; int p = 0; size_t l = 0; do { ptr += strspn(ptr, "\r\n\t "); if (*ptr == '\0' || ptr >= buf+len) { break; } l = strcspn(ptr, "\r\n\t "); if (l > 3 && ptr+l <= buf+len) { p+=base64decode_block(outbuf+p, ptr, l); ptr += l; } else { break; } } while (1); outbuf[p] = 0; *size = p; return outbuf; } CWE ID: CWE-125 Target: 1 Example 2: Code: bool ImageDataNaClBackend::IsMapped() const { return map_count_ > 0; } CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool SessionRestore::IsRestoring(const Profile* profile) { return (profiles_getting_restored && profiles_getting_restored->find(profile) != profiles_getting_restored->end()); } 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: GURL DevToolsUI::SanitizeFrontendURL(const GURL& url) { return ::SanitizeFrontendURL(url, content::kChromeDevToolsScheme, chrome::kChromeUIDevToolsHost, SanitizeFrontendPath(url.path()), true); } CWE ID: CWE-200 Target: 1 Example 2: Code: PresentationConnection::~PresentationConnection() { ASSERT(!m_blobLoader); } 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 bta_av_rc_disc(uint8_t disc) { tBTA_AV_CB* p_cb = &bta_av_cb; tAVRC_SDP_DB_PARAMS db_params; uint16_t attr_list[] = {ATTR_ID_SERVICE_CLASS_ID_LIST, ATTR_ID_BT_PROFILE_DESC_LIST, ATTR_ID_SUPPORTED_FEATURES}; uint8_t hdi; tBTA_AV_SCB* p_scb; RawAddress peer_addr = RawAddress::kEmpty; uint8_t rc_handle; APPL_TRACE_DEBUG("%s: disc: 0x%x, bta_av_cb.disc: 0x%x", __func__, disc, bta_av_cb.disc); if ((bta_av_cb.disc != 0) || (disc == 0)) return; if ((disc & BTA_AV_CHNL_MSK) == BTA_AV_CHNL_MSK) { /* this is the rc handle/index to tBTA_AV_RCB */ rc_handle = disc & (~BTA_AV_CHNL_MSK); if (p_cb->rcb[rc_handle].lidx) { peer_addr = p_cb->lcb[p_cb->rcb[rc_handle].lidx - 1].addr; } } else { hdi = (disc & BTA_AV_HNDL_MSK) - 1; p_scb = p_cb->p_scb[hdi]; if (p_scb) { APPL_TRACE_DEBUG("%s: rc_handle %d", __func__, p_scb->rc_handle); peer_addr = p_scb->PeerAddress(); } } if (!peer_addr.IsEmpty()) { /* allocate discovery database */ if (p_cb->p_disc_db == NULL) p_cb->p_disc_db = (tSDP_DISCOVERY_DB*)osi_malloc(BTA_AV_DISC_BUF_SIZE); /* set up parameters */ db_params.db_len = BTA_AV_DISC_BUF_SIZE; db_params.num_attr = 3; db_params.p_db = p_cb->p_disc_db; db_params.p_attrs = attr_list; /* searching for UUID_SERVCLASS_AV_REMOTE_CONTROL gets both TG and CT */ if (AVRC_FindService(UUID_SERVCLASS_AV_REMOTE_CONTROL, peer_addr, &db_params, base::Bind(bta_av_avrc_sdp_cback)) == AVRC_SUCCESS) { p_cb->disc = disc; APPL_TRACE_DEBUG("%s: disc 0x%x", __func__, p_cb->disc); } } } CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DateTimeFieldElement::updateVisibleValue(EventBehavior eventBehavior) { Text* const textNode = toText(firstChild()); const String newVisibleValue = visibleValue(); ASSERT(newVisibleValue.length() > 0); if (textNode->wholeText() == newVisibleValue) return; textNode->replaceWholeText(newVisibleValue, ASSERT_NO_EXCEPTION); setAttribute(aria_valuetextAttr, hasValue() ? newVisibleValue : AXDateTimeFieldEmptyValueText()); setAttribute(aria_valuenowAttr, newVisibleValue); if (eventBehavior == DispatchEvent && m_fieldOwner) m_fieldOwner->fieldValueChanged(); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int intf_next_seq(struct ipmi_smi *intf, struct ipmi_recv_msg *recv_msg, unsigned long timeout, int retries, int broadcast, unsigned char *seq, long *seqid) { int rv = 0; unsigned int i; if (timeout == 0) timeout = default_retry_ms; if (retries < 0) retries = default_max_retries; for (i = intf->curr_seq; (i+1)%IPMI_IPMB_NUM_SEQ != intf->curr_seq; i = (i+1)%IPMI_IPMB_NUM_SEQ) { if (!intf->seq_table[i].inuse) break; } if (!intf->seq_table[i].inuse) { intf->seq_table[i].recv_msg = recv_msg; /* * Start with the maximum timeout, when the send response * comes in we will start the real timer. */ intf->seq_table[i].timeout = MAX_MSG_TIMEOUT; intf->seq_table[i].orig_timeout = timeout; intf->seq_table[i].retries_left = retries; intf->seq_table[i].broadcast = broadcast; intf->seq_table[i].inuse = 1; intf->seq_table[i].seqid = NEXT_SEQID(intf->seq_table[i].seqid); *seq = i; *seqid = intf->seq_table[i].seqid; intf->curr_seq = (i+1)%IPMI_IPMB_NUM_SEQ; need_waiter(intf); } else { rv = -EAGAIN; } return rv; } 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: status_t MediaPlayer::setDataSource(int fd, int64_t offset, int64_t length) { ALOGV("setDataSource(%d, %" PRId64 ", %" PRId64 ")", fd, offset, length); status_t err = UNKNOWN_ERROR; const sp<IMediaPlayerService>& service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(fd, offset, length))) { player.clear(); } err = attachNewPlayer(player); } return err; } 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: v8::Local<v8::Value> PrivateScriptRunner::runDOMAttributeGetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> getter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "get")).ToLocal(&getter) || !getter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute getter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(getter), scriptState->getExecutionContext(), holder, 0, 0, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::GetterContext, attributeName, className); block.ReThrow(); return v8::Local<v8::Value>(); } return result; } CWE ID: CWE-79 Target: 1 Example 2: Code: static views::View* AddPaddedTitleCard(views::View* view, TitleCard* title_card, int width) { views::View* titled_view = new views::View(); views::GridLayout* layout = titled_view->SetLayoutManager( std::make_unique<views::GridLayout>(titled_view)); ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); const gfx::Insets dialog_insets = provider->GetInsetsMetric(views::INSETS_DIALOG); views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddPaddingColumn(1.0, dialog_insets.left()); int available_width = width - dialog_insets.width(); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, views::GridLayout::kFixedSize, views::GridLayout::FIXED, available_width, available_width); columns->AddPaddingColumn(1.0, dialog_insets.right()); layout->AddColumnSet(1)->AddColumn( views::GridLayout::FILL, views::GridLayout::FILL, views::GridLayout::kFixedSize, views::GridLayout::FIXED, width, width); layout->StartRowWithPadding(1.0, 0, views::GridLayout::kFixedSize, kVerticalSpacing); layout->AddView(title_card); layout->StartRowWithPadding(1.0, 1.0, views::GridLayout::kFixedSize, kVerticalSpacing); layout->AddView(new views::Separator()); layout->StartRow(1.0, 1.0); layout->AddView(view); return titled_view; } 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 CLASS packed_load_raw() { int vbits=0, bwide, pwide, rbits, bite, half, irow, row, col, val, i; int zero=0; UINT64 bitbuf=0; if ((ushort)(raw_width * 8) >= width * tiff_bps) /* Is raw_width in bytes? */ pwide = (bwide = raw_width) * 8 / tiff_bps; else bwide = (pwide = raw_width) * tiff_bps / 8; rbits = bwide * 8 - pwide * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; fseek (ifp, top_margin*bwide, SEEK_CUR); bite = 8 + (load_flags & 24); half = (height+1) >> 1; for (irow=0; irow < height; irow++) { row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col=0; col < pwide; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); i = (col ^ (load_flags >> 6)) - left_margin; if ((unsigned) i < width) BAYER(row,i) = val; else if (load_flags & 32) { black += val; zero += !val; } if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && col < width+left_margin) derror(); } vbits -= rbits; } if (load_flags & 32 && pwide > width) black /= (pwide - width) * height; if (zero*4 > (pwide - width) * height) black = 0; } 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: METHODDEF(JDIMENSION) get_word_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading raw-word-format PGM files with any maxval */ { ppm_source_ptr source = (ppm_source_ptr)sinfo; register JSAMPROW ptr; register U_CHAR *bufferptr; register JSAMPLE *rescale = source->rescale; JDIMENSION col; unsigned int maxval = source->maxval; if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width)) ERREXIT(cinfo, JERR_INPUT_EOF); ptr = source->pub.buffer[0]; bufferptr = source->iobuffer; for (col = cinfo->image_width; col > 0; col--) { register unsigned int temp; temp = UCH(*bufferptr++) << 8; temp |= UCH(*bufferptr++); if (temp > maxval) ERREXIT(cinfo, JERR_PPM_TOOLARGE); *ptr++ = rescale[temp]; } return 1; } CWE ID: CWE-125 Target: 1 Example 2: Code: PlatformSensorFusion::~PlatformSensorFusion() { for (const auto& pair : source_sensors_) pair.second->RemoveClient(this); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual const ImePropertyList& current_ime_properties() const { return current_ime_properties_; } CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { VLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (base::RandDouble() > upload_rate) { VLOG(1) << "AutofillDownloadManager: Upload request is ignored."; return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } CWE ID: CWE-399 Target: 1 Example 2: Code: static bool isImageOrAltText(LayoutBoxModelObject* box, Node* node) { if (box && box->isImage()) return true; if (isHTMLImageElement(node)) return true; if (isHTMLInputElement(node) && toHTMLInputElement(node)->hasFallbackContent()) return true; return 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 long madvise_remove(struct vm_area_struct *vma, struct vm_area_struct **prev, unsigned long start, unsigned long end) { loff_t offset; int error; *prev = NULL; /* tell sys_madvise we drop mmap_sem */ if (vma->vm_flags & (VM_LOCKED|VM_NONLINEAR|VM_HUGETLB)) return -EINVAL; if (!vma->vm_file || !vma->vm_file->f_mapping || !vma->vm_file->f_mapping->host) { return -EINVAL; } if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE)) return -EACCES; offset = (loff_t)(start - vma->vm_start) + ((loff_t)vma->vm_pgoff << PAGE_SHIFT); /* filesystem's fallocate may need to take i_mutex */ up_read(&current->mm->mmap_sem); error = do_fallocate(vma->vm_file, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset, end - start); down_read(&current->mm->mmap_sem); return error; } 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: int bnep_add_connection(struct bnep_connadd_req *req, struct socket *sock) { struct net_device *dev; struct bnep_session *s, *ss; u8 dst[ETH_ALEN], src[ETH_ALEN]; int err; BT_DBG(""); baswap((void *) dst, &l2cap_pi(sock->sk)->chan->dst); baswap((void *) src, &l2cap_pi(sock->sk)->chan->src); /* session struct allocated as private part of net_device */ dev = alloc_netdev(sizeof(struct bnep_session), (*req->device) ? req->device : "bnep%d", NET_NAME_UNKNOWN, bnep_net_setup); if (!dev) return -ENOMEM; down_write(&bnep_session_sem); ss = __bnep_get_session(dst); if (ss && ss->state == BT_CONNECTED) { err = -EEXIST; goto failed; } s = netdev_priv(dev); /* This is rx header therefore addresses are swapped. * ie. eh.h_dest is our local address. */ memcpy(s->eh.h_dest, &src, ETH_ALEN); memcpy(s->eh.h_source, &dst, ETH_ALEN); memcpy(dev->dev_addr, s->eh.h_dest, ETH_ALEN); s->dev = dev; s->sock = sock; s->role = req->role; s->state = BT_CONNECTED; s->msg.msg_flags = MSG_NOSIGNAL; #ifdef CONFIG_BT_BNEP_MC_FILTER /* Set default mc filter */ set_bit(bnep_mc_hash(dev->broadcast), (ulong *) &s->mc_filter); #endif #ifdef CONFIG_BT_BNEP_PROTO_FILTER /* Set default protocol filter */ bnep_set_default_proto_filter(s); #endif SET_NETDEV_DEV(dev, bnep_get_device(s)); SET_NETDEV_DEVTYPE(dev, &bnep_type); err = register_netdev(dev); if (err) goto failed; __bnep_link_session(s); __module_get(THIS_MODULE); s->task = kthread_run(bnep_session, s, "kbnepd %s", dev->name); if (IS_ERR(s->task)) { /* Session thread start failed, gotta cleanup. */ module_put(THIS_MODULE); unregister_netdev(dev); __bnep_unlink_session(s); err = PTR_ERR(s->task); goto failed; } up_write(&bnep_session_sem); strcpy(req->device, dev->name); return 0; failed: up_write(&bnep_session_sem); free_netdev(dev); return err; } CWE ID: CWE-20 Target: 1 Example 2: Code: GF_Err gitn_Write(GF_Box *s, GF_BitStream *bs) { GF_Err e; u32 i; GroupIdToNameBox *ptr = (GroupIdToNameBox *) s; if (!s) return GF_BAD_PARAM; e = gf_isom_full_box_write(s, bs); if (e) return e; gf_bs_write_u16(bs, ptr->nb_entries); for (i=0; i<ptr->nb_entries; i++) { gf_bs_write_u32(bs, ptr->entries[i].group_id); if (ptr->entries[i].name) gf_bs_write_data(bs, ptr->entries[i].name, (u32)strlen(ptr->entries[i].name) ); gf_bs_write_u8(bs, 0); } return GF_OK; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ScopedFramebufferCopyBinder::ScopedFramebufferCopyBinder( GLES2DecoderImpl* decoder, GLint x, GLint y, GLint width, GLint height) : decoder_(decoder) { const Framebuffer::Attachment* attachment = decoder->framebuffer_state_.bound_read_framebuffer.get() ->GetReadBufferAttachment(); DCHECK(attachment); auto* api = decoder_->api(); api->glGenTexturesFn(1, &temp_texture_); ScopedTextureBinder texture_binder(&decoder->state_, decoder->error_state_.get(), temp_texture_, GL_TEXTURE_2D); if (width == 0 || height == 0) { api->glCopyTexImage2DFn(GL_TEXTURE_2D, 0, attachment->internal_format(), 0, 0, attachment->width(), attachment->height(), 0); } else { api->glCopyTexImage2DFn(GL_TEXTURE_2D, 0, attachment->internal_format(), x, y, width, height, 0); } api->glGenFramebuffersEXTFn(1, &temp_framebuffer_); framebuffer_binder_ = std::make_unique<ScopedFramebufferBinder>(decoder, temp_framebuffer_); api->glFramebufferTexture2DEXTFn(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, temp_texture_, 0); api->glReadBufferFn(GL_COLOR_ATTACHMENT0); } 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 V8ContextNativeHandler::RunWithNativesEnabledModuleSystem( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(args.Length(), 1); CHECK(args[0]->IsFunction()); v8::Local<v8::Value> call_with_args[] = { context()->module_system()->NewInstance()}; ModuleSystem::NativesEnabledScope natives_enabled(context()->module_system()); context()->CallFunction(v8::Local<v8::Function>::Cast(args[0]), 1, call_with_args); } CWE ID: CWE-79 Target: 1 Example 2: Code: void ImageInputType::handleDOMActivateEvent(Event* event) { RefPtrWillBeRawPtr<HTMLInputElement> element(this->element()); if (element->isDisabledFormControl() || !element->form()) return; element->setActivatedSubmit(true); m_clickLocation = extractClickLocation(event); element->form()->prepareForSubmission(event); // Event handlers can run. element->setActivatedSubmit(false); event->setDefaultHandled(); } CWE ID: CWE-361 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static vpx_codec_err_t vp8_peek_si_internal(const uint8_t *data, unsigned int data_sz, vpx_codec_stream_info_t *si, vpx_decrypt_cb decrypt_cb, void *decrypt_state) { vpx_codec_err_t res = VPX_CODEC_OK; if(data + data_sz <= data) { res = VPX_CODEC_INVALID_PARAM; } else { /* Parse uncompresssed part of key frame header. * 3 bytes:- including version, frame type and an offset * 3 bytes:- sync code (0x9d, 0x01, 0x2a) * 4 bytes:- including image width and height in the lowest 14 bits * of each 2-byte value. */ uint8_t clear_buffer[10]; const uint8_t *clear = data; if (decrypt_cb) { int n = MIN(sizeof(clear_buffer), data_sz); decrypt_cb(decrypt_state, data, clear_buffer, n); clear = clear_buffer; } si->is_kf = 0; if (data_sz >= 10 && !(clear[0] & 0x01)) /* I-Frame */ { si->is_kf = 1; /* vet via sync code */ if (clear[3] != 0x9d || clear[4] != 0x01 || clear[5] != 0x2a) return VPX_CODEC_UNSUP_BITSTREAM; si->w = (clear[6] | (clear[7] << 8)) & 0x3fff; si->h = (clear[8] | (clear[9] << 8)) & 0x3fff; /*printf("w=%d, h=%d\n", si->w, si->h);*/ if (!(si->h | si->w)) res = VPX_CODEC_UNSUP_BITSTREAM; } else { res = VPX_CODEC_UNSUP_BITSTREAM; } } return res; } 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 SyncBackendHost::Initialize( SyncFrontend* frontend, const GURL& sync_service_url, const syncable::ModelTypeSet& types, net::URLRequestContextGetter* baseline_context_getter, const SyncCredentials& credentials, bool delete_sync_data_folder) { if (!core_thread_.Start()) return; frontend_ = frontend; DCHECK(frontend); registrar_.workers[GROUP_DB] = new DatabaseModelWorker(); registrar_.workers[GROUP_UI] = new UIModelWorker(); registrar_.workers[GROUP_PASSIVE] = new ModelSafeWorker(); if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableSyncTypedUrls) || types.count(syncable::TYPED_URLS)) { registrar_.workers[GROUP_HISTORY] = new HistoryModelWorker( profile_->GetHistoryService(Profile::IMPLICIT_ACCESS)); } for (syncable::ModelTypeSet::const_iterator it = types.begin(); it != types.end(); ++it) { registrar_.routing_info[(*it)] = GROUP_PASSIVE; } PasswordStore* password_store = profile_->GetPasswordStore(Profile::IMPLICIT_ACCESS); if (password_store) { registrar_.workers[GROUP_PASSWORD] = new PasswordModelWorker(password_store); } else { LOG_IF(WARNING, types.count(syncable::PASSWORDS) > 0) << "Password store " << "not initialized, cannot sync passwords"; registrar_.routing_info.erase(syncable::PASSWORDS); } registrar_.routing_info[syncable::NIGORI] = GROUP_PASSIVE; core_->CreateSyncNotifier(baseline_context_getter); InitCore(Core::DoInitializeOptions( sync_service_url, MakeHttpBridgeFactory(baseline_context_getter), credentials, delete_sync_data_folder, RestoreEncryptionBootstrapToken(), false)); } CWE ID: CWE-399 Target: 1 Example 2: Code: inherit_event(struct perf_event *parent_event, struct task_struct *parent, struct perf_event_context *parent_ctx, struct task_struct *child, struct perf_event *group_leader, struct perf_event_context *child_ctx) { enum perf_event_active_state parent_state = parent_event->state; struct perf_event *child_event; unsigned long flags; /* * Instead of creating recursive hierarchies of events, * we link inherited events back to the original parent, * which has a filp for sure, which we use as the reference * count: */ if (parent_event->parent) parent_event = parent_event->parent; child_event = perf_event_alloc(&parent_event->attr, parent_event->cpu, child, group_leader, parent_event, NULL, NULL, -1); if (IS_ERR(child_event)) return child_event; /* * is_orphaned_event() and list_add_tail(&parent_event->child_list) * must be under the same lock in order to serialize against * perf_event_release_kernel(), such that either we must observe * is_orphaned_event() or they will observe us on the child_list. */ mutex_lock(&parent_event->child_mutex); if (is_orphaned_event(parent_event) || !atomic_long_inc_not_zero(&parent_event->refcount)) { mutex_unlock(&parent_event->child_mutex); free_event(child_event); return NULL; } get_ctx(child_ctx); /* * Make the child state follow the state of the parent event, * not its attr.disabled bit. We hold the parent's mutex, * so we won't race with perf_event_{en, dis}able_family. */ if (parent_state >= PERF_EVENT_STATE_INACTIVE) child_event->state = PERF_EVENT_STATE_INACTIVE; else child_event->state = PERF_EVENT_STATE_OFF; if (parent_event->attr.freq) { u64 sample_period = parent_event->hw.sample_period; struct hw_perf_event *hwc = &child_event->hw; hwc->sample_period = sample_period; hwc->last_period = sample_period; local64_set(&hwc->period_left, sample_period); } child_event->ctx = child_ctx; child_event->overflow_handler = parent_event->overflow_handler; child_event->overflow_handler_context = parent_event->overflow_handler_context; /* * Precalculate sample_data sizes */ perf_event__header_size(child_event); perf_event__id_header_size(child_event); /* * Link it up in the child's context: */ raw_spin_lock_irqsave(&child_ctx->lock, flags); add_event_to_ctx(child_event, child_ctx); raw_spin_unlock_irqrestore(&child_ctx->lock, flags); /* * Link this into the parent event's child list */ list_add_tail(&child_event->child_list, &parent_event->child_list); mutex_unlock(&parent_event->child_mutex); return child_event; } 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: ChromeURLRequestContextGetter::CreateOffTheRecord( Profile* profile, const ProfileIOData* profile_io_data, content::ProtocolHandlerMap* protocol_handlers) { DCHECK(profile->IsOffTheRecord()); return new ChromeURLRequestContextGetter( new FactoryForMain(profile_io_data, protocol_handlers)); } 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 ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) { if (fields) { if (fields->Buffer) { free(fields->Buffer); fields->Len = 0; fields->MaxLen = 0; fields->Buffer = NULL; fields->BufferOffset = 0; } } } CWE ID: CWE-125 Target: 1 Example 2: Code: static int proc_read_status(char *page, char **start, off_t off, int count, int *eof, void *data) { char *p = page; int len; p += sprintf(p, "Emulated SWP:\t\t%lu\n", swpcounter); p += sprintf(p, "Emulated SWPB:\t\t%lu\n", swpbcounter); p += sprintf(p, "Aborted SWP{B}:\t\t%lu\n", abtcounter); if (previous_pid != 0) p += sprintf(p, "Last process:\t\t%d\n", previous_pid); len = (p - page) - off; if (len < 0) len = 0; *eof = (len <= count) ? 1 : 0; *start = page + off; return len; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); } 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: BufferMeta(const sp<IMemory> &mem, bool is_backup = false) : mMem(mem), mIsBackup(is_backup) { } CWE ID: CWE-119 Target: 1 Example 2: Code: derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus, u_int8_t cookie[8], u_int8_t id[16]) { u_int8_t hbuf[2048], sbuf[2048], obuf[SSH_DIGEST_MAX_LENGTH]; struct ssh_digest_ctx *hashctx = NULL; size_t hlen, slen; int r; hlen = BN_num_bytes(host_modulus); slen = BN_num_bytes(server_modulus); if (hlen < (512 / 8) || (u_int)hlen > sizeof(hbuf) || slen < (512 / 8) || (u_int)slen > sizeof(sbuf)) return SSH_ERR_KEY_BITS_MISMATCH; if (BN_bn2bin(host_modulus, hbuf) <= 0 || BN_bn2bin(server_modulus, sbuf) <= 0) { r = SSH_ERR_LIBCRYPTO_ERROR; goto out; } if ((hashctx = ssh_digest_start(SSH_DIGEST_MD5)) == NULL) { r = SSH_ERR_ALLOC_FAIL; goto out; } if (ssh_digest_update(hashctx, hbuf, hlen) != 0 || ssh_digest_update(hashctx, sbuf, slen) != 0 || ssh_digest_update(hashctx, cookie, 8) != 0 || ssh_digest_final(hashctx, obuf, sizeof(obuf)) != 0) { r = SSH_ERR_LIBCRYPTO_ERROR; goto out; } memcpy(id, obuf, ssh_digest_bytes(SSH_DIGEST_MD5)); r = 0; out: ssh_digest_free(hashctx); explicit_bzero(hbuf, sizeof(hbuf)); explicit_bzero(sbuf, sizeof(sbuf)); explicit_bzero(obuf, sizeof(obuf)); return r; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BlockEntry::BlockEntry(Cluster* p, long idx) : m_pCluster(p), m_index(idx) { } 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: eXosip_init (struct eXosip_t *excontext) { osip_t *osip; int i; memset (excontext, 0, sizeof (eXosip_t)); excontext->dscp = 0x1A; snprintf (excontext->ipv4_for_gateway, 256, "%s", "217.12.3.11"); snprintf (excontext->ipv6_for_gateway, 256, "%s", "2001:638:500:101:2e0:81ff:fe24:37c6"); #ifdef WIN32 /* Initializing windows socket library */ { WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD (1, 1); i = WSAStartup (wVersionRequested, &wsaData); if (i != 0) { OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_WARNING, NULL, "eXosip: Unable to initialize WINSOCK, reason: %d\n", i)); /* return -1; It might be already initilized?? */ } } #endif excontext->user_agent = osip_strdup ("eXosip/" EXOSIP_VERSION); if (excontext->user_agent == NULL) return OSIP_NOMEM; excontext->j_calls = NULL; excontext->j_stop_ua = 0; #ifndef OSIP_MONOTHREAD excontext->j_thread = NULL; #endif i = osip_list_init (&excontext->j_transactions); excontext->j_reg = NULL; #ifndef OSIP_MONOTHREAD #if !defined (_WIN32_WCE) excontext->j_cond = (struct osip_cond *) osip_cond_init (); if (excontext->j_cond == NULL) { osip_free (excontext->user_agent); excontext->user_agent = NULL; return OSIP_NOMEM; } #endif excontext->j_mutexlock = (struct osip_mutex *) osip_mutex_init (); if (excontext->j_mutexlock == NULL) { osip_free (excontext->user_agent); excontext->user_agent = NULL; #if !defined (_WIN32_WCE) osip_cond_destroy ((struct osip_cond *) excontext->j_cond); excontext->j_cond = NULL; #endif return OSIP_NOMEM; } #endif i = osip_init (&osip); if (i != 0) { OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_ERROR, NULL, "eXosip: Cannot initialize osip!\n")); return i; } osip_set_application_context (osip, &excontext); _eXosip_set_callbacks (osip); excontext->j_osip = osip; #ifndef OSIP_MONOTHREAD /* open a TCP socket to wake up the application when needed. */ excontext->j_socketctl = jpipe (); if (excontext->j_socketctl == NULL) return OSIP_UNDEFINED_ERROR; excontext->j_socketctl_event = jpipe (); if (excontext->j_socketctl_event == NULL) return OSIP_UNDEFINED_ERROR; #endif /* To be changed in osip! */ excontext->j_events = (osip_fifo_t *) osip_malloc (sizeof (osip_fifo_t)); if (excontext->j_events == NULL) return OSIP_NOMEM; osip_fifo_init (excontext->j_events); excontext->use_rport = 1; excontext->dns_capabilities = 2; excontext->enable_dns_cache = 1; excontext->ka_interval = 17000; snprintf(excontext->ka_crlf, sizeof(excontext->ka_crlf), "\r\n\r\n"); excontext->ka_options = 0; excontext->autoanswer_bye = 1; excontext->auto_masquerade_contact = 1; excontext->masquerade_via=0; return OSIP_SUCCESS; } CWE ID: CWE-189 Target: 1 Example 2: Code: void BluetoothAdapterChromeOS::OnPropertyChangeCompleted( const base::Closure& callback, const ErrorCallback& error_callback, bool success) { if (success) callback.Run(); else error_callback.Run(); } 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 MemBackendImpl::EvictIfNeeded() { if (current_size_ <= max_size_) return; int target_size = std::max(0, max_size_ - kDefaultEvictionSize); base::LinkNode<MemEntryImpl>* entry = lru_list_.head(); while (current_size_ > target_size && entry != lru_list_.end()) { MemEntryImpl* to_doom = entry->value(); do { entry = entry->next(); } while (entry != lru_list_.end() && entry->value()->parent() == to_doom); if (!to_doom->InUse()) to_doom->Doom(); } } CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } CWE ID: CWE-369 Target: 1 Example 2: Code: void GraphicsContext::fillRect(const FloatRect& rect) { if (paintingDisabled()) return; SkRect r = rect; if (!isRectSkiaSafe(getCTM(), r)) { ClipRectToCanvas(*platformContext()->canvas(), r, &r); } platformContext()->save(); SkPaint paint; platformContext()->setupPaintForFilling(&paint); platformContext()->canvas()->drawRect(r, paint); platformContext()->restore(); } CWE ID: CWE-19 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int crypto_ccm_auth(struct aead_request *req, struct scatterlist *plain, unsigned int cryptlen) { struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req); struct crypto_aead *aead = crypto_aead_reqtfm(req); struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead); AHASH_REQUEST_ON_STACK(ahreq, ctx->mac); unsigned int assoclen = req->assoclen; struct scatterlist sg[3]; u8 odata[16]; u8 idata[16]; int ilen, err; /* format control data for input */ err = format_input(odata, req, cryptlen); if (err) goto out; sg_init_table(sg, 3); sg_set_buf(&sg[0], odata, 16); /* format associated data and compute into mac */ if (assoclen) { ilen = format_adata(idata, assoclen); sg_set_buf(&sg[1], idata, ilen); sg_chain(sg, 3, req->src); } else { ilen = 0; sg_chain(sg, 2, req->src); } ahash_request_set_tfm(ahreq, ctx->mac); ahash_request_set_callback(ahreq, pctx->flags, NULL, NULL); ahash_request_set_crypt(ahreq, sg, NULL, assoclen + ilen + 16); err = crypto_ahash_init(ahreq); if (err) goto out; err = crypto_ahash_update(ahreq); if (err) goto out; /* we need to pad the MAC input to a round multiple of the block size */ ilen = 16 - (assoclen + ilen) % 16; if (ilen < 16) { memset(idata, 0, ilen); sg_init_table(sg, 2); sg_set_buf(&sg[0], idata, ilen); if (plain) sg_chain(sg, 2, plain); plain = sg; cryptlen += ilen; } ahash_request_set_crypt(ahreq, plain, pctx->odata, cryptlen); err = crypto_ahash_finup(ahreq); out: return err; } 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 FindBarController::EndFindSession(SelectionAction action) { find_bar_->Hide(true); if (tab_contents_) { FindManager* find_manager = tab_contents_->GetFindManager(); find_manager->StopFinding(action); if (action != kKeepSelection) find_bar_->ClearResults(find_manager->find_result()); find_bar_->RestoreSavedFocus(); } } CWE ID: CWE-20 Target: 1 Example 2: Code: handleAll() { char constraint[128]; sprintf( constraint, "%s >= 0", ATTR_CLUSTER_ID ); CondorError errstack; if( doWorkByConstraint(constraint, &errstack) ) { fprintf( stdout, "All jobs %s.\n", (mode == JA_REMOVE_JOBS) ? "marked for removal" : (mode == JA_REMOVE_X_JOBS) ? "removed locally (remote state unknown)" : actionWord(mode,true) ); } else { fprintf( stderr, "%s\n", errstack.getFullText(true) ); if (had_error) { fprintf( stderr, "Could not %s all jobs.\n", actionWord(mode,false) ); } } } CWE ID: CWE-134 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err) { struct sk_buff *skb; struct nlmsghdr *rep; struct nlmsgerr *errmsg; size_t payload = sizeof(*errmsg); /* error messages get the original request appened */ if (err) payload += nlmsg_len(nlh); skb = nlmsg_new(payload, GFP_KERNEL); if (!skb) { struct sock *sk; sk = netlink_lookup(sock_net(in_skb->sk), in_skb->sk->sk_protocol, NETLINK_CB(in_skb).pid); if (sk) { sk->sk_err = ENOBUFS; sk->sk_error_report(sk); sock_put(sk); } return; } rep = __nlmsg_put(skb, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq, NLMSG_ERROR, payload, 0); errmsg = nlmsg_data(rep); errmsg->error = err; memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(*nlh)); netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).pid, MSG_DONTWAIT); } CWE ID: CWE-287 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: unsigned long long Track::GetUid() const { return m_info.uid; } CWE ID: CWE-119 Target: 1 Example 2: Code: PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, PKCS8_PRIV_KEY_INFO **p8inf) { return ASN1_d2i_bio_of(PKCS8_PRIV_KEY_INFO,PKCS8_PRIV_KEY_INFO_new, d2i_PKCS8_PRIV_KEY_INFO,bp,p8inf); } 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: create_filesystem_object(struct archive_write_disk *a) { /* Create the entry. */ const char *linkname; mode_t final_mode, mode; int r; /* We identify hard/symlinks according to the link names. */ /* Since link(2) and symlink(2) don't handle modes, we're done here. */ linkname = archive_entry_hardlink(a->entry); if (linkname != NULL) { #if !HAVE_LINK return (EPERM); #else r = link(linkname, a->name) ? errno : 0; /* * New cpio and pax formats allow hardlink entries * to carry data, so we may have to open the file * for hardlink entries. * * If the hardlink was successfully created and * the archive doesn't have carry data for it, * consider it to be non-authoritative for meta data. * This is consistent with GNU tar and BSD pax. * If the hardlink does carry data, let the last * archive entry decide ownership. */ if (r == 0 && a->filesize <= 0) { a->todo = 0; a->deferred = 0; } else if (r == 0 && a->filesize > 0) { a->fd = open(a->name, O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC); __archive_ensure_cloexec_flag(a->fd); if (a->fd < 0) r = errno; } return (r); #endif } linkname = archive_entry_symlink(a->entry); if (linkname != NULL) { #if HAVE_SYMLINK return symlink(linkname, a->name) ? errno : 0; #else return (EPERM); #endif } /* * The remaining system calls all set permissions, so let's * try to take advantage of that to avoid an extra chmod() * call. (Recall that umask is set to zero right now!) */ /* Mode we want for the final restored object (w/o file type bits). */ final_mode = a->mode & 07777; /* * The mode that will actually be restored in this step. Note * that SUID, SGID, etc, require additional work to ensure * security, so we never restore them at this point. */ mode = final_mode & 0777 & ~a->user_umask; switch (a->mode & AE_IFMT) { default: /* POSIX requires that we fall through here. */ /* FALLTHROUGH */ case AE_IFREG: a->fd = open(a->name, O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode); __archive_ensure_cloexec_flag(a->fd); r = (a->fd < 0); break; case AE_IFCHR: #ifdef HAVE_MKNOD /* Note: we use AE_IFCHR for the case label, and * S_IFCHR for the mknod() call. This is correct. */ r = mknod(a->name, mode | S_IFCHR, archive_entry_rdev(a->entry)); break; #else /* TODO: Find a better way to warn about our inability * to restore a char device node. */ return (EINVAL); #endif /* HAVE_MKNOD */ case AE_IFBLK: #ifdef HAVE_MKNOD r = mknod(a->name, mode | S_IFBLK, archive_entry_rdev(a->entry)); break; #else /* TODO: Find a better way to warn about our inability * to restore a block device node. */ return (EINVAL); #endif /* HAVE_MKNOD */ case AE_IFDIR: mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE; r = mkdir(a->name, mode); if (r == 0) { /* Defer setting dir times. */ a->deferred |= (a->todo & TODO_TIMES); a->todo &= ~TODO_TIMES; /* Never use an immediate chmod(). */ /* We can't avoid the chmod() entirely if EXTRACT_PERM * because of SysV SGID inheritance. */ if ((mode != final_mode) || (a->flags & ARCHIVE_EXTRACT_PERM)) a->deferred |= (a->todo & TODO_MODE); a->todo &= ~TODO_MODE; } break; case AE_IFIFO: #ifdef HAVE_MKFIFO r = mkfifo(a->name, mode); break; #else /* TODO: Find a better way to warn about our inability * to restore a fifo. */ return (EINVAL); #endif /* HAVE_MKFIFO */ } /* All the system calls above set errno on failure. */ if (r) return (errno); /* If we managed to set the final mode, we've avoided a chmod(). */ if (mode == final_mode) a->todo &= ~TODO_MODE; 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 append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr, char* key_name TSRMLS_DC) { zval** ele_value = NULL; int i = 0; int isFirstSubtag = 0; int max_value = 0; /* Variant/ Extlang/Private etc. */ if( zend_hash_find( hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) { if( Z_TYPE_PP(ele_value) == IS_STRING ){ add_prefix( loc_name , key_name); smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); return SUCCESS; } else if(Z_TYPE_PP(ele_value) == IS_ARRAY ) { HashPosition pos; HashTable *arr = HASH_OF(*ele_value); zval **data = NULL; zend_hash_internal_pointer_reset_ex(arr, &pos); while(zend_hash_get_current_data_ex(arr, (void **)&data, &pos) != FAILURE) { if(Z_TYPE_PP(data) != IS_STRING) { return FAILURE; } if (isFirstSubtag++ == 0){ add_prefix(loc_name , key_name); } smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(data) , Z_STRLEN_PP(data)); zend_hash_move_forward_ex(arr, &pos); } return SUCCESS; } else { return FAILURE; } } else { char cur_key_name[31]; /* Decide the max_value: the max. no. of elements allowed */ if( strcmp(key_name , LOC_VARIANT_TAG) ==0 ){ max_value = MAX_NO_VARIANT; } if( strcmp(key_name , LOC_EXTLANG_TAG) ==0 ){ max_value = MAX_NO_EXTLANG; } if( strcmp(key_name , LOC_PRIVATE_TAG) ==0 ){ max_value = MAX_NO_PRIVATE; } /* Multiple variant values as variant0, variant1 ,variant2 */ isFirstSubtag = 0; for( i=0 ; i< max_value; i++ ){ snprintf( cur_key_name , 30, "%s%d", key_name , i); if( zend_hash_find( hash_arr , cur_key_name , strlen(cur_key_name) + 1,(void **)&ele_value ) == SUCCESS ){ if( Z_TYPE_PP(ele_value)!= IS_STRING ){ /* variant is not a string */ return FAILURE; } /* Add the contents */ if (isFirstSubtag++ == 0){ add_prefix(loc_name , cur_key_name); } smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1); smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value)); } } /* end of for */ } /* end of else */ return SUCCESS; } CWE ID: CWE-125 Target: 1 Example 2: Code: static void ttwu_queue_remote(struct task_struct *p, int cpu) { if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) smp_send_reschedule(cpu); } 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: bool IsReloadLoadType(FrameLoadType type) { return type == kFrameLoadTypeReload || type == kFrameLoadTypeReloadBypassingCache; } 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: static int kvm_vm_ioctl_assign_device(struct kvm *kvm, struct kvm_assigned_pci_dev *assigned_dev) { int r = 0, idx; struct kvm_assigned_dev_kernel *match; struct pci_dev *dev; if (!(assigned_dev->flags & KVM_DEV_ASSIGN_ENABLE_IOMMU)) return -EINVAL; mutex_lock(&kvm->lock); idx = srcu_read_lock(&kvm->srcu); match = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head, assigned_dev->assigned_dev_id); if (match) { /* device already assigned */ r = -EEXIST; goto out; } match = kzalloc(sizeof(struct kvm_assigned_dev_kernel), GFP_KERNEL); if (match == NULL) { printk(KERN_INFO "%s: Couldn't allocate memory\n", __func__); r = -ENOMEM; goto out; } dev = pci_get_domain_bus_and_slot(assigned_dev->segnr, assigned_dev->busnr, assigned_dev->devfn); if (!dev) { printk(KERN_INFO "%s: host device not found\n", __func__); r = -EINVAL; goto out_free; } if (pci_enable_device(dev)) { printk(KERN_INFO "%s: Could not enable PCI device\n", __func__); r = -EBUSY; goto out_put; } r = pci_request_regions(dev, "kvm_assigned_device"); if (r) { printk(KERN_INFO "%s: Could not get access to device regions\n", __func__); goto out_disable; } pci_reset_function(dev); pci_save_state(dev); match->pci_saved_state = pci_store_saved_state(dev); if (!match->pci_saved_state) printk(KERN_DEBUG "%s: Couldn't store %s saved state\n", __func__, dev_name(&dev->dev)); match->assigned_dev_id = assigned_dev->assigned_dev_id; match->host_segnr = assigned_dev->segnr; match->host_busnr = assigned_dev->busnr; match->host_devfn = assigned_dev->devfn; match->flags = assigned_dev->flags; match->dev = dev; spin_lock_init(&match->intx_lock); match->irq_source_id = -1; match->kvm = kvm; match->ack_notifier.irq_acked = kvm_assigned_dev_ack_irq; list_add(&match->list, &kvm->arch.assigned_dev_head); if (!kvm->arch.iommu_domain) { r = kvm_iommu_map_guest(kvm); if (r) goto out_list_del; } r = kvm_assign_device(kvm, match); if (r) goto out_list_del; out: srcu_read_unlock(&kvm->srcu, idx); mutex_unlock(&kvm->lock); return r; out_list_del: if (pci_load_and_free_saved_state(dev, &match->pci_saved_state)) printk(KERN_INFO "%s: Couldn't reload %s saved state\n", __func__, dev_name(&dev->dev)); list_del(&match->list); pci_release_regions(dev); out_disable: pci_disable_device(dev); out_put: pci_dev_put(dev); out_free: kfree(match); srcu_read_unlock(&kvm->srcu, idx); mutex_unlock(&kvm->lock); return r; } CWE ID: CWE-264 Target: 1 Example 2: Code: void ResourceFetcher::garbageCollectDocumentResources() { typedef Vector<String, 10> StringVector; StringVector resourcesToDelete; for (DocumentResourceMap::iterator it = m_documentResources.begin(); it != m_documentResources.end(); ++it) { if (it->value->hasOneHandle()) resourcesToDelete.append(it->key); } m_documentResources.removeAll(resourcesToDelete); } 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 Document::HasValidNamespaceForAttributes(const QualifiedName& q_name) { return HasValidNamespaceForElements(q_name); } 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: int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr) { struct ip_options *opt; opt = inet_sk(sk)->opt; if (opt == NULL || opt->cipso == 0) return -ENOMSG; return cipso_v4_getattr(opt->__data + opt->cipso - sizeof(struct iphdr), secattr); } CWE ID: CWE-362 Target: 1 Example 2: Code: TestExtensionSystem::serial_connection_manager() { return NULL; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PrintPreviewUI* PrintPreviewMessageHandler::GetPrintPreviewUI() { WebContents* dialog = GetPrintPreviewDialog(); if (!dialog || !dialog->GetWebUI()) return nullptr; return static_cast<PrintPreviewUI*>(dialog->GetWebUI()->GetController()); } 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: v8::MaybeLocal<v8::Value> V8Debugger::functionScopes(v8::Local<v8::Function> function) { if (!enabled()) { NOTREACHED(); return v8::Local<v8::Value>::New(m_isolate, v8::Undefined(m_isolate)); } v8::Local<v8::Value> argv[] = { function }; v8::Local<v8::Value> scopesValue; if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue) || !scopesValue->IsArray()) return v8::MaybeLocal<v8::Value>(); v8::Local<v8::Array> scopes = scopesValue.As<v8::Array>(); v8::Local<v8::Context> context = m_debuggerContext.Get(m_isolate); if (!markAsInternal(context, scopes, V8InternalValueType::kScopeList)) return v8::MaybeLocal<v8::Value>(); if (!markArrayEntriesAsInternal(context, scopes, V8InternalValueType::kScope)) return v8::MaybeLocal<v8::Value>(); if (!scopes->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) return v8::Undefined(m_isolate); return scopes; } CWE ID: CWE-79 Target: 1 Example 2: Code: static void __netdev_printk(const char *level, const struct net_device *dev, struct va_format *vaf) { if (dev && dev->dev.parent) { dev_printk_emit(level[1] - '0', dev->dev.parent, "%s %s %s%s: %pV", dev_driver_string(dev->dev.parent), dev_name(dev->dev.parent), netdev_name(dev), netdev_reg_state(dev), vaf); } else if (dev) { printk("%s%s%s: %pV", level, netdev_name(dev), netdev_reg_state(dev), vaf); } else { printk("%s(NULL net_device): %pV", level, vaf); } } 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: mrb_mod_s_constants(mrb_state *mrb, mrb_value mod) { mrb_raise(mrb, E_NOTIMP_ERROR, "Module.constants not implemented"); return mrb_nil_value(); /* not reached */ } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xmlParseComment(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int size = XML_PARSER_BUFFER_SIZE; int len = 0; xmlParserInputState state; const xmlChar *in; int nbchar = 0, ccol; int inputid; /* * Check that there is a comment right here. */ if ((RAW != '<') || (NXT(1) != '!') || (NXT(2) != '-') || (NXT(3) != '-')) return; state = ctxt->instate; ctxt->instate = XML_PARSER_COMMENT; inputid = ctxt->input->id; SKIP(4); SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ in = ctxt->input->cur; do { if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); } get_more: ccol = ctxt->input->col; while (((*in > '-') && (*in <= 0x7F)) || ((*in >= 0x20) && (*in < '-')) || (*in == 0x09)) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } nbchar = in - ctxt->input->cur; /* * save current set of data */ if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL)) { if (buf == NULL) { if ((*in == '-') && (in[1] == '-')) size = nbchar + 1; else size = XML_PARSER_BUFFER_SIZE + nbchar; buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } len = 0; } else if (len + nbchar + 1 >= size) { xmlChar *new_buf; size += len + nbchar + XML_PARSER_BUFFER_SIZE; new_buf = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (new_buf == NULL) { xmlFree (buf); xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } buf = new_buf; } memcpy(&buf[len], ctxt->input->cur, nbchar); len += nbchar; buf[len] = 0; } } ctxt->input->cur = in; if (*in == 0xA) { in++; ctxt->input->line++; ctxt->input->col = 1; } if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } SHRINK; GROW; in = ctxt->input->cur; if (*in == '-') { if (in[1] == '-') { if (in[2] == '>') { if (ctxt->input->id != inputid) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, "comment doesn't start and stop in the same entity\n"); } SKIP(3); if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) && (!ctxt->disableSAX)) { if (buf != NULL) ctxt->sax->comment(ctxt->userData, buf); else ctxt->sax->comment(ctxt->userData, BAD_CAST ""); } if (buf != NULL) xmlFree(buf); ctxt->instate = state; return; } if (buf != NULL) xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, "Comment not terminated \n<!--%.50s\n", buf); else xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, "Comment not terminated \n", NULL); in++; ctxt->input->col++; } in++; ctxt->input->col++; goto get_more; } } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); xmlParseCommentComplex(ctxt, buf, len, size); ctxt->instate = state; return; } CWE ID: CWE-119 Target: 1 Example 2: Code: WebGLRenderingContextBase::CreateWebGraphicsContext3DProvider( CanvasRenderingContextHost* host, const CanvasContextCreationAttributes& attributes, unsigned web_gl_version) { if (!host->IsWebGLAllowed()) { host->HostDispatchEvent(WebGLContextEvent::Create( EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context.")); return nullptr; } return CreateContextProviderInternal(host, attributes, web_gl_version); } 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: MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) (width*height); image_view=AcquireVirtualCacheView(image,exception); threshold_view=AcquireAuthenticCacheView(threshold_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,threshold_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket channel_bias, channel_sum; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p, *magick_restrict r; register IndexPacket *magick_restrict threshold_indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); channel_bias=zero; channel_sum=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { if (u == (ssize_t) (width-1)) { channel_bias.red+=r[u].red; channel_bias.green+=r[u].green; channel_bias.blue+=r[u].blue; channel_bias.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } channel_sum.red+=r[u].red; channel_sum.green+=r[u].green; channel_sum.blue+=r[u].blue; channel_sum.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u); } r+=image->columns+width; } for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean; mean=zero; r=p; channel_sum.red-=channel_bias.red; channel_sum.green-=channel_bias.green; channel_sum.blue-=channel_bias.blue; channel_sum.opacity-=channel_bias.opacity; channel_sum.index-=channel_bias.index; channel_bias=zero; for (v=0; v < (ssize_t) height; v++) { channel_bias.red+=r[0].red; channel_bias.green+=r[0].green; channel_bias.blue+=r[0].blue; channel_bias.opacity+=r[0].opacity; if (image->colorspace == CMYKColorspace) channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0); channel_sum.red+=r[width-1].red; channel_sum.green+=r[width-1].green; channel_sum.blue+=r[width-1].blue; channel_sum.opacity+=r[width-1].opacity; if (image->colorspace == CMYKColorspace) channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+ width-1); r+=image->columns+width; } mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset); mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset); mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset); mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset); SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ? 0 : QuantumRange); SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ? 0 : QuantumRange); SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ? 0 : QuantumRange); SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex( threshold_indexes+x) <= mean.index) ? 0 : QuantumRange)); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } 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: krb5_gss_context_time(minor_status, context_handle, time_rec) OM_uint32 *minor_status; gss_ctx_id_t context_handle; OM_uint32 *time_rec; { krb5_error_code code; krb5_gss_ctx_id_rec *ctx; krb5_timestamp now; krb5_deltat lifetime; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } if ((code = krb5_timeofday(ctx->k5_context, &now))) { *minor_status = code; save_error_info(*minor_status, ctx->k5_context); return(GSS_S_FAILURE); } if ((lifetime = ctx->krb_times.endtime - now) <= 0) { *time_rec = 0; *minor_status = 0; return(GSS_S_CONTEXT_EXPIRED); } else { *time_rec = lifetime; *minor_status = 0; return(GSS_S_COMPLETE); } } CWE ID: Target: 1 Example 2: Code: LayerTreeHostImpl::~LayerTreeHostImpl() { DCHECK(task_runner_provider_->IsImplThread()); TRACE_EVENT0("cc", "LayerTreeHostImpl::~LayerTreeHostImpl()"); TRACE_EVENT_OBJECT_DELETED_WITH_ID(TRACE_DISABLED_BY_DEFAULT("cc.debug"), "cc::LayerTreeHostImpl", id_); DCHECK(!compositor_frame_sink_); DCHECK(!resource_provider_); DCHECK(!resource_pool_); DCHECK(!single_thread_synchronous_task_graph_runner_); DCHECK(!image_decode_cache_); if (input_handler_client_) { input_handler_client_->WillShutdown(); input_handler_client_ = NULL; } if (scroll_elasticity_helper_) scroll_elasticity_helper_.reset(); if (recycle_tree_) recycle_tree_->Shutdown(); if (pending_tree_) pending_tree_->Shutdown(); active_tree_->Shutdown(); recycle_tree_ = nullptr; pending_tree_ = nullptr; active_tree_ = nullptr; mutator_host_->ClearMutators(); mutator_host_->SetMutatorHostClient(nullptr); } 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: Ins_GT( INS_ARG ) { DO_GT } 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: decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; } CWE ID: CWE-415 Target: 1 Example 2: Code: DbeStubScreen(DbeScreenPrivPtr pDbeScreenPriv, int *nStubbedScreens) { /* Stub DIX. */ pDbeScreenPriv->SetupBackgroundPainter = NULL; /* Do not unwrap PositionWindow nor DestroyWindow. If the DDX * initialization function failed, we assume that it did not wrap * PositionWindow. Also, DestroyWindow is only wrapped if the DDX * initialization function succeeded. */ /* Stub DDX. */ pDbeScreenPriv->GetVisualInfo = NULL; pDbeScreenPriv->AllocBackBufferName = NULL; pDbeScreenPriv->SwapBuffers = NULL; pDbeScreenPriv->WinPrivDelete = NULL; (*nStubbedScreens)++; } /* DbeStubScreen() */ CWE ID: CWE-190 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: TIFFNumberOfStrips(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; uint32 nstrips; /* If the value was already computed and store in td_nstrips, then return it, since ChopUpSingleUncompressedStrip might have altered and resized the since the td_stripbytecount and td_stripoffset arrays to the new value after the initial affectation of td_nstrips = TIFFNumberOfStrips() in tif_dirread.c ~line 3612. See http://bugzilla.maptools.org/show_bug.cgi?id=2587 */ if( td->td_nstrips ) return td->td_nstrips; nstrips = (td->td_rowsperstrip == (uint32) -1 ? 1 : TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip)); if (td->td_planarconfig == PLANARCONFIG_SEPARATE) nstrips = _TIFFMultiply32(tif, nstrips, (uint32)td->td_samplesperpixel, "TIFFNumberOfStrips"); return (nstrips); } 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: static uint32_t color_string_to_rgba(const char *p, int len) { uint32_t ret = 0xFF000000; const ColorEntry *entry; char color_name[100]; if (*p == '#') { p++; len--; if (len == 3) { ret |= (hex_char_to_number(p[2]) << 4) | (hex_char_to_number(p[1]) << 12) | (hex_char_to_number(p[0]) << 20); } else if (len == 4) { ret = (hex_char_to_number(p[3]) << 4) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 20) | (hex_char_to_number(p[0]) << 28); } else if (len == 6) { ret |= hex_char_to_number(p[5]) | (hex_char_to_number(p[4]) << 4) | (hex_char_to_number(p[3]) << 8) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 16) | (hex_char_to_number(p[0]) << 20); } else if (len == 8) { ret = hex_char_to_number(p[7]) | (hex_char_to_number(p[6]) << 4) | (hex_char_to_number(p[5]) << 8) | (hex_char_to_number(p[4]) << 12) | (hex_char_to_number(p[3]) << 16) | (hex_char_to_number(p[2]) << 20) | (hex_char_to_number(p[1]) << 24) | (hex_char_to_number(p[0]) << 28); } } else { strncpy(color_name, p, len); color_name[len] = '\0'; entry = bsearch(color_name, color_table, FF_ARRAY_ELEMS(color_table), sizeof(ColorEntry), color_table_compare); if (!entry) return ret; ret = entry->rgb_color; } return ret; } CWE ID: CWE-119 Target: 1 Example 2: Code: void OnBaseReplyMethod(const ProtobufMethodCallback& callback, dbus::Response* response) { cryptohome::BaseReply reply; if (!response) { callback.Run(DBUS_METHOD_CALL_FAILURE, false, reply); return; } dbus::MessageReader reader(response); if (!reader.PopArrayOfBytesAsProto(&reply)) { callback.Run(DBUS_METHOD_CALL_FAILURE, false, reply); return; } callback.Run(DBUS_METHOD_CALL_SUCCESS, true, reply); } 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 rawsock_create(struct net *net, struct socket *sock, const struct nfc_protocol *nfc_proto) { struct sock *sk; pr_debug("sock=%p\n", sock); if (sock->type != SOCK_SEQPACKET) return -ESOCKTNOSUPPORT; sock->ops = &rawsock_ops; sk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sk->sk_protocol = nfc_proto->id; sk->sk_destruct = rawsock_destruct; sock->state = SS_UNCONNECTED; INIT_WORK(&nfc_rawsock(sk)->tx_work, rawsock_tx_work); nfc_rawsock(sk)->tx_work_scheduled = false; return 0; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) + len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); } CWE ID: CWE-125 Target: 1 Example 2: Code: bool BrowserCommandController::UpdateCommandEnabled(int id, bool state) { if (is_locked_fullscreen_) return false; return command_updater_.UpdateCommandEnabled(id, state); } 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 ShellMainDelegate::ZygoteForked() { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableCrashReporter)) { std::string process_type = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessType); breakpad::InitCrashReporter(process_type); } } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BluetoothDeviceChromeOS::Connect( BluetoothDevice::PairingDelegate* pairing_delegate, const base::Closure& callback, const ConnectErrorCallback& error_callback) { if (num_connecting_calls_++ == 0) adapter_->NotifyDeviceChanged(this); VLOG(1) << object_path_.value() << ": Connecting, " << num_connecting_calls_ << " in progress"; if (IsPaired() || !pairing_delegate || !IsPairable()) { ConnectInternal(false, callback, error_callback); } else { DCHECK(!pairing_delegate_); DCHECK(agent_.get() == NULL); pairing_delegate_ = pairing_delegate; pairing_delegate_used_ = false; dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus(); agent_.reset(BluetoothAgentServiceProvider::Create( system_bus, dbus::ObjectPath(kAgentPath), this)); DCHECK(agent_.get()); VLOG(1) << object_path_.value() << ": Registering agent for pairing"; DBusThreadManager::Get()->GetBluetoothAgentManagerClient()-> RegisterAgent( dbus::ObjectPath(kAgentPath), bluetooth_agent_manager::kKeyboardDisplayCapability, base::Bind(&BluetoothDeviceChromeOS::OnRegisterAgent, weak_ptr_factory_.GetWeakPtr(), callback, error_callback), base::Bind(&BluetoothDeviceChromeOS::OnRegisterAgentError, weak_ptr_factory_.GetWeakPtr(), error_callback)); } } CWE ID: Target: 1 Example 2: Code: int tls_construct_next_proto(SSL *s) { unsigned int len, padding_len; unsigned char *d; len = s->next_proto_negotiated_len; padding_len = 32 - ((len + 2) % 32); d = (unsigned char *)s->init_buf->data; d[4] = len; memcpy(d + 5, s->next_proto_negotiated, len); d[5 + len] = padding_len; memset(d + 6 + len, 0, padding_len); *(d++) = SSL3_MT_NEXT_PROTO; l2n3(2 + len + padding_len, d); s->init_num = 4 + 2 + len + padding_len; s->init_off = 0; return 1; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int handle_opendir(FsContext *ctx, V9fsPath *fs_path, V9fsFidOpenState *fs) { int ret; ret = handle_open(ctx, fs_path, O_DIRECTORY, fs); if (ret < 0) { return -1; } fs->dir.stream = fdopendir(ret); if (!fs->dir.stream) { return -1; } return 0; } CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct atm_vcc *vcc; struct sk_buff *skb; int copied, error = -EINVAL; if (sock->state != SS_CONNECTED) return -ENOTCONN; /* only handle MSG_DONTWAIT and MSG_PEEK */ if (flags & ~(MSG_DONTWAIT | MSG_PEEK)) return -EOPNOTSUPP; vcc = ATM_SD(sock); if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) return 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error); if (!skb) return error; copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (error) return error; sock_recv_ts_and_drops(msg, sk, skb); if (!(flags & MSG_PEEK)) { pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc), skb->truesize); atm_return(vcc, skb->truesize); } skb_free_datagram(sk, skb); return copied; } CWE ID: CWE-200 Target: 1 Example 2: Code: bool TestRenderWidgetHostView::HasAcceleratedSurface( const gfx::Size& desired_size) { return 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: ConfirmInfoBarDelegate::ConfirmInfoBarDelegate() : InfoBarDelegate() { } 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: int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *inet = inet_sk(sk); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); int is_udp4; bool slow; if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len, addr_len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len, addr_len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; is_udp4 = (skb->protocol == htons(ETH_P_IP)); /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_msg(skb, sizeof(struct udphdr), msg, copied); else { err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udpv6_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) { if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); } sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (msg->msg_name) { DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name); sin6->sin6_family = AF_INET6; sin6->sin6_port = udp_hdr(skb)->source; sin6->sin6_flowinfo = 0; if (is_udp4) { ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &sin6->sin6_addr); sin6->sin6_scope_id = 0; } else { sin6->sin6_addr = ipv6_hdr(skb)->saddr; sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, inet6_iif(skb)); } *addr_len = sizeof(*sin6); } if (np->rxopt.all) ip6_datagram_recv_common_ctl(sk, msg, skb); if (is_udp4) { if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); } else { if (np->rxopt.all) ip6_datagram_recv_specific_ctl(sk, msg, skb); } err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { if (is_udp4) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } else { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } CWE ID: CWE-399 Target: 1 Example 2: Code: String AXObject::ariaTextAlternative(bool recursive, bool inAriaLabelledByTraversal, AXObjectSet& visited, AXNameFrom& nameFrom, AXRelatedObjectVector* relatedObjects, NameSources* nameSources, bool* foundTextAlternative) const { String textAlternative; bool alreadyVisited = visited.contains(this); visited.insert(this); if (!inAriaLabelledByTraversal && isHiddenForTextAlternativeCalculation()) { *foundTextAlternative = true; return String(); } if (!inAriaLabelledByTraversal && !alreadyVisited) { const QualifiedName& attr = hasAttribute(aria_labeledbyAttr) && !hasAttribute(aria_labelledbyAttr) ? aria_labeledbyAttr : aria_labelledbyAttr; nameFrom = AXNameFromRelatedElement; if (nameSources) { nameSources->push_back(NameSource(*foundTextAlternative, attr)); nameSources->back().type = nameFrom; } const AtomicString& ariaLabelledby = getAttribute(attr); if (!ariaLabelledby.isNull()) { if (nameSources) nameSources->back().attributeValue = ariaLabelledby; AXObjectSet visitedCopy = visited; textAlternative = textFromAriaLabelledby(visitedCopy, relatedObjects); if (!textAlternative.isNull()) { if (nameSources) { NameSource& source = nameSources->back(); source.type = nameFrom; source.relatedObjects = *relatedObjects; source.text = textAlternative; *foundTextAlternative = true; } else { *foundTextAlternative = true; return textAlternative; } } else if (nameSources) { nameSources->back().invalid = true; } } } nameFrom = AXNameFromAttribute; if (nameSources) { nameSources->push_back(NameSource(*foundTextAlternative, aria_labelAttr)); nameSources->back().type = nameFrom; } const AtomicString& ariaLabel = getAOMPropertyOrARIAAttribute(AOMStringProperty::kLabel); if (!ariaLabel.isEmpty()) { textAlternative = ariaLabel; if (nameSources) { NameSource& source = nameSources->back(); source.text = textAlternative; source.attributeValue = ariaLabel; *foundTextAlternative = true; } else { *foundTextAlternative = true; return textAlternative; } } return textAlternative; } 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: virtual void ShowContextMenu(const content::ContextMenuParams& params) {} 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: struct crypto_alg *crypto_larval_lookup(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; if (!name) return ERR_PTR(-ENOENT); mask &= ~(CRYPTO_ALG_LARVAL | CRYPTO_ALG_DEAD); type &= mask; alg = crypto_alg_lookup(name, type, mask); if (!alg) { request_module("%s", name); if (!((type ^ CRYPTO_ALG_NEED_FALLBACK) & mask & CRYPTO_ALG_NEED_FALLBACK)) request_module("%s-all", name); alg = crypto_alg_lookup(name, type, mask); } if (alg) return crypto_is_larval(alg) ? crypto_larval_wait(alg) : alg; return crypto_larval_add(name, type, mask); } CWE ID: CWE-264 Target: 1 Example 2: Code: void AudioMixerAlsa::Connect() { DCHECK(MessageLoop::current() == thread_->message_loop()); DCHECK(!alsa_mixer_); if (disconnected_event_.IsSignaled()) return; if (!ConnectInternal()) { thread_->message_loop()->PostDelayedTask(FROM_HERE, base::Bind(&AudioMixerAlsa::Connect, base::Unretained(this)), kConnectionRetrySleepSec * 1000); } } 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 WebMediaPlayerMS::DidGetOpaqueResponseFromServiceWorker() const { DCHECK(thread_checker_.CalledOnValidThread()); return false; } CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: svc_set_num_threads(struct svc_serv *serv, struct svc_pool *pool, int nrservs) { struct svc_rqst *rqstp; struct task_struct *task; struct svc_pool *chosen_pool; int error = 0; unsigned int state = serv->sv_nrthreads-1; int node; if (pool == NULL) { /* The -1 assumes caller has done a svc_get() */ nrservs -= (serv->sv_nrthreads-1); } else { spin_lock_bh(&pool->sp_lock); nrservs -= pool->sp_nrthreads; spin_unlock_bh(&pool->sp_lock); } /* create new threads */ while (nrservs > 0) { nrservs--; chosen_pool = choose_pool(serv, pool, &state); node = svc_pool_map_get_node(chosen_pool->sp_id); rqstp = svc_prepare_thread(serv, chosen_pool, node); if (IS_ERR(rqstp)) { error = PTR_ERR(rqstp); break; } __module_get(serv->sv_ops->svo_module); task = kthread_create_on_node(serv->sv_ops->svo_function, rqstp, node, "%s", serv->sv_name); if (IS_ERR(task)) { error = PTR_ERR(task); module_put(serv->sv_ops->svo_module); svc_exit_thread(rqstp); break; } rqstp->rq_task = task; if (serv->sv_nrpools > 1) svc_pool_map_set_cpumask(task, chosen_pool->sp_id); svc_sock_update_bufs(serv); wake_up_process(task); } /* destroy old threads */ while (nrservs < 0 && (task = choose_victim(serv, pool, &state)) != NULL) { send_sig(SIGINT, task, 1); nrservs++; } return error; } CWE ID: CWE-404 Target: 1 Example 2: Code: xsltCompileIdKeyPattern(xsltParserContextPtr ctxt, xmlChar *name, int aid, int novar, xsltAxis axis) { xmlChar *lit = NULL; xmlChar *lit2 = NULL; if (CUR != '(') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ( expected\n"); ctxt->error = 1; return; } if ((aid) && (xmlStrEqual(name, (const xmlChar *)"id"))) { if (axis != 0) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : NodeTest expected\n"); ctxt->error = 1; return; } NEXT; SKIP_BLANKS; lit = xsltScanLiteral(ctxt); if (ctxt->error) return; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } NEXT; PUSH(XSLT_OP_ID, lit, NULL, novar); } else if ((aid) && (xmlStrEqual(name, (const xmlChar *)"key"))) { if (axis != 0) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : NodeTest expected\n"); ctxt->error = 1; return; } NEXT; SKIP_BLANKS; lit = xsltScanLiteral(ctxt); if (ctxt->error) return; SKIP_BLANKS; if (CUR != ',') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : , expected\n"); ctxt->error = 1; return; } NEXT; SKIP_BLANKS; lit2 = xsltScanLiteral(ctxt); if (ctxt->error) return; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } NEXT; /* URGENT TODO: support namespace in keys */ PUSH(XSLT_OP_KEY, lit, lit2, novar); } else if (xmlStrEqual(name, (const xmlChar *)"processing-instruction")) { NEXT; SKIP_BLANKS; if (CUR != ')') { lit = xsltScanLiteral(ctxt); if (ctxt->error) return; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } } NEXT; PUSH(XSLT_OP_PI, lit, NULL, novar); } else if (xmlStrEqual(name, (const xmlChar *)"text")) { NEXT; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } NEXT; PUSH(XSLT_OP_TEXT, NULL, NULL, novar); } else if (xmlStrEqual(name, (const xmlChar *)"comment")) { NEXT; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } NEXT; PUSH(XSLT_OP_COMMENT, NULL, NULL, novar); } else if (xmlStrEqual(name, (const xmlChar *)"node")) { NEXT; SKIP_BLANKS; if (CUR != ')') { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : ) expected\n"); ctxt->error = 1; return; } NEXT; if (axis == AXIS_ATTRIBUTE) { PUSH(XSLT_OP_ATTR, NULL, NULL, novar); } else { PUSH(XSLT_OP_NODE, NULL, NULL, novar); } } else if (aid) { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : expecting 'key' or 'id' or node type\n"); ctxt->error = 1; return; } else { xsltTransformError(NULL, NULL, NULL, "xsltCompileIdKeyPattern : node type\n"); ctxt->error = 1; return; } error: if (name != NULL) xmlFree(name); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: passphrase_callback(struct archive *a, void *_client_data) { struct bsdtar *bsdtar = (struct bsdtar *)_client_data; (void)a; /* UNUSED */ if (bsdtar->ppbuff == NULL) { bsdtar->ppbuff = malloc(PPBUFF_SIZE); if (bsdtar->ppbuff == NULL) lafe_errc(1, errno, "Out of memory"); } return lafe_readpassphrase("Enter passphrase:", bsdtar->ppbuff, PPBUFF_SIZE); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void mark_screen_rdonly(struct mm_struct *mm) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; spinlock_t *ptl; int i; pgd = pgd_offset(mm, 0xA0000); if (pgd_none_or_clear_bad(pgd)) goto out; pud = pud_offset(pgd, 0xA0000); if (pud_none_or_clear_bad(pud)) goto out; pmd = pmd_offset(pud, 0xA0000); split_huge_page_pmd(mm, pmd); if (pmd_none_or_clear_bad(pmd)) goto out; pte = pte_offset_map_lock(mm, pmd, 0xA0000, &ptl); for (i = 0; i < 32; i++) { if (pte_present(*pte)) set_pte(pte, pte_wrprotect(*pte)); pte++; } pte_unmap_unlock(pte, ptl); out: flush_tlb(); } CWE ID: CWE-264 Target: 1 Example 2: Code: static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb, struct iocb *iocb, struct kiocb_batch *batch, bool compat) { struct kiocb *req; struct file *file; ssize_t ret; /* enforce forwards compatibility on users */ if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) { pr_debug("EINVAL: io_submit: reserve field set\n"); return -EINVAL; } /* prevent overflows */ if (unlikely( (iocb->aio_buf != (unsigned long)iocb->aio_buf) || (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) || ((ssize_t)iocb->aio_nbytes < 0) )) { pr_debug("EINVAL: io_submit: overflow check\n"); return -EINVAL; } file = fget(iocb->aio_fildes); if (unlikely(!file)) return -EBADF; req = aio_get_req(ctx, batch); /* returns with 2 references to req */ if (unlikely(!req)) { fput(file); return -EAGAIN; } req->ki_filp = file; if (iocb->aio_flags & IOCB_FLAG_RESFD) { /* * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an * instance of the file* now. The file descriptor must be * an eventfd() fd, and will be signaled for each completed * event using the eventfd_signal() function. */ req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd); if (IS_ERR(req->ki_eventfd)) { ret = PTR_ERR(req->ki_eventfd); req->ki_eventfd = NULL; goto out_put_req; } } ret = put_user(req->ki_key, &user_iocb->aio_key); if (unlikely(ret)) { dprintk("EFAULT: aio_key\n"); goto out_put_req; } req->ki_obj.user = user_iocb; req->ki_user_data = iocb->aio_data; req->ki_pos = iocb->aio_offset; req->ki_buf = (char __user *)(unsigned long)iocb->aio_buf; req->ki_left = req->ki_nbytes = iocb->aio_nbytes; req->ki_opcode = iocb->aio_lio_opcode; ret = aio_setup_iocb(req, compat); if (ret) goto out_put_req; spin_lock_irq(&ctx->ctx_lock); /* * We could have raced with io_destroy() and are currently holding a * reference to ctx which should be destroyed. We cannot submit IO * since ctx gets freed as soon as io_submit() puts its reference. The * check here is reliable: io_destroy() sets ctx->dead before waiting * for outstanding IO and the barrier between these two is realized by * unlock of mm->ioctx_lock and lock of ctx->ctx_lock. Analogously we * increment ctx->reqs_active before checking for ctx->dead and the * barrier is realized by unlock and lock of ctx->ctx_lock. Thus if we * don't see ctx->dead set here, io_destroy() waits for our IO to * finish. */ if (ctx->dead) { spin_unlock_irq(&ctx->ctx_lock); ret = -EINVAL; goto out_put_req; } aio_run_iocb(req); if (!list_empty(&ctx->run_list)) { /* drain the run list */ while (__aio_run_iocbs(ctx)) ; } spin_unlock_irq(&ctx->ctx_lock); aio_put_req(req); /* drop extra ref to req */ return 0; out_put_req: aio_put_req(req); /* drop extra ref to req */ aio_put_req(req); /* drop i/o ref to req */ 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: XpmCreateDataFromXpmImage( char ***data_return, XpmImage *image, XpmInfo *info) { /* calculation variables */ int ErrorStatus; char buf[BUFSIZ]; char **header = NULL, **data, **sptr, **sptr2, *s; unsigned int header_size, header_nlines; unsigned int data_size, data_nlines; unsigned int extensions = 0, ext_size = 0, ext_nlines = 0; unsigned int offset, l, n; *data_return = NULL; extensions = info && (info->valuemask & XpmExtensions) && info->nextensions; /* compute the number of extensions lines and size */ if (extensions) CountExtensions(info->extensions, info->nextensions, &ext_size, &ext_nlines); /* * alloc a temporary array of char pointer for the header section which */ header_nlines = 1 + image->ncolors; /* this may wrap and/or become 0 */ /* 2nd check superfluous if we do not need header_nlines any further */ if(header_nlines <= image->ncolors || header_nlines >= UINT_MAX / sizeof(char *)) return(XpmNoMemory); header_size = sizeof(char *) * header_nlines; if (header_size >= UINT_MAX / sizeof(char *)) return (XpmNoMemory); header = (char **) XpmCalloc(header_size, sizeof(char *)); /* can we trust image->ncolors */ if (!header) return (XpmNoMemory); /* print the hints line */ s = buf; #ifndef VOID_SPRINTF s += #endif sprintf(s, "%d %d %d %d", image->width, image->height, image->ncolors, image->cpp); #ifdef VOID_SPRINTF s += strlen(s); #endif if (info && (info->valuemask & XpmHotspot)) { #ifndef VOID_SPRINTF s += #endif sprintf(s, " %d %d", info->x_hotspot, info->y_hotspot); #ifdef VOID_SPRINTF s += strlen(s); #endif } if (extensions) { strcpy(s, " XPMEXT"); s += 7; } l = s - buf + 1; *header = (char *) XpmMalloc(l); if (!*header) RETURN(XpmNoMemory); header_size += l; strcpy(*header, buf); /* print colors */ ErrorStatus = CreateColors(header + 1, &header_size, image->colorTable, image->ncolors, image->cpp); if (ErrorStatus != XpmSuccess) RETURN(ErrorStatus); /* now we know the size needed, alloc the data and copy the header lines */ offset = image->width * image->cpp + 1; if(offset <= image->width || offset <= image->cpp) if(offset <= image->width || offset <= image->cpp) RETURN(XpmNoMemory); if( (image->height + ext_nlines) >= UINT_MAX / sizeof(char *)) RETURN(XpmNoMemory); data_size = (image->height + ext_nlines) * sizeof(char *); RETURN(XpmNoMemory); data_size += image->height * offset; RETURN(XpmNoMemory); data_size += image->height * offset; if( (header_size + ext_size) >= (UINT_MAX - data_size) ) RETURN(XpmNoMemory); data_size += header_size + ext_size; data_nlines = header_nlines + image->height + ext_nlines; *data = (char *) (data + data_nlines); /* can header have less elements then n suggests? */ n = image->ncolors; for (l = 0, sptr = data, sptr2 = header; l <= n && sptr && sptr2; l++, sptr++, sptr2++) { strcpy(*sptr, *sptr2); *(sptr + 1) = *sptr + strlen(*sptr2) + 1; } /* print pixels */ data[header_nlines] = (char *) data + header_size + (image->height + ext_nlines) * sizeof(char *); CreatePixels(data + header_nlines, data_size-header_nlines, image->width, image->height, image->cpp, image->data, image->colorTable); /* print extensions */ if (extensions) CreateExtensions(data + header_nlines + image->height - 1, data_size - header_nlines - image->height + 1, offset, info->extensions, info->nextensions, ext_nlines); *data_return = data; ErrorStatus = XpmSuccess; /* exit point, free only locally allocated variables */ exit: if (header) { for (l = 0; l < header_nlines; l++) if (header[l]) XpmFree(header[l]); XpmFree(header); } return(ErrorStatus); } CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GLManager::InitializeWithWorkaroundsImpl( const GLManager::Options& options, const GpuDriverBugWorkarounds& workarounds) { const SharedMemoryLimits limits; const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); DCHECK(!command_line.HasSwitch(switches::kDisableGLExtensions)); InitializeGpuPreferencesForTestingFromCommandLine(command_line, &gpu_preferences_); if (options.share_mailbox_manager) { mailbox_manager_ = options.share_mailbox_manager->mailbox_manager(); } else if (options.share_group_manager) { mailbox_manager_ = options.share_group_manager->mailbox_manager(); } else { mailbox_manager_ = &owned_mailbox_manager_; } gl::GLShareGroup* share_group = NULL; if (options.share_group_manager) { share_group = options.share_group_manager->share_group(); } else if (options.share_mailbox_manager) { share_group = options.share_mailbox_manager->share_group(); } gles2::ContextGroup* context_group = NULL; scoped_refptr<gles2::ShareGroup> client_share_group; if (options.share_group_manager) { context_group = options.share_group_manager->decoder_->GetContextGroup(); client_share_group = options.share_group_manager->gles2_implementation()->share_group(); } gl::GLContext* real_gl_context = NULL; if (options.virtual_manager && !gpu_preferences_.use_passthrough_cmd_decoder) { real_gl_context = options.virtual_manager->context(); } share_group_ = share_group ? share_group : new gl::GLShareGroup; ContextCreationAttribs attribs; attribs.red_size = 8; attribs.green_size = 8; attribs.blue_size = 8; attribs.alpha_size = 8; attribs.depth_size = 16; attribs.stencil_size = 8; attribs.context_type = options.context_type; attribs.samples = options.multisampled ? 4 : 0; attribs.sample_buffers = options.multisampled ? 1 : 0; attribs.alpha_size = options.backbuffer_alpha ? 8 : 0; attribs.should_use_native_gmb_for_backbuffer = options.image_factory != nullptr; attribs.offscreen_framebuffer_size = options.size; attribs.buffer_preserved = options.preserve_backbuffer; attribs.bind_generates_resource = options.bind_generates_resource; translator_cache_ = std::make_unique<gles2::ShaderTranslatorCache>(gpu_preferences_); if (!context_group) { scoped_refptr<gles2::FeatureInfo> feature_info = new gles2::FeatureInfo(workarounds); context_group = new gles2::ContextGroup( gpu_preferences_, true, mailbox_manager_, nullptr /* memory_tracker */, translator_cache_.get(), &completeness_cache_, feature_info, options.bind_generates_resource, &image_manager_, options.image_factory, nullptr /* progress_reporter */, GpuFeatureInfo(), &discardable_manager_); } command_buffer_.reset(new CommandBufferCheckLostContext( context_group->transfer_buffer_manager(), options.sync_point_manager, options.context_lost_allowed)); decoder_.reset(::gpu::gles2::GLES2Decoder::Create( command_buffer_.get(), command_buffer_->service(), &outputter_, context_group)); if (options.force_shader_name_hashing) { decoder_->SetForceShaderNameHashingForTest(true); } command_buffer_->set_handler(decoder_.get()); surface_ = gl::init::CreateOffscreenGLSurface(gfx::Size()); ASSERT_TRUE(surface_.get() != NULL) << "could not create offscreen surface"; if (base_context_) { context_ = scoped_refptr<gl::GLContext>(new gpu::GLContextVirtual( share_group_.get(), base_context_->get(), decoder_->AsWeakPtr())); ASSERT_TRUE(context_->Initialize( surface_.get(), GenerateGLContextAttribs(attribs, context_group))); } else { if (real_gl_context) { context_ = scoped_refptr<gl::GLContext>(new gpu::GLContextVirtual( share_group_.get(), real_gl_context, decoder_->AsWeakPtr())); ASSERT_TRUE(context_->Initialize( surface_.get(), GenerateGLContextAttribs(attribs, context_group))); } else { context_ = gl::init::CreateGLContext( share_group_.get(), surface_.get(), GenerateGLContextAttribs(attribs, context_group)); g_gpu_feature_info.ApplyToGLContext(context_.get()); } } ASSERT_TRUE(context_.get() != NULL) << "could not create GL context"; ASSERT_TRUE(context_->MakeCurrent(surface_.get())); auto result = decoder_->Initialize(surface_.get(), context_.get(), true, ::gpu::gles2::DisallowedFeatures(), attribs); if (result != gpu::ContextResult::kSuccess) return; capabilities_ = decoder_->GetCapabilities(); gles2_helper_.reset(new gles2::GLES2CmdHelper(command_buffer_.get())); ASSERT_EQ(gles2_helper_->Initialize(limits.command_buffer_size), gpu::ContextResult::kSuccess); transfer_buffer_.reset(new TransferBuffer(gles2_helper_.get())); const bool support_client_side_arrays = true; gles2_implementation_.reset(new gles2::GLES2Implementation( gles2_helper_.get(), std::move(client_share_group), transfer_buffer_.get(), options.bind_generates_resource, options.lose_context_when_out_of_memory, support_client_side_arrays, this)); ASSERT_EQ(gles2_implementation_->Initialize(limits), gpu::ContextResult::kSuccess) << "Could not init GLES2Implementation"; MakeCurrent(); } CWE ID: CWE-200 Target: 1 Example 2: Code: e1000e_set_phy_page(E1000ECore *core, int index, uint16_t val) { core->phy[0][PHY_PAGE] = val & PHY_PAGE_RW_MASK; } CWE ID: CWE-835 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool svm_xsaves_supported(void) { return false; } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BufferQueueConsumer::dump(String8& result, const char* prefix) const { mCore->dump(result, prefix); } CWE ID: CWE-264 Target: 1 Example 2: Code: OMX_ERRORTYPE omx_video::push_empty_eos_buffer(OMX_HANDLETYPE hComp, OMX_BUFFERHEADERTYPE* buffer) { OMX_BUFFERHEADERTYPE* opqBuf = NULL; OMX_ERRORTYPE retVal = OMX_ErrorNone; unsigned index = 0; DEBUG_PRINT_LOW("In push empty eos buffer"); do { if (mUsesColorConversion) { if (pdest_frame) { opqBuf = pdest_frame; pdest_frame = NULL; } else if (m_opq_pmem_q.m_size) { unsigned long address = 0, p2, id; m_opq_pmem_q.pop_entry(&address,&p2,&id); opqBuf = (OMX_BUFFERHEADERTYPE* ) address; } index = opqBuf - m_inp_mem_ptr; } else { opqBuf = (OMX_BUFFERHEADERTYPE* ) buffer; index = opqBuf - meta_buffer_hdr; } if (!opqBuf || index >= m_sInPortDef.nBufferCountActual) { DEBUG_PRINT_ERROR("push_empty_eos_buffer: Could not find a " "color-conversion buffer to queue ! defer until available"); return OMX_ErrorNone; } struct pmem Input_pmem_info; Input_pmem_info.buffer = opqBuf; Input_pmem_info.fd = m_pInput_pmem[index].fd; Input_pmem_info.offset = 0; Input_pmem_info.size = m_pInput_pmem[index].size; if (dev_use_buf(&Input_pmem_info, PORT_INDEX_IN, 0) != true) { DEBUG_PRINT_ERROR("ERROR: in dev_use_buf for empty eos buffer"); retVal = OMX_ErrorBadParameter; break; } OMX_BUFFERHEADERTYPE emptyEosBufHdr; memcpy(&emptyEosBufHdr, opqBuf, sizeof(OMX_BUFFERHEADERTYPE)); emptyEosBufHdr.nFilledLen = 0; emptyEosBufHdr.nTimeStamp = buffer->nTimeStamp; emptyEosBufHdr.nFlags = buffer->nFlags; emptyEosBufHdr.pBuffer = NULL; if (!mUsesColorConversion) emptyEosBufHdr.nAllocLen = m_sInPortDef.nBufferSize; if (dev_empty_buf(&emptyEosBufHdr, 0, index, m_pInput_pmem[index].fd) != true) { DEBUG_PRINT_ERROR("ERROR: in dev_empty_buf for empty eos buffer"); dev_free_buf(&Input_pmem_info, PORT_INDEX_IN); retVal = OMX_ErrorBadParameter; break; } mEmptyEosBuffer = opqBuf; } while(false); m_pCallbacks.EmptyBufferDone(hComp, m_app_data, buffer); --pending_input_buffers; return retVal; } 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 hash_setkey(void *private, const u8 *key, unsigned int keylen) { return crypto_ahash_setkey(private, key, keylen); } CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void NavigationControllerImpl::Reload(ReloadType reload_type, bool check_for_repost) { DCHECK_NE(ReloadType::NONE, reload_type); if (transient_entry_index_ != -1) { NavigationEntryImpl* transient_entry = GetTransientEntry(); if (!transient_entry) return; LoadURL(transient_entry->GetURL(), Referrer(), ui::PAGE_TRANSITION_RELOAD, transient_entry->extra_headers()); return; } NavigationEntryImpl* entry = nullptr; int current_index = -1; if (IsInitialNavigation() && pending_entry_) { entry = pending_entry_; current_index = pending_entry_index_; } else { DiscardNonCommittedEntriesInternal(); current_index = GetCurrentEntryIndex(); if (current_index != -1) { entry = GetEntryAtIndex(current_index); } } if (!entry) return; if (last_committed_reload_type_ != ReloadType::NONE) { DCHECK(!last_committed_reload_time_.is_null()); base::Time now = time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run()); DCHECK_GT(now, last_committed_reload_time_); if (!last_committed_reload_time_.is_null() && now > last_committed_reload_time_) { base::TimeDelta delta = now - last_committed_reload_time_; UMA_HISTOGRAM_MEDIUM_TIMES("Navigation.Reload.ReloadToReloadDuration", delta); if (last_committed_reload_type_ == ReloadType::NORMAL) { UMA_HISTOGRAM_MEDIUM_TIMES( "Navigation.Reload.ReloadMainResourceToReloadDuration", delta); } } } entry->set_reload_type(reload_type); if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) { delegate_->NotifyBeforeFormRepostWarningShow(); pending_reload_ = reload_type; delegate_->ActivateAndShowRepostFormWarningDialog(); } else { if (!IsInitialNavigation()) DiscardNonCommittedEntriesInternal(); SiteInstanceImpl* site_instance = entry->site_instance(); bool is_for_guests_only = site_instance && site_instance->HasProcess() && site_instance->GetProcess()->IsForGuestsOnly(); if (!is_for_guests_only && site_instance && site_instance->HasWrongProcessForURL(entry->GetURL())) { NavigationEntryImpl* nav_entry = NavigationEntryImpl::FromNavigationEntry( CreateNavigationEntry(entry->GetURL(), entry->GetReferrer(), entry->GetTransitionType(), false, entry->extra_headers(), browser_context_, nullptr /* blob_url_loader_factory */) .release()); reload_type = ReloadType::NONE; nav_entry->set_should_replace_entry(true); pending_entry_ = nav_entry; DCHECK_EQ(-1, pending_entry_index_); } else { pending_entry_ = entry; pending_entry_index_ = current_index; pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD); } NavigateToPendingEntry(reload_type, nullptr /* navigation_ui_data */); } } CWE ID: Target: 1 Example 2: Code: static inline void *align_ptr(void *p, unsigned int align) { return (void *)ALIGN((unsigned long)p, align); } 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 PSIR_FileWriter::SetImgRsrc ( XMP_Uns16 id, const void* clientPtr, XMP_Uns32 length ) { InternalRsrcInfo* rsrcPtr = 0; InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id ); if ( rsrcPos == this->imgRsrcs.end() ) { InternalRsrcMap::value_type mapValue ( id, InternalRsrcInfo ( id, length, this->fileParsed ) ); rsrcPos = this->imgRsrcs.insert ( rsrcPos, mapValue ); rsrcPtr = &rsrcPos->second; } else { rsrcPtr = &rsrcPos->second; if ( (length == rsrcPtr->dataLen) && (memcmp ( rsrcPtr->dataPtr, clientPtr, length ) == 0) ) { return; } rsrcPtr->FreeData(); // Release any existing data allocation. rsrcPtr->dataLen = length; // And this might be changing. } rsrcPtr->changed = true; rsrcPtr->dataPtr = malloc ( length ); if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); memcpy ( rsrcPtr->dataPtr, clientPtr, length ); // AUDIT: Safe, malloc'ed length bytes above. this->changed = true; } // PSIR_FileWriter::SetImgRsrc 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: ltree_in(PG_FUNCTION_ARGS) { char *buf = (char *) PG_GETARG_POINTER(0); char *ptr; nodeitem *list, *lptr; int num = 0, totallen = 0; int state = LTPRS_WAITNAME; ltree *result; ltree_level *curlevel; int charlen; int pos = 0; ptr = buf; while (*ptr) { charlen = pg_mblen(ptr); if (charlen == 1 && t_iseq(ptr, '.')) num++; ptr += charlen; } list = lptr = (nodeitem *) palloc(sizeof(nodeitem) * (num + 1)); ptr = buf; while (*ptr) { charlen = pg_mblen(ptr); if (state == LTPRS_WAITNAME) { if (ISALNUM(ptr)) { lptr->start = ptr; lptr->wlen = 0; state = LTPRS_WAITDELIM; } else UNCHAR; } else if (state == LTPRS_WAITDELIM) { if (charlen == 1 && t_iseq(ptr, '.')) { lptr->len = ptr - lptr->start; if (lptr->wlen > 255) ereport(ERROR, (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("Name length is %d, must " "be < 256, in position %d.", lptr->wlen, pos))); totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE); lptr++; state = LTPRS_WAITNAME; } else if (!ISALNUM(ptr)) UNCHAR; } else /* internal error */ elog(ERROR, "internal error in parser"); ptr += charlen; lptr->wlen++; pos++; } if (state == LTPRS_WAITDELIM) { lptr->len = ptr - lptr->start; if (lptr->wlen > 255) ereport(ERROR, (errcode(ERRCODE_NAME_TOO_LONG), errmsg("name of level is too long"), errdetail("Name length is %d, must " "be < 256, in position %d.", lptr->wlen, pos))); totallen += MAXALIGN(lptr->len + LEVEL_HDRSIZE); lptr++; } else if (!(state == LTPRS_WAITNAME && lptr == list)) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("syntax error"), errdetail("Unexpected end of line."))); result = (ltree *) palloc0(LTREE_HDRSIZE + totallen); SET_VARSIZE(result, LTREE_HDRSIZE + totallen); result->numlevel = lptr - list; curlevel = LTREE_FIRST(result); lptr = list; while (lptr - list < result->numlevel) { curlevel->len = (uint16) lptr->len; memcpy(curlevel->name, lptr->start, lptr->len); curlevel = LEVEL_NEXT(curlevel); lptr++; } pfree(list); PG_RETURN_POINTER(result); } CWE ID: CWE-189 Target: 1 Example 2: Code: static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) { size_t i; unsigned key = 0; unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ for(i = 0; i < palettesize; i++) { if(!key && palette[4 * i + 3] == 0) { r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2]; key = 1; i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ } else if(palette[4 * i + 3] != 255) return 2; /*when key, no opaque RGB may have key's RGB*/ else if(key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2; } return key; } CWE ID: CWE-772 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int64 GetReceivedListPrefValue(size_t index) { return ListPrefInt64Value(*received_update_, index); } 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: void ResourceDispatcherHostImpl::OnSSLCertificateError( net::URLRequest* request, const net::SSLInfo& ssl_info, bool is_hsts_host) { DCHECK(request); ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); DCHECK(info); GlobalRequestID request_id(info->GetChildID(), info->GetRequestID()); int render_process_id; int render_view_id; if(!info->GetAssociatedRenderView(&render_process_id, &render_view_id)) NOTREACHED(); SSLManager::OnSSLCertificateError(ssl_delegate_weak_factory_.GetWeakPtr(), request_id, info->GetResourceType(), request->url(), render_process_id, render_view_id, ssl_info, is_hsts_host); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int ahci_dma_rw_buf(IDEDMA *dma, int is_write) { AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma); IDEState *s = &ad->port.ifs[0]; uint8_t *p = s->io_buffer + s->io_buffer_index; int l = s->io_buffer_size - s->io_buffer_index; if (ahci_populate_sglist(ad, &s->sg, s->io_buffer_offset)) { return 0; } if (is_write) { dma_buf_read(p, l, &s->sg); } else { dma_buf_write(p, l, &s->sg); } /* free sglist that was created in ahci_populate_sglist() */ qemu_sglist_destroy(&s->sg); /* update number of transferred bytes */ ad->cur_cmd->status = cpu_to_le32(le32_to_cpu(ad->cur_cmd->status) + l); s->io_buffer_index += l; s->io_buffer_offset += l; DPRINTF(ad->port_no, "len=%#x\n", l); return 1; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int parse_token(char **name, char **value, char **cp) { char *end; if (!name || !value || !cp) return -BLKID_ERR_PARAM; if (!(*value = strchr(*cp, '='))) return 0; **value = '\0'; *name = strip_line(*cp); *value = skip_over_blank(*value + 1); if (**value == '"') { end = strchr(*value + 1, '"'); if (!end) { DBG(READ, ul_debug("unbalanced quotes at: %s", *value)); *cp = *value; return -BLKID_ERR_CACHE; } (*value)++; *end = '\0'; end++; } else { end = skip_over_word(*value); if (*end) { *end = '\0'; end++; } } *cp = end; return 1; } CWE ID: CWE-77 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void SetUp() { const tuple<int, int, VarianceFunctionType>& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; variance_ = get<2>(params); rnd(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; src_ = new uint8_t[block_size_]; ref_ = new uint8_t[block_size_]; ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(ref_ != NULL); } CWE ID: CWE-119 Target: 1 Example 2: Code: static int jp2_putuint16(jas_stream_t *out, uint_fast16_t val) { if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF || jas_stream_putc(out, val & 0xff) == EOF) { return -1; } return 0; } CWE ID: CWE-476 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num) { const uni_to_enc *l = table, *h = &table[num-1], *m; unsigned short code_key; /* we have no mappings outside the BMP */ if (code_key_a > 0xFFFFU) return 0; code_key = (unsigned short) code_key_a; while (l <= h) { m = l + (h - l) / 2; if (code_key < m->un_code_point) h = m - 1; else if (code_key > m->un_code_point) l = m + 1; else return m->cs_code; } return 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: acc_ctx_new(OM_uint32 *minor_status, gss_buffer_t buf, gss_ctx_id_t *ctx, spnego_gss_cred_id_t spcred, gss_buffer_t *mechToken, gss_buffer_t *mechListMIC, OM_uint32 *negState, send_token_flag *return_token) { OM_uint32 tmpmin, ret, req_flags; gss_OID_set supported_mechSet, mechTypes; gss_buffer_desc der_mechTypes; gss_OID mech_wanted; spnego_gss_ctx_id_t sc = NULL; ret = GSS_S_DEFECTIVE_TOKEN; der_mechTypes.length = 0; der_mechTypes.value = NULL; *mechToken = *mechListMIC = GSS_C_NO_BUFFER; supported_mechSet = mechTypes = GSS_C_NO_OID_SET; *return_token = ERROR_TOKEN_SEND; *negState = REJECT; *minor_status = 0; ret = get_negTokenInit(minor_status, buf, &der_mechTypes, &mechTypes, &req_flags, mechToken, mechListMIC); if (ret != GSS_S_COMPLETE) { goto cleanup; } ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT, &supported_mechSet); if (ret != GSS_S_COMPLETE) { *return_token = NO_TOKEN_SEND; goto cleanup; } /* * Select the best match between the list of mechs * that the initiator requested and the list that * the acceptor will support. */ mech_wanted = negotiate_mech(supported_mechSet, mechTypes, negState); if (*negState == REJECT) { ret = GSS_S_BAD_MECH; goto cleanup; } sc = (spnego_gss_ctx_id_t)*ctx; if (sc != NULL) { gss_release_buffer(&tmpmin, &sc->DER_mechTypes); assert(mech_wanted != GSS_C_NO_OID); } else sc = create_spnego_ctx(); if (sc == NULL) { ret = GSS_S_FAILURE; *return_token = NO_TOKEN_SEND; goto cleanup; } sc->mech_set = mechTypes; mechTypes = GSS_C_NO_OID_SET; sc->internal_mech = mech_wanted; sc->DER_mechTypes = der_mechTypes; der_mechTypes.length = 0; der_mechTypes.value = NULL; if (*negState == REQUEST_MIC) sc->mic_reqd = 1; *return_token = INIT_TOKEN_SEND; sc->firstpass = 1; *ctx = (gss_ctx_id_t)sc; ret = GSS_S_COMPLETE; cleanup: gss_release_oid_set(&tmpmin, &mechTypes); gss_release_oid_set(&tmpmin, &supported_mechSet); if (der_mechTypes.length != 0) gss_release_buffer(&tmpmin, &der_mechTypes); return ret; } CWE ID: CWE-18 Target: 1 Example 2: Code: TabContents* Browser::AddRestoredTab( const std::vector<TabNavigation>& navigations, int tab_index, int selected_navigation, const std::string& extension_app_id, bool select, bool pin, bool from_last_session, SessionStorageNamespace* session_storage_namespace) { TabContentsWrapper* wrapper = TabContentsFactory(profile(), NULL, MSG_ROUTING_NONE, GetSelectedTabContents(), session_storage_namespace); TabContents* new_tab = wrapper->tab_contents(); wrapper->extension_tab_helper()->SetExtensionAppById(extension_app_id); new_tab->controller().RestoreFromState(navigations, selected_navigation, from_last_session); int add_types = select ? TabStripModel::ADD_ACTIVE : TabStripModel::ADD_NONE; if (pin) { tab_index = std::min(tab_index, tabstrip_model()->IndexOfFirstNonMiniTab()); add_types |= TabStripModel::ADD_PINNED; } tab_handler_->GetTabStripModel()->InsertTabContentsAt(tab_index, wrapper, add_types); if (select) { window_->Activate(); } else { new_tab->view()->SizeContents(window_->GetRestoredBounds().size()); new_tab->HideContents(); } if (profile_->HasSessionService()) { SessionService* session_service = profile_->GetSessionService(); if (session_service) session_service->TabRestored(&new_tab->controller(), pin); } return new_tab; } 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 get_user_pages_locked(unsigned long start, unsigned long nr_pages, unsigned int gup_flags, struct page **pages, int *locked) { return __get_user_pages_locked(current, current->mm, start, nr_pages, pages, NULL, locked, gup_flags | FOLL_TOUCH); } 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: long Segment::ParseNext(const Cluster* pCurr, const Cluster*& pResult, long long& pos, long& len) { assert(pCurr); assert(!pCurr->EOS()); assert(m_clusters); pResult = 0; if (pCurr->m_index >= 0) { // loaded (not merely preloaded) assert(m_clusters[pCurr->m_index] == pCurr); const long next_idx = pCurr->m_index + 1; if (next_idx < m_clusterCount) { pResult = m_clusters[next_idx]; return 0; // success } const long result = LoadCluster(pos, len); if (result < 0) // error or underflow return result; if (result > 0) // no more clusters { return 1; } pResult = GetLast(); return 0; // success } assert(m_pos > 0); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; pos = pCurr->m_element_start; if (pCurr->m_element_size >= 0) pos += pCurr->m_element_size; else { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(m_pReader, pos, len); if (id != 0x0F43B675) // weird: not Cluster ID return -1; pos += len; // consume ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) // TODO: should never happen return E_FILE_FORMAT_INVALID; // TODO: resolve this if ((segment_stop >= 0) && ((pos + size) > segment_stop)) return E_FILE_FORMAT_INVALID; pos += size; // consume payload (that is, the current cluster) assert((segment_stop < 0) || (pos <= segment_stop)); } for (;;) { const long status = DoParseNext(pResult, pos, len); if (status <= 1) return status; } } CWE ID: CWE-20 Target: 1 Example 2: Code: nfsd_permission(struct svc_rqst *rqstp, struct svc_export *exp, struct dentry *dentry, int acc) { struct inode *inode = d_inode(dentry); int err; if ((acc & NFSD_MAY_MASK) == NFSD_MAY_NOP) return 0; #if 0 dprintk("nfsd: permission 0x%x%s%s%s%s%s%s%s mode 0%o%s%s%s\n", acc, (acc & NFSD_MAY_READ)? " read" : "", (acc & NFSD_MAY_WRITE)? " write" : "", (acc & NFSD_MAY_EXEC)? " exec" : "", (acc & NFSD_MAY_SATTR)? " sattr" : "", (acc & NFSD_MAY_TRUNC)? " trunc" : "", (acc & NFSD_MAY_LOCK)? " lock" : "", (acc & NFSD_MAY_OWNER_OVERRIDE)? " owneroverride" : "", inode->i_mode, IS_IMMUTABLE(inode)? " immut" : "", IS_APPEND(inode)? " append" : "", __mnt_is_readonly(exp->ex_path.mnt)? " ro" : ""); dprintk(" owner %d/%d user %d/%d\n", inode->i_uid, inode->i_gid, current_fsuid(), current_fsgid()); #endif /* Normally we reject any write/sattr etc access on a read-only file * system. But if it is IRIX doing check on write-access for a * device special file, we ignore rofs. */ if (!(acc & NFSD_MAY_LOCAL_ACCESS)) if (acc & (NFSD_MAY_WRITE | NFSD_MAY_SATTR | NFSD_MAY_TRUNC)) { if (exp_rdonly(rqstp, exp) || __mnt_is_readonly(exp->ex_path.mnt)) return nfserr_rofs; if (/* (acc & NFSD_MAY_WRITE) && */ IS_IMMUTABLE(inode)) return nfserr_perm; } if ((acc & NFSD_MAY_TRUNC) && IS_APPEND(inode)) return nfserr_perm; if (acc & NFSD_MAY_LOCK) { /* If we cannot rely on authentication in NLM requests, * just allow locks, otherwise require read permission, or * ownership */ if (exp->ex_flags & NFSEXP_NOAUTHNLM) return 0; else acc = NFSD_MAY_READ | NFSD_MAY_OWNER_OVERRIDE; } /* * The file owner always gets access permission for accesses that * would normally be checked at open time. This is to make * file access work even when the client has done a fchmod(fd, 0). * * However, `cp foo bar' should fail nevertheless when bar is * readonly. A sensible way to do this might be to reject all * attempts to truncate a read-only file, because a creat() call * always implies file truncation. * ... but this isn't really fair. A process may reasonably call * ftruncate on an open file descriptor on a file with perm 000. * We must trust the client to do permission checking - using "ACCESS" * with NFSv3. */ if ((acc & NFSD_MAY_OWNER_OVERRIDE) && uid_eq(inode->i_uid, current_fsuid())) return 0; /* This assumes NFSD_MAY_{READ,WRITE,EXEC} == MAY_{READ,WRITE,EXEC} */ err = inode_permission(inode, acc & (MAY_READ|MAY_WRITE|MAY_EXEC)); /* Allow read access to binaries even when mode 111 */ if (err == -EACCES && S_ISREG(inode->i_mode) && (acc == (NFSD_MAY_READ | NFSD_MAY_OWNER_OVERRIDE) || acc == (NFSD_MAY_READ | NFSD_MAY_READ_IF_EXEC))) err = inode_permission(inode, MAY_EXEC); return err? nfserrno(err) : 0; } CWE ID: CWE-404 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct timeval ns_to_timeval(const s64 nsec) { struct timespec ts = ns_to_timespec(nsec); struct timeval tv; tv.tv_sec = ts.tv_sec; tv.tv_usec = (suseconds_t) ts.tv_nsec / 1000; return tv; } 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: int lock_flags) __releases(RCU) { struct inode *inode = VFS_I(ip); struct xfs_mount *mp = ip->i_mount; int error; /* * check for re-use of an inode within an RCU grace period due to the * radix tree nodes not being updated yet. We monitor for this by * setting the inode number to zero before freeing the inode structure. * If the inode has been reallocated and set up, then the inode number * will not match, so check for that, too. */ spin_lock(&ip->i_flags_lock); if (ip->i_ino != ino) { trace_xfs_iget_skip(ip); XFS_STATS_INC(mp, xs_ig_frecycle); error = -EAGAIN; goto out_error; } /* * If we are racing with another cache hit that is currently * instantiating this inode or currently recycling it out of * reclaimabe state, wait for the initialisation to complete * before continuing. * * XXX(hch): eventually we should do something equivalent to * wait_on_inode to wait for these flags to be cleared * instead of polling for it. */ if (ip->i_flags & (XFS_INEW|XFS_IRECLAIM)) { trace_xfs_iget_skip(ip); XFS_STATS_INC(mp, xs_ig_frecycle); error = -EAGAIN; goto out_error; } /* * If lookup is racing with unlink return an error immediately. */ if (VFS_I(ip)->i_mode == 0 && !(flags & XFS_IGET_CREATE)) { error = -ENOENT; goto out_error; } /* * If IRECLAIMABLE is set, we've torn down the VFS inode already. * Need to carefully get it back into useable state. */ if (ip->i_flags & XFS_IRECLAIMABLE) { trace_xfs_iget_reclaim(ip); if (flags & XFS_IGET_INCORE) { error = -EAGAIN; goto out_error; } /* * We need to set XFS_IRECLAIM to prevent xfs_reclaim_inode * from stomping over us while we recycle the inode. We can't * clear the radix tree reclaimable tag yet as it requires * pag_ici_lock to be held exclusive. */ ip->i_flags |= XFS_IRECLAIM; spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); error = xfs_reinit_inode(mp, inode); if (error) { bool wake; /* * Re-initializing the inode failed, and we are in deep * trouble. Try to re-add it to the reclaim list. */ rcu_read_lock(); spin_lock(&ip->i_flags_lock); wake = !!__xfs_iflags_test(ip, XFS_INEW); ip->i_flags &= ~(XFS_INEW | XFS_IRECLAIM); if (wake) wake_up_bit(&ip->i_flags, __XFS_INEW_BIT); ASSERT(ip->i_flags & XFS_IRECLAIMABLE); trace_xfs_iget_reclaim_fail(ip); goto out_error; } spin_lock(&pag->pag_ici_lock); spin_lock(&ip->i_flags_lock); /* * Clear the per-lifetime state in the inode as we are now * effectively a new inode and need to return to the initial * state before reuse occurs. */ ip->i_flags &= ~XFS_IRECLAIM_RESET_FLAGS; ip->i_flags |= XFS_INEW; xfs_inode_clear_reclaim_tag(pag, ip->i_ino); inode->i_state = I_NEW; ASSERT(!rwsem_is_locked(&inode->i_rwsem)); init_rwsem(&inode->i_rwsem); spin_unlock(&ip->i_flags_lock); spin_unlock(&pag->pag_ici_lock); } else { /* If the VFS inode is being torn down, pause and try again. */ if (!igrab(inode)) { trace_xfs_iget_skip(ip); error = -EAGAIN; goto out_error; } /* We've got a live one. */ spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); trace_xfs_iget_hit(ip); } if (lock_flags != 0) xfs_ilock(ip, lock_flags); if (!(flags & XFS_IGET_INCORE)) xfs_iflags_clear(ip, XFS_ISTALE | XFS_IDONTCACHE); XFS_STATS_INC(mp, xs_ig_found); return 0; out_error: spin_unlock(&ip->i_flags_lock); rcu_read_unlock(); return error; } CWE ID: CWE-476 Target: 1 Example 2: Code: void Instance::DocumentSizeUpdated(const pp::Size& size) { document_size_ = size; OnGeometryChanged(zoom_, device_scale_); } 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 gboolean cosine_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset) { gint64 offset; int pkt_len; char line[COSINE_LINE_LENGTH]; /* Find the next packet */ offset = cosine_seek_next_packet(wth, err, err_info, line); if (offset < 0) return FALSE; *data_offset = offset; /* Parse the header */ pkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info); if (pkt_len == -1) return FALSE; /* Convert the ASCII hex dump to binary data */ return parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len, wth->frame_buffer, err, err_info); } 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: xsltResolveSASCallback(xsltAttrElemPtr values, xsltStylesheetPtr style, const xmlChar *name, const xmlChar *ns, ATTRIBUTE_UNUSED const xmlChar *ignored) { xsltAttrElemPtr tmp; xsltAttrElemPtr refs; tmp = values; while (tmp != NULL) { if (tmp->set != NULL) { /* * Check against cycles ! */ if ((xmlStrEqual(name, tmp->set)) && (xmlStrEqual(ns, tmp->ns))) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets recursion detected on %s\n", name); } else { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "Importing attribute list %s\n", tmp->set); #endif refs = xsltGetSAS(style, tmp->set, tmp->ns); if (refs == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : use-attribute-sets %s reference missing %s\n", name, tmp->set); } else { /* * recurse first for cleanup */ xsltResolveSASCallback(refs, style, name, ns, NULL); /* * Then merge */ xsltMergeAttrElemList(style, values, refs); /* * Then suppress the reference */ tmp->set = NULL; tmp->ns = NULL; } } } tmp = tmp->next; } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int __svc_rpcb_register4(struct net *net, const u32 program, const u32 version, const unsigned short protocol, const unsigned short port) { const struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_ANY), .sin_port = htons(port), }; const char *netid; int error; switch (protocol) { case IPPROTO_UDP: netid = RPCBIND_NETID_UDP; break; case IPPROTO_TCP: netid = RPCBIND_NETID_TCP; break; default: return -ENOPROTOOPT; } error = rpcb_v4_register(net, program, version, (const struct sockaddr *)&sin, netid); /* * User space didn't support rpcbind v4, so retry this * registration request with the legacy rpcbind v2 protocol. */ if (error == -EPROTONOSUPPORT) error = rpcb_register(net, program, version, protocol, port); return error; } CWE ID: CWE-404 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void SocketStream::CheckPrivacyMode() { if (context_.get() && context_->network_delegate()) { bool enable = context_->network_delegate()->CanEnablePrivacyMode(url_, url_); privacy_mode_ = enable ? kPrivacyModeEnabled : kPrivacyModeDisabled; if (enable) server_ssl_config_.channel_id_enabled = false; } } 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 output_quantization_factor(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { if (out_depth == 16 && in_depth != 16 && pm->calculations_use_input_precision) return 257; else return 1; } CWE ID: Target: 1 Example 2: Code: void Document::EnqueueScrollEventForNode(Node* target) { Event* scroll_event = target->IsDocumentNode() ? Event::CreateBubble(EventTypeNames::scroll) : Event::Create(EventTypeNames::scroll); scroll_event->SetTarget(target); EnsureScriptedAnimationController().EnqueuePerFrameEvent(scroll_event); } CWE ID: CWE-732 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int pcrypt_create_aead(struct crypto_template *tmpl, struct rtattr **tb, u32 type, u32 mask) { struct pcrypt_instance_ctx *ctx; struct crypto_attr_type *algt; struct aead_instance *inst; struct aead_alg *alg; const char *name; int err; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return PTR_ERR(algt); name = crypto_attr_alg_name(tb[1]); if (IS_ERR(name)) return PTR_ERR(name); inst = kzalloc(sizeof(*inst) + sizeof(*ctx), GFP_KERNEL); if (!inst) return -ENOMEM; ctx = aead_instance_ctx(inst); crypto_set_aead_spawn(&ctx->spawn, aead_crypto_instance(inst)); err = crypto_grab_aead(&ctx->spawn, name, 0, 0); if (err) goto out_free_inst; alg = crypto_spawn_aead_alg(&ctx->spawn); err = pcrypt_init_instance(aead_crypto_instance(inst), &alg->base); if (err) goto out_drop_aead; inst->alg.base.cra_flags = CRYPTO_ALG_ASYNC; inst->alg.ivsize = crypto_aead_alg_ivsize(alg); inst->alg.maxauthsize = crypto_aead_alg_maxauthsize(alg); inst->alg.base.cra_ctxsize = sizeof(struct pcrypt_aead_ctx); inst->alg.init = pcrypt_aead_init_tfm; inst->alg.exit = pcrypt_aead_exit_tfm; inst->alg.setkey = pcrypt_aead_setkey; inst->alg.setauthsize = pcrypt_aead_setauthsize; inst->alg.encrypt = pcrypt_aead_encrypt; inst->alg.decrypt = pcrypt_aead_decrypt; err = aead_register_instance(tmpl, inst); if (err) goto out_drop_aead; out: return err; out_drop_aead: crypto_drop_aead(&ctx->spawn); out_free_inst: kfree(inst); goto out; } CWE ID: CWE-763 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 TranslateInfoBarDelegate::IsTranslatableLanguageByPrefs() { Profile* profile = Profile::FromBrowserContext(GetWebContents()->GetBrowserContext()); Profile* original_profile = profile->GetOriginalProfile(); scoped_ptr<TranslatePrefs> translate_prefs( TranslateTabHelper::CreateTranslatePrefs(original_profile->GetPrefs())); TranslateAcceptLanguages* accept_languages = TranslateTabHelper::GetTranslateAcceptLanguages(original_profile); return translate_prefs->CanTranslateLanguage(accept_languages, original_language_code()); } CWE ID: CWE-362 Target: 1 Example 2: Code: static void VariableArgsFunc(const char* format, ...) { va_list org; va_start(org, format); va_list dup; GG_VA_COPY(dup, org); int i1 = va_arg(org, int); int j1 = va_arg(org, int); char* s1 = va_arg(org, char*); double d1 = va_arg(org, double); va_end(org); int i2 = va_arg(dup, int); int j2 = va_arg(dup, int); char* s2 = va_arg(dup, char*); double d2 = va_arg(dup, double); EXPECT_EQ(i1, i2); EXPECT_EQ(j1, j2); EXPECT_STREQ(s1, s2); EXPECT_EQ(d1, d2); va_end(dup); } 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: KeyedService* LogoServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = static_cast<Profile*>(context); DCHECK(!profile->IsOffTheRecord()); #if defined(OS_ANDROID) bool use_gray_background = !GetIsChromeHomeEnabled(); #else bool use_gray_background = false; #endif return new LogoService(profile->GetPath().Append(kCachedLogoDirectory), TemplateURLServiceFactory::GetForProfile(profile), base::MakeUnique<suggestions::ImageDecoderImpl>(), profile->GetRequestContext(), use_gray_background); } 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 PluginChannel::OnChannelError() { base::CloseProcessHandle(renderer_handle_); renderer_handle_ = 0; NPChannelBase::OnChannelError(); CleanUp(); } CWE ID: Target: 1 Example 2: Code: static int act_open_rpl(struct t3cdev *tdev, struct sk_buff *skb, void *ctx) { struct iwch_ep *ep = ctx; struct cpl_act_open_rpl *rpl = cplhdr(skb); PDBG("%s ep %p status %u errno %d\n", __func__, ep, rpl->status, status2errno(rpl->status)); connect_reply_upcall(ep, status2errno(rpl->status)); state_set(&ep->com, DEAD); if (ep->com.tdev->type != T3A && act_open_has_tid(rpl->status)) release_tid(ep->com.tdev, GET_TID(rpl), NULL); cxgb3_free_atid(ep->com.tdev, ep->atid); dst_release(ep->dst); l2t_release(ep->com.tdev, ep->l2t); put_ep(&ep->com); return CPL_RET_BUF_DONE; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GLboolean WebGLRenderingContextBase::isProgram(WebGLProgram* program) { if (!program || isContextLost()) return 0; return ContextGL()->IsProgram(program->Object()); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse) { InheritException(exception,&mean_image->exception); mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) mean_image->columns; x++) { MagickPixelPacket mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetMagickPixelPacket(image,&mean_pixel); SetMagickPixelPacket(image,p,indexes+x,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; MagickPixelPacket sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetMagickPixelPacket(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelPacket pixel; status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.opacity+=pixel.opacity; count++; } } } } gamma=1.0/count; mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.opacity=gamma*sum_pixel.opacity; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } q->red=ClampToQuantum(mean_pixel.red); q->green=ClampToQuantum(mean_pixel.green); q->blue=ClampToQuantum(mean_pixel.blue); q->opacity=ClampToQuantum(mean_pixel.opacity); p++; q++; } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); } CWE ID: CWE-369 Target: 1 Example 2: Code: int activeExpireCycleTryExpire(redisDb *db, dictEntry *de, long long now) { long long t = dictGetSignedIntegerVal(de); if (now > t) { sds key = dictGetKey(de); robj *keyobj = createStringObject(key,sdslen(key)); propagateExpire(db,keyobj); dbDelete(db,keyobj); notifyKeyspaceEvent(NOTIFY_EXPIRED, "expired",keyobj,db->id); decrRefCount(keyobj); server.stat_expiredkeys++; return 1; } else { return 0; } } 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: ChromeURLRequestContext::ChromeURLRequestContext( ContextType type, chrome_browser_net::LoadTimeStats* load_time_stats) : load_time_stats_(load_time_stats) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (load_time_stats_) load_time_stats_->RegisterURLRequestContext(this, type); } 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 ext4_put_super(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; int i, err; ext4_unregister_li_request(sb); dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED); flush_workqueue(sbi->rsv_conversion_wq); destroy_workqueue(sbi->rsv_conversion_wq); if (sbi->s_journal) { err = jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; if (err < 0) ext4_abort(sb, "Couldn't clean up the journal"); } ext4_unregister_sysfs(sb); ext4_es_unregister_shrinker(sbi); del_timer_sync(&sbi->s_err_report); ext4_release_system_zone(sb); ext4_mb_release(sb); ext4_ext_release(sb); ext4_xattr_put_super(sb); if (!(sb->s_flags & MS_RDONLY)) { ext4_clear_feature_journal_needs_recovery(sb); es->s_state = cpu_to_le16(sbi->s_mount_state); } if (!(sb->s_flags & MS_RDONLY)) ext4_commit_super(sb, 1); for (i = 0; i < sbi->s_gdb_count; i++) brelse(sbi->s_group_desc[i]); kvfree(sbi->s_group_desc); kvfree(sbi->s_flex_groups); percpu_counter_destroy(&sbi->s_freeclusters_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyclusters_counter); brelse(sbi->s_sbh); #ifdef CONFIG_QUOTA for (i = 0; i < EXT4_MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif /* Debugging code just in case the in-memory inode orphan list * isn't empty. The on-disk one can be non-empty if we've * detected an error and taken the fs readonly, but the * in-memory list had better be clean by this point. */ if (!list_empty(&sbi->s_orphan)) dump_orphan_list(sb, sbi); J_ASSERT(list_empty(&sbi->s_orphan)); sync_blockdev(sb->s_bdev); invalidate_bdev(sb->s_bdev); if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) { /* * Invalidate the journal device's buffers. We don't want them * floating about in memory - the physical journal device may * hotswapped, and it breaks the `ro-after' testing code. */ sync_blockdev(sbi->journal_bdev); invalidate_bdev(sbi->journal_bdev); ext4_blkdev_remove(sbi); } if (sbi->s_mb_cache) { ext4_xattr_destroy_cache(sbi->s_mb_cache); sbi->s_mb_cache = NULL; } if (sbi->s_mmp_tsk) kthread_stop(sbi->s_mmp_tsk); sb->s_fs_info = NULL; /* * Now that we are completely done shutting down the * superblock, we need to actually destroy the kobject. */ kobject_put(&sbi->s_kobj); wait_for_completion(&sbi->s_kobj_unregister); if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->s_blockgroup_lock); kfree(sbi); } CWE ID: CWE-19 Target: 1 Example 2: Code: void OMXCodec::setMinBufferSize(OMX_U32 portIndex, OMX_U32 size) { OMX_PARAM_PORTDEFINITIONTYPE def; InitOMXParams(&def); def.nPortIndex = portIndex; status_t err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); CHECK_EQ(err, (status_t)OK); if ((portIndex == kPortIndexInput && (mQuirks & kInputBufferSizesAreBogus)) || (def.nBufferSize < size)) { def.nBufferSize = size; } err = mOMX->setParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); CHECK_EQ(err, (status_t)OK); err = mOMX->getParameter( mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)); CHECK_EQ(err, (status_t)OK); if (portIndex == kPortIndexInput && (mQuirks & kInputBufferSizesAreBogus)) { CHECK_EQ(def.nBufferSize, size); } else { CHECK(def.nBufferSize >= size); } } CWE ID: CWE-284 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PassRefPtr<RTCSessionDescription> RTCPeerConnection::remoteDescription(ExceptionCode& ec) { if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) { ec = INVALID_STATE_ERR; return 0; } RefPtr<RTCSessionDescriptionDescriptor> descriptor = m_peerHandler->remoteDescription(); if (!descriptor) return 0; RefPtr<RTCSessionDescription> desc = RTCSessionDescription::create(descriptor.release()); return desc.release(); } 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: long 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 = ReadID(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 || len < 1 || len > 8) { return E_FILE_FORMAT_INVALID; } const unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size if (stop >= 0 && pos >= stop) return E_FILE_FORMAT_INVALID; return 0; // success } CWE ID: CWE-20 Target: 1 Example 2: Code: perf_event_aux_ctx(struct perf_event_context *ctx, perf_event_aux_output_cb output, void *data) { struct perf_event *event; list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { if (event->state < PERF_EVENT_STATE_INACTIVE) continue; if (!event_filter_match(event)) continue; output(event, data); } } 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 GCInfoTable::Resize() { static const int kGcInfoZapValue = 0x33; const size_t kInitialSize = 512; size_t new_size = gc_info_table_size_ ? 2 * gc_info_table_size_ : kInitialSize; DCHECK(new_size < GCInfoTable::kMaxIndex); g_gc_info_table = reinterpret_cast<GCInfo const**>(WTF::Partitions::FastRealloc( g_gc_info_table, new_size * sizeof(GCInfo), "GCInfo")); DCHECK(g_gc_info_table); memset(reinterpret_cast<uint8_t*>(g_gc_info_table) + gc_info_table_size_ * sizeof(GCInfo), kGcInfoZapValue, (new_size - gc_info_table_size_) * sizeof(GCInfo)); gc_info_table_size_ = new_size; } CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ext4_split_unwritten_extents(handle_t *handle, struct inode *inode, struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags) { struct ext4_extent *ex, newex, orig_ex; struct ext4_extent *ex1 = NULL; struct ext4_extent *ex2 = NULL; struct ext4_extent *ex3 = NULL; ext4_lblk_t ee_block, eof_block; unsigned int allocated, ee_len, depth; ext4_fsblk_t newblock; int err = 0; int may_zeroout; ext_debug("ext4_split_unwritten_extents: inode %lu, logical" "block %llu, max_blocks %u\n", inode->i_ino, (unsigned long long)map->m_lblk, map->m_len); eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits; if (eof_block < map->m_lblk + map->m_len) eof_block = map->m_lblk + map->m_len; depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); allocated = ee_len - (map->m_lblk - ee_block); newblock = map->m_lblk - ee_block + ext4_ext_pblock(ex); ex2 = ex; orig_ex.ee_block = ex->ee_block; orig_ex.ee_len = cpu_to_le16(ee_len); ext4_ext_store_pblock(&orig_ex, ext4_ext_pblock(ex)); /* * It is safe to convert extent to initialized via explicit * zeroout only if extent is fully insde i_size or new_size. */ may_zeroout = ee_block + ee_len <= eof_block; /* * If the uninitialized extent begins at the same logical * block where the write begins, and the write completely * covers the extent, then we don't need to split it. */ if ((map->m_lblk == ee_block) && (allocated <= map->m_len)) return allocated; err = ext4_ext_get_access(handle, inode, path + depth); if (err) goto out; /* ex1: ee_block to map->m_lblk - 1 : uninitialized */ if (map->m_lblk > ee_block) { ex1 = ex; ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block); ext4_ext_mark_uninitialized(ex1); ex2 = &newex; } /* * for sanity, update the length of the ex2 extent before * we insert ex3, if ex1 is NULL. This is to avoid temporary * overlap of blocks. */ if (!ex1 && allocated > map->m_len) ex2->ee_len = cpu_to_le16(map->m_len); /* ex3: to ee_block + ee_len : uninitialised */ if (allocated > map->m_len) { unsigned int newdepth; ex3 = &newex; ex3->ee_block = cpu_to_le32(map->m_lblk + map->m_len); ext4_ext_store_pblock(ex3, newblock + map->m_len); ex3->ee_len = cpu_to_le16(allocated - map->m_len); ext4_ext_mark_uninitialized(ex3); err = ext4_ext_insert_extent(handle, inode, path, ex3, flags); if (err == -ENOSPC && may_zeroout) { err = ext4_ext_zeroout(inode, &orig_ex); if (err) goto fix_extent_len; /* update the extent length and mark as initialized */ ex->ee_block = orig_ex.ee_block; ex->ee_len = orig_ex.ee_len; ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex)); ext4_ext_dirty(handle, inode, path + depth); /* zeroed the full extent */ /* blocks available from map->m_lblk */ return allocated; } else if (err) goto fix_extent_len; /* * The depth, and hence eh & ex might change * as part of the insert above. */ newdepth = ext_depth(inode); /* * update the extent length after successful insert of the * split extent */ ee_len -= ext4_ext_get_actual_len(ex3); orig_ex.ee_len = cpu_to_le16(ee_len); may_zeroout = ee_block + ee_len <= eof_block; depth = newdepth; ext4_ext_drop_refs(path); path = ext4_ext_find_extent(inode, map->m_lblk, path); if (IS_ERR(path)) { err = PTR_ERR(path); goto out; } ex = path[depth].p_ext; if (ex2 != &newex) ex2 = ex; err = ext4_ext_get_access(handle, inode, path + depth); if (err) goto out; allocated = map->m_len; } /* * If there was a change of depth as part of the * insertion of ex3 above, we need to update the length * of the ex1 extent again here */ if (ex1 && ex1 != ex) { ex1 = ex; ex1->ee_len = cpu_to_le16(map->m_lblk - ee_block); ext4_ext_mark_uninitialized(ex1); ex2 = &newex; } /* * ex2: map->m_lblk to map->m_lblk + map->m_len-1 : to be written * using direct I/O, uninitialised still. */ ex2->ee_block = cpu_to_le32(map->m_lblk); ext4_ext_store_pblock(ex2, newblock); ex2->ee_len = cpu_to_le16(allocated); ext4_ext_mark_uninitialized(ex2); if (ex2 != ex) goto insert; /* Mark modified extent as dirty */ err = ext4_ext_dirty(handle, inode, path + depth); ext_debug("out here\n"); goto out; insert: err = ext4_ext_insert_extent(handle, inode, path, &newex, flags); if (err == -ENOSPC && may_zeroout) { err = ext4_ext_zeroout(inode, &orig_ex); if (err) goto fix_extent_len; /* update the extent length and mark as initialized */ ex->ee_block = orig_ex.ee_block; ex->ee_len = orig_ex.ee_len; ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex)); ext4_ext_dirty(handle, inode, path + depth); /* zero out the first half */ return allocated; } else if (err) goto fix_extent_len; out: ext4_ext_show_leaf(inode, path); return err ? err : allocated; fix_extent_len: ex->ee_block = orig_ex.ee_block; ex->ee_len = orig_ex.ee_len; ext4_ext_store_pblock(ex, ext4_ext_pblock(&orig_ex)); ext4_ext_mark_uninitialized(ex); ext4_ext_dirty(handle, inode, path + depth); return err; } CWE ID: Target: 1 Example 2: Code: void WebGL2RenderingContextBase::clearBufferiv(GLenum buffer, GLint drawbuffer, MaybeShared<DOMInt32Array> value, GLuint src_offset) { if (isContextLost() || !ValidateClearBuffer("clearBufferiv", buffer, value.View()->length(), src_offset)) return; ScopedRGBEmulationColorMask emulation_color_mask(this, color_mask_, drawing_buffer_.get()); ContextGL()->ClearBufferiv(buffer, drawbuffer, value.View()->DataMaybeShared() + src_offset); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma, struct page *page, unsigned long address) { struct hstate *h = hstate_vma(vma); struct vm_area_struct *iter_vma; struct address_space *mapping; struct prio_tree_iter iter; pgoff_t pgoff; /* * vm_pgoff is in PAGE_SIZE units, hence the different calculation * from page cache lookup which is in HPAGE_SIZE units. */ address = address & huge_page_mask(h); pgoff = vma_hugecache_offset(h, vma, address); mapping = (struct address_space *)page_private(page); /* * Take the mapping lock for the duration of the table walk. As * this mapping should be shared between all the VMAs, * __unmap_hugepage_range() is called as the lock is already held */ mutex_lock(&mapping->i_mmap_mutex); vma_prio_tree_foreach(iter_vma, &iter, &mapping->i_mmap, pgoff, pgoff) { /* Do not unmap the current VMA */ if (iter_vma == vma) continue; /* * Unmap the page from other VMAs without their own reserves. * They get marked to be SIGKILLed if they fault in these * areas. This is because a future no-page fault on this VMA * could insert a zeroed page instead of the data existing * from the time of fork. This would look like data corruption */ if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER)) __unmap_hugepage_range(iter_vma, address, address + huge_page_size(h), page); } mutex_unlock(&mapping->i_mmap_mutex); return 1; } 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: ExtensionsGuestViewMessageFilter::MaybeCreateThrottle( NavigationHandle* handle) { DCHECK(content::MimeHandlerViewMode::UsesCrossProcessFrame()); if (!handle->GetParentFrame()) { return nullptr; } int32_t parent_process_id = handle->GetParentFrame()->GetProcess()->GetID(); auto& map = *GetProcessIdToFilterMap(); if (!base::ContainsKey(map, parent_process_id) || !map[parent_process_id]) { return nullptr; } for (auto& pair : map[parent_process_id]->frame_navigation_helpers_) { if (!pair.second->ShouldCancelAndIgnore(handle)) continue; return std::make_unique<CancelAndIgnoreNavigationForPluginFrameThrottle>( handle); } return nullptr; } CWE ID: CWE-362 Target: 1 Example 2: Code: CIFSSMBQueryReparseLinkInfo(const int xid, struct cifs_tcon *tcon, const unsigned char *searchName, char *symlinkinfo, const int buflen, __u16 fid, const struct nls_table *nls_codepage) { int rc = 0; int bytes_returned; struct smb_com_transaction_ioctl_req *pSMB; struct smb_com_transaction_ioctl_rsp *pSMBr; cFYI(1, "In Windows reparse style QueryLink for path %s", searchName); rc = smb_init(SMB_COM_NT_TRANSACT, 23, tcon, (void **) &pSMB, (void **) &pSMBr); if (rc) return rc; pSMB->TotalParameterCount = 0 ; pSMB->TotalDataCount = 0; pSMB->MaxParameterCount = cpu_to_le32(2); /* BB find exact data count max from sess structure BB */ pSMB->MaxDataCount = cpu_to_le32((tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE) & 0xFFFFFF00); pSMB->MaxSetupCount = 4; pSMB->Reserved = 0; pSMB->ParameterOffset = 0; pSMB->DataCount = 0; pSMB->DataOffset = 0; pSMB->SetupCount = 4; pSMB->SubCommand = cpu_to_le16(NT_TRANSACT_IOCTL); pSMB->ParameterCount = pSMB->TotalParameterCount; pSMB->FunctionCode = cpu_to_le32(FSCTL_GET_REPARSE_POINT); pSMB->IsFsctl = 1; /* FSCTL */ pSMB->IsRootFlag = 0; pSMB->Fid = fid; /* file handle always le */ pSMB->ByteCount = 0; rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB, (struct smb_hdr *) pSMBr, &bytes_returned, 0); if (rc) { cFYI(1, "Send error in QueryReparseLinkInfo = %d", rc); } else { /* decode response */ __u32 data_offset = le32_to_cpu(pSMBr->DataOffset); __u32 data_count = le32_to_cpu(pSMBr->DataCount); if (get_bcc(&pSMBr->hdr) < 2 || data_offset > 512) { /* BB also check enough total bytes returned */ rc = -EIO; /* bad smb */ goto qreparse_out; } if (data_count && (data_count < 2048)) { char *end_of_smb = 2 /* sizeof byte count */ + get_bcc(&pSMBr->hdr) + (char *)&pSMBr->ByteCount; struct reparse_data *reparse_buf = (struct reparse_data *) ((char *)&pSMBr->hdr.Protocol + data_offset); if ((char *)reparse_buf >= end_of_smb) { rc = -EIO; goto qreparse_out; } if ((reparse_buf->LinkNamesBuf + reparse_buf->TargetNameOffset + reparse_buf->TargetNameLen) > end_of_smb) { cFYI(1, "reparse buf beyond SMB"); rc = -EIO; goto qreparse_out; } if (pSMBr->hdr.Flags2 & SMBFLG2_UNICODE) { cifs_from_ucs2(symlinkinfo, (__le16 *) (reparse_buf->LinkNamesBuf + reparse_buf->TargetNameOffset), buflen, reparse_buf->TargetNameLen, nls_codepage, 0); } else { /* ASCII names */ strncpy(symlinkinfo, reparse_buf->LinkNamesBuf + reparse_buf->TargetNameOffset, min_t(const int, buflen, reparse_buf->TargetNameLen)); } } else { rc = -EIO; cFYI(1, "Invalid return data count on " "get reparse info ioctl"); } symlinkinfo[buflen] = 0; /* just in case so the caller does not go off the end of the buffer */ cFYI(1, "readlink result - %s", symlinkinfo); } qreparse_out: cifs_buf_release(pSMB); /* Note: On -EAGAIN error only caller can retry on handle based calls since file handle passed in no longer valid */ return rc; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ApiTestEnvironment::RegisterModules() { v8_schema_registry_.reset(new V8SchemaRegistry); const std::vector<std::pair<std::string, int> > resources = Dispatcher::GetJsResources(); for (std::vector<std::pair<std::string, int> >::const_iterator resource = resources.begin(); resource != resources.end(); ++resource) { if (resource->first != "test_environment_specific_bindings") env()->RegisterModule(resource->first, resource->second); } Dispatcher::RegisterNativeHandlers(env()->module_system(), env()->context(), NULL, NULL, v8_schema_registry_.get()); env()->module_system()->RegisterNativeHandler( "process", scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler( env()->context(), env()->context()->GetExtensionID(), env()->context()->GetContextTypeDescription(), false, false, 2, false))); env()->RegisterTestFile("test_environment_specific_bindings", "unit_test_environment_specific_bindings.js"); env()->OverrideNativeHandler("activityLogger", "exports.LogAPICall = function() {};"); env()->OverrideNativeHandler( "apiDefinitions", "exports.GetExtensionAPIDefinitionsForTest = function() { return [] };"); env()->OverrideNativeHandler( "event_natives", "exports.AttachEvent = function() {};" "exports.DetachEvent = function() {};" "exports.AttachFilteredEvent = function() {};" "exports.AttachFilteredEvent = function() {};" "exports.MatchAgainstEventFilter = function() { return [] };"); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Core::kModuleName, mojo::js::Core::GetModule(env()->isolate())); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Support::kModuleName, mojo::js::Support::GetModule(env()->isolate())); gin::Handle<TestServiceProvider> service_provider = TestServiceProvider::Create(env()->isolate()); service_provider_ = service_provider.get(); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), "content/public/renderer/service_provider", service_provider.ToV8()); } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void MediaControlsProgressView::OnGestureEvent(ui::GestureEvent* event) { gfx::Point location_in_bar(event->location()); ConvertPointToTarget(this, this->progress_bar_, &location_in_bar); if (event->type() != ui::ET_GESTURE_TAP || !progress_bar_->GetLocalBounds().Contains(location_in_bar)) { return; } HandleSeeking(location_in_bar); event->SetHandled(); } CWE ID: CWE-200 Target: 1 Example 2: Code: static u64 mask_for_index(int idx) { return event_encoding(sparc_pmu->event_mask, idx); } 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 completion_done(struct completion *x) { unsigned long flags; int ret = 1; spin_lock_irqsave(&x->wait.lock, flags); if (!x->done) ret = 0; spin_unlock_irqrestore(&x->wait.lock, flags); return ret; } 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: av_cold void ff_mpv_idct_init(MpegEncContext *s) { ff_idctdsp_init(&s->idsp, s->avctx); /* load & permutate scantables * note: only wmv uses different ones */ if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); } ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } CWE ID: CWE-476 Target: 1 Example 2: Code: static int net_read(struct wif *wi, unsigned char *h80211, int len, struct rx_info *ri) { struct priv_net *pn = wi_priv(wi); uint32_t buf[512]; // 512 * 4 = 2048 unsigned char *bufc = (unsigned char*)buf; int cmd; int sz = sizeof(*ri); int l; int ret; /* try queue */ l = queue_get(pn, buf, sizeof(buf)); if (!l) { /* try reading form net */ l = sizeof(buf); cmd = net_get(pn->pn_s, buf, &l); if (cmd == -1) return -1; if (cmd == NET_RC) { ret = ntohl((buf[0])); return ret; } assert(cmd == NET_PACKET); } /* XXX */ if (ri) { ri->ri_mactime = __be64_to_cpu(((uint64_t)buf[0] << 32 || buf[1] )); ri->ri_power = __be32_to_cpu(buf[2]); ri->ri_noise = __be32_to_cpu(buf[3]); ri->ri_channel = __be32_to_cpu(buf[4]); ri->ri_rate = __be32_to_cpu(buf[5]); ri->ri_antenna = __be32_to_cpu(buf[6]); } l -= sz; assert(l > 0); if (l > len) l = len; memcpy(h80211, &bufc[sz], l); return l; } 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: cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h, const cdf_stream_t *sst, const uint64_t clsid[2]) { cdf_summary_info_header_t si; cdf_property_info_t *info; size_t count; int m; if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1) return -1; if (NOTMIME(ms)) { const char *str; if (file_printf(ms, "Composite Document File V2 Document") == -1) return -1; if (file_printf(ms, ", %s Endian", si.si_byte_order == 0xfffe ? "Little" : "Big") == -1) return -2; switch (si.si_os) { case 2: if (file_printf(ms, ", Os: Windows, Version %d.%d", si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; case 1: if (file_printf(ms, ", Os: MacOS, Version %d.%d", (uint32_t)si.si_os_version >> 8, si.si_os_version & 0xff) == -1) return -2; break; default: if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os, si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; } str = cdf_clsid_to_mime(clsid, clsid2desc); if (str) if (file_printf(ms, ", %s", str) == -1) return -2; } m = cdf_file_property_info(ms, info, count, clsid); free(info); return m == -1 ? -2 : m; } 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 diff_bytes_c(uint8_t *dst, const uint8_t *src1, const uint8_t *src2, int w){ long i; #if !HAVE_FAST_UNALIGNED if((long)src2 & (sizeof(long)-1)){ for(i=0; i+7<w; i+=8){ dst[i+0] = src1[i+0]-src2[i+0]; dst[i+1] = src1[i+1]-src2[i+1]; dst[i+2] = src1[i+2]-src2[i+2]; dst[i+3] = src1[i+3]-src2[i+3]; dst[i+4] = src1[i+4]-src2[i+4]; dst[i+5] = src1[i+5]-src2[i+5]; dst[i+6] = src1[i+6]-src2[i+6]; dst[i+7] = src1[i+7]-src2[i+7]; } }else #endif for(i=0; i<=w-sizeof(long); i+=sizeof(long)){ long a = *(long*)(src1+i); long b = *(long*)(src2+i); *(long*)(dst+i) = ((a|pb_80) - (b&pb_7f)) ^ ((a^b^pb_80)&pb_80); } for(; i<w; i++) dst[i+0] = src1[i+0]-src2[i+0]; } CWE ID: CWE-189 Target: 1 Example 2: Code: WebSize WebLocalFrameImpl::GetScrollOffset() const { if (ScrollableArea* scrollable_area = LayoutViewport()) return scrollable_area->ScrollOffsetInt(); return WebSize(); } 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 limitedToOnlyOneAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectV8Internal::limitedToOnlyOneAttributeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: R_API void r_anal_bb_free(RAnalBlock *bb) { if (!bb) { return; } r_anal_cond_free (bb->cond); R_FREE (bb->fingerprint); r_anal_diff_free (bb->diff); bb->diff = NULL; R_FREE (bb->op_bytes); r_anal_switch_op_free (bb->switch_op); bb->switch_op = NULL; bb->fingerprint = NULL; bb->cond = NULL; R_FREE (bb->label); R_FREE (bb->op_pos); R_FREE (bb->parent_reg_arena); if (bb->prev) { if (bb->prev->jumpbb == bb) { bb->prev->jumpbb = NULL; } if (bb->prev->failbb == bb) { bb->prev->failbb = NULL; } bb->prev = NULL; } if (bb->jumpbb) { bb->jumpbb->prev = NULL; bb->jumpbb = NULL; } if (bb->failbb) { bb->failbb->prev = NULL; bb->failbb = NULL; } R_FREE (bb); } CWE ID: CWE-416 Target: 1 Example 2: Code: static int snd_compr_update_tstamp(struct snd_compr_stream *stream, struct snd_compr_tstamp *tstamp) { if (!stream->ops->pointer) return -ENOTSUPP; stream->ops->pointer(stream, tstamp); pr_debug("dsp consumed till %d total %d bytes\n", tstamp->byte_offset, tstamp->copied_total); if (stream->direction == SND_COMPRESS_PLAYBACK) stream->runtime->total_bytes_transferred = tstamp->copied_total; else stream->runtime->total_bytes_available = tstamp->copied_total; return 0; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) { struct console_font_op cfo = { .op = KD_FONT_OP_GET, .width = UINT_MAX, .height = UINT_MAX, .charcount = UINT_MAX, }; struct unimapinit adv = {}; struct unimapdesc unimapd; _cleanup_free_ struct unipair* unipairs = NULL; _cleanup_free_ void *fontbuf = NULL; unsigned i; int r; unipairs = new(struct unipair, USHRT_MAX); if (!unipairs) { log_oom(); return; } /* get metadata of the current font (width, height, count) */ r = ioctl(src_fd, KDFONTOP, &cfo); if (r < 0) log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to get the font metadata: %m"); else { /* verify parameter sanity first */ if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512) log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)", cfo.width, cfo.height, cfo.charcount); else { /* * Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512 * characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always * requires 32 per glyph, regardless of the actual height - see the comment above #define * max_font_size 65536 in drivers/tty/vt/vt.c for more details. */ fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount); if (!fontbuf) { log_oom(); return; } /* get fonts from the source console */ cfo.data = fontbuf; r = ioctl(src_fd, KDFONTOP, &cfo); if (r < 0) log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m"); else { unimapd.entries = unipairs; unimapd.entry_ct = USHRT_MAX; r = ioctl(src_fd, GIO_UNIMAP, &unimapd); if (r < 0) log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m"); else cfo.op = KD_FONT_OP_SET; } } } if (cfo.op != KD_FONT_OP_SET) log_warning("Fonts will not be copied to remaining consoles"); for (i = 1; i <= 63; i++) { char ttyname[sizeof("/dev/tty63")]; _cleanup_close_ int fd_d = -1; if (i == src_idx || verify_vc_allocation(i) < 0) continue; /* try to open terminal */ xsprintf(ttyname, "/dev/tty%u", i); fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd_d < 0) { log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i); continue; } if (verify_vc_kbmode(fd_d) < 0) continue; toggle_utf8(ttyname, fd_d, utf8); if (cfo.op != KD_FONT_OP_SET) continue; r = ioctl(fd_d, KDFONTOP, &cfo); if (r < 0) { int last_errno, mode; /* The fonts couldn't have been copied. It might be due to the * terminal being in graphical mode. In this case the kernel * returns -EINVAL which is too generic for distinguishing this * specific case. So we need to retrieve the terminal mode and if * the graphical mode is in used, let's assume that something else * is using the terminal and the failure was expected as we * shouldn't have tried to copy the fonts. */ last_errno = errno; if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT) log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i); else log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i); continue; } /* * copy unicode translation table unimapd is a ushort count and a pointer * to an array of struct unipair { ushort, ushort } */ r = ioctl(fd_d, PIO_UNIMAPCLR, &adv); if (r < 0) { log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i); continue; } r = ioctl(fd_d, PIO_UNIMAP, &unimapd); if (r < 0) { log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i); continue; } log_debug("Font and unimap successfully copied to %s", ttyname); } } CWE ID: CWE-255 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass) { png_const_structp pp = ppIn; PNG_CONST standard_display *dp = voidcast(standard_display*, png_get_progressive_ptr(pp)); /* When handling interlacing some rows will be absent in each pass, the * callback still gets called, but with a NULL pointer. This is checked * in the 'else' clause below. We need our own 'cbRow', but we can't call * png_get_rowbytes because we got no info structure. */ if (new_row != NULL) { png_bytep row; /* In the case where the reader doesn't do the interlace it gives * us the y in the sub-image: */ if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7) { #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED /* Use this opportunity to validate the png 'current' APIs: */ if (y != png_get_current_row_number(pp)) png_error(pp, "png_get_current_row_number is broken"); if (pass != png_get_current_pass_number(pp)) png_error(pp, "png_get_current_pass_number is broken"); #endif y = PNG_ROW_FROM_PASS_ROW(y, pass); } /* Validate this just in case. */ if (y >= dp->h) png_error(pp, "invalid y to progressive row callback"); row = store_image_row(dp->ps, pp, 0, y); #ifdef PNG_READ_INTERLACING_SUPPORTED /* Combine the new row into the old: */ if (dp->do_interlace) { if (dp->interlace_type == PNG_INTERLACE_ADAM7) deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass); else row_copy(row, new_row, dp->pixel_size * dp->w); } else png_progressive_combine_row(pp, row, new_row); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } #ifdef PNG_READ_INTERLACING_SUPPORTED else if (dp->interlace_type == PNG_INTERLACE_ADAM7 && PNG_ROW_IN_INTERLACE_PASS(y, pass) && PNG_PASS_COLS(dp->w, pass) > 0) png_error(pp, "missing row in progressive de-interlacing"); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } CWE ID: Target: 1 Example 2: Code: _dbus_parse_uid (const DBusString *uid_str, dbus_uid_t *uid) { int end; long val; if (_dbus_string_get_length (uid_str) == 0) { _dbus_verbose ("UID string was zero length\n"); return FALSE; } val = -1; end = 0; if (!_dbus_string_parse_int (uid_str, 0, &val, &end)) { _dbus_verbose ("could not parse string as a UID\n"); return FALSE; } if (end != _dbus_string_get_length (uid_str)) { _dbus_verbose ("string contained trailing stuff after UID\n"); return FALSE; } *uid = val; return TRUE; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BluetoothAdapter::RemoveObserver(BluetoothAdapter::Observer* observer) { DCHECK(observer); observers_.RemoveObserver(observer); } 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: ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction( const ExtensionHostMsg_Request_Params& params, const Extension* extension, int requesting_process_id, const extensions::ProcessMap& process_map, extensions::ExtensionAPI* api, void* profile, IPC::Sender* ipc_sender, RenderViewHost* render_view_host, int routing_id) { if (!extension) { LOG(ERROR) << "Specified extension does not exist."; SendAccessDenied(ipc_sender, routing_id, params.request_id); return NULL; } if (api->IsPrivileged(params.name) && !process_map.Contains(extension->id(), requesting_process_id)) { LOG(ERROR) << "Extension API called from incorrect process " << requesting_process_id << " from URL " << params.source_url.spec(); SendAccessDenied(ipc_sender, routing_id, params.request_id); return NULL; } ExtensionFunction* function = ExtensionFunctionRegistry::GetInstance()->NewFunction(params.name); function->SetArgs(&params.arguments); function->set_source_url(params.source_url); function->set_request_id(params.request_id); function->set_has_callback(params.has_callback); function->set_user_gesture(params.user_gesture); function->set_extension(extension); function->set_profile_id(profile); UIThreadExtensionFunction* function_ui = function->AsUIThreadExtensionFunction(); if (function_ui) { function_ui->SetRenderViewHost(render_view_host); } return function; } CWE ID: CWE-264 Target: 1 Example 2: Code: void Document::tasksWereResumed() { scriptRunner()->resume(); if (m_parser) m_parser->resumeScheduledTasks(); if (m_scriptedAnimationController) m_scriptedAnimationController->resume(); MutationObserver::resumeSuspendedObservers(); } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameImpl::DidChangeOpener(blink::WebFrame* opener) { DCHECK(!opener || opener->IsWebLocalFrame()); int opener_routing_id = opener ? RenderFrameImpl::FromWebFrame(opener->ToWebLocalFrame()) ->GetRoutingID() : MSG_ROUTING_NONE; Send(new FrameHostMsg_DidChangeOpener(routing_id_, opener_routing_id)); } 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: long FrameSequenceState_gif::drawFrame(int frameNr, Color8888* outputPtr, int outputPixelStride, int previousFrameNr) { GifFileType* gif = mFrameSequence.getGif(); if (!gif) { ALOGD("Cannot drawFrame, mGif is NULL"); return -1; } #if GIF_DEBUG ALOGD(" drawFrame on %p nr %d on addr %p, previous frame nr %d", this, frameNr, outputPtr, previousFrameNr); #endif const int height = mFrameSequence.getHeight(); const int width = mFrameSequence.getWidth(); GraphicsControlBlock gcb; int start = max(previousFrameNr + 1, 0); for (int i = max(start - 1, 0); i < frameNr; i++) { int neededPreservedFrame = mFrameSequence.getRestoringFrame(i); if (neededPreservedFrame >= 0 && (mPreserveBufferFrame != neededPreservedFrame)) { #if GIF_DEBUG ALOGD("frame %d needs frame %d preserved, but %d is currently, so drawing from scratch", i, neededPreservedFrame, mPreserveBufferFrame); #endif start = 0; } } for (int i = start; i <= frameNr; i++) { DGifSavedExtensionToGCB(gif, i, &gcb); const SavedImage& frame = gif->SavedImages[i]; #if GIF_DEBUG bool frameOpaque = gcb.TransparentColor == NO_TRANSPARENT_COLOR; ALOGD("producing frame %d, drawing frame %d (opaque %d, disp %d, del %d)", frameNr, i, frameOpaque, gcb.DisposalMode, gcb.DelayTime); #endif if (i == 0) { Color8888 bgColor = mFrameSequence.getBackgroundColor(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { outputPtr[y * outputPixelStride + x] = bgColor; } } } else { GraphicsControlBlock prevGcb; DGifSavedExtensionToGCB(gif, i - 1, &prevGcb); const SavedImage& prevFrame = gif->SavedImages[i - 1]; bool prevFrameDisposed = willBeCleared(prevGcb); bool newFrameOpaque = gcb.TransparentColor == NO_TRANSPARENT_COLOR; bool prevFrameCompletelyCovered = newFrameOpaque && checkIfCover(frame.ImageDesc, prevFrame.ImageDesc); if (prevFrameDisposed && !prevFrameCompletelyCovered) { switch (prevGcb.DisposalMode) { case DISPOSE_BACKGROUND: { Color8888* dst = outputPtr + prevFrame.ImageDesc.Left + prevFrame.ImageDesc.Top * outputPixelStride; GifWord copyWidth, copyHeight; getCopySize(prevFrame.ImageDesc, width, height, copyWidth, copyHeight); for (; copyHeight > 0; copyHeight--) { setLineColor(dst, TRANSPARENT, copyWidth); dst += outputPixelStride; } } break; case DISPOSE_PREVIOUS: { restorePreserveBuffer(outputPtr, outputPixelStride); } break; } } if (mFrameSequence.getPreservedFrame(i - 1)) { savePreserveBuffer(outputPtr, outputPixelStride, i - 1); } } bool willBeCleared = gcb.DisposalMode == DISPOSE_BACKGROUND || gcb.DisposalMode == DISPOSE_PREVIOUS; if (i == frameNr || !willBeCleared) { const ColorMapObject* cmap = gif->SColorMap; if (frame.ImageDesc.ColorMap) { cmap = frame.ImageDesc.ColorMap; } if (cmap == NULL || cmap->ColorCount != (1 << cmap->BitsPerPixel)) { ALOGW("Warning: potentially corrupt color map"); } const unsigned char* src = (unsigned char*)frame.RasterBits; Color8888* dst = outputPtr + frame.ImageDesc.Left + frame.ImageDesc.Top * outputPixelStride; GifWord copyWidth, copyHeight; getCopySize(frame.ImageDesc, width, height, copyWidth, copyHeight); for (; copyHeight > 0; copyHeight--) { copyLine(dst, src, cmap, gcb.TransparentColor, copyWidth); src += frame.ImageDesc.Width; dst += outputPixelStride; } } } const int maxFrame = gif->ImageCount; const int lastFrame = (frameNr + maxFrame - 1) % maxFrame; DGifSavedExtensionToGCB(gif, lastFrame, &gcb); return getDelayMs(gcb); } CWE ID: CWE-20 Target: 1 Example 2: Code: static inline int check_pgd_range(struct vm_area_struct *vma, unsigned long addr, unsigned long end, const nodemask_t *nodes, unsigned long flags, void *private) { pgd_t *pgd; unsigned long next; pgd = pgd_offset(vma->vm_mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) continue; if (check_pud_range(vma, pgd, addr, next, nodes, flags, private)) return -EIO; } while (pgd++, addr = next, addr != end); return 0; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MagickExport MagickBooleanType WriteImages(const ImageInfo *image_info, Image *images,const char *filename,ExceptionInfo *exception) { #define WriteImageTag "Write/Image" ExceptionInfo *sans_exception; ImageInfo *write_info; MagickBooleanType proceed; MagickOffsetType progress; MagickProgressMonitor progress_monitor; MagickSizeType number_images; MagickStatusType status; register Image *p; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); write_info=CloneImageInfo(image_info); *write_info->magick='\0'; images=GetFirstImageInList(images); if (filename != (const char *) NULL) for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) (void) CopyMagickString(p->filename,filename,MagickPathExtent); (void) CopyMagickString(write_info->filename,images->filename,MagickPathExtent); sans_exception=AcquireExceptionInfo(); (void) SetImageInfo(write_info,(unsigned int) GetImageListLength(images), sans_exception); sans_exception=DestroyExceptionInfo(sans_exception); if (*write_info->magick == '\0') (void) CopyMagickString(write_info->magick,images->magick,MagickPathExtent); p=images; for ( ; GetNextImageInList(p) != (Image *) NULL; p=GetNextImageInList(p)) if (p->scene >= GetNextImageInList(p)->scene) { register ssize_t i; /* Generate consistent scene numbers. */ i=(ssize_t) images->scene; for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) p->scene=(size_t) i++; break; } /* Write images. */ status=MagickTrue; progress_monitor=(MagickProgressMonitor) NULL; progress=0; number_images=GetImageListLength(images); for (p=images; p != (Image *) NULL; p=GetNextImageInList(p)) { if (number_images != 1) progress_monitor=SetImageProgressMonitor(p,(MagickProgressMonitor) NULL, p->client_data); status&=WriteImage(write_info,p,exception); if (number_images != 1) (void) SetImageProgressMonitor(p,progress_monitor,p->client_data); if (write_info->adjoin != MagickFalse) break; if (number_images != 1) { proceed=SetImageProgress(p,WriteImageTag,progress++,number_images); if (proceed == MagickFalse) break; } } write_info=DestroyImageInfo(write_info); return(status != 0 ? MagickTrue : MagickFalse); } 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: s_aes_process(stream_state * ss, stream_cursor_read * pr, stream_cursor_write * pw, bool last) { stream_aes_state *const state = (stream_aes_state *) ss; const unsigned char *limit; const long in_size = pr->limit - pr->ptr; const long out_size = pw->limit - pw->ptr; unsigned char temp[16]; int status = 0; /* figure out if we're going to run out of space */ if (in_size > out_size) { limit = pr->ptr + out_size; status = 1; /* need more output space */ } else { limit = pr->limit; status = last ? EOFC : 0; /* need more input */ } /* set up state and context */ if (state->ctx == NULL) { /* allocate the aes context. this is a public struct but it contains internal pointers, so we need to store it separately in immovable memory like any opaque structure. */ state->ctx = (aes_context *)gs_alloc_bytes_immovable(state->memory, sizeof(aes_context), "aes context structure"); if (state->ctx == NULL) { gs_throw(gs_error_VMerror, "could not allocate aes context"); return ERRC; } if (state->keylength < 1 || state->keylength > SAES_MAX_KEYLENGTH) { gs_throw1(gs_error_rangecheck, "invalid aes key length (%d bytes)", state->keylength); } aes_setkey_dec(state->ctx, state->key, state->keylength * 8); } if (!state->initialized) { /* read the initialization vector from the first 16 bytes */ if (in_size < 16) return 0; /* get more data */ memcpy(state->iv, pr->ptr + 1, 16); state->initialized = 1; pr->ptr += 16; } /* decrypt available blocks */ while (pr->ptr + 16 <= limit) { aes_crypt_cbc(state->ctx, AES_DECRYPT, 16, state->iv, pr->ptr + 1, temp); pr->ptr += 16; if (last && pr->ptr == pr->limit) { /* we're on the last block; unpad if necessary */ int pad; if (state->use_padding) { /* we are using RFC 1423-style padding, so the last byte of the plaintext gives the number of bytes to discard */ pad = temp[15]; if (pad < 1 || pad > 16) { /* Bug 692343 - don't error here, just warn. Take padding to be * zero. This may give us a stream that's too long - preferable * to the alternatives. */ gs_warn1("invalid aes padding byte (0x%02x)", (unsigned char)pad); pad = 0; } } else { /* not using padding */ pad = 0; } memcpy(pw->ptr + 1, temp, 16 - pad); pw->ptr += 16 - pad; return EOFC; } memcpy(pw->ptr + 1, temp, 16); pw->ptr += 16; } /* if we got to the end of the file without triggering the padding check, the input must not have been a multiple of 16 bytes long. complain. */ if (status == EOFC) { gs_throw(gs_error_rangecheck, "aes stream isn't a multiple of 16 bytes"); return 0; } return status; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void eventHandlerAttrAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); moveEventListenerToNewWrapper(info.Holder(), imp->eventHandlerAttr(), jsValue, V8TestObject::eventListenerCacheIndex, info.GetIsolate()); imp->setEventHandlerAttr(V8EventListenerList::getEventListener(jsValue, true, ListenerFindOrCreate)); } 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 mailimf_minus_parse(const char * message, size_t length, size_t * indx) { return mailimf_unstrict_char_parse(message, length, indx, '-'); } CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long video_ioctl2(struct file *file, unsigned int cmd, unsigned long arg) { char sbuf[128]; void *mbuf = NULL; void *parg = (void *)arg; long err = -EINVAL; bool has_array_args; size_t array_size = 0; void __user *user_ptr = NULL; void **kernel_ptr = NULL; /* Copy arguments into temp kernel buffer */ if (_IOC_DIR(cmd) != _IOC_NONE) { if (_IOC_SIZE(cmd) <= sizeof(sbuf)) { parg = sbuf; } else { /* too big to allocate from stack */ mbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL); if (NULL == mbuf) return -ENOMEM; parg = mbuf; } err = -EFAULT; if (_IOC_DIR(cmd) & _IOC_WRITE) { unsigned long n = cmd_input_size(cmd); if (copy_from_user(parg, (void __user *)arg, n)) goto out; /* zero out anything we don't copy from userspace */ if (n < _IOC_SIZE(cmd)) memset((u8 *)parg + n, 0, _IOC_SIZE(cmd) - n); } else { /* read-only ioctl */ memset(parg, 0, _IOC_SIZE(cmd)); } } err = check_array_args(cmd, parg, &array_size, &user_ptr, &kernel_ptr); if (err < 0) goto out; has_array_args = err; if (has_array_args) { /* * When adding new types of array args, make sure that the * parent argument to ioctl (which contains the pointer to the * array) fits into sbuf (so that mbuf will still remain * unused up to here). */ mbuf = kmalloc(array_size, GFP_KERNEL); err = -ENOMEM; if (NULL == mbuf) goto out_array_args; err = -EFAULT; if (copy_from_user(mbuf, user_ptr, array_size)) goto out_array_args; *kernel_ptr = mbuf; } /* Handles IOCTL */ err = __video_do_ioctl(file, cmd, parg); if (err == -ENOIOCTLCMD) err = -EINVAL; if (has_array_args) { *kernel_ptr = user_ptr; if (copy_to_user(user_ptr, mbuf, array_size)) err = -EFAULT; goto out_array_args; } if (err < 0) goto out; out_array_args: /* Copy results into user buffer */ switch (_IOC_DIR(cmd)) { case _IOC_READ: case (_IOC_WRITE | _IOC_READ): if (copy_to_user((void __user *)arg, parg, _IOC_SIZE(cmd))) err = -EFAULT; break; } out: kfree(mbuf); return err; } CWE ID: CWE-399 Target: 1 Example 2: Code: static const char *register_fixups_hook(cmd_parms *cmd, void *_cfg, const char *file, const char *function) { return register_named_file_function_hook("fixups", cmd, _cfg, file, function, APR_HOOK_MIDDLE); } 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 AXTree::ComputeSetSizePosInSetAndCache(const AXNode& node, const AXNode* ordered_set) { DCHECK(ordered_set); std::vector<const AXNode*> items; bool node_is_radio_button = (node.data().role == ax::mojom::Role::kRadioButton); PopulateOrderedSetItems(ordered_set, ordered_set, items, node_is_radio_button); int32_t num_elements = 0; int32_t largest_assigned_set_size = 0; for (size_t i = 0; i < items.size(); ++i) { const AXNode* item = items[i]; ordered_set_info_map_[item->id()] = OrderedSetInfo(); int32_t pos_in_set_value = 0; pos_in_set_value = num_elements + 1; pos_in_set_value = std::max(pos_in_set_value, item->GetIntAttribute(ax::mojom::IntAttribute::kPosInSet)); ordered_set_info_map_[item->id()].pos_in_set = pos_in_set_value; num_elements = pos_in_set_value; if (item->HasIntAttribute(ax::mojom::IntAttribute::kSetSize)) largest_assigned_set_size = std::max(largest_assigned_set_size, item->GetIntAttribute(ax::mojom::IntAttribute::kSetSize)); } int32_t ordered_set_candidate = ordered_set->GetIntAttribute(ax::mojom::IntAttribute::kSetSize); int32_t set_size_value = std::max( std::max(num_elements, largest_assigned_set_size), ordered_set_candidate); if (ordered_set_info_map_.find(ordered_set->id()) == ordered_set_info_map_.end()) ordered_set_info_map_[ordered_set->id()] = OrderedSetInfo(); if (node.SetRoleMatchesItemRole(ordered_set) || ordered_set == &node) ordered_set_info_map_[ordered_set->id()].set_size = set_size_value; for (size_t j = 0; j < items.size(); ++j) { const AXNode* item = items[j]; ordered_set_info_map_[item->id()].set_size = set_size_value; } } CWE ID: CWE-190 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ExtensionService::IsDownloadFromGallery(const GURL& download_url, const GURL& referrer_url) { if (IsDownloadFromMiniGallery(download_url) && StartsWithASCII(referrer_url.spec(), extension_urls::kMiniGalleryBrowsePrefix, false)) { return true; } const Extension* download_extension = GetExtensionByWebExtent(download_url); const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url); const Extension* webstore_app = GetWebStoreApp(); bool referrer_valid = (referrer_extension == webstore_app); bool download_valid = (download_extension == webstore_app); GURL store_url = GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kAppsGalleryURL)); if (!store_url.is_empty()) { std::string store_tld = net::RegistryControlledDomainService::GetDomainAndRegistry(store_url); if (!referrer_valid) { std::string referrer_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( referrer_url); referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld); } if (!download_valid) { std::string download_tld = net::RegistryControlledDomainService::GetDomainAndRegistry( download_url); download_valid = (download_tld == store_tld); } } return (referrer_valid && download_valid); } CWE ID: CWE-264 Target: 1 Example 2: Code: static int skt_disconnect(int fd) { INFO("fd %d", fd); if (fd != AUDIO_SKT_DISCONNECTED) { shutdown(fd, SHUT_RDWR); close(fd); } return 0; } CWE ID: CWE-284 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xsltGetKey(xsltTransformContextPtr ctxt, const xmlChar *name, const xmlChar *nameURI, const xmlChar *value) { xmlNodeSetPtr ret; xsltKeyTablePtr table; int init_table = 0; if ((ctxt == NULL) || (name == NULL) || (value == NULL) || (ctxt->document == NULL)) return(NULL); #ifdef WITH_XSLT_DEBUG_KEYS xsltGenericDebug(xsltGenericDebugContext, "Get key %s, value %s\n", name, value); #endif /* * keys are computed only on-demand on first key access for a document */ if ((ctxt->document->nbKeysComputed < ctxt->nbKeys) && (ctxt->keyInitLevel == 0)) { /* * If non-recursive behaviour, just try to initialize all keys */ if (xsltInitAllDocKeys(ctxt)) return(NULL); } retry: table = (xsltKeyTablePtr) ctxt->document->keys; while (table != NULL) { if (((nameURI != NULL) == (table->nameURI != NULL)) && xmlStrEqual(table->name, name) && xmlStrEqual(table->nameURI, nameURI)) { ret = (xmlNodeSetPtr)xmlHashLookup(table->keys, value); return(ret); } table = table->next; } if ((ctxt->keyInitLevel != 0) && (init_table == 0)) { /* * Apparently one key is recursive and this one is needed, * initialize just it, that time and retry */ xsltInitDocKeyTable(ctxt, name, nameURI); init_table = 1; goto retry; } return(NULL); } 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: HostCache::HostCache(size_t max_entries) : max_entries_(max_entries), network_changes_(0) {} CWE ID: Target: 1 Example 2: Code: static int kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; s64 kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __this_cpu_read(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->pv_time_enabled) return 0; if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time, &guest_hv_clock, sizeof(guest_hv_clock)))) return 0; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; kvm_write_guest_cached(v->kvm, &vcpu->pv_time, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); return 0; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ChromeContentBrowserClient::GetInitiatorSchemeBypassingDocumentBlocking() { #if BUILDFLAG(ENABLE_EXTENSIONS) return extensions::kExtensionScheme; #else return nullptr; #endif } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams( int version, const std::string& selection, const std::string& base_page_url, int now_on_tap_version) : version(version), start(base::string16::npos), end(base::string16::npos), selection(selection), base_page_url(base_page_url), now_on_tap_version(now_on_tap_version) {} CWE ID: Target: 1 Example 2: Code: bool HTMLFormControlElement::MatchesValidityPseudoClasses() const { return willValidate(); } CWE ID: CWE-704 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 InspectorNetworkAgent::DidReceiveWebSocketFrameError( unsigned long identifier, const String& error_message) { GetFrontend()->webSocketFrameError(IdentifiersFactory::RequestId(identifier), MonotonicallyIncreasingTime(), error_message); } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int logi_dj_raw_event(struct hid_device *hdev, struct hid_report *report, u8 *data, int size) { struct dj_receiver_dev *djrcv_dev = hid_get_drvdata(hdev); struct dj_report *dj_report = (struct dj_report *) data; unsigned long flags; bool report_processed = false; dbg_hid("%s, size:%d\n", __func__, size); /* Here we receive all data coming from iface 2, there are 4 cases: * * 1) Data should continue its normal processing i.e. data does not * come from the DJ collection, in which case we do nothing and * return 0, so hid-core can continue normal processing (will forward * to associated hidraw device) * * 2) Data is from DJ collection, and is intended for this driver i. e. * data contains arrival, departure, etc notifications, in which case * we queue them for delayed processing by the work queue. We return 1 * to hid-core as no further processing is required from it. * * 3) Data is from DJ collection, and informs a connection change, * if the change means rf link loss, then we must send a null report * to the upper layer to discard potentially pressed keys that may be * repeated forever by the input layer. Return 1 to hid-core as no * further processing is required. * * 4) Data is from DJ collection and is an actual input event from * a paired DJ device in which case we forward it to the correct hid * device (via hid_input_report() ) and return 1 so hid-core does not do * anything else with it. */ spin_lock_irqsave(&djrcv_dev->lock, flags); if (dj_report->report_id == REPORT_ID_DJ_SHORT) { switch (dj_report->report_type) { case REPORT_TYPE_NOTIF_DEVICE_PAIRED: case REPORT_TYPE_NOTIF_DEVICE_UNPAIRED: logi_dj_recv_queue_notification(djrcv_dev, dj_report); break; case REPORT_TYPE_NOTIF_CONNECTION_STATUS: if (dj_report->report_params[CONNECTION_STATUS_PARAM_STATUS] == STATUS_LINKLOSS) { logi_dj_recv_forward_null_report(djrcv_dev, dj_report); } break; default: logi_dj_recv_forward_report(djrcv_dev, dj_report); } report_processed = true; } spin_unlock_irqrestore(&djrcv_dev->lock, flags); return report_processed; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool PrintRenderFrameHelper::CreatePreviewDocument() { if (!print_pages_params_ || CheckForCancel()) return false; UMA_HISTOGRAM_ENUMERATION("PrintPreview.PreviewEvent", PREVIEW_EVENT_CREATE_DOCUMENT, PREVIEW_EVENT_MAX); const PrintMsg_Print_Params& print_params = print_pages_params_->params; const std::vector<int>& pages = print_pages_params_->pages; if (!print_preview_context_.CreatePreviewDocument( std::move(prep_frame_view_), pages, print_params.printed_doc_type)) { return false; } PageSizeMargins default_page_layout; double scale_factor = print_params.scale_factor >= kEpsilon ? print_params.scale_factor : 1.0f; ComputePageLayoutInPointsForCss(print_preview_context_.prepared_frame(), 0, print_params, ignore_css_margins_, &scale_factor, &default_page_layout); bool has_page_size_style = PrintingFrameHasPageSizeStyle(print_preview_context_.prepared_frame(), print_preview_context_.total_page_count()); int dpi = GetDPI(&print_params); gfx::Rect printable_area_in_points( ConvertUnit(print_params.printable_area.x(), dpi, kPointsPerInch), ConvertUnit(print_params.printable_area.y(), dpi, kPointsPerInch), ConvertUnit(print_params.printable_area.width(), dpi, kPointsPerInch), ConvertUnit(print_params.printable_area.height(), dpi, kPointsPerInch)); double fit_to_page_scale_factor = 1.0f; if (!print_preview_context_.IsModifiable()) { blink::WebLocalFrame* source_frame = print_preview_context_.source_frame(); const blink::WebNode& source_node = print_preview_context_.source_node(); blink::WebPrintPresetOptions preset_options; if (source_frame->GetPrintPresetOptionsForPlugin(source_node, &preset_options)) { if (preset_options.is_page_size_uniform) { bool is_printable_area_landscape = printable_area_in_points.width() > printable_area_in_points.height(); bool is_preset_landscape = preset_options.uniform_page_size.width > preset_options.uniform_page_size.height; bool rotate = is_printable_area_landscape != is_preset_landscape; double printable_width = rotate ? printable_area_in_points.height() : printable_area_in_points.width(); double printable_height = rotate ? printable_area_in_points.width() : printable_area_in_points.height(); double scale_width = printable_width / static_cast<double>(preset_options.uniform_page_size.width); double scale_height = printable_height / static_cast<double>(preset_options.uniform_page_size.height); fit_to_page_scale_factor = std::min(scale_width, scale_height); } else { fit_to_page_scale_factor = 0.0f; } } } int fit_to_page_scaling = static_cast<int>(100.0f * fit_to_page_scale_factor); Send(new PrintHostMsg_DidGetDefaultPageLayout( routing_id(), default_page_layout, printable_area_in_points, has_page_size_style)); PrintHostMsg_DidGetPreviewPageCount_Params params; params.page_count = print_preview_context_.total_page_count(); params.fit_to_page_scaling = fit_to_page_scaling; params.preview_request_id = print_params.preview_request_id; params.clear_preview_data = print_preview_context_.generate_draft_pages() || !print_preview_context_.IsModifiable(); Send(new PrintHostMsg_DidGetPreviewPageCount(routing_id(), params)); if (CheckForCancel()) return false; while (!print_preview_context_.IsFinalPageRendered()) { int page_number = print_preview_context_.GetNextPageNumber(); DCHECK_GE(page_number, 0); if (!RenderPreviewPage(page_number, print_params)) return false; if (CheckForCancel()) return false; if (print_preview_context_.IsFinalPageRendered()) print_preview_context_.AllPagesRendered(); if (print_preview_context_.IsLastPageOfPrintReadyMetafile()) { DCHECK(print_preview_context_.IsModifiable() || print_preview_context_.IsFinalPageRendered()); if (!FinalizePrintReadyDocument()) return false; } } print_preview_context_.Finished(); return true; } 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 NavigateNamedFrame(const ToRenderFrameHost& caller_frame, const GURL& url, const std::string& name) { bool success = false; EXPECT_TRUE(ExecuteScriptAndExtractBool( caller_frame, "window.domAutomationController.send(" " !!window.open('" + url.spec() + "', '" + name + "'));", &success)); EXPECT_TRUE(success); } CWE ID: CWE-285 Output:
0
Here are some example code snippets. Analyze the following 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 put_prev_task(struct rq *rq, struct task_struct *prev) { if (prev->se.on_rq) update_rq_clock(rq); rq->skip_clock_update = 0; prev->sched_class->put_prev_task(rq, prev); } CWE ID: Target: 1 Example 2: Code: void CommandBufferProxyImpl::OnBufferPresented( uint64_t swap_id, const gfx::PresentationFeedback& feedback) { DCHECK(gl::IsPresentationCallbackEnabled()); if (presentation_callback_) presentation_callback_.Run(swap_id, feedback); if (update_vsync_parameters_completion_callback_ && feedback.timestamp != base::TimeTicks()) { update_vsync_parameters_completion_callback_.Run(feedback.timestamp, feedback.interval); } } CWE ID: CWE-787 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool SupervisedUserService::MustRemainDisabled( const Extension* extension, extensions::disable_reason::DisableReason* reason, base::string16* error) const { DCHECK(ProfileIsSupervised()); ExtensionState state = GetExtensionState(*extension); bool must_remain_disabled = state == ExtensionState::REQUIRE_APPROVAL; if (must_remain_disabled) { if (error) *error = GetExtensionsLockedMessage(); ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile_); if (extension_prefs->HasDisableReason( extension->id(), extensions::disable_reason::DISABLE_PERMISSIONS_INCREASE)) { if (reason) *reason = extensions::disable_reason::DISABLE_PERMISSIONS_INCREASE; return true; } if (reason) *reason = extensions::disable_reason::DISABLE_CUSTODIAN_APPROVAL_REQUIRED; if (base::FeatureList::IsEnabled( supervised_users::kSupervisedUserInitiatedExtensionInstall)) { if (!extension_prefs->HasDisableReason( extension->id(), extensions::disable_reason:: DISABLE_CUSTODIAN_APPROVAL_REQUIRED)) { SupervisedUserService* supervised_user_service = SupervisedUserServiceFactory::GetForProfile(profile_); supervised_user_service->AddExtensionInstallRequest( extension->id(), extension->version()); } } } return must_remain_disabled; } 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: OMX_ERRORTYPE SoftAACEncoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = OMX_AUDIO_AACObjectMain; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: virtual bool CanRestoreTab() { return false; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int perf_pmu_register(struct pmu *pmu, const char *name, int type) { int cpu, ret; mutex_lock(&pmus_lock); ret = -ENOMEM; pmu->pmu_disable_count = alloc_percpu(int); if (!pmu->pmu_disable_count) goto unlock; pmu->type = -1; if (!name) goto skip_type; pmu->name = name; if (type < 0) { type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL); if (type < 0) { ret = type; goto free_pdc; } } pmu->type = type; if (pmu_bus_running) { ret = pmu_dev_alloc(pmu); if (ret) goto free_idr; } skip_type: pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr); if (pmu->pmu_cpu_context) goto got_cpu_context; ret = -ENOMEM; pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context); if (!pmu->pmu_cpu_context) goto free_dev; for_each_possible_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); __perf_event_init_context(&cpuctx->ctx); lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); cpuctx->ctx.type = cpu_context; cpuctx->ctx.pmu = pmu; __perf_cpu_hrtimer_init(cpuctx, cpu); INIT_LIST_HEAD(&cpuctx->rotation_list); cpuctx->unique_pmu = pmu; } got_cpu_context: if (!pmu->start_txn) { if (pmu->pmu_enable) { /* * If we have pmu_enable/pmu_disable calls, install * transaction stubs that use that to try and batch * hardware accesses. */ pmu->start_txn = perf_pmu_start_txn; pmu->commit_txn = perf_pmu_commit_txn; pmu->cancel_txn = perf_pmu_cancel_txn; } else { pmu->start_txn = perf_pmu_nop_void; pmu->commit_txn = perf_pmu_nop_int; pmu->cancel_txn = perf_pmu_nop_void; } } if (!pmu->pmu_enable) { pmu->pmu_enable = perf_pmu_nop_void; pmu->pmu_disable = perf_pmu_nop_void; } if (!pmu->event_idx) pmu->event_idx = perf_event_idx_default; list_add_rcu(&pmu->entry, &pmus); ret = 0; unlock: mutex_unlock(&pmus_lock); return ret; free_dev: device_del(pmu->dev); put_device(pmu->dev); free_idr: if (pmu->type >= PERF_TYPE_MAX) idr_remove(&pmu_idr, pmu->type); free_pdc: free_percpu(pmu->pmu_disable_count); goto unlock; } 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: bool UsbChooserContext::HasDevicePermission( const GURL& requesting_origin, const GURL& embedding_origin, const device::mojom::UsbDeviceInfo& device_info) { if (UsbBlocklist::Get().IsExcluded(device_info)) return false; if (!CanRequestObjectPermission(requesting_origin, embedding_origin)) return false; auto it = ephemeral_devices_.find( std::make_pair(requesting_origin, embedding_origin)); if (it != ephemeral_devices_.end() && base::ContainsKey(it->second, device_info.guid)) { return true; } std::vector<std::unique_ptr<base::DictionaryValue>> device_list = GetGrantedObjects(requesting_origin, embedding_origin); for (const std::unique_ptr<base::DictionaryValue>& device_dict : device_list) { int vendor_id; int product_id; base::string16 serial_number; if (device_dict->GetInteger(kVendorIdKey, &vendor_id) && device_info.vendor_id == vendor_id && device_dict->GetInteger(kProductIdKey, &product_id) && device_info.product_id == product_id && device_dict->GetString(kSerialNumberKey, &serial_number) && device_info.serial_number == serial_number) { return true; } } return false; } CWE ID: CWE-119 Target: 1 Example 2: Code: static void process_service_search_rsp(tCONN_CB* p_ccb, uint8_t* p_reply, uint8_t* p_reply_end) { uint16_t xx; uint16_t total, cur_handles, orig; uint8_t cont_len; /* Skip transaction, and param len */ p_reply += 4; BE_STREAM_TO_UINT16(total, p_reply); BE_STREAM_TO_UINT16(cur_handles, p_reply); orig = p_ccb->num_handles; p_ccb->num_handles += cur_handles; if (p_ccb->num_handles == 0) { SDP_TRACE_WARNING("SDP - Rcvd ServiceSearchRsp, no matches"); sdp_disconnect(p_ccb, SDP_NO_RECS_MATCH); return; } /* Save the handles that match. We will can only process a certain number. */ if (total > sdp_cb.max_recs_per_search) total = sdp_cb.max_recs_per_search; if (p_ccb->num_handles > sdp_cb.max_recs_per_search) p_ccb->num_handles = sdp_cb.max_recs_per_search; for (xx = orig; xx < p_ccb->num_handles; xx++) BE_STREAM_TO_UINT32(p_ccb->handles[xx], p_reply); BE_STREAM_TO_UINT8(cont_len, p_reply); if (cont_len != 0) { if (cont_len > SDP_MAX_CONTINUATION_LEN) { sdp_disconnect(p_ccb, SDP_INVALID_CONT_STATE); return; } if (p_reply + cont_len > p_reply_end) { android_errorWriteLog(0x534e4554, "68161546"); sdp_disconnect(p_ccb, SDP_INVALID_CONT_STATE); return; } /* stay in the same state */ sdp_snd_service_search_req(p_ccb, cont_len, p_reply); } else { /* change state */ p_ccb->disc_state = SDP_DISC_WAIT_ATTR; /* Kick off the first attribute request */ process_service_attr_rsp(p_ccb, NULL, NULL); } } 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 HTMLFormElement::setDemoted(bool demoted) { if (demoted) UseCounter::count(&document(), UseCounter::DemotedFormElement); m_wasDemoted = demoted; } 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: ospf6_print_lshdr(netdissect_options *ndo, register const struct lsa6_hdr *lshp, const u_char *dataend) { if ((const u_char *)(lshp + 1) > dataend) goto trunc; ND_TCHECK(lshp->ls_type); ND_TCHECK(lshp->ls_seq); ND_PRINT((ndo, "\n\t Advertising Router %s, seq 0x%08x, age %us, length %u", ipaddr_string(ndo, &lshp->ls_router), EXTRACT_32BITS(&lshp->ls_seq), EXTRACT_16BITS(&lshp->ls_age), EXTRACT_16BITS(&lshp->ls_length)-(u_int)sizeof(struct lsa6_hdr))); ospf6_print_ls_type(ndo, EXTRACT_16BITS(&lshp->ls_type), &lshp->ls_stateid); return (0); trunc: return (1); } CWE ID: CWE-125 Target: 1 Example 2: Code: R_API int r_core_cmd_command(RCore *core, const char *command) { int ret, len; char *buf, *rcmd, *ptr; char *cmd = r_core_sysenv_begin (core, command); rcmd = ptr = buf = r_sys_cmd_str (cmd, 0, &len); if (!buf) { free (cmd); return -1; } ret = r_core_cmd (core, rcmd, 0); r_core_sysenv_end (core, command); free (buf); 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: SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } 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: void PlatformSensorProviderLinux::CreateFusionSensor( mojom::SensorType type, mojo::ScopedSharedBufferMapping mapping, const CreateSensorCallback& callback) { DCHECK(IsFusionSensorType(type)); std::unique_ptr<PlatformSensorFusionAlgorithm> fusion_algorithm; switch (type) { case mojom::SensorType::LINEAR_ACCELERATION: fusion_algorithm = std::make_unique< LinearAccelerationFusionAlgorithmUsingAccelerometer>(); break; case mojom::SensorType::RELATIVE_ORIENTATION_EULER_ANGLES: fusion_algorithm = std::make_unique< RelativeOrientationEulerAnglesFusionAlgorithmUsingAccelerometer>(); break; case mojom::SensorType::RELATIVE_ORIENTATION_QUATERNION: fusion_algorithm = std::make_unique< OrientationQuaternionFusionAlgorithmUsingEulerAngles>( false /* absolute */); break; default: NOTREACHED(); } DCHECK(fusion_algorithm); PlatformSensorFusion::Create(std::move(mapping), this, std::move(fusion_algorithm), callback); } CWE ID: CWE-732 Target: 1 Example 2: Code: adjust_exit_policy_from_exitpolicy_failure(origin_circuit_t *circ, entry_connection_t *conn, node_t *node, const tor_addr_t *addr) { int make_reject_all = 0; const sa_family_t family = tor_addr_family(addr); if (node) { tor_addr_t tmp; int asked_for_family = tor_addr_parse(&tmp, conn->socks_request->address); if (family == AF_UNSPEC) { make_reject_all = 1; } else if (node_exit_policy_is_exact(node, family) && asked_for_family != -1 && !conn->chosen_exit_name) { make_reject_all = 1; } if (make_reject_all) { log_info(LD_APP, "Exitrouter %s seems to be more restrictive than its exit " "policy. Not using this router as exit for now.", node_describe(node)); policies_set_node_exitpolicy_to_reject_all(node); } } if (family != AF_UNSPEC) addr_policy_append_reject_addr(&circ->prepend_policy, addr); } 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: unsigned long unmap_vmas(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long start_addr, unsigned long end_addr, unsigned long *nr_accounted, struct zap_details *details) { unsigned long start = start_addr; struct mm_struct *mm = vma->vm_mm; mmu_notifier_invalidate_range_start(mm, start_addr, end_addr); for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next) { unsigned long end; start = max(vma->vm_start, start_addr); if (start >= vma->vm_end) continue; end = min(vma->vm_end, end_addr); if (end <= vma->vm_start) continue; if (vma->vm_flags & VM_ACCOUNT) *nr_accounted += (end - start) >> PAGE_SHIFT; if (unlikely(is_pfn_mapping(vma))) untrack_pfn_vma(vma, 0, 0); while (start != end) { if (unlikely(is_vm_hugetlb_page(vma))) { /* * It is undesirable to test vma->vm_file as it * should be non-null for valid hugetlb area. * However, vm_file will be NULL in the error * cleanup path of do_mmap_pgoff. When * hugetlbfs ->mmap method fails, * do_mmap_pgoff() nullifies vma->vm_file * before calling this function to clean up. * Since no pte has actually been setup, it is * safe to do nothing in this case. */ if (vma->vm_file) unmap_hugepage_range(vma, start, end, NULL); start = end; } else start = unmap_page_range(tlb, vma, start, end, details); } } mmu_notifier_invalidate_range_end(mm, start_addr, end_addr); return start; /* which is now the end (or restart) address */ } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PermissionsRequestFunction::InstallUIAbort(bool user_initiated) { results_ = Request::Results::Create(false); SendResponse(true); Release(); // Balanced in RunImpl(). } CWE ID: CWE-264 Target: 1 Example 2: Code: base::string16 AuthenticatorGenericErrorSheetModel::GetCancelButtonLabel() const { return l10n_util::GetStringUTF16(IDS_CLOSE); } 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: PassRefPtr<RTCSessionDescriptionDescriptor> RTCPeerConnectionHandlerChromium::remoteDescription() { if (!m_webHandler) return 0; return m_webHandler->remoteDescription(); } 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: png_set_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth, int color_type, int interlace_type, int compression_type, int filter_type) { png_debug1(1, "in %s storage function", "IHDR"); if (png_ptr == NULL || info_ptr == NULL) return; info_ptr->width = width; info_ptr->height = height; info_ptr->bit_depth = (png_byte)bit_depth; info_ptr->color_type = (png_byte)color_type; info_ptr->compression_type = (png_byte)compression_type; info_ptr->filter_type = (png_byte)filter_type; info_ptr->interlace_type = (png_byte)interlace_type; png_check_IHDR (png_ptr, info_ptr->width, info_ptr->height, info_ptr->bit_depth, info_ptr->color_type, info_ptr->interlace_type, info_ptr->compression_type, info_ptr->filter_type); if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) info_ptr->channels = 3; else info_ptr->channels = 1; if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) info_ptr->channels++; info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); /* Check for potential overflow */ if (width > (PNG_UINT_32_MAX >> 3) /* 8-byte RGBA pixels */ - 64 /* bigrowbuf hack */ - 1 /* filter byte */ - 7*8 /* rounding of width to multiple of 8 pixels */ - 8) /* extra max_pixel_depth pad */ info_ptr->rowbytes = (png_size_t)0; else info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width); } CWE ID: CWE-119 Target: 1 Example 2: Code: static void spl_ptr_heap_zval_dtor(spl_ptr_heap_element elem TSRMLS_DC) { /* {{{ */ if (elem) { zval_ptr_dtor((zval **)&elem); } } /* }}} */ 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 RenderWidgetHostViewAura::OnBoundsChanged(const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) { if (is_fullscreen_) SetSize(new_bounds.size()); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct extent_tree *et; struct extent_node *en; struct extent_info ei; if (!f2fs_may_extent_tree(inode)) { /* drop largest extent */ if (i_ext && i_ext->len) { i_ext->len = 0; return true; } return false; } et = __grab_extent_tree(inode); if (!i_ext || !i_ext->len) return false; get_extent_info(&ei, i_ext); write_lock(&et->lock); if (atomic_read(&et->node_cnt)) goto out; en = __init_extent_tree(sbi, et, &ei); if (en) { spin_lock(&sbi->extent_lock); list_add_tail(&en->list, &sbi->extent_list); spin_unlock(&sbi->extent_lock); } out: write_unlock(&et->lock); return false; } CWE ID: CWE-119 Target: 1 Example 2: Code: void BrowserWindowGtk::RegisterUserPrefs(PrefService* prefs) { bool custom_frame_default = false; if (ui::XDisplayExists() && !prefs->HasPrefPath(prefs::kUseCustomChromeFrame)) { custom_frame_default = GetCustomFramePrefDefault(); } prefs->RegisterBooleanPref(prefs::kUseCustomChromeFrame, custom_frame_default, PrefService::SYNCABLE_PREF); } 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 hns_rcb_update_stats(struct hnae_queue *queue) { struct ring_pair_cb *ring = container_of(queue, struct ring_pair_cb, q); struct dsaf_device *dsaf_dev = ring->rcb_common->dsaf_dev; struct ppe_common_cb *ppe_common = dsaf_dev->ppe_common[ring->rcb_common->comm_index]; struct hns_ring_hw_stats *hw_stats = &ring->hw_stats; hw_stats->rx_pkts += dsaf_read_dev(queue, RCB_RING_RX_RING_PKTNUM_RECORD_REG); dsaf_write_dev(queue, RCB_RING_RX_RING_PKTNUM_RECORD_REG, 0x1); hw_stats->ppe_rx_ok_pkts += dsaf_read_dev(ppe_common, PPE_COM_HIS_RX_PKT_QID_OK_CNT_REG + 4 * ring->index); hw_stats->ppe_rx_drop_pkts += dsaf_read_dev(ppe_common, PPE_COM_HIS_RX_PKT_QID_DROP_CNT_REG + 4 * ring->index); hw_stats->tx_pkts += dsaf_read_dev(queue, RCB_RING_TX_RING_PKTNUM_RECORD_REG); dsaf_write_dev(queue, RCB_RING_TX_RING_PKTNUM_RECORD_REG, 0x1); hw_stats->ppe_tx_ok_pkts += dsaf_read_dev(ppe_common, PPE_COM_HIS_TX_PKT_QID_OK_CNT_REG + 4 * ring->index); hw_stats->ppe_tx_drop_pkts += dsaf_read_dev(ppe_common, PPE_COM_HIS_TX_PKT_QID_ERR_CNT_REG + 4 * ring->index); } 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: const char* SegmentInfo::GetWritingAppAsUTF8() const { return m_pWritingAppAsUTF8; } CWE ID: CWE-119 Target: 1 Example 2: Code: int CLASS ljpeg_diff (ushort *huff) { int len, diff; len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } 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 VerifyMarkDirty(base::PlatformFileError error, const std::string& resource_id, const std::string& md5, const FilePath& cache_file_path) { VerifyCacheFileState(error, resource_id, md5); if (error == base::PLATFORM_FILE_OK) { FilePath base_name = cache_file_path.BaseName(); EXPECT_EQ(util::EscapeCacheFileName(resource_id) + FilePath::kExtensionSeparator + "local", base_name.value()); } else { EXPECT_TRUE(cache_file_path.empty()); } } 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: AccessType GetExtensionAccess(const Extension* extension, const GURL& url, int tab_id) { bool allowed_script = IsAllowedScript(extension, url, tab_id); bool allowed_capture = extension->permissions_data()->CanCaptureVisiblePage(tab_id, nullptr); if (allowed_script && allowed_capture) return ALLOWED_SCRIPT_AND_CAPTURE; if (allowed_script) return ALLOWED_SCRIPT_ONLY; if (allowed_capture) return ALLOWED_CAPTURE_ONLY; return DISALLOWED; } CWE ID: CWE-20 Target: 1 Example 2: Code: void CWebServer::StoreSession(const WebEmStoredSession & session) { if (session.id.empty()) { _log.Log(LOG_ERROR, "SessionStore : cannot store session without id."); return; } char szExpires[30]; struct tm ltime; localtime_r(&session.expires, &ltime); strftime(szExpires, sizeof(szExpires), "%Y-%m-%d %H:%M:%S", &ltime); std::string remote_host = (session.remote_host.size() <= 50) ? // IPv4 : 15, IPv6 : (39|45) session.remote_host : session.remote_host.substr(0, 50); WebEmStoredSession storedSession = GetSession(session.id); if (storedSession.id.empty()) { m_sql.safe_query( "INSERT INTO UserSessions (SessionID, Username, AuthToken, ExpirationDate, RemoteHost) VALUES ('%q', '%q', '%q', '%q', '%q')", session.id.c_str(), base64_encode(session.username).c_str(), session.auth_token.c_str(), szExpires, remote_host.c_str()); } else { m_sql.safe_query( "UPDATE UserSessions set AuthToken = '%q', ExpirationDate = '%q', RemoteHost = '%q', LastUpdate = datetime('now', 'localtime') WHERE SessionID = '%q'", session.auth_token.c_str(), szExpires, remote_host.c_str(), session.id.c_str()); } } CWE ID: CWE-89 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If 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 nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 len; UINT32 left; BYTE value; left = originalSize; while (left > 4) { value = *in++; if (left == 5) { *out++ = value; left--; } else if (value == *in) { in++; if (*in < 0xFF) { len = (UINT32) * in++; len += 2; } else { in++; len = *((UINT32*) in); in += 4; } FillMemory(out, len, value); out += len; left -= len; } else { *out++ = value; left--; } } *((UINT32*)out) = *((UINT32*)in); } 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: OMX_ERRORTYPE SoftGSM::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1) { return OMX_ErrorUndefined; } if (pcmParams->nSamplingRate != 8000) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.gsm", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } CWE ID: CWE-119 Target: 1 Example 2: Code: int tls1_check_ec_tmp_key(SSL *s, unsigned long cid) { unsigned char curve_id[2]; EC_KEY *ec = s->cert->ecdh_tmp; # ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL /* Allow any curve: not just those peer supports */ if (s->cert->cert_flags & SSL_CERT_FLAG_BROKEN_PROTOCOL) return 1; # endif /* * If Suite B, AES128 MUST use P-256 and AES256 MUST use P-384, no other * curves permitted. */ if (tls1_suiteb(s)) { /* Curve to check determined by ciphersuite */ if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) curve_id[1] = TLSEXT_curve_P_256; else if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) curve_id[1] = TLSEXT_curve_P_384; else return 0; curve_id[0] = 0; /* Check this curve is acceptable */ if (!tls1_check_ec_key(s, curve_id, NULL)) return 0; /* If auto or setting curve from callback assume OK */ if (s->cert->ecdh_tmp_auto || s->cert->ecdh_tmp_cb) return 1; /* Otherwise check curve is acceptable */ else { unsigned char curve_tmp[2]; if (!ec) return 0; if (!tls1_set_ec_id(curve_tmp, NULL, ec)) return 0; if (!curve_tmp[0] || curve_tmp[1] == curve_id[1]) return 1; return 0; } } if (s->cert->ecdh_tmp_auto) { /* Need a shared curve */ if (tls1_shared_curve(s, 0)) return 1; else return 0; } if (!ec) { if (s->cert->ecdh_tmp_cb) return 1; else return 0; } if (!tls1_set_ec_id(curve_id, NULL, ec)) return 0; /* Set this to allow use of invalid curves for testing */ # if 0 return 1; # else return tls1_check_ec_key(s, curve_id, NULL); # endif } 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 Element::setHasPendingResources() { ensureElementRareData()->setHasPendingResources(true); } 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 BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { RemoveInterstitialObservers(old_contents); AddInterstitialObservers(new_contents->web_contents()); } CWE ID: CWE-20 Target: 1 Example 2: Code: void BookmarksIOFunction::MultiFilesSelected( const std::vector<base::FilePath>& files, void* params) { Release(); // Balanced in BookmarsIOFunction::SelectFile() NOTREACHED() << "Should not be able to select multiple files"; } 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 __ptrace_unlink(struct task_struct *child) { BUG_ON(!child->ptrace); child->ptrace = 0; child->parent = child->real_parent; list_del_init(&child->ptrace_entry); spin_lock(&child->sighand->siglock); /* * Clear all pending traps and TRAPPING. TRAPPING should be * cleared regardless of JOBCTL_STOP_PENDING. Do it explicitly. */ task_clear_jobctl_pending(child, JOBCTL_TRAP_MASK); task_clear_jobctl_trapping(child); /* * Reinstate JOBCTL_STOP_PENDING if group stop is in effect and * @child isn't dead. */ if (!(child->flags & PF_EXITING) && (child->signal->flags & SIGNAL_STOP_STOPPED || child->signal->group_stop_count)) { child->jobctl |= JOBCTL_STOP_PENDING; /* * This is only possible if this thread was cloned by the * traced task running in the stopped group, set the signal * for the future reports. * FIXME: we should change ptrace_init_task() to handle this * case. */ if (!(child->jobctl & JOBCTL_STOP_SIGMASK)) child->jobctl |= SIGSTOP; } /* * If transition to TASK_STOPPED is pending or in TASK_TRACED, kick * @child in the butt. Note that @resume should be used iff @child * is in TASK_TRACED; otherwise, we might unduly disrupt * TASK_KILLABLE sleeps. */ if (child->jobctl & JOBCTL_STOP_PENDING || task_is_traced(child)) ptrace_signal_wake_up(child, true); spin_unlock(&child->sighand->siglock); } 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 inline struct sem_array *sem_obtain_lock(struct ipc_namespace *ns, int id) { struct kern_ipc_perm *ipcp; struct sem_array *sma; rcu_read_lock(); ipcp = ipc_obtain_object(&sem_ids(ns), id); if (IS_ERR(ipcp)) { sma = ERR_CAST(ipcp); goto err; } spin_lock(&ipcp->lock); /* ipc_rmid() may have already freed the ID while sem_lock * was spinning: verify that the structure is still valid */ if (!ipcp->deleted) return container_of(ipcp, struct sem_array, sem_perm); spin_unlock(&ipcp->lock); sma = ERR_PTR(-EINVAL); err: rcu_read_unlock(); return sma; } CWE ID: CWE-189 Target: 1 Example 2: Code: smp_fetch_fhdr_cnt(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_idx *idx = &txn->hdr_idx; struct hdr_ctx ctx; const struct http_msg *msg = ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &txn->req : &txn->rsp; int cnt; if (!args || args->type != ARGT_STR) return 0; CHECK_HTTP_MESSAGE_FIRST(); ctx.idx = 0; cnt = 0; while (http_find_full_header2(args->data.str.str, args->data.str.len, msg->chn->buf->p, idx, &ctx)) cnt++; smp->type = SMP_T_UINT; smp->data.uint = cnt; smp->flags = SMP_F_VOL_HDR; return 1; } 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: struct hash_alg_common *ahash_attr_alg(struct rtattr *rta, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_attr_alg2(rta, &crypto_ahash_type, type, mask); return IS_ERR(alg) ? ERR_CAST(alg) : __crypto_hash_alg_common(alg); } CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: my_object_many_return (MyObject *obj, guint32 *arg0, char **arg1, gint32 *arg2, guint32 *arg3, guint32 *arg4, const char **arg5, GError **error) { *arg0 = 42; *arg1 = g_strdup ("42"); *arg2 = -67; *arg3 = 2; *arg4 = 26; *arg5 = "hello world"; /* Annotation specifies as const */ return TRUE; } CWE ID: CWE-264 Target: 1 Example 2: Code: static void pmac_ide_flush(DBDMA_io *io) { MACIOIDEState *m = io->opaque; if (m->aiocb) { blk_drain_all(); } } 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: kg_seal(minor_status, context_handle, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer, toktype) OM_uint32 *minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; gss_buffer_t input_message_buffer; int *conf_state; gss_buffer_t output_message_buffer; int toktype; { krb5_gss_ctx_id_rec *ctx; krb5_error_code code; krb5_context context; output_message_buffer->length = 0; output_message_buffer->value = NULL; /* Only default qop or matching established cryptosystem is allowed. There are NO EXTENSIONS to this set for AES and friends! The new spec says "just use 0". The old spec plus extensions would actually allow for certain non-zero values. Fix this to handle them later. */ if (qop_req != 0) { *minor_status = (OM_uint32) G_UNKNOWN_QOP; return GSS_S_FAILURE; } ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } context = ctx->k5_context; switch (ctx->proto) { case 0: code = make_seal_token_v1(context, ctx->enc, ctx->seq, &ctx->seq_send, ctx->initiate, input_message_buffer, output_message_buffer, ctx->signalg, ctx->cksum_size, ctx->sealalg, conf_req_flag, toktype, ctx->mech_used); break; case 1: code = gss_krb5int_make_seal_token_v3(context, ctx, input_message_buffer, output_message_buffer, conf_req_flag, toktype); break; default: code = G_UNKNOWN_QOP; /* XXX */ break; } if (code) { *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } if (conf_state) *conf_state = conf_req_flag; *minor_status = 0; return(GSS_S_COMPLETE); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } CWE ID: CWE-200 Target: 1 Example 2: Code: static int midi_setup_sysex_yamaha_reset(struct _mdi *mdi) { MIDI_EVENT_DEBUG(__FUNCTION__,0,0); _WM_CheckEventMemoryPool(mdi); mdi->events[mdi->event_count].do_event = *_WM_do_sysex_roland_reset; mdi->events[mdi->event_count].event_data.channel = 0; mdi->events[mdi->event_count].event_data.data.value = 0; mdi->events[mdi->event_count].samples_to_next = 0; mdi->event_count++; return (0); } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void TestBrowserWindow::ExecuteExtensionCommand( const extensions::Extension* extension, const extensions::Command& command) {} 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: RTCSessionDescriptionRequestSuccededTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCSessionDescriptionRequest& request, const WebKit::WebRTCSessionDescriptionDescriptor& result) : MethodTask<MockWebRTCPeerConnectionHandler>(object) , m_request(request) , m_result(result) { } CWE ID: CWE-20 Target: 1 Example 2: Code: RenderFrameImpl::CreateWorkerContentSettingsClient() { if (!frame_ || !frame_->View()) return nullptr; return GetContentClient()->renderer()->CreateWorkerContentSettingsClient( 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: float AudioParam::finalValue() { float value; calculateFinalValues(&value, 1, false); return value; } 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: get_matching_model_microcode(int cpu, unsigned long start, void *data, size_t size, struct mc_saved_data *mc_saved_data, unsigned long *mc_saved_in_initrd, struct ucode_cpu_info *uci) { u8 *ucode_ptr = data; unsigned int leftover = size; enum ucode_state state = UCODE_OK; unsigned int mc_size; struct microcode_header_intel *mc_header; struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT]; unsigned int mc_saved_count = mc_saved_data->mc_saved_count; int i; while (leftover) { mc_header = (struct microcode_header_intel *)ucode_ptr; mc_size = get_totalsize(mc_header); if (!mc_size || mc_size > leftover || microcode_sanity_check(ucode_ptr, 0) < 0) break; leftover -= mc_size; /* * Since APs with same family and model as the BSP may boot in * the platform, we need to find and save microcode patches * with the same family and model as the BSP. */ if (matching_model_microcode(mc_header, uci->cpu_sig.sig) != UCODE_OK) { ucode_ptr += mc_size; continue; } _save_mc(mc_saved_tmp, ucode_ptr, &mc_saved_count); ucode_ptr += mc_size; } if (leftover) { state = UCODE_ERROR; goto out; } if (mc_saved_count == 0) { state = UCODE_NFOUND; goto out; } for (i = 0; i < mc_saved_count; i++) mc_saved_in_initrd[i] = (unsigned long)mc_saved_tmp[i] - start; mc_saved_data->mc_saved_count = mc_saved_count; out: return state; } CWE ID: CWE-119 Target: 1 Example 2: Code: gs_pop_integer(gs_main_instance * minst, long *result) { i_ctx_t *i_ctx_p = minst->i_ctx_p; ref vref; int code = pop_value(i_ctx_p, &vref); if (code < 0) return code; check_type_only(vref, t_integer); *result = vref.value.intval; ref_stack_pop(&o_stack, 1); return 0; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int jas_image_readcmpt(jas_image_t *image, int cmptno, jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, jas_matrix_t *data) { jas_image_cmpt_t *cmpt; jas_image_coord_t i; jas_image_coord_t j; int k; jas_seqent_t v; int c; jas_seqent_t *dr; jas_seqent_t *d; int drs; if (cmptno < 0 || cmptno >= image->numcmpts_) { return -1; } cmpt = image->cmpts_[cmptno]; if (x >= cmpt->width_ || y >= cmpt->height_ || x + width > cmpt->width_ || y + height > cmpt->height_) { return -1; } if (!jas_matrix_numrows(data) || !jas_matrix_numcols(data)) { return -1; } if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) { if (jas_matrix_resize(data, height, width)) { return -1; } } dr = jas_matrix_getref(data, 0, 0); drs = jas_matrix_rowstep(data); for (i = 0; i < height; ++i, dr += drs) { d = dr; if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) * cmpt->cps_, SEEK_SET) < 0) { return -1; } for (j = width; j > 0; --j, ++d) { v = 0; for (k = cmpt->cps_; k > 0; --k) { if ((c = jas_stream_getc(cmpt->stream_)) == EOF) { return -1; } v = (v << 8) | (c & 0xff); } *d = bitstoint(v, cmpt->prec_, cmpt->sgnd_); } } return 0; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ras_putdatastd(jas_stream_t *out, ras_hdr_t *hdr, jas_image_t *image, int numcmpts, int *cmpts) { int rowsize; int pad; unsigned int z; int nz; int c; int x; int y; int v; jas_matrix_t *data[3]; int i; for (i = 0; i < numcmpts; ++i) { data[i] = jas_matrix_create(jas_image_height(image), jas_image_width(image)); assert(data[i]); } rowsize = RAS_ROWSIZE(hdr); pad = rowsize - (hdr->width * hdr->depth + 7) / 8; hdr->length = hdr->height * rowsize; for (y = 0; y < hdr->height; y++) { for (i = 0; i < numcmpts; ++i) { if (jas_image_readcmpt(image, cmpts[i], 0, y, jas_image_width(image), 1, data[i])) { return -1; } } z = 0; nz = 0; for (x = 0; x < hdr->width; x++) { z <<= hdr->depth; if (RAS_ISRGB(hdr)) { v = RAS_RED((jas_matrix_getv(data[0], x))) | RAS_GREEN((jas_matrix_getv(data[1], x))) | RAS_BLUE((jas_matrix_getv(data[2], x))); } else { v = (jas_matrix_getv(data[0], x)); } z |= v & RAS_ONES(hdr->depth); nz += hdr->depth; while (nz >= 8) { c = (z >> (nz - 8)) & 0xff; if (jas_stream_putc(out, c) == EOF) { return -1; } nz -= 8; z &= RAS_ONES(nz); } } if (nz > 0) { c = (z >> (8 - nz)) & RAS_ONES(nz); if (jas_stream_putc(out, c) == EOF) { return -1; } } if (pad % 2) { if (jas_stream_putc(out, 0) == EOF) { return -1; } } } for (i = 0; i < numcmpts; ++i) { jas_matrix_destroy(data[i]); } return 0; } CWE ID: Target: 1 Example 2: Code: bool AppListControllerDelegate::UserMayModifySettings( Profile* profile, const std::string& app_id) { const extensions::Extension* extension = GetExtension(profile, app_id); const extensions::ManagementPolicy* policy = extensions::ExtensionSystem::Get(profile)->management_policy(); return extension && policy->UserMayModifySettings(extension, NULL); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void LayerTreeHostQt::didInstallPageOverlay() { createPageOverlayLayer(); scheduleLayerFlush(); } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void WebDevToolsAgentImpl::clearBrowserCache() { m_client->clearBrowserCache(); } CWE ID: Target: 1 Example 2: Code: pa_data_add_pac_request(krb5_context context, krb5_get_init_creds_ctx *ctx, METHOD_DATA *md) { size_t len = 0, length; krb5_error_code ret; PA_PAC_REQUEST req; void *buf; switch (ctx->req_pac) { case KRB5_INIT_CREDS_TRISTATE_UNSET: return 0; /* don't bother */ case KRB5_INIT_CREDS_TRISTATE_TRUE: req.include_pac = 1; break; case KRB5_INIT_CREDS_TRISTATE_FALSE: req.include_pac = 0; } ASN1_MALLOC_ENCODE(PA_PAC_REQUEST, buf, length, &req, &len, ret); if (ret) return ret; if(len != length) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_padata_add(context, md, KRB5_PADATA_PA_PAC_REQUEST, buf, len); if (ret) free(buf); return 0; } CWE ID: CWE-320 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Document& Document::EnsureTemplateDocument() { if (IsTemplateDocument()) return *this; if (template_document_) return *template_document_; if (IsHTMLDocument()) { template_document_ = HTMLDocument::Create(DocumentInit::Create() .WithContextDocument(ContextDocument()) .WithURL(BlankURL()) .WithNewRegistrationContext()); } else { template_document_ = Document::Create(DocumentInit::Create().WithURL(BlankURL())); } template_document_->template_document_host_ = this; // balanced in dtor. return *template_document_.Get(); } 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: virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); RenderViewHostTestHarness::TearDown(); } CWE ID: CWE-264 Target: 1 Example 2: Code: static void hwahc_destroy(struct hwahc *hwahc) { struct wusbhc *wusbhc = &hwahc->wusbhc; mutex_lock(&wusbhc->mutex); __wa_destroy(&hwahc->wa); wusbhc_destroy(&hwahc->wusbhc); hwahc_security_release(hwahc); hwahc->wusbhc.dev = NULL; uwb_rc_put(wusbhc->uwb_rc); usb_put_intf(hwahc->wa.usb_iface); usb_put_dev(hwahc->wa.usb_dev); mutex_unlock(&wusbhc->mutex); } 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: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionIdbKey(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); PassRefPtr<IDBKey> key(createIDBKeyFromValue(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->idbKey(key); return JSValue::encode(jsUndefined()); } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BrowserContextDestroyer::BrowserContextDestroyer( BrowserContext* context, const std::set<content::RenderProcessHost*>& hosts) : context_(context), pending_hosts_(0) { for (std::set<content::RenderProcessHost*>::iterator it = hosts.begin(); it != hosts.end(); ++it) { (*it)->AddObserver(this); ++pending_hosts_; } } CWE ID: CWE-20 Target: 1 Example 2: Code: static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size) { unsigned ncpy = min(*size, cs->len); if (val) { void *pgaddr = kmap_atomic(cs->pg); void *buf = pgaddr + cs->offset; if (cs->write) memcpy(buf, *val, ncpy); else memcpy(*val, buf, ncpy); kunmap_atomic(pgaddr); *val += ncpy; } *size -= ncpy; cs->len -= ncpy; cs->offset += ncpy; return ncpy; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void write_bin_error(conn *c, protocol_binary_response_status err, int swallow) { const char *errstr = "Unknown error"; size_t len; switch (err) { case PROTOCOL_BINARY_RESPONSE_ENOMEM: errstr = "Out of memory"; break; case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND: errstr = "Unknown command"; break; case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT: errstr = "Not found"; break; case PROTOCOL_BINARY_RESPONSE_EINVAL: errstr = "Invalid arguments"; break; case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS: errstr = "Data exists for key."; break; case PROTOCOL_BINARY_RESPONSE_E2BIG: errstr = "Too large."; break; case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL: errstr = "Non-numeric server-side value for incr or decr"; break; case PROTOCOL_BINARY_RESPONSE_NOT_STORED: errstr = "Not stored."; break; case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR: errstr = "Auth failure."; break; default: assert(false); errstr = "UNHANDLED ERROR"; fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err); } if (settings.verbose > 1) { fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr); } len = strlen(errstr); add_bin_header(c, err, 0, 0, len); if (len > 0) { add_iov(c, errstr, len); } conn_set_state(c, conn_mwrite); if(swallow > 0) { c->sbytes = swallow; c->write_and_go = conn_swallow; } else { c->write_and_go = conn_new_cmd; } } 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 pcd_detect(void) { char id[18]; int k, unit; struct pcd_unit *cd; printk("%s: %s version %s, major %d, nice %d\n", name, name, PCD_VERSION, major, nice); par_drv = pi_register_driver(name); if (!par_drv) { pr_err("failed to register %s driver\n", name); return -1; } k = 0; if (pcd_drive_count == 0) { /* nothing spec'd - so autoprobe for 1 */ cd = pcd; if (pi_init(cd->pi, 1, -1, -1, -1, -1, -1, pcd_buffer, PI_PCD, verbose, cd->name)) { if (!pcd_probe(cd, -1, id) && cd->disk) { cd->present = 1; k++; } else pi_release(cd->pi); } } else { for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { int *conf = *drives[unit]; if (!conf[D_PRT]) continue; if (!pi_init(cd->pi, 0, conf[D_PRT], conf[D_MOD], conf[D_UNI], conf[D_PRO], conf[D_DLY], pcd_buffer, PI_PCD, verbose, cd->name)) continue; if (!pcd_probe(cd, conf[D_SLV], id) && cd->disk) { cd->present = 1; k++; } else pi_release(cd->pi); } } if (k) return 0; printk("%s: No CD-ROM drive found\n", name); for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { blk_cleanup_queue(cd->disk->queue); cd->disk->queue = NULL; blk_mq_free_tag_set(&cd->tag_set); put_disk(cd->disk); } pi_unregister_driver(par_drv); return -1; } CWE ID: CWE-476 Target: 1 Example 2: Code: void rt_cache_flush_batch(struct net *net) { rt_do_flush(net, !in_softirq()); } 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 smp_process_keypress_notification(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = (uint8_t*)p_data; uint8_t reason = SMP_INVALID_PARAMETERS; SMP_TRACE_DEBUG("%s", __func__); p_cb->status = *(uint8_t*)p_data; if (smp_command_has_invalid_parameters(p_cb)) { smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); return; } if (p != NULL) { STREAM_TO_UINT8(p_cb->peer_keypress_notification, p); } else { p_cb->peer_keypress_notification = BTM_SP_KEY_OUT_OF_RANGE; } p_cb->cb_evt = SMP_PEER_KEYPR_NOT_EVT; } 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: static inline void sem_getref_and_unlock(struct sem_array *sma) { ipc_rcu_getref(sma); ipc_unlock(&(sma)->sem_perm); } CWE ID: CWE-189 Target: 1 Example 2: Code: HeadlessWebContents::Builder& HeadlessWebContents::Builder::SetAllowTabSockets( bool tab_sockets_allowed) { tab_sockets_allowed_ = tab_sockets_allowed; return *this; } CWE ID: CWE-254 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameDevToolsAgentHost::DestroyOnRenderFrameGone() { scoped_refptr<RenderFrameDevToolsAgentHost> protect(this); if (IsAttached()) RevokePolicy(); ForceDetachAllClients(); frame_host_ = nullptr; agent_ptr_.reset(); SetFrameTreeNode(nullptr); Release(); } 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 inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn, struct nlattr *rp) { struct xfrm_replay_state_esn *up; int ulen; if (!replay_esn || !rp) return 0; up = nla_data(rp); ulen = xfrm_replay_state_esn_len(up); if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen) return -EINVAL; if (up->replay_window > up->bmp_len * sizeof(__u32) * 8) return -EINVAL; return 0; } CWE ID: Target: 1 Example 2: Code: status_t MPEG4Extractor::readMetaData() { if (mInitCheck != NO_INIT) { return mInitCheck; } off64_t offset = 0; status_t err; while (true) { off64_t orig_offset = offset; err = parseChunk(&offset, 0); if (err != OK && err != UNKNOWN_ERROR) { break; } else if (offset <= orig_offset) { ALOGE("did not advance: 0x%lld->0x%lld", orig_offset, offset); err = ERROR_MALFORMED; break; } else if (err == OK) { continue; } uint32_t hdr[2]; if (mDataSource->readAt(offset, hdr, 8) < 8) { break; } uint32_t chunk_type = ntohl(hdr[1]); if (chunk_type == FOURCC('m', 'o', 'o', 'f')) { mMoofOffset = offset; } else if (chunk_type != FOURCC('m', 'd', 'a', 't')) { continue; } break; } if (mInitCheck == OK) { if (mHasVideo) { mFileMetaData->setCString( kKeyMIMEType, MEDIA_MIMETYPE_CONTAINER_MPEG4); } else { mFileMetaData->setCString(kKeyMIMEType, "audio/mp4"); } } else { mInitCheck = err; } CHECK_NE(err, (status_t)NO_INIT); int psshsize = 0; for (size_t i = 0; i < mPssh.size(); i++) { psshsize += 20 + mPssh[i].datalen; } if (psshsize) { char *buf = (char*)malloc(psshsize); char *ptr = buf; for (size_t i = 0; i < mPssh.size(); i++) { memcpy(ptr, mPssh[i].uuid, 20); // uuid + length memcpy(ptr + 20, mPssh[i].data, mPssh[i].datalen); ptr += (20 + mPssh[i].datalen); } mFileMetaData->setData(kKeyPssh, 'pssh', buf, psshsize); free(buf); } return mInitCheck; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool GraphicsContext3D::getImageData(Image* image, GC3Denum format, GC3Denum type, bool premultiplyAlpha, bool ignoreGammaAndColorProfile, Vector<uint8_t>& outputVector) { if (!image) return false; CGImageRef cgImage; RetainPtr<CGImageRef> decodedImage; bool hasAlpha = image->isBitmapImage() ? static_cast<BitmapImage*>(image)->frameHasAlphaAtIndex(0) : true; if ((ignoreGammaAndColorProfile || (hasAlpha && !premultiplyAlpha)) && image->data()) { ImageSource decoder(ImageSource::AlphaNotPremultiplied, ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied); decoder.setData(image->data(), true); if (!decoder.frameCount()) return false; decodedImage.adoptCF(decoder.createFrameAtIndex(0)); cgImage = decodedImage.get(); } else cgImage = image->nativeImageForCurrentFrame(); if (!cgImage) return false; size_t width = CGImageGetWidth(cgImage); size_t height = CGImageGetHeight(cgImage); if (!width || !height) return false; CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage); CGColorSpaceModel model = CGColorSpaceGetModel(colorSpace); if (model == kCGColorSpaceModelIndexed) { RetainPtr<CGContextRef> bitmapContext; bitmapContext.adoptCF(CGBitmapContextCreate(0, width, height, 8, width * 4, deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); if (!bitmapContext) return false; CGContextSetBlendMode(bitmapContext.get(), kCGBlendModeCopy); CGContextSetInterpolationQuality(bitmapContext.get(), kCGInterpolationNone); CGContextDrawImage(bitmapContext.get(), CGRectMake(0, 0, width, height), cgImage); decodedImage.adoptCF(CGBitmapContextCreateImage(bitmapContext.get())); cgImage = decodedImage.get(); } size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage); size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage); if (bitsPerComponent != 8 && bitsPerComponent != 16) return false; if (bitsPerPixel % bitsPerComponent) return false; size_t componentsPerPixel = bitsPerPixel / bitsPerComponent; CGBitmapInfo bitInfo = CGImageGetBitmapInfo(cgImage); bool bigEndianSource = false; if (bitsPerComponent == 16) { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder16Big: bigEndianSource = true; break; case kCGBitmapByteOrder16Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: bigEndianSource = true; break; default: return false; } } else { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder32Big: bigEndianSource = true; break; case kCGBitmapByteOrder32Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: bigEndianSource = true; break; default: return false; } } AlphaOp neededAlphaOp = AlphaDoNothing; AlphaFormat alphaFormat = AlphaFormatNone; switch (CGImageGetAlphaInfo(cgImage)) { case kCGImageAlphaPremultipliedFirst: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaFirst: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaNoneSkipFirst: alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaPremultipliedLast: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaLast: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNoneSkipLast: alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNone: alphaFormat = AlphaFormatNone; break; default: return false; } SourceDataFormat srcDataFormat = getSourceDataFormat(componentsPerPixel, alphaFormat, bitsPerComponent == 16, bigEndianSource); if (srcDataFormat == SourceFormatNumFormats) return false; RetainPtr<CFDataRef> pixelData; pixelData.adoptCF(CGDataProviderCopyData(CGImageGetDataProvider(cgImage))); if (!pixelData) return false; const UInt8* rgba = CFDataGetBytePtr(pixelData.get()); unsigned int packedSize; if (computeImageSizeInBytes(format, type, width, height, 1, &packedSize, 0) != GraphicsContext3D::NO_ERROR) return false; outputVector.resize(packedSize); unsigned int srcUnpackAlignment = 0; size_t bytesPerRow = CGImageGetBytesPerRow(cgImage); unsigned int padding = bytesPerRow - bitsPerPixel / 8 * width; if (padding) { srcUnpackAlignment = padding + 1; while (bytesPerRow % srcUnpackAlignment) ++srcUnpackAlignment; } bool rt = packPixels(rgba, srcDataFormat, width, height, srcUnpackAlignment, format, type, neededAlphaOp, outputVector.data()); return rt; } 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 VaapiVideoDecodeAccelerator::Cleanup() { DCHECK(task_runner_->BelongsToCurrentThread()); base::AutoLock auto_lock(lock_); if (state_ == kUninitialized || state_ == kDestroying) return; VLOGF(2) << "Destroying VAVDA"; state_ = kDestroying; client_ptr_factory_.reset(); weak_this_factory_.InvalidateWeakPtrs(); input_ready_.Signal(); surfaces_available_.Signal(); { base::AutoUnlock auto_unlock(lock_); decoder_thread_.Stop(); } state_ = kUninitialized; } CWE ID: CWE-362 Target: 1 Example 2: Code: gfx::Rect ClientControlledShellSurface::GetShadowBounds() const { gfx::Rect shadow_bounds = ShellSurfaceBase::GetShadowBounds(); const ash::NonClientFrameViewAsh* frame_view = GetFrameView(); if (frame_view->GetVisible()) { shadow_bounds.set_size( frame_view->GetWindowBoundsForClientBounds(shadow_bounds).size()); } return shadow_bounds; } 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: DummyProofSource() {} CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DrawingBuffer::DrawingBuffer( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, std::unique_ptr<Extensions3DUtil> extensions_util, Client* client, bool discard_framebuffer_supported, bool want_alpha_channel, bool premultiplied_alpha, PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, bool want_depth, bool want_stencil, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) : client_(client), preserve_drawing_buffer_(preserve), web_gl_version_(web_gl_version), context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper( std::move(context_provider)))), gl_(this->ContextProvider()->ContextGL()), extensions_util_(std::move(extensions_util)), discard_framebuffer_supported_(discard_framebuffer_supported), want_alpha_channel_(want_alpha_channel), premultiplied_alpha_(premultiplied_alpha), software_rendering_(this->ContextProvider()->IsSoftwareRendering()), want_depth_(want_depth), want_stencil_(want_stencil), color_space_(color_params.GetGfxColorSpace()), chromium_image_usage_(chromium_image_usage) { TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation", TRACE_EVENT_SCOPE_GLOBAL); } CWE ID: CWE-119 Target: 1 Example 2: Code: int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx, struct kvm_io_device *dev) { int i, r; struct kvm_io_bus *new_bus, *bus; bus = kvm->buses[bus_idx]; new_bus = kmemdup(bus, sizeof(*bus), GFP_KERNEL); if (!new_bus) return -ENOMEM; r = -ENOENT; for (i = 0; i < new_bus->dev_count; i++) if (new_bus->range[i].dev == dev) { r = 0; new_bus->dev_count--; new_bus->range[i] = new_bus->range[new_bus->dev_count]; sort(new_bus->range, new_bus->dev_count, sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp, NULL); break; } if (r) { kfree(new_bus); return r; } rcu_assign_pointer(kvm->buses[bus_idx], new_bus); synchronize_srcu_expedited(&kvm->srcu); kfree(bus); return r; } 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: AudioNode* AudioNode::connect(AudioNode* destination, unsigned output_index, unsigned input_index, ExceptionState& exception_state) { DCHECK(IsMainThread()); BaseAudioContext::GraphAutoLocker locker(context()); if (context()->IsContextClosed()) { exception_state.ThrowDOMException( kInvalidStateError, "Cannot connect after the context has been closed."); return nullptr; } if (!destination) { exception_state.ThrowDOMException(kSyntaxError, "invalid destination node."); return nullptr; } if (output_index >= numberOfOutputs()) { exception_state.ThrowDOMException( kIndexSizeError, "output index (" + String::Number(output_index) + ") exceeds number of outputs (" + String::Number(numberOfOutputs()) + ")."); return nullptr; } if (destination && input_index >= destination->numberOfInputs()) { exception_state.ThrowDOMException( kIndexSizeError, "input index (" + String::Number(input_index) + ") exceeds number of inputs (" + String::Number(destination->numberOfInputs()) + ")."); return nullptr; } if (context() != destination->context()) { exception_state.ThrowDOMException( kInvalidAccessError, "cannot connect to a destination " "belonging to a different audio context."); return nullptr; } if (Handler().GetNodeType() == AudioHandler::kNodeTypeScriptProcessor && Handler().NumberOfOutputChannels() == 0) { exception_state.ThrowDOMException(kInvalidAccessError, "cannot connect a ScriptProcessorNode " "with 0 output channels to any " "destination node."); return nullptr; } destination->Handler() .Input(input_index) .Connect(Handler().Output(output_index)); if (!connected_nodes_[output_index]) connected_nodes_[output_index] = new HeapHashSet<Member<AudioNode>>(); connected_nodes_[output_index]->insert(destination); context()->IncrementConnectionCount(); return destination; } CWE ID: CWE-416 Output:
0