prompt
stringlengths
799
20.4k
output
int64
0
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void NetworkHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; host_ = frame_host; } CWE ID: CWE-20 Target: 1 Example 2: Code: bool TestBrowserWindow::IsFullscreenBubbleVisible() const { 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: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; int buffer_size = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; int nbchars = 0; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: chrm_modification_init(chrm_modification *me, png_modifier *pm, PNG_CONST color_encoding *encoding) { CIE_color white = white_point(encoding); /* Original end points: */ me->encoding = encoding; /* Chromaticities (in fixed point): */ me->wx = fix(chromaticity_x(white)); me->wy = fix(chromaticity_y(white)); me->rx = fix(chromaticity_x(encoding->red)); me->ry = fix(chromaticity_y(encoding->red)); me->gx = fix(chromaticity_x(encoding->green)); me->gy = fix(chromaticity_y(encoding->green)); me->bx = fix(chromaticity_x(encoding->blue)); me->by = fix(chromaticity_y(encoding->blue)); modification_init(&me->this); me->this.chunk = CHUNK_cHRM; me->this.modify_fn = chrm_modify; me->this.add = CHUNK_PLTE; me->this.next = pm->modifications; pm->modifications = &me->this; } CWE ID: Target: 1 Example 2: Code: QMimeData *IRCView::createMimeDataFromSelection() const { const QTextDocumentFragment fragment(textCursor()); return new IrcViewMimeData(fragment); } 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: bool SharedMemory::Create(const SharedMemoryCreateOptions& options) { DCHECK_EQ(-1, mapped_file_); if (options.size == 0) return false; if (options.size > static_cast<size_t>(std::numeric_limits<int>::max())) return false; base::ThreadRestrictions::ScopedAllowIO allow_io; FILE *fp; bool fix_size = true; FilePath path; if (options.name == NULL || options.name->empty()) { DCHECK(!options.open_existing); fp = file_util::CreateAndOpenTemporaryShmemFile(&path, options.executable); if (fp) { if (unlink(path.value().c_str())) PLOG(WARNING) << "unlink"; } } else { if (!FilePathForMemoryName(*options.name, &path)) return false; fp = file_util::OpenFile(path, "w+x"); if (fp == NULL && options.open_existing) { fp = file_util::OpenFile(path, "a+"); fix_size = false; } } if (fp && fix_size) { struct stat stat; if (fstat(fileno(fp), &stat) != 0) { file_util::CloseFile(fp); return false; } const size_t current_size = stat.st_size; if (current_size != options.size) { if (HANDLE_EINTR(ftruncate(fileno(fp), options.size)) != 0) { file_util::CloseFile(fp); return false; } } requested_size_ = options.size; } if (fp == NULL) { #if !defined(OS_MACOSX) PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; FilePath dir = path.DirName(); if (access(dir.value().c_str(), W_OK | X_OK) < 0) { PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value(); if (dir.value() == "/dev/shm") { LOG(FATAL) << "This is frequently caused by incorrect permissions on " << "/dev/shm. Try 'sudo chmod 1777 /dev/shm' to fix."; } } #else PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed"; #endif return false; } return PrepareMapFile(fp); } 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 FrameFetchContext::DispatchWillSendRequest( unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo& initiator_info) { if (IsDetached()) return; if (redirect_response.IsNull()) { GetFrame()->Loader().Progress().WillStartLoading(identifier, request.Priority()); } probe::willSendRequest(GetFrame()->GetDocument(), identifier, MasterDocumentLoader(), request, redirect_response, initiator_info); if (IdlenessDetector* idleness_detector = GetFrame()->GetIdlenessDetector()) idleness_detector->OnWillSendRequest(); if (GetFrame()->FrameScheduler()) GetFrame()->FrameScheduler()->DidStartLoading(identifier); } CWE ID: CWE-119 Target: 1 Example 2: Code: RenderLayer* InRegionScrollableArea::layer() const { ASSERT(!m_isNull); return m_layer; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GBool maskInvert) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, 1, 1); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmalloc (row_stride * maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int x, y; int invert_bit; invert_bit = maskInvert ? 1 : 0; for (y = 0; y < maskHeight; y++) { pix = maskImgStr->getLine(); maskDest = maskBuffer + y * row_stride; for (x = 0; x < maskWidth; x++) { if (pix[x] ^ invert_bit) *maskDest++ = 0; else *maskDest++ = 255; } } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); /* scale the mask to the size of the image unlike softMask */ cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &matrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; } CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CueTimeline::UpdateActiveCues(double movie_time) { if (IgnoreUpdateRequests()) return; HTMLMediaElement& media_element = MediaElement(); if (media_element.GetDocument().IsDetached()) return; CueList current_cues; if (media_element.getReadyState() != HTMLMediaElement::kHaveNothing && media_element.GetWebMediaPlayer()) current_cues = cue_tree_.AllOverlaps(cue_tree_.CreateInterval(movie_time, movie_time)); CueList previous_cues; CueList missed_cues; previous_cues = currently_active_cues_; double last_time = last_update_time_; double last_seek_time = media_element.LastSeekTime(); if (last_time >= 0 && last_seek_time < movie_time) { CueList potentially_skipped_cues = cue_tree_.AllOverlaps(cue_tree_.CreateInterval(last_time, movie_time)); for (CueInterval cue : potentially_skipped_cues) { if (cue.Low() > std::max(last_seek_time, last_time) && cue.High() < movie_time) missed_cues.push_back(cue); } } last_update_time_ = movie_time; if (!media_element.seeking() && last_seek_time < last_time) media_element.ScheduleTimeupdateEvent(true); size_t missed_cues_size = missed_cues.size(); size_t previous_cues_size = previous_cues.size(); bool active_set_changed = missed_cues_size; for (size_t i = 0; !active_set_changed && i < previous_cues_size; ++i) { if (!current_cues.Contains(previous_cues[i]) && previous_cues[i].Data()->IsActive()) active_set_changed = true; } for (CueInterval current_cue : current_cues) { if (current_cue.Data()->IsActive()) current_cue.Data()->UpdatePastAndFutureNodes(movie_time); else active_set_changed = true; } if (!active_set_changed) return; for (size_t i = 0; !media_element.paused() && i < previous_cues_size; ++i) { if (previous_cues[i].Data()->pauseOnExit() && previous_cues[i].Data()->IsActive() && !current_cues.Contains(previous_cues[i])) media_element.pause(); } for (size_t i = 0; !media_element.paused() && i < missed_cues_size; ++i) { if (missed_cues[i].Data()->pauseOnExit()) media_element.pause(); } HeapVector<std::pair<double, Member<TextTrackCue>>> event_tasks; HeapVector<Member<TextTrack>> affected_tracks; for (const auto& missed_cue : missed_cues) { event_tasks.push_back( std::make_pair(missed_cue.Data()->startTime(), missed_cue.Data())); if (missed_cue.Data()->startTime() < missed_cue.Data()->endTime()) { event_tasks.push_back( std::make_pair(missed_cue.Data()->endTime(), missed_cue.Data())); } } for (const auto& previous_cue : previous_cues) { if (!current_cues.Contains(previous_cue)) { event_tasks.push_back( std::make_pair(previous_cue.Data()->endTime(), previous_cue.Data())); } } for (const auto& current_cue : current_cues) { if (!previous_cues.Contains(current_cue)) { event_tasks.push_back( std::make_pair(current_cue.Data()->startTime(), current_cue.Data())); } } NonCopyingSort(event_tasks.begin(), event_tasks.end(), EventTimeCueCompare); for (const auto& task : event_tasks) { if (!affected_tracks.Contains(task.second->track())) affected_tracks.push_back(task.second->track()); if (task.second->startTime() >= task.second->endTime()) { media_element.ScheduleEvent( CreateEventWithTarget(EventTypeNames::enter, task.second.Get())); media_element.ScheduleEvent( CreateEventWithTarget(EventTypeNames::exit, task.second.Get())); } else { bool is_enter_event = task.first == task.second->startTime(); AtomicString event_name = is_enter_event ? EventTypeNames::enter : EventTypeNames::exit; media_element.ScheduleEvent( CreateEventWithTarget(event_name, task.second.Get())); } } NonCopyingSort(affected_tracks.begin(), affected_tracks.end(), TrackIndexCompare); for (const auto& track : affected_tracks) { media_element.ScheduleEvent( CreateEventWithTarget(EventTypeNames::cuechange, track.Get())); if (track->TrackType() == TextTrack::kTrackElement) { HTMLTrackElement* track_element = ToLoadableTextTrack(track.Get())->TrackElement(); DCHECK(track_element); media_element.ScheduleEvent( CreateEventWithTarget(EventTypeNames::cuechange, track_element)); } } for (const auto& cue : current_cues) cue.Data()->SetIsActive(true); for (const auto& previous_cue : previous_cues) { if (!current_cues.Contains(previous_cue)) { TextTrackCue* cue = previous_cue.Data(); cue->SetIsActive(false); cue->RemoveDisplayTree(); } } currently_active_cues_ = current_cues; media_element.UpdateTextTrackDisplay(); } CWE ID: Target: 1 Example 2: Code: xdr_gpol_arg(XDR *xdrs, gpol_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->name)) { return (FALSE); } return (TRUE); } 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: BlockEntry::~BlockEntry() { } 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 FileAPIMessageFilter::OnCreateSnapshotFile( int request_id, const GURL& blob_url, const GURL& path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); FileSystemURL url(path); base::Callback<void(const FilePath&)> register_file_callback = base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob, this, blob_url, url.path()); FileSystemOperation* operation = GetNewOperation(url, request_id); if (!operation) return; operation->CreateSnapshotFile( url, base::Bind(&FileAPIMessageFilter::DidCreateSnapshot, this, request_id, register_file_callback)); } CWE ID: CWE-264 Target: 1 Example 2: Code: static int unix_scm_to_skb(struct scm_cookie *scm, struct sk_buff *skb, bool send_fds) { int err = 0; UNIXCB(skb).pid = get_pid(scm->pid); UNIXCB(skb).uid = scm->creds.uid; UNIXCB(skb).gid = scm->creds.gid; UNIXCB(skb).fp = NULL; if (scm->fp && send_fds) err = unix_attach_fds(scm, skb); skb->destructor = unix_destruct_scm; return err; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ctdb_tcp_listen_automatic(struct ctdb_context *ctdb) { struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data, struct ctdb_tcp); ctdb_sock_addr sock; int lock_fd, i; const char *lock_path = "/tmp/.ctdb_socket_lock"; struct flock lock; int one = 1; int sock_size; struct tevent_fd *fde; /* If there are no nodes, then it won't be possible to find * the first one. Log a failure and short circuit the whole * process. */ if (ctdb->num_nodes == 0) { DEBUG(DEBUG_CRIT,("No nodes available to attempt bind to - is the nodes file empty?\n")); return -1; } /* in order to ensure that we don't get two nodes with the same adddress, we must make the bind() and listen() calls atomic. The SO_REUSEADDR setsockopt only prevents double binds if the first socket is in LISTEN state */ lock_fd = open(lock_path, O_RDWR|O_CREAT, 0666); if (lock_fd == -1) { DEBUG(DEBUG_CRIT,("Unable to open %s\n", lock_path)); return -1; } lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 1; lock.l_pid = 0; if (fcntl(lock_fd, F_SETLKW, &lock) != 0) { DEBUG(DEBUG_CRIT,("Unable to lock %s\n", lock_path)); close(lock_fd); return -1; } for (i=0; i < ctdb->num_nodes; i++) { if (ctdb->nodes[i]->flags & NODE_FLAGS_DELETED) { continue; } ZERO_STRUCT(sock); if (ctdb_tcp_get_address(ctdb, ctdb->nodes[i]->address.address, &sock) != 0) { continue; } switch (sock.sa.sa_family) { case AF_INET: sock.ip.sin_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip); break; case AF_INET6: sock.ip6.sin6_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip6); break; default: DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n", sock.sa.sa_family)); continue; } #ifdef HAVE_SOCK_SIN_LEN sock.ip.sin_len = sock_size; #endif ctcp->listen_fd = socket(sock.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); if (ctcp->listen_fd == -1) { ctdb_set_error(ctdb, "socket failed\n"); continue; } set_close_on_exec(ctcp->listen_fd); setsockopt(ctcp->listen_fd,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one)); if (bind(ctcp->listen_fd, (struct sockaddr * )&sock, sock_size) == 0) { break; } if (errno == EADDRNOTAVAIL) { DEBUG(DEBUG_DEBUG,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } else { DEBUG(DEBUG_ERR,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } } if (i == ctdb->num_nodes) { DEBUG(DEBUG_CRIT,("Unable to bind to any of the node addresses - giving up\n")); goto failed; } ctdb->address.address = talloc_strdup(ctdb, ctdb->nodes[i]->address.address); ctdb->address.port = ctdb->nodes[i]->address.port; ctdb->name = talloc_asprintf(ctdb, "%s:%u", ctdb->address.address, ctdb->address.port); ctdb->pnn = ctdb->nodes[i]->pnn; DEBUG(DEBUG_INFO,("ctdb chose network address %s:%u pnn %u\n", ctdb->address.address, ctdb->address.port, ctdb->pnn)); if (listen(ctcp->listen_fd, 10) == -1) { goto failed; } fde = event_add_fd(ctdb->ev, ctcp, ctcp->listen_fd, EVENT_FD_READ, ctdb_listen_event, ctdb); tevent_fd_set_auto_close(fde); close(lock_fd); return 0; failed: close(lock_fd); close(ctcp->listen_fd); ctcp->listen_fd = -1; return -1; } 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 Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit, const ContentSecurityPolicy* previous_document_csp) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else { if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); } } if (!policy_to_inherit) policy_to_inherit = previous_document_csp; if (policy_to_inherit && (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); } CWE ID: CWE-20 Target: 1 Example 2: Code: FrameSelection::ComputeVisibleSelectionInFlatTree() const { return selection_editor_->ComputeVisibleSelectionInFlatTree(); } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewImpl::StopFinding(StopFindAction action) { WebView* view = webview(); if (!view) return; WebDocument doc = view->mainFrame()->document(); if (doc.isPluginDocument() && GetWebPluginFromPluginDocument()) { GetWebPluginFromPluginDocument()->stopFind(); return; } bool clear_selection = action == STOP_FIND_ACTION_CLEAR_SELECTION; if (clear_selection) view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect")); WebFrame* frame = view->mainFrame(); while (frame) { frame->stopFinding(clear_selection); frame = frame->traverseNext(false); } if (action == STOP_FIND_ACTION_ACTIVATE_SELECTION) { WebFrame* focused_frame = view->focusedFrame(); if (focused_frame) { WebDocument doc = focused_frame->document(); if (!doc.isNull()) { WebNode node = doc.focusedNode(); if (!node.isNull()) node.simulateClick(); } } } } 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 long vop_ioctl(struct file *f, unsigned int cmd, unsigned long arg) { struct vop_vdev *vdev = f->private_data; struct vop_info *vi = vdev->vi; void __user *argp = (void __user *)arg; int ret; switch (cmd) { case MIC_VIRTIO_ADD_DEVICE: { struct mic_device_desc dd, *dd_config; if (copy_from_user(&dd, argp, sizeof(dd))) return -EFAULT; if (mic_aligned_desc_size(&dd) > MIC_MAX_DESC_BLK_SIZE || dd.num_vq > MIC_MAX_VRINGS) return -EINVAL; dd_config = kzalloc(mic_desc_size(&dd), GFP_KERNEL); if (!dd_config) return -ENOMEM; if (copy_from_user(dd_config, argp, mic_desc_size(&dd))) { ret = -EFAULT; goto free_ret; } mutex_lock(&vdev->vdev_mutex); mutex_lock(&vi->vop_mutex); ret = vop_virtio_add_device(vdev, dd_config); if (ret) goto unlock_ret; list_add_tail(&vdev->list, &vi->vdev_list); unlock_ret: mutex_unlock(&vi->vop_mutex); mutex_unlock(&vdev->vdev_mutex); free_ret: kfree(dd_config); return ret; } case MIC_VIRTIO_COPY_DESC: { struct mic_copy_desc copy; mutex_lock(&vdev->vdev_mutex); ret = vop_vdev_inited(vdev); if (ret) goto _unlock_ret; if (copy_from_user(&copy, argp, sizeof(copy))) { ret = -EFAULT; goto _unlock_ret; } ret = vop_virtio_copy_desc(vdev, &copy); if (ret < 0) goto _unlock_ret; if (copy_to_user( &((struct mic_copy_desc __user *)argp)->out_len, &copy.out_len, sizeof(copy.out_len))) ret = -EFAULT; _unlock_ret: mutex_unlock(&vdev->vdev_mutex); return ret; } case MIC_VIRTIO_CONFIG_CHANGE: { void *buf; mutex_lock(&vdev->vdev_mutex); ret = vop_vdev_inited(vdev); if (ret) goto __unlock_ret; buf = kzalloc(vdev->dd->config_len, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto __unlock_ret; } if (copy_from_user(buf, argp, vdev->dd->config_len)) { ret = -EFAULT; goto done; } ret = vop_virtio_config_change(vdev, buf); done: kfree(buf); __unlock_ret: mutex_unlock(&vdev->vdev_mutex); return ret; } default: return -ENOIOCTLCMD; }; return 0; } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderWidgetHostImpl::ForwardKeyboardEvent( const NativeWebKeyboardEvent& key_event) { ui::LatencyInfo latency_info; if (key_event.GetType() == WebInputEvent::kRawKeyDown || key_event.GetType() == WebInputEvent::kChar) { latency_info.set_source_event_type(ui::SourceEventType::KEY_PRESS); } ForwardKeyboardEventWithLatencyInfo(key_event, latency_info); } 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: ns_nprint(netdissect_options *ndo, register const u_char *cp, register const u_char *bp) { register u_int i, l; register const u_char *rp = NULL; register int compress = 0; int chars_processed; int elt; int data_size = ndo->ndo_snapend - bp; if ((l = labellen(ndo, cp)) == (u_int)-1) return(NULL); if (!ND_TTEST2(*cp, 1)) return(NULL); chars_processed = 1; if (((i = *cp++) & INDIR_MASK) != INDIR_MASK) { compress = 0; rp = cp + l; } if (i != 0) while (i && cp < ndo->ndo_snapend) { if ((i & INDIR_MASK) == INDIR_MASK) { if (!compress) { rp = cp + 1; compress = 1; } if (!ND_TTEST2(*cp, 1)) return(NULL); cp = bp + (((i << 8) | *cp) & 0x3fff); if ((l = labellen(ndo, cp)) == (u_int)-1) return(NULL); if (!ND_TTEST2(*cp, 1)) return(NULL); i = *cp++; chars_processed++; /* * If we've looked at every character in * the message, this pointer will make * us look at some character again, * which means we're looping. */ if (chars_processed >= data_size) { ND_PRINT((ndo, "<LOOP>")); return (NULL); } continue; } if ((i & INDIR_MASK) == EDNS0_MASK) { elt = (i & ~INDIR_MASK); switch(elt) { case EDNS0_ELT_BITLABEL: if (blabel_print(ndo, cp) == NULL) return (NULL); break; default: /* unknown ELT */ ND_PRINT((ndo, "<ELT %d>", elt)); return(NULL); } } else { if (fn_printn(ndo, cp, l, ndo->ndo_snapend)) return(NULL); } cp += l; chars_processed += l; ND_PRINT((ndo, ".")); if ((l = labellen(ndo, cp)) == (u_int)-1) return(NULL); if (!ND_TTEST2(*cp, 1)) return(NULL); i = *cp++; chars_processed++; if (!compress) rp += l + 1; } else ND_PRINT((ndo, ".")); return (rp); } CWE ID: CWE-835 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 l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sock *sk = sock->sk; struct sockaddr_l2 la; int len, err = 0; BT_DBG("sk %p", sk); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&la, 0, sizeof(la)); len = min_t(unsigned int, sizeof(la), alen); memcpy(&la, addr, len); if (la.l2_cid) return -EINVAL; lock_sock(sk); if (sk->sk_type == SOCK_SEQPACKET && !la.l2_psm) { err = -EINVAL; goto done; } switch (l2cap_pi(sk)->mode) { case L2CAP_MODE_BASIC: break; case L2CAP_MODE_ERTM: if (enable_ertm) break; /* fall through */ default: err = -ENOTSUPP; goto done; } switch (sk->sk_state) { case BT_CONNECT: case BT_CONNECT2: case BT_CONFIG: /* Already connecting */ goto wait; case BT_CONNECTED: /* Already connected */ goto done; case BT_OPEN: case BT_BOUND: /* Can connect */ break; default: err = -EBADFD; goto done; } /* Set destination address and psm */ bacpy(&bt_sk(sk)->dst, &la.l2_bdaddr); l2cap_pi(sk)->psm = la.l2_psm; err = l2cap_do_connect(sk); if (err) goto done; wait: err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } CWE ID: CWE-119 Target: 1 Example 2: Code: PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y) { if (!renderer()) return 0; LayoutPoint localPoint; RenderObject* renderer = rendererFromPoint(this, x, y, &localPoint); if (!renderer) return 0; Node* node = renderer->node(); Node* shadowAncestorNode = ancestorInThisScope(node); if (shadowAncestorNode != node) { unsigned offset = shadowAncestorNode->nodeIndex(); ContainerNode* container = shadowAncestorNode->parentNode(); return Range::create(*this, container, offset, container, offset); } PositionWithAffinity positionWithAffinity = renderer->positionForPoint(localPoint); if (positionWithAffinity.position().isNull()) return 0; Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent(); return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition); } 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 reset_terminal(const char *name) { _cleanup_close_ int fd = -1; /* We open the terminal with O_NONBLOCK here, to ensure we * don't block on carrier if this is a terminal with carrier * configured. */ fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return fd; return reset_terminal_fd(fd, true); } CWE ID: CWE-255 Output:
0
Here are some example code snippets. Analyze the following 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 tcp_disconnect(struct sock *sk, int flags) { struct inet_sock *inet = inet_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int err = 0; int old_state = sk->sk_state; if (old_state != TCP_CLOSE) tcp_set_state(sk, TCP_CLOSE); /* ABORT function of RFC793 */ if (old_state == TCP_LISTEN) { inet_csk_listen_stop(sk); } else if (unlikely(tp->repair)) { sk->sk_err = ECONNABORTED; } else if (tcp_need_reset(old_state) || (tp->snd_nxt != tp->write_seq && (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) { /* The last check adjusts for discrepancy of Linux wrt. RFC * states */ tcp_send_active_reset(sk, gfp_any()); sk->sk_err = ECONNRESET; } else if (old_state == TCP_SYN_SENT) sk->sk_err = ECONNRESET; tcp_clear_xmit_timers(sk); __skb_queue_purge(&sk->sk_receive_queue); tcp_write_queue_purge(sk); tcp_fastopen_active_disable_ofo_check(sk); skb_rbtree_purge(&tp->out_of_order_queue); inet->inet_dport = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); sk->sk_shutdown = 0; sock_reset_flag(sk, SOCK_DONE); tp->srtt_us = 0; tp->write_seq += tp->max_window + 2; if (tp->write_seq == 0) tp->write_seq = 1; icsk->icsk_backoff = 0; tp->snd_cwnd = 2; icsk->icsk_probes_out = 0; tp->packets_out = 0; tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; tp->snd_cwnd_cnt = 0; tp->window_clamp = 0; tcp_set_ca_state(sk, TCP_CA_Open); tcp_clear_retrans(tp); inet_csk_delack_init(sk); tcp_init_send_head(sk); memset(&tp->rx_opt, 0, sizeof(tp->rx_opt)); __sk_dst_reset(sk); tcp_saved_syn_free(tp); /* Clean up fastopen related fields */ tcp_free_fastopen_req(tp); inet->defer_connect = 0; WARN_ON(inet->inet_num && !icsk->icsk_bind_hash); sk->sk_error_report(sk); return err; } CWE ID: CWE-369 Target: 1 Example 2: Code: static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx) { struct stream_interface *si = appctx->owner; struct dns_resolvers *resolvers; struct dns_nameserver *ns; chunk_reset(&trash); switch (appctx->st2) { case STAT_ST_INIT: appctx->st2 = STAT_ST_LIST; /* let's start producing data */ /* fall through */ case STAT_ST_LIST: if (LIST_ISEMPTY(&dns_resolvers)) { chunk_appendf(&trash, "No resolvers found\n"); } else { list_for_each_entry(resolvers, &dns_resolvers, list) { if (appctx->ctx.cli.p0 != NULL && appctx->ctx.cli.p0 != resolvers) continue; chunk_appendf(&trash, "Resolvers section %s\n", resolvers->id); list_for_each_entry(ns, &resolvers->nameservers, list) { chunk_appendf(&trash, " nameserver %s:\n", ns->id); chunk_appendf(&trash, " sent: %lld\n", ns->counters.sent); chunk_appendf(&trash, " snd_error: %lld\n", ns->counters.snd_error); chunk_appendf(&trash, " valid: %lld\n", ns->counters.valid); chunk_appendf(&trash, " update: %lld\n", ns->counters.update); chunk_appendf(&trash, " cname: %lld\n", ns->counters.cname); chunk_appendf(&trash, " cname_error: %lld\n", ns->counters.cname_error); chunk_appendf(&trash, " any_err: %lld\n", ns->counters.any_err); chunk_appendf(&trash, " nx: %lld\n", ns->counters.nx); chunk_appendf(&trash, " timeout: %lld\n", ns->counters.timeout); chunk_appendf(&trash, " refused: %lld\n", ns->counters.refused); chunk_appendf(&trash, " other: %lld\n", ns->counters.other); chunk_appendf(&trash, " invalid: %lld\n", ns->counters.invalid); chunk_appendf(&trash, " too_big: %lld\n", ns->counters.too_big); chunk_appendf(&trash, " truncated: %lld\n", ns->counters.truncated); chunk_appendf(&trash, " outdated: %lld\n", ns->counters.outdated); } chunk_appendf(&trash, "\n"); } } /* display response */ if (ci_putchk(si_ic(si), &trash) == -1) { /* let's try again later from this session. We add ourselves into * this session's users so that it can remove us upon termination. */ si_rx_room_blk(si); return 0; } /* fall through */ default: appctx->st2 = STAT_ST_FIN; return 1; } } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: formChooseOptionByMenu(struct form_item_list *fi, int x, int y) { int i, n, selected = -1, init_select = fi->selected; FormSelectOptionItem *opt; char **label; for (n = 0, opt = fi->select_option; opt != NULL; n++, opt = opt->next) ; label = New_N(char *, n + 1); for (i = 0, opt = fi->select_option; opt != NULL; i++, opt = opt->next) label[i] = opt->label->ptr; label[n] = NULL; optionMenu(x, y, label, &selected, init_select, NULL); if (selected < 0) return 0; for (i = 0, opt = fi->select_option; opt != NULL; i++, opt = opt->next) { if (i == selected) { fi->selected = selected; fi->value = opt->value; fi->label = opt->label; break; } } updateSelectOption(fi, fi->select_option); return 1; } 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 UINT drdynvc_process_create_request(drdynvcPlugin* drdynvc, int Sp, int cbChId, wStream* s) { size_t pos; UINT status; UINT32 ChannelId; wStream* data_out; UINT channel_status; if (!drdynvc) return CHANNEL_RC_BAD_CHANNEL_HANDLE; if (drdynvc->state == DRDYNVC_STATE_CAPABILITIES) { /** * For some reason the server does not always send the * capabilities pdu as it should. When this happens, * send a capabilities response. */ drdynvc->version = 3; if ((status = drdynvc_send_capability_response(drdynvc))) { WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_send_capability_response failed!"); return status; } drdynvc->state = DRDYNVC_STATE_READY; } ChannelId = drdynvc_read_variable_uint(s, cbChId); pos = Stream_GetPosition(s); WLog_Print(drdynvc->log, WLOG_DEBUG, "process_create_request: ChannelId=%"PRIu32" ChannelName=%s", ChannelId, Stream_Pointer(s)); channel_status = dvcman_create_channel(drdynvc, drdynvc->channel_mgr, ChannelId, (char*) Stream_Pointer(s)); data_out = Stream_New(NULL, pos + 4); if (!data_out) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } Stream_Write_UINT8(data_out, 0x10 | cbChId); Stream_SetPosition(s, 1); Stream_Copy(s, data_out, pos - 1); if (channel_status == CHANNEL_RC_OK) { WLog_Print(drdynvc->log, WLOG_DEBUG, "channel created"); Stream_Write_UINT32(data_out, 0); } else { WLog_Print(drdynvc->log, WLOG_DEBUG, "no listener"); Stream_Write_UINT32(data_out, (UINT32)0xC0000001); /* same code used by mstsc */ } status = drdynvc_send(drdynvc, data_out); if (status != CHANNEL_RC_OK) { WLog_Print(drdynvc->log, WLOG_ERROR, "VirtualChannelWriteEx failed with %s [%08"PRIX32"]", WTSErrorToString(status), status); return status; } if (channel_status == CHANNEL_RC_OK) { if ((status = dvcman_open_channel(drdynvc, drdynvc->channel_mgr, ChannelId))) { WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_open_channel failed with error %"PRIu32"!", status); return status; } } else { if ((status = dvcman_close_channel(drdynvc->channel_mgr, ChannelId))) WLog_Print(drdynvc->log, WLOG_ERROR, "dvcman_close_channel failed with error %"PRIu32"!", status); } return status; } CWE ID: Target: 1 Example 2: Code: static int ftrace_process_locs(struct module *mod, unsigned long *start, unsigned long *end) { struct ftrace_page *start_pg; struct ftrace_page *pg; struct dyn_ftrace *rec; unsigned long count; unsigned long *p; unsigned long addr; unsigned long flags = 0; /* Shut up gcc */ int ret = -ENOMEM; count = end - start; if (!count) return 0; sort(start, count, sizeof(*start), ftrace_cmp_ips, ftrace_swap_ips); start_pg = ftrace_allocate_pages(count); if (!start_pg) return -ENOMEM; mutex_lock(&ftrace_lock); /* * Core and each module needs their own pages, as * modules will free them when they are removed. * Force a new page to be allocated for modules. */ if (!mod) { WARN_ON(ftrace_pages || ftrace_pages_start); /* First initialization */ ftrace_pages = ftrace_pages_start = start_pg; } else { if (!ftrace_pages) goto out; if (WARN_ON(ftrace_pages->next)) { /* Hmm, we have free pages? */ while (ftrace_pages->next) ftrace_pages = ftrace_pages->next; } ftrace_pages->next = start_pg; } p = start; pg = start_pg; while (p < end) { addr = ftrace_call_adjust(*p++); /* * Some architecture linkers will pad between * the different mcount_loc sections of different * object files to satisfy alignments. * Skip any NULL pointers. */ if (!addr) continue; if (pg->index == pg->size) { /* We should have allocated enough */ if (WARN_ON(!pg->next)) break; pg = pg->next; } rec = &pg->records[pg->index++]; rec->ip = addr; } /* We should have used all pages */ WARN_ON(pg->next); /* Assign the last page to ftrace_pages */ ftrace_pages = pg; /* These new locations need to be initialized */ ftrace_new_pgs = start_pg; /* * We only need to disable interrupts on start up * because we are modifying code that an interrupt * may execute, and the modification is not atomic. * But for modules, nothing runs the code we modify * until we are finished with it, and there's no * reason to cause large interrupt latencies while we do it. */ if (!mod) local_irq_save(flags); ftrace_update_code(mod); if (!mod) local_irq_restore(flags); ret = 0; out: mutex_unlock(&ftrace_lock); return ret; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned cmd, struct dwc3_gadget_ep_cmd_params *params) { const struct usb_endpoint_descriptor *desc = dep->endpoint.desc; struct dwc3 *dwc = dep->dwc; u32 timeout = 1000; u32 reg; int cmd_status = 0; int susphy = false; int ret = -EINVAL; /* * Synopsys Databook 2.60a states, on section 6.3.2.5.[1-8], that if * we're issuing an endpoint command, we must check if * GUSB2PHYCFG.SUSPHY bit is set. If it is, then we need to clear it. * * We will also set SUSPHY bit to what it was before returning as stated * by the same section on Synopsys databook. */ if (dwc->gadget.speed <= USB_SPEED_HIGH) { reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0)); if (unlikely(reg & DWC3_GUSB2PHYCFG_SUSPHY)) { susphy = true; reg &= ~DWC3_GUSB2PHYCFG_SUSPHY; dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg); } } if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_STARTTRANSFER) { int needs_wakeup; needs_wakeup = (dwc->link_state == DWC3_LINK_STATE_U1 || dwc->link_state == DWC3_LINK_STATE_U2 || dwc->link_state == DWC3_LINK_STATE_U3); if (unlikely(needs_wakeup)) { ret = __dwc3_gadget_wakeup(dwc); dev_WARN_ONCE(dwc->dev, ret, "wakeup failed --> %d\n", ret); } } dwc3_writel(dep->regs, DWC3_DEPCMDPAR0, params->param0); dwc3_writel(dep->regs, DWC3_DEPCMDPAR1, params->param1); dwc3_writel(dep->regs, DWC3_DEPCMDPAR2, params->param2); /* * Synopsys Databook 2.60a states in section 6.3.2.5.6 of that if we're * not relying on XferNotReady, we can make use of a special "No * Response Update Transfer" command where we should clear both CmdAct * and CmdIOC bits. * * With this, we don't need to wait for command completion and can * straight away issue further commands to the endpoint. * * NOTICE: We're making an assumption that control endpoints will never * make use of Update Transfer command. This is a safe assumption * because we can never have more than one request at a time with * Control Endpoints. If anybody changes that assumption, this chunk * needs to be updated accordingly. */ if (DWC3_DEPCMD_CMD(cmd) == DWC3_DEPCMD_UPDATETRANSFER && !usb_endpoint_xfer_isoc(desc)) cmd &= ~(DWC3_DEPCMD_CMDIOC | DWC3_DEPCMD_CMDACT); else cmd |= DWC3_DEPCMD_CMDACT; dwc3_writel(dep->regs, DWC3_DEPCMD, cmd); do { reg = dwc3_readl(dep->regs, DWC3_DEPCMD); if (!(reg & DWC3_DEPCMD_CMDACT)) { cmd_status = DWC3_DEPCMD_STATUS(reg); switch (cmd_status) { case 0: ret = 0; break; case DEPEVT_TRANSFER_NO_RESOURCE: ret = -EINVAL; break; case DEPEVT_TRANSFER_BUS_EXPIRY: /* * SW issues START TRANSFER command to * isochronous ep with future frame interval. If * future interval time has already passed when * core receives the command, it will respond * with an error status of 'Bus Expiry'. * * Instead of always returning -EINVAL, let's * give a hint to the gadget driver that this is * the case by returning -EAGAIN. */ ret = -EAGAIN; break; default: dev_WARN(dwc->dev, "UNKNOWN cmd status\n"); } break; } } while (--timeout); if (timeout == 0) { ret = -ETIMEDOUT; cmd_status = -ETIMEDOUT; } trace_dwc3_gadget_ep_cmd(dep, cmd, params, cmd_status); if (ret == 0) { switch (DWC3_DEPCMD_CMD(cmd)) { case DWC3_DEPCMD_STARTTRANSFER: dep->flags |= DWC3_EP_TRANSFER_STARTED; break; case DWC3_DEPCMD_ENDTRANSFER: dep->flags &= ~DWC3_EP_TRANSFER_STARTED; break; default: /* nothing */ break; } } if (unlikely(susphy)) { reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0)); reg |= DWC3_GUSB2PHYCFG_SUSPHY; dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg); } return ret; } CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RunFwdTxfm(int16_t *in, int16_t *out, int stride) { fwd_txfm_(in, out, stride, tx_type_); } CWE ID: CWE-119 Target: 1 Example 2: Code: void Browser::OpenCurrentURL() { UserMetrics::RecordAction(UserMetricsAction("LoadURL"), profile_); LocationBar* location_bar = window_->GetLocationBar(); WindowOpenDisposition open_disposition = location_bar->GetWindowOpenDisposition(); if (OpenInstant(open_disposition)) return; GURL url(WideToUTF8(location_bar->GetInputString())); browser::NavigateParams params(this, url, location_bar->GetPageTransition()); params.disposition = open_disposition; params.tabstrip_add_types = TabStripModel::ADD_FORCE_INDEX | TabStripModel::ADD_INHERIT_OPENER; browser::Navigate(&params); if (profile_->GetExtensionService()->IsInstalledApp(url)) { UMA_HISTOGRAM_ENUMERATION(extension_misc::kAppLaunchHistogram, extension_misc::APP_LAUNCH_OMNIBOX_LOCATION, extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); } } 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: MockCachingHostResolver* GetMockHostResolver() { return &host_resolver_; } CWE ID: CWE-19 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; } ; } /* header_put_le_8byte */ CWE ID: CWE-119 Target: 1 Example 2: Code: int64_t ATSParser::Program::convertPTSToTimestamp(uint64_t PTS) { PTS = recoverPTS(PTS); if (!(mParser->mFlags & TS_TIMESTAMPS_ARE_ABSOLUTE)) { if (!mFirstPTSValid) { mFirstPTSValid = true; mFirstPTS = PTS; PTS = 0; } else if (PTS < mFirstPTS) { PTS = 0; } else { PTS -= mFirstPTS; } } int64_t timeUs = (PTS * 100) / 9; if (mParser->mAbsoluteTimeAnchorUs >= 0ll) { timeUs += mParser->mAbsoluteTimeAnchorUs; } if (mParser->mTimeOffsetValid) { timeUs += mParser->mTimeOffsetUs; } return timeUs; } 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: ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr, const char **elem_rtrn, const char **field_rtrn, ExprDef **index_rtrn) { switch (expr->expr.op) { case EXPR_IDENT: *elem_rtrn = NULL; *field_rtrn = xkb_atom_text(ctx, expr->ident.ident); *index_rtrn = NULL; return true; case EXPR_FIELD_REF: *elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->field_ref.field); *index_rtrn = NULL; return true; case EXPR_ARRAY_REF: *elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element); *field_rtrn = xkb_atom_text(ctx, expr->array_ref.field); *index_rtrn = expr->array_ref.entry; return true; default: break; } log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op); return false; } 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: static struct rmap_item *scan_get_next_rmap_item(struct page **page) { struct mm_struct *mm; struct mm_slot *slot; struct vm_area_struct *vma; struct rmap_item *rmap_item; if (list_empty(&ksm_mm_head.mm_list)) return NULL; slot = ksm_scan.mm_slot; if (slot == &ksm_mm_head) { /* * A number of pages can hang around indefinitely on per-cpu * pagevecs, raised page count preventing write_protect_page * from merging them. Though it doesn't really matter much, * it is puzzling to see some stuck in pages_volatile until * other activity jostles them out, and they also prevented * LTP's KSM test from succeeding deterministically; so drain * them here (here rather than on entry to ksm_do_scan(), * so we don't IPI too often when pages_to_scan is set low). */ lru_add_drain_all(); root_unstable_tree = RB_ROOT; spin_lock(&ksm_mmlist_lock); slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list); ksm_scan.mm_slot = slot; spin_unlock(&ksm_mmlist_lock); next_mm: ksm_scan.address = 0; ksm_scan.rmap_list = &slot->rmap_list; } mm = slot->mm; down_read(&mm->mmap_sem); if (ksm_test_exit(mm)) vma = NULL; else vma = find_vma(mm, ksm_scan.address); for (; vma; vma = vma->vm_next) { if (!(vma->vm_flags & VM_MERGEABLE)) continue; if (ksm_scan.address < vma->vm_start) ksm_scan.address = vma->vm_start; if (!vma->anon_vma) ksm_scan.address = vma->vm_end; while (ksm_scan.address < vma->vm_end) { if (ksm_test_exit(mm)) break; *page = follow_page(vma, ksm_scan.address, FOLL_GET); if (IS_ERR_OR_NULL(*page)) { ksm_scan.address += PAGE_SIZE; cond_resched(); continue; } if (PageAnon(*page) || page_trans_compound_anon(*page)) { flush_anon_page(vma, *page, ksm_scan.address); flush_dcache_page(*page); rmap_item = get_next_rmap_item(slot, ksm_scan.rmap_list, ksm_scan.address); if (rmap_item) { ksm_scan.rmap_list = &rmap_item->rmap_list; ksm_scan.address += PAGE_SIZE; } else put_page(*page); up_read(&mm->mmap_sem); return rmap_item; } put_page(*page); ksm_scan.address += PAGE_SIZE; cond_resched(); } } if (ksm_test_exit(mm)) { ksm_scan.address = 0; ksm_scan.rmap_list = &slot->rmap_list; } /* * Nuke all the rmap_items that are above this current rmap: * because there were no VM_MERGEABLE vmas with such addresses. */ remove_trailing_rmap_items(slot, ksm_scan.rmap_list); spin_lock(&ksm_mmlist_lock); ksm_scan.mm_slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list); if (ksm_scan.address == 0) { /* * We've completed a full scan of all vmas, holding mmap_sem * throughout, and found no VM_MERGEABLE: so do the same as * __ksm_exit does to remove this mm from all our lists now. * This applies either when cleaning up after __ksm_exit * (but beware: we can reach here even before __ksm_exit), * or when all VM_MERGEABLE areas have been unmapped (and * mmap_sem then protects against race with MADV_MERGEABLE). */ hlist_del(&slot->link); list_del(&slot->mm_list); spin_unlock(&ksm_mmlist_lock); free_mm_slot(slot); clear_bit(MMF_VM_MERGEABLE, &mm->flags); up_read(&mm->mmap_sem); mmdrop(mm); } else { spin_unlock(&ksm_mmlist_lock); up_read(&mm->mmap_sem); } /* Repeat until we've completed scanning the whole list */ slot = ksm_scan.mm_slot; if (slot != &ksm_mm_head) goto next_mm; ksm_scan.seqnr++; return NULL; } CWE ID: CWE-362 Target: 1 Example 2: Code: PlainTextRange getSelectionOffsets(LocalFrame* frame) { EphemeralRange range = firstEphemeralRangeOf( frame->selection().computeVisibleSelectionInDOMTreeDeprecated()); if (range.isNull()) return PlainTextRange(); ContainerNode* const editable = rootEditableElementOrTreeScopeRootNodeOf( frame->selection().computeVisibleSelectionInDOMTreeDeprecated()); DCHECK(editable); return PlainTextRange::create(*editable, range); } 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: lib_file_open(gs_file_path_ptr lib_path, const gs_memory_t *mem, i_ctx_t *i_ctx_p, const char *fname, uint flen, char *buffer, int blen, uint *pclen, ref *pfile) { /* i_ctx_p is NULL running arg (@) files. * lib_path and mem are never NULL */ bool starting_arg_file = (i_ctx_p == NULL) ? true : i_ctx_p->starting_arg_file; bool search_with_no_combine = false; bool search_with_combine = false; char fmode[2] = { 'r', 0}; gx_io_device *iodev = iodev_default(mem); gs_main_instance *minst = get_minst_from_memory(mem); int code; /* when starting arg files (@ files) iodev_default is not yet set */ if (iodev == 0) iodev = (gx_io_device *)gx_io_device_table[0]; search_with_combine = false; } else { search_with_no_combine = starting_arg_file; search_with_combine = true; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; * Begin Time Functions * ***********************/ static int date_from_ISO8601 (const char *text, time_t * value) { struct tm tm; int n; int i; char buf[18]; if (strchr (text, '-')) { char *p = (char *) text, *p2 = buf; } if (*p != '-') { *p2 = *p; p2++; } p++; } } CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderViewImpl::OnUpdateWindowScreenRect(gfx::Rect window_screen_rect) { RenderWidget::OnUpdateWindowScreenRect(window_screen_rect); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int unix_stream_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock_iocb *siocb = kiocb_to_siocb(iocb); struct scm_cookie tmp_scm; struct sock *sk = sock->sk; struct unix_sock *u = unix_sk(sk); struct sockaddr_un *sunaddr = msg->msg_name; int copied = 0; int check_creds = 0; int target; int err = 0; long timeo; int skip; err = -EINVAL; if (sk->sk_state != TCP_ESTABLISHED) goto out; err = -EOPNOTSUPP; if (flags&MSG_OOB) goto out; target = sock_rcvlowat(sk, flags&MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT); msg->msg_namelen = 0; /* Lock the socket to prevent queue disordering * while sleeps in memcpy_tomsg */ if (!siocb->scm) { siocb->scm = &tmp_scm; memset(&tmp_scm, 0, sizeof(tmp_scm)); } err = mutex_lock_interruptible(&u->readlock); if (err) { err = sock_intr_errno(timeo); goto out; } do { int chunk; struct sk_buff *skb, *last; unix_state_lock(sk); last = skb = skb_peek(&sk->sk_receive_queue); again: if (skb == NULL) { unix_sk(sk)->recursion_level = 0; if (copied >= target) goto unlock; /* * POSIX 1003.1g mandates this order. */ err = sock_error(sk); if (err) goto unlock; if (sk->sk_shutdown & RCV_SHUTDOWN) goto unlock; unix_state_unlock(sk); err = -EAGAIN; if (!timeo) break; mutex_unlock(&u->readlock); timeo = unix_stream_data_wait(sk, timeo, last); if (signal_pending(current) || mutex_lock_interruptible(&u->readlock)) { err = sock_intr_errno(timeo); goto out; } continue; unlock: unix_state_unlock(sk); break; } skip = sk_peek_offset(sk, flags); while (skip >= unix_skb_len(skb)) { skip -= unix_skb_len(skb); last = skb; skb = skb_peek_next(skb, &sk->sk_receive_queue); if (!skb) goto again; } unix_state_unlock(sk); if (check_creds) { /* Never glue messages from different writers */ if ((UNIXCB(skb).pid != siocb->scm->pid) || !uid_eq(UNIXCB(skb).uid, siocb->scm->creds.uid) || !gid_eq(UNIXCB(skb).gid, siocb->scm->creds.gid)) break; } else if (test_bit(SOCK_PASSCRED, &sock->flags)) { /* Copy credentials */ scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid); check_creds = 1; } /* Copy address just once */ if (sunaddr) { unix_copy_addr(msg, skb->sk); sunaddr = NULL; } chunk = min_t(unsigned int, unix_skb_len(skb) - skip, size); if (skb_copy_datagram_iovec(skb, UNIXCB(skb).consumed + skip, msg->msg_iov, chunk)) { if (copied == 0) copied = -EFAULT; break; } copied += chunk; size -= chunk; /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { UNIXCB(skb).consumed += chunk; sk_peek_offset_bwd(sk, chunk); if (UNIXCB(skb).fp) unix_detach_fds(siocb->scm, skb); if (unix_skb_len(skb)) break; skb_unlink(skb, &sk->sk_receive_queue); consume_skb(skb); if (siocb->scm->fp) break; } else { /* It is questionable, see note in unix_dgram_recvmsg. */ if (UNIXCB(skb).fp) siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp); sk_peek_offset_fwd(sk, chunk); break; } } while (size); mutex_unlock(&u->readlock); scm_recv(sock, msg, siocb->scm, flags); out: return copied ? : err; } CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd, struct epoll_event __user *, event) { int error; int did_lock_epmutex = 0; struct file *file, *tfile; struct eventpoll *ep; struct epitem *epi; struct epoll_event epds; error = -EFAULT; if (ep_op_has_event(op) && copy_from_user(&epds, event, sizeof(struct epoll_event))) goto error_return; /* Get the "struct file *" for the eventpoll file */ error = -EBADF; file = fget(epfd); if (!file) goto error_return; /* Get the "struct file *" for the target file */ tfile = fget(fd); if (!tfile) goto error_fput; /* The target file descriptor must support poll */ error = -EPERM; if (!tfile->f_op || !tfile->f_op->poll) goto error_tgt_fput; /* * We have to check that the file structure underneath the file descriptor * the user passed to us _is_ an eventpoll file. And also we do not permit * adding an epoll file descriptor inside itself. */ error = -EINVAL; if (file == tfile || !is_file_epoll(file)) goto error_tgt_fput; /* * At this point it is safe to assume that the "private_data" contains * our own data structure. */ ep = file->private_data; /* * When we insert an epoll file descriptor, inside another epoll file * descriptor, there is the change of creating closed loops, which are * better be handled here, than in more critical paths. While we are * checking for loops we also determine the list of files reachable * and hang them on the tfile_check_list, so we can check that we * haven't created too many possible wakeup paths. * * We need to hold the epmutex across both ep_insert and ep_remove * b/c we want to make sure we are looking at a coherent view of * epoll network. */ if (op == EPOLL_CTL_ADD || op == EPOLL_CTL_DEL) { mutex_lock(&epmutex); did_lock_epmutex = 1; } if (op == EPOLL_CTL_ADD) { if (is_file_epoll(tfile)) { error = -ELOOP; if (ep_loop_check(ep, tfile) != 0) goto error_tgt_fput; } else list_add(&tfile->f_tfile_llink, &tfile_check_list); } mutex_lock_nested(&ep->mtx, 0); /* * Try to lookup the file inside our RB tree, Since we grabbed "mtx" * above, we can be sure to be able to use the item looked up by * ep_find() till we release the mutex. */ epi = ep_find(ep, tfile, fd); error = -EINVAL; switch (op) { case EPOLL_CTL_ADD: if (!epi) { epds.events |= POLLERR | POLLHUP; error = ep_insert(ep, &epds, tfile, fd); } else error = -EEXIST; clear_tfile_check_list(); break; case EPOLL_CTL_DEL: if (epi) error = ep_remove(ep, epi); else error = -ENOENT; break; case EPOLL_CTL_MOD: if (epi) { epds.events |= POLLERR | POLLHUP; error = ep_modify(ep, epi, &epds); } else error = -ENOENT; break; } mutex_unlock(&ep->mtx); error_tgt_fput: if (did_lock_epmutex) mutex_unlock(&epmutex); fput(tfile); error_fput: fput(file); error_return: return error; } CWE ID: Target: 1 Example 2: Code: struct net_device *dev_get_by_name(struct net *net, const char *name) { struct net_device *dev; rcu_read_lock(); dev = dev_get_by_name_rcu(net, name); if (dev) dev_hold(dev); rcu_read_unlock(); return dev; } 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 ImageResource::IsAccessAllowed( const SecurityOrigin* security_origin, ImageResourceInfo::DoesCurrentFrameHaveSingleSecurityOrigin does_current_frame_has_single_security_origin) const { if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque) return false; if (does_current_frame_has_single_security_origin != ImageResourceInfo::kHasSingleSecurityOrigin) return false; if (IsSameOriginOrCORSSuccessful()) return true; return !security_origin->TaintsCanvas(GetResponse().Url()); } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int recv_msg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t buf_len, int flags) { struct sock *sk = sock->sk; struct tipc_port *tport = tipc_sk_port(sk); struct sk_buff *buf; struct tipc_msg *msg; long timeout; unsigned int sz; u32 err; int res; /* Catch invalid receive requests */ if (unlikely(!buf_len)) return -EINVAL; lock_sock(sk); if (unlikely(sock->state == SS_UNCONNECTED)) { res = -ENOTCONN; goto exit; } timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); restart: /* Look for a message in receive queue; wait if necessary */ while (skb_queue_empty(&sk->sk_receive_queue)) { if (sock->state == SS_DISCONNECTING) { res = -ENOTCONN; goto exit; } if (timeout <= 0L) { res = timeout ? timeout : -EWOULDBLOCK; goto exit; } release_sock(sk); timeout = wait_event_interruptible_timeout(*sk_sleep(sk), tipc_rx_ready(sock), timeout); lock_sock(sk); } /* Look at first message in receive queue */ buf = skb_peek(&sk->sk_receive_queue); msg = buf_msg(buf); sz = msg_data_sz(msg); err = msg_errcode(msg); /* Discard an empty non-errored message & try again */ if ((!sz) && (!err)) { advance_rx_queue(sk); goto restart; } /* Capture sender's address (optional) */ set_orig_addr(m, msg); /* Capture ancillary data (optional) */ res = anc_data_recv(m, msg, tport); if (res) goto exit; /* Capture message data (if valid) & compute return value (always) */ if (!err) { if (unlikely(buf_len < sz)) { sz = buf_len; m->msg_flags |= MSG_TRUNC; } res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg), m->msg_iov, sz); if (res) goto exit; res = sz; } else { if ((sock->state == SS_READY) || ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)) res = 0; else res = -ECONNRESET; } /* Consume received message (optional) */ if (likely(!(flags & MSG_PEEK))) { if ((sock->state != SS_READY) && (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN)) tipc_acknowledge(tport->ref, tport->conn_unacked); advance_rx_queue(sk); } exit: release_sock(sk); return res; } CWE ID: CWE-200 Target: 1 Example 2: Code: std::string NameForChoice(const Experiment& e, int index) { DCHECK_EQ(Experiment::MULTI_VALUE, e.type); DCHECK_LT(index, e.num_choices); return std::string(e.internal_name) + about_flags::testing::kMultiSeparator + base::IntToString(index); } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DownloadRequestLimiter::SetOnCanDownloadDecidedCallbackForTesting( Callback callback) { on_can_download_decided_callback_ = callback; } 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 HTMLMediaElement::isAutoplayAllowedPerSettings() const { LocalFrame* frame = document().frame(); if (!frame) return false; FrameLoaderClient* frameLoaderClient = frame->loader().client(); return frameLoaderClient && frameLoaderClient->allowAutoplay(false); } CWE ID: CWE-119 Target: 1 Example 2: Code: read_compressed_image(Gif_Image *gfi, Gif_Reader *grr, int read_flags) { if (grr->is_record) { const uint32_t image_pos = grr->pos; /* scan over image */ ++grr->pos; /* skip min code size */ while (grr->pos < grr->length) { int amt = grr->v[grr->pos]; grr->pos += amt + 1; if (amt == 0) break; } if (grr->pos > grr->length) grr->pos = grr->length; gfi->compressed_len = grr->pos - image_pos; gfi->compressed_errors = 0; if (read_flags & GIF_READ_CONST_RECORD) { gfi->compressed = (uint8_t*) &grr->v[image_pos]; gfi->free_compressed = 0; } else { gfi->compressed = Gif_NewArray(uint8_t, gfi->compressed_len); gfi->free_compressed = Gif_Free; if (!gfi->compressed) return 0; memcpy(gfi->compressed, &grr->v[image_pos], gfi->compressed_len); } } else { /* non-record; have to read it block by block. */ uint32_t comp_cap = 1024; uint32_t comp_len; uint8_t *comp = Gif_NewArray(uint8_t, comp_cap); int i; if (!comp) return 0; /* min code size */ i = gifgetbyte(grr); comp[0] = i; comp_len = 1; i = gifgetbyte(grr); while (i > 0) { /* add 2 before check so we don't have to check after loop when appending 0 block */ if (comp_len + i + 2 > comp_cap) { comp_cap *= 2; Gif_ReArray(comp, uint8_t, comp_cap); if (!comp) return 0; } comp[comp_len] = i; gifgetblock(comp + comp_len + 1, i, grr); comp_len += i + 1; i = gifgetbyte(grr); } comp[comp_len++] = 0; gfi->compressed_len = comp_len; gfi->compressed_errors = 0; gfi->compressed = comp; gfi->free_compressed = Gif_Free; } return 1; } CWE ID: CWE-415 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static boolean str_match_nocase_whole( const char **pcur, const char *str ) { const char *cur = *pcur; if (str_match_no_case(&cur, str) && !is_digit_alpha_underscore(cur)) { *pcur = cur; return TRUE; } return FALSE; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in *usin = (struct sockaddr_in *)uaddr; struct inet_sock *inet = inet_sk(sk); struct tcp_sock *tp = tcp_sk(sk); __be16 orig_sport, orig_dport; __be32 daddr, nexthop; struct flowi4 fl4; struct rtable *rt; int err; if (addr_len < sizeof(struct sockaddr_in)) return -EINVAL; if (usin->sin_family != AF_INET) return -EAFNOSUPPORT; nexthop = daddr = usin->sin_addr.s_addr; if (inet->opt && inet->opt->srr) { if (!daddr) return -EINVAL; nexthop = inet->opt->faddr; } orig_sport = inet->inet_sport; orig_dport = usin->sin_port; rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if, IPPROTO_TCP, orig_sport, orig_dport, sk, true); if (IS_ERR(rt)) { err = PTR_ERR(rt); if (err == -ENETUNREACH) IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); return err; } if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) { ip_rt_put(rt); return -ENETUNREACH; } if (!inet->opt || !inet->opt->srr) daddr = rt->rt_dst; if (!inet->inet_saddr) inet->inet_saddr = rt->rt_src; inet->inet_rcv_saddr = inet->inet_saddr; if (tp->rx_opt.ts_recent_stamp && inet->inet_daddr != daddr) { /* Reset inherited state */ tp->rx_opt.ts_recent = 0; tp->rx_opt.ts_recent_stamp = 0; tp->write_seq = 0; } if (tcp_death_row.sysctl_tw_recycle && !tp->rx_opt.ts_recent_stamp && rt->rt_dst == daddr) { struct inet_peer *peer = rt_get_peer(rt); /* * VJ's idea. We save last timestamp seen from * the destination in peer table, when entering state * TIME-WAIT * and initialize rx_opt.ts_recent from it, * when trying new connection. */ if (peer) { inet_peer_refcheck(peer); if ((u32)get_seconds() - peer->tcp_ts_stamp <= TCP_PAWS_MSL) { tp->rx_opt.ts_recent_stamp = peer->tcp_ts_stamp; tp->rx_opt.ts_recent = peer->tcp_ts; } } } inet->inet_dport = usin->sin_port; inet->inet_daddr = daddr; inet_csk(sk)->icsk_ext_hdr_len = 0; if (inet->opt) inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen; tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT; /* Socket identity is still unknown (sport may be zero). * However we set state to SYN-SENT and not releasing socket * lock select source port, enter ourselves into the hash tables and * complete initialization after this. */ tcp_set_state(sk, TCP_SYN_SENT); err = inet_hash_connect(&tcp_death_row, sk); if (err) goto failure; rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport, inet->inet_sport, inet->inet_dport, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto failure; } /* OK, now commit destination to socket. */ sk->sk_gso_type = SKB_GSO_TCPV4; sk_setup_caps(sk, &rt->dst); if (!tp->write_seq) tp->write_seq = secure_tcp_sequence_number(inet->inet_saddr, inet->inet_daddr, inet->inet_sport, usin->sin_port); inet->inet_id = tp->write_seq ^ jiffies; err = tcp_connect(sk); rt = NULL; if (err) goto failure; return 0; failure: /* * This unhashes the socket and releases the local port, * if necessary. */ tcp_set_state(sk, TCP_CLOSE); ip_rt_put(rt); sk->sk_route_caps = 0; inet->inet_dport = 0; return err; } CWE ID: CWE-362 Target: 1 Example 2: Code: bool SharedMemory::Unmap() { if (memory_ == NULL) return false; UnmapViewOfFile(memory_); memory_ = NULL; return true; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: IHEVCD_ERROR_T ihevcd_cabac_init(cab_ctxt_t *ps_cabac, bitstrm_t *ps_bitstrm, WORD32 qp, WORD32 cabac_init_idc, const UWORD8 *pu1_init_ctxt) { /* Sanity checks */ ASSERT(ps_cabac != NULL); ASSERT(ps_bitstrm != NULL); ASSERT((qp >= 0) && (qp < 52)); ASSERT((cabac_init_idc >= 0) && (cabac_init_idc < 3)); UNUSED(qp); UNUSED(cabac_init_idc); /* CABAC engine uses 32 bit range instead of 9 bits as specified by * the spec. This is done to reduce number of renormalizations */ /* cabac engine initialization */ #if FULLRANGE ps_cabac->u4_range = (UWORD32)510 << RANGE_SHIFT; BITS_GET(ps_cabac->u4_ofst, ps_bitstrm->pu4_buf, ps_bitstrm->u4_bit_ofst, ps_bitstrm->u4_cur_word, ps_bitstrm->u4_nxt_word, (9 + RANGE_SHIFT)); #else ps_cabac->u4_range = (UWORD32)510; BITS_GET(ps_cabac->u4_ofst, ps_bitstrm->pu4_buf, ps_bitstrm->u4_bit_ofst, ps_bitstrm->u4_cur_word, ps_bitstrm->u4_nxt_word, 9); #endif /* cabac context initialization based on init idc and slice qp */ memcpy(ps_cabac->au1_ctxt_models, pu1_init_ctxt, IHEVC_CAB_CTXT_END); DEBUG_RANGE_OFST("init", ps_cabac->u4_range, ps_cabac->u4_ofst); return ((IHEVCD_ERROR_T)IHEVCD_SUCCESS); } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) { uint8_t ead, eal, fcs; uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset; uint8_t* p_start = p_data; uint16_t len; if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) { RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len); return (RFC_EVENT_BAD_FRAME); } RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data); if (!ead) { RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)"); return (RFC_EVENT_BAD_FRAME); } RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data); RFCOMM_PARSE_LEN_FIELD(eal, len, p_data); p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */ p_buf->offset += (3 + !ead + !eal); /* handle credit if credit based flow control */ if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) && (p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) { p_frame->credit = *p_data++; p_buf->len--; p_buf->offset++; } else p_frame->credit = 0; if (p_buf->len != len) { RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len); return (RFC_EVENT_BAD_FRAME); } fcs = *(p_data + len); /* All control frames that we are sending are sent with P=1, expect */ /* reply with F=1 */ /* According to TS 07.10 spec ivalid frames are discarded without */ /* notification to the sender */ switch (p_frame->type) { case RFCOMM_SABME: if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad SABME"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_SABME); case RFCOMM_UA: if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad UA"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_UA); case RFCOMM_DM: if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad DM"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_DM); case RFCOMM_DISC: if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad DISC"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_DISC); case RFCOMM_UIH: if (!RFCOMM_VALID_DLCI(p_frame->dlci)) { RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI"); return (RFC_EVENT_BAD_FRAME); } else if (!rfc_check_fcs(2, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad UIH - FCS"); return (RFC_EVENT_BAD_FRAME); } else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) { /* we assume that this is ok to allow bad implementations to work */ RFCOMM_TRACE_ERROR("Bad UIH - response"); return (RFC_EVENT_UIH); } else return (RFC_EVENT_UIH); } return (RFC_EVENT_BAD_FRAME); } CWE ID: CWE-125 Target: 1 Example 2: Code: void GfxColorSpace::getGrayLine(Guchar *in, unsigned char *out, int length) { int i, j, n; GfxColor color; GfxGray gray; n = getNComps(); for (i = 0; i < length; i++) { for (j = 0; j < n; j++) color.c[j] = in[i * n + j] * 256; getGray (&color, &gray); out[i] = colToByte(gray); } } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points) { path->incReserve(numPoints); path->moveTo(WebCoreFloatToSkScalar(points[0].x()), WebCoreFloatToSkScalar(points[0].y())); for (size_t i = 1; i < numPoints; ++i) { path->lineTo(WebCoreFloatToSkScalar(points[i].x()), WebCoreFloatToSkScalar(points[i].y())); } path->setIsConvex(true); } CWE ID: CWE-19 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 RequestSender::OnNetworkFetcherComplete( const GURL& original_url, std::unique_ptr<std::string> response_body, int net_error, const std::string& header_etag, int64_t xheader_retry_after_sec) { DCHECK(thread_checker_.CalledOnValidThread()); VLOG(1) << "request completed from url: " << original_url.spec(); int error = -1; if (response_body && response_code_ == 200) { DCHECK_EQ(0, net_error); error = 0; } else if (response_code_ != -1) { error = response_code_; } else { error = net_error; } int retry_after_sec = -1; if (original_url.SchemeIsCryptographic() && error > 0) retry_after_sec = base::saturated_cast<int>(xheader_retry_after_sec); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&RequestSender::SendInternalComplete, base::Unretained(this), error, response_body ? *response_body : std::string(), header_etag, retry_after_sec)); } CWE ID: CWE-20 Target: 1 Example 2: Code: Status _xvmc_destroy_subpicture( Display *dpy, XvMCSubpicture *subpicture ) { XExtDisplayInfo *info = xvmc_find_display(dpy); xvmcDestroySubpictureReq *req; XvMCCheckExtension (dpy, info, BadImplementation); LockDisplay (dpy); XvMCGetReq (DestroySubpicture, req); req->subpicture_id = subpicture->subpicture_id; UnlockDisplay (dpy); SyncHandle (); return Success; } 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 xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct km_event c; u8 type = XFRM_POLICY_TYPE_MAIN; int err; struct xfrm_audit audit_info; err = copy_from_user_policy_type(&type, attrs); if (err) return err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); security_task_getsecid(current, &audit_info.secid); err = xfrm_policy_flush(net, type, &audit_info); if (err) { if (err == -ESRCH) /* empty table */ return 0; return err; } c.data.type = type; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.net = net; km_policy_notify(NULL, 0, &c); 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 void nfs4_open_release(void *calldata) { struct nfs4_opendata *data = calldata; struct nfs4_state *state = NULL; /* If this request hasn't been cancelled, do nothing */ if (data->cancelled == 0) goto out_free; /* In case of error, no cleanup! */ if (data->rpc_status != 0 || !data->rpc_done) goto out_free; /* In case we need an open_confirm, no cleanup! */ if (data->o_res.rflags & NFS4_OPEN_RESULT_CONFIRM) goto out_free; state = nfs4_opendata_to_nfs4_state(data); if (!IS_ERR(state)) nfs4_close_state(&data->path, state, data->o_arg.open_flags); out_free: nfs4_opendata_put(data); } CWE ID: Target: 1 Example 2: Code: static void webkit_web_view_real_cut_clipboard(WebKitWebView* webView) { Frame* frame = core(webView)->focusController()->focusedOrMainFrame(); frame->editor()->command("Cut").execute(); } 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: gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn, PNG_CONST png_byte bit_depthIn, PNG_CONST int palette_numberIn, PNG_CONST int interlace_typeIn, PNG_CONST double file_gammaIn, PNG_CONST double screen_gammaIn, PNG_CONST png_byte sbitIn, PNG_CONST int threshold_testIn, PNG_CONST char *name, PNG_CONST int use_input_precisionIn, PNG_CONST int scale16In, PNG_CONST int expand16In, PNG_CONST int do_backgroundIn, PNG_CONST png_color_16 *bkgd_colorIn, double bkgd_gammaIn) { gamma_display d; context(&pmIn->this, fault); gamma_display_init(&d, pmIn, FILEID(colour_typeIn, bit_depthIn, palette_numberIn, interlace_typeIn, 0, 0, 0), file_gammaIn, screen_gammaIn, sbitIn, threshold_testIn, use_input_precisionIn, scale16In, expand16In, do_backgroundIn, bkgd_colorIn, bkgd_gammaIn); Try { png_structp pp; png_infop pi; gama_modification gama_mod; srgb_modification srgb_mod; sbit_modification sbit_mod; /* For the moment don't use the png_modifier support here. */ d.pm->encoding_counter = 0; modifier_set_encoding(d.pm); /* Just resets everything */ d.pm->current_gamma = d.file_gamma; /* Make an appropriate modifier to set the PNG file gamma to the * given gamma value and the sBIT chunk to the given precision. */ d.pm->modifications = NULL; gama_modification_init(&gama_mod, d.pm, d.file_gamma); srgb_modification_init(&srgb_mod, d.pm, 127 /*delete*/); if (d.sbit > 0) sbit_modification_init(&sbit_mod, d.pm, d.sbit); modification_reset(d.pm->modifications); /* Get a png_struct for writing the image. */ pp = set_modifier_for_read(d.pm, &pi, d.this.id, name); standard_palette_init(&d.this); /* Introduce the correct read function. */ if (d.pm->this.progressive) { /* Share the row function with the standard implementation. */ png_set_progressive_read_fn(pp, &d, gamma_info, progressive_row, gamma_end); /* Now feed data into the reader until we reach the end: */ modifier_progressive_read(d.pm, pp, pi); } else { /* modifier_read expects a png_modifier* */ png_set_read_fn(pp, d.pm, modifier_read); /* Check the header values: */ png_read_info(pp, pi); /* Process the 'info' requirements. Only one image is generated */ gamma_info_imp(&d, pp, pi); sequential_row(&d.this, pp, pi, -1, 0); if (!d.this.speed) gamma_image_validate(&d, pp, pi); else d.this.ps->validated = 1; } modifier_reset(d.pm); if (d.pm->log && !d.threshold_test && !d.this.speed) fprintf(stderr, "%d bit %s %s: max error %f (%.2g, %2g%%)\n", d.this.bit_depth, colour_types[d.this.colour_type], name, d.maxerrout, d.maxerrabs, 100*d.maxerrpc); /* Log the summary values too. */ if (d.this.colour_type == 0 || d.this.colour_type == 4) { switch (d.this.bit_depth) { case 1: break; case 2: if (d.maxerrout > d.pm->error_gray_2) d.pm->error_gray_2 = d.maxerrout; break; case 4: if (d.maxerrout > d.pm->error_gray_4) d.pm->error_gray_4 = d.maxerrout; break; case 8: if (d.maxerrout > d.pm->error_gray_8) d.pm->error_gray_8 = d.maxerrout; break; case 16: if (d.maxerrout > d.pm->error_gray_16) d.pm->error_gray_16 = d.maxerrout; break; default: png_error(pp, "bad bit depth (internal: 1)"); } } else if (d.this.colour_type == 2 || d.this.colour_type == 6) { switch (d.this.bit_depth) { case 8: if (d.maxerrout > d.pm->error_color_8) d.pm->error_color_8 = d.maxerrout; break; case 16: if (d.maxerrout > d.pm->error_color_16) d.pm->error_color_16 = d.maxerrout; break; default: png_error(pp, "bad bit depth (internal: 2)"); } } else if (d.this.colour_type == 3) { if (d.maxerrout > d.pm->error_indexed) d.pm->error_indexed = d.maxerrout; } } Catch(fault) modifier_reset(voidcast(png_modifier*,(void*)fault)); } CWE ID: Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool GesturePoint::IsInSecondClickTimeWindow() const { double duration = last_touch_time_ - last_tap_time_; return duration < kMaximumSecondsBetweenDoubleClick; } CWE ID: CWE-20 Target: 1 Example 2: Code: static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector bKGD; ucvector_init(&bKGD); if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r / 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_g / 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_g % 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_b / 256)); ucvector_push_back(&bKGD, (unsigned char)(info->background_b % 256)); } else if(info->color.colortype == LCT_PALETTE) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r % 256)); /*palette index*/ } error = addChunk(out, "bKGD", bKGD.data, bKGD.size); ucvector_cleanup(&bKGD); return error; } 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: static __u8 *nci_extract_rf_params_nfca_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfca_poll *nfca_poll, __u8 *data) { nfca_poll->sens_res = __le16_to_cpu(*((__u16 *)data)); data += 2; nfca_poll->nfcid1_len = *data++; pr_debug("sens_res 0x%x, nfcid1_len %d\n", nfca_poll->sens_res, nfca_poll->nfcid1_len); memcpy(nfca_poll->nfcid1, data, nfca_poll->nfcid1_len); data += nfca_poll->nfcid1_len; nfca_poll->sel_res_len = *data++; if (nfca_poll->sel_res_len != 0) nfca_poll->sel_res = *data++; pr_debug("sel_res_len %d, sel_res 0x%x\n", nfca_poll->sel_res_len, nfca_poll->sel_res); return data; } 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: DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : saml2md::DynamicMetadataProvider(e), m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)), m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)), m_encoded(true), m_trust(nullptr) { const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst); if (child && child->hasChildNodes()) { auto_ptr_char s(child->getFirstChild()->getNodeValue()); if (s.get() && *s.get()) { m_subst = s.get(); m_encoded = XMLHelper::getAttrBool(child, true, encoded); m_hashed = XMLHelper::getAttrString(child, nullptr, hashed); } } if (m_subst.empty()) { child = XMLHelper::getFirstChildElement(e, Regex); if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) { m_match = XMLHelper::getAttrString(child, nullptr, match); auto_ptr_char repl(child->getFirstChild()->getNodeValue()); if (repl.get() && *repl.get()) m_regex = repl.get(); } } if (!m_ignoreTransport) { child = XMLHelper::getFirstChildElement(e, _TrustEngine); string t = XMLHelper::getAttrString(child, nullptr, _type); if (!t.empty()) { TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child); if (!dynamic_cast<X509TrustEngine*>(trust)) { delete trust; throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin."); } m_trust.reset(dynamic_cast<X509TrustEngine*>(trust)); m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr)); } if (!m_trust.get() || !m_dummyCR.get()) throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true."); } } CWE ID: CWE-347 Target: 1 Example 2: Code: static gpa_t translate_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access) { return gpa; } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void nl_fib_lookup(struct net *net, struct fib_result_nl *frn) { struct fib_result res; struct flowi4 fl4 = { .flowi4_mark = frn->fl_mark, .daddr = frn->fl_addr, .flowi4_tos = frn->fl_tos, .flowi4_scope = frn->fl_scope, }; struct fib_table *tb; rcu_read_lock(); tb = fib_get_table(net, frn->tb_id_in); frn->err = -ENOENT; if (tb) { local_bh_disable(); frn->tb_id = tb->tb_id; frn->err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF); if (!frn->err) { frn->prefixlen = res.prefixlen; frn->nh_sel = res.nh_sel; frn->type = res.type; frn->scope = res.scope; } local_bh_enable(); } rcu_read_unlock(); } 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 BrowserMainParts::PostDestroyThreads() { if (BrowserProcessMain::GetInstance()->GetProcessModel() == PROCESS_MODEL_SINGLE_PROCESS) { BrowserContext::AssertNoContextsExist(); } device_client_.reset(); display::Screen::SetScreenInstance(nullptr); gpu::oxide_shim::SetGLShareGroup(nullptr); gl_share_context_ = nullptr; #if defined(OS_LINUX) gpu::SetGpuInfoCollectorOxideLinux(nullptr); #endif } CWE ID: CWE-20 Target: 1 Example 2: Code: static int fuse_copy_fill(struct fuse_copy_state *cs) { struct page *page; int err; err = unlock_request(cs->req); if (err) return err; fuse_copy_finish(cs); if (cs->pipebufs) { struct pipe_buffer *buf = cs->pipebufs; if (!cs->write) { err = pipe_buf_confirm(cs->pipe, buf); if (err) return err; BUG_ON(!cs->nr_segs); cs->currbuf = buf; cs->pg = buf->page; cs->offset = buf->offset; cs->len = buf->len; cs->pipebufs++; cs->nr_segs--; } else { if (cs->nr_segs == cs->pipe->buffers) return -EIO; page = alloc_page(GFP_HIGHUSER); if (!page) return -ENOMEM; buf->page = page; buf->offset = 0; buf->len = 0; cs->currbuf = buf; cs->pg = page; cs->offset = 0; cs->len = PAGE_SIZE; cs->pipebufs++; cs->nr_segs++; } } else { size_t off; err = iov_iter_get_pages(cs->iter, &page, PAGE_SIZE, 1, &off); if (err < 0) return err; BUG_ON(!err); cs->len = err; cs->offset = off; cs->pg = page; iov_iter_advance(cs->iter, err); } return lock_request(cs->req); } 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: base::WeakPtr<OTRBrowserContextImpl> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } 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 DownloadController::StartAndroidDownload( const content::ResourceRequestInfo::WebContentsGetter& wc_getter, bool must_download, const DownloadInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); WebContents* web_contents = wc_getter.Run(); if (!web_contents) { LOG(ERROR) << "Download failed on URL:" << info.url.spec(); return; } AcquireFileAccessPermission( web_contents, base::Bind(&DownloadController::StartAndroidDownloadInternal, base::Unretained(this), wc_getter, must_download, info)); } CWE ID: CWE-254 Target: 1 Example 2: Code: char *drm_get_encoder_name(struct drm_encoder *encoder) { static char buf[32]; snprintf(buf, 32, "%s-%d", drm_encoder_enum_list[encoder->encoder_type].name, encoder->base.id); return buf; } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int mp_pack(lua_State *L) { int nargs = lua_gettop(L); int i; mp_buf *buf; if (nargs == 0) return luaL_argerror(L, 0, "MessagePack pack needs input."); buf = mp_buf_new(L); for(i = 1; i <= nargs; i++) { /* Copy argument i to top of stack for _encode processing; * the encode function pops it from the stack when complete. */ lua_pushvalue(L, i); mp_encode_lua_type(L,buf,0); lua_pushlstring(L,(char*)buf->b,buf->len); /* Reuse the buffer for the next operation by * setting its free count to the total buffer size * and the current position to zero. */ buf->free += buf->len; buf->len = 0; } mp_buf_free(L, buf); /* Concatenate all nargs buffers together */ lua_concat(L, nargs); return 1; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ClearActiveTab() { active_tab_->permissions_data()->ClearTabSpecificPermissions(kTabId); } CWE ID: CWE-20 Target: 1 Example 2: Code: bool FrameSelection::SelectWordAroundCaret() { const VisibleSelection& selection = ComputeVisibleSelectionInDOMTree(); if (!selection.IsCaret()) return false; const VisiblePosition& position = selection.VisibleStart(); static const EWordSide kWordSideList[2] = {kNextWordIfOnBoundary, kPreviousWordIfOnBoundary}; for (EWordSide word_side : kWordSideList) { VisiblePosition start = StartOfWord(position, word_side); VisiblePosition end = EndOfWord(position, word_side); String text = PlainText(EphemeralRange(start.DeepEquivalent(), end.DeepEquivalent())); if (!text.IsEmpty() && !IsSeparator(text.CharacterStartingAt(0))) { SetSelection(SelectionInDOMTree::Builder() .Collapse(start.ToPositionWithAffinity()) .Extend(end.DeepEquivalent()) .Build(), SetSelectionOptions::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetGranularity(TextGranularity::kWord) .Build()); return true; } } return false; } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = ""; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, "%s", sep)); sep = ","; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, "%s", tok2str(ip_option_values,"unknown %u",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: ip_printts(ndo, cp, option_len); break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: if (ip_printroute(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, " [bad length %u]", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); } 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 int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Error: invalid .Xauthority file\n"); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); if (chown(dest, getuid(), getgid()) == -1) errExit("fchown"); if (chmod(dest, 0600) == -1) errExit("fchmod"); return 1; // file copied } return 0; } CWE ID: CWE-269 Target: 1 Example 2: Code: ~TaskManagerTableModel() { model_->RemoveObserver(this); } 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 inline unsigned long zap_pmd_range(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud, unsigned long addr, unsigned long end, struct zap_details *details) { pmd_t *pmd; unsigned long next; pmd = pmd_offset(pud, addr); do { next = pmd_addr_end(addr, end); if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) continue; next = zap_pte_range(tlb, vma, pmd, addr, next, details); cond_resched(); } while (pmd++, addr = next, addr != end); return addr; } CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int rawv6_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_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name; struct sk_buff *skb; size_t copied; int err; if (flags & MSG_OOB) return -EOPNOTSUPP; if (addr_len) *addr_len=sizeof(*sin6); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { copied = len; msg->msg_flags |= MSG_TRUNC; } if (skb_csum_unnecessary(skb)) { err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); } else if (msg->msg_flags&MSG_TRUNC) { if (__skb_checksum_complete(skb)) goto csum_copy_err; err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); } else { err = skb_copy_and_csum_datagram_iovec(skb, 0, msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (err) goto out_free; /* Copy the address. */ if (sin6) { sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ipv6_hdr(skb)->saddr; sin6->sin6_flowinfo = 0; sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); } sock_recv_ts_and_drops(msg, sk, skb); if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); err = copied; if (flags & MSG_TRUNC) err = skb->len; out_free: skb_free_datagram(sk, skb); out: return err; csum_copy_err: skb_kill_datagram(sk, skb, flags); /* Error for blocking case is chosen to masquerade as some normal condition. */ err = (flags&MSG_DONTWAIT) ? -EAGAIN : -EHOSTUNREACH; goto out; } CWE ID: CWE-200 Target: 1 Example 2: Code: static inline void preempt_latency_stop(int val) { } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHP_FUNCTION(imageloadfont) { char *file; int file_name, hdr_size = sizeof(gdFont) - sizeof(char *); int ind, body_size, n = 0, b, i, body_size_check; gdFontPtr font; php_stream *stream; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &file, &file_name) == FAILURE) { return; } stream = php_stream_open_wrapper(file, "rb", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL); if (stream == NULL) { RETURN_FALSE; } /* Only supports a architecture-dependent binary dump format * at the moment. * The file format is like this on machines with 32-byte integers: * * byte 0-3: (int) number of characters in the font * byte 4-7: (int) value of first character in the font (often 32, space) * byte 8-11: (int) pixel width of each character * byte 12-15: (int) pixel height of each character * bytes 16-: (char) array with character data, one byte per pixel * in each character, for a total of * (nchars*width*height) bytes. */ font = (gdFontPtr) emalloc(sizeof(gdFont)); b = 0; while (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) { b += n; } if (!n) { efree(font); if (php_stream_eof(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading header"); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading header"); } php_stream_close(stream); RETURN_FALSE; } i = php_stream_tell(stream); php_stream_seek(stream, 0, SEEK_END); body_size_check = php_stream_tell(stream) - hdr_size; php_stream_seek(stream, i, SEEK_SET); body_size = font->w * font->h * font->nchars; if (body_size != body_size_check) { font->w = FLIPWORD(font->w); font->h = FLIPWORD(font->h); font->nchars = FLIPWORD(font->nchars); body_size = font->w * font->h * font->nchars; } if (overflow2(font->nchars, font->h)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header"); efree(font); php_stream_close(stream); RETURN_FALSE; } if (overflow2(font->nchars * font->h, font->w )) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header"); efree(font); php_stream_close(stream); RETURN_FALSE; } if (body_size != body_size_check) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font"); efree(font); php_stream_close(stream); RETURN_FALSE; } font->data = emalloc(body_size); b = 0; while (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) { b += n; } if (!n) { efree(font->data); efree(font); if (php_stream_eof(stream)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading body"); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading body"); } php_stream_close(stream); RETURN_FALSE; } php_stream_close(stream); /* Adding 5 to the font index so we will never have font indices * that overlap with the old fonts (with indices 1-5). The first * list index given out is always 1. */ ind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC); RETURN_LONG(ind); } CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void OomInterventionImpl::Check(TimerBase*) { DCHECK(host_); OomInterventionMetrics current_memory = GetCurrentMemoryMetrics(); bool oom_detected = false; oom_detected |= detection_args_->blink_workload_threshold > 0 && current_memory.current_blink_usage_kb * 1024 > detection_args_->blink_workload_threshold; oom_detected |= detection_args_->private_footprint_threshold > 0 && current_memory.current_private_footprint_kb * 1024 > detection_args_->private_footprint_threshold; oom_detected |= detection_args_->swap_threshold > 0 && current_memory.current_swap_kb * 1024 > detection_args_->swap_threshold; oom_detected |= detection_args_->virtual_memory_thresold > 0 && current_memory.current_vm_size_kb * 1024 > detection_args_->virtual_memory_thresold; ReportMemoryStats(current_memory); if (oom_detected) { if (navigate_ads_enabled_) { for (const auto& page : Page::OrdinaryPages()) { if (page->MainFrame()->IsLocalFrame()) { ToLocalFrame(page->MainFrame()) ->GetDocument() ->NavigateLocalAdsFrames(); } } } if (renderer_pause_enabled_) { pauser_.reset(new ScopedPagePauser); } host_->OnHighMemoryUsage(); timer_.Stop(); V8GCForContextDispose::Instance().SetForcePageNavigationGC(); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static void power_pmu_disable(struct pmu *pmu) { struct cpu_hw_events *cpuhw; unsigned long flags; if (!ppmu) return; local_irq_save(flags); cpuhw = &__get_cpu_var(cpu_hw_events); if (!cpuhw->disabled) { cpuhw->disabled = 1; cpuhw->n_added = 0; /* * Check if we ever enabled the PMU on this cpu. */ if (!cpuhw->pmcs_enabled) { ppc_enable_pmcs(); cpuhw->pmcs_enabled = 1; } /* * Disable instruction sampling if it was enabled */ if (cpuhw->mmcr[2] & MMCRA_SAMPLE_ENABLE) { mtspr(SPRN_MMCRA, cpuhw->mmcr[2] & ~MMCRA_SAMPLE_ENABLE); mb(); } /* * Set the 'freeze counters' bit. * The barrier is to make sure the mtspr has been * executed and the PMU has frozen the events * before we return. */ write_mmcr0(cpuhw, mfspr(SPRN_MMCR0) | MMCR0_FC); mb(); } local_irq_restore(flags); } CWE ID: CWE-189 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid) { FILE *fp = fopen(dest_filename, "w"); if (!fp) return false; unsigned fd = 0; while (fd <= 99999) /* paranoia check */ { sprintf(source_filename + source_base_ofs, "fd/%u", fd); char *name = malloc_readlink(source_filename); if (!name) break; fprintf(fp, "%u:%s\n", fd, name); free(name); sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd); fd++; FILE *in = fopen(source_filename, "r"); if (!in) continue; char buf[128]; while (fgets(buf, sizeof(buf)-1, in)) { /* in case the line is not terminated, terminate it */ char *eol = strchrnul(buf, '\n'); eol[0] = '\n'; eol[1] = '\0'; fputs(buf, fp); } fclose(in); } const int dest_fd = fileno(fp); if (fchown(dest_fd, uid, gid) < 0) { perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid); fclose(fp); unlink(dest_filename); return false; } fclose(fp); return true; } CWE ID: CWE-59 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 TabLifecycleUnitSource::TabLifecycleUnit::CanFreeze( DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!IsValidStateChange(GetState(), LifecycleUnitState::PENDING_FREEZE, StateChangeReason::BROWSER_INITIATED)) { return false; } if (TabLoadTracker::Get()->GetLoadingState(GetWebContents()) != TabLoadTracker::LoadingState::LOADED) { return false; } if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); IsMediaTabImpl(decision_details); if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); } CWE ID: Target: 1 Example 2: Code: int drm_mode_rmfb(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_mode_object *obj; struct drm_framebuffer *fb = NULL; struct drm_framebuffer *fbl = NULL; uint32_t *id = data; int ret = 0; int found = 0; if (!drm_core_check_feature(dev, DRIVER_MODESET)) return -EINVAL; mutex_lock(&dev->mode_config.mutex); obj = drm_mode_object_find(dev, *id, DRM_MODE_OBJECT_FB); /* TODO check that we really get a framebuffer back. */ if (!obj) { DRM_ERROR("mode invalid framebuffer id\n"); ret = -EINVAL; goto out; } fb = obj_to_fb(obj); list_for_each_entry(fbl, &file_priv->fbs, filp_head) if (fb == fbl) found = 1; if (!found) { DRM_ERROR("tried to remove a fb that we didn't own\n"); ret = -EINVAL; goto out; } /* TODO release all crtc connected to the framebuffer */ /* TODO unhock the destructor from the buffer object */ list_del(&fb->filp_head); fb->funcs->destroy(fb); out: mutex_unlock(&dev->mode_config.mutex); return ret; } 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 PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh, bool source_is_modifiable) { DCHECK(print_preview_rfh_); if (rfh != print_preview_rfh_) return; PrintPreviewDialogController* dialog_controller = PrintPreviewDialogController::GetInstance(); if (!dialog_controller) { PrintPreviewDone(); return; } dialog_controller->PrintPreview(web_contents()); PrintHostMsg_RequestPrintPreview_Params params; params.is_modifiable = source_is_modifiable; PrintPreviewUI::SetInitialParams( dialog_controller->GetPrintPreviewForContents(web_contents()), params); } 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: krb5_gss_wrap_size_limit(minor_status, context_handle, conf_req_flag, qop_req, req_output_size, max_input_size) OM_uint32 *minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; OM_uint32 req_output_size; OM_uint32 *max_input_size; { krb5_gss_ctx_id_rec *ctx; OM_uint32 data_size, conflen; OM_uint32 ohlen; int overhead; /* only default qop is allowed */ if (qop_req != GSS_C_QOP_DEFAULT) { *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); } if (ctx->proto == 1) { /* No pseudo-ASN.1 wrapper overhead, so no sequence length and OID. */ OM_uint32 sz = req_output_size; /* Token header: 16 octets. */ if (conf_req_flag) { krb5_key key; krb5_enctype enctype; key = ctx->have_acceptor_subkey ? ctx->acceptor_subkey : ctx->subkey; enctype = key->keyblock.enctype; while (sz > 0 && krb5_encrypt_size(sz, enctype) + 16 > req_output_size) sz--; /* Allow for encrypted copy of header. */ if (sz > 16) sz -= 16; else sz = 0; #ifdef CFX_EXERCISE /* Allow for EC padding. In the MIT implementation, only added while testing. */ if (sz > 65535) sz -= 65535; else sz = 0; #endif } else { krb5_cksumtype cksumtype; krb5_error_code err; size_t cksumsize; cksumtype = ctx->have_acceptor_subkey ? ctx->acceptor_subkey_cksumtype : ctx->cksumtype; err = krb5_c_checksum_length(ctx->k5_context, cksumtype, &cksumsize); if (err) { *minor_status = err; return GSS_S_FAILURE; } /* Allow for token header and checksum. */ if (sz < 16 + cksumsize) sz = 0; else sz -= (16 + cksumsize); } *max_input_size = sz; *minor_status = 0; return GSS_S_COMPLETE; } /* Calculate the token size and subtract that from the output size */ overhead = 7 + ctx->mech_used->length; data_size = req_output_size; conflen = kg_confounder_size(ctx->k5_context, ctx->enc->keyblock.enctype); data_size = (conflen + data_size + 8) & (~(OM_uint32)7); ohlen = g_token_size(ctx->mech_used, (unsigned int) (data_size + ctx->cksum_size + 14)) - req_output_size; if (ohlen+overhead < req_output_size) /* * Cannot have trailer length that will cause us to pad over our * length. */ *max_input_size = (req_output_size - ohlen - overhead) & (~(OM_uint32)7); else *max_input_size = 0; *minor_status = 0; return(GSS_S_COMPLETE); } CWE ID: Target: 1 Example 2: Code: GF_Err mdri_dump(GF_Box *a, FILE * trace) { gf_isom_box_dump_start(a, "OMADRMMutableInformationBox", trace); fprintf(trace, ">\n"); gf_isom_box_dump_done("OMADRMMutableInformationBox", a, trace); 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: OnNotificationBalloonCountObserver::OnNotificationBalloonCountObserver( AutomationProvider* provider, IPC::Message* reply_message, int count) : automation_(provider->AsWeakPtr()), reply_message_(reply_message), collection_( g_browser_process->notification_ui_manager()->balloon_collection()), count_(count) { registrar_.Add(this, chrome::NOTIFICATION_NOTIFY_BALLOON_CONNECTED, content::NotificationService::AllSources()); collection_->set_on_collection_changed_callback( base::Bind(&OnNotificationBalloonCountObserver::CheckBalloonCount, base::Unretained(this))); CheckBalloonCount(); } 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 amd_gpio_probe(struct platform_device *pdev) { int ret = 0; int irq_base; struct resource *res; struct amd_gpio *gpio_dev; gpio_dev = devm_kzalloc(&pdev->dev, sizeof(struct amd_gpio), GFP_KERNEL); if (!gpio_dev) return -ENOMEM; spin_lock_init(&gpio_dev->lock); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "Failed to get gpio io resource.\n"); return -EINVAL; } gpio_dev->base = devm_ioremap_nocache(&pdev->dev, res->start, resource_size(res)); if (!gpio_dev->base) return -ENOMEM; irq_base = platform_get_irq(pdev, 0); if (irq_base < 0) { dev_err(&pdev->dev, "Failed to get gpio IRQ.\n"); return -EINVAL; } gpio_dev->pdev = pdev; gpio_dev->gc.direction_input = amd_gpio_direction_input; gpio_dev->gc.direction_output = amd_gpio_direction_output; gpio_dev->gc.get = amd_gpio_get_value; gpio_dev->gc.set = amd_gpio_set_value; gpio_dev->gc.set_debounce = amd_gpio_set_debounce; gpio_dev->gc.dbg_show = amd_gpio_dbg_show; gpio_dev->gc.base = 0; gpio_dev->gc.label = pdev->name; gpio_dev->gc.owner = THIS_MODULE; gpio_dev->gc.parent = &pdev->dev; gpio_dev->gc.ngpio = TOTAL_NUMBER_OF_PINS; #if defined(CONFIG_OF_GPIO) gpio_dev->gc.of_node = pdev->dev.of_node; #endif gpio_dev->groups = kerncz_groups; gpio_dev->ngroups = ARRAY_SIZE(kerncz_groups); amd_pinctrl_desc.name = dev_name(&pdev->dev); gpio_dev->pctrl = pinctrl_register(&amd_pinctrl_desc, &pdev->dev, gpio_dev); if (IS_ERR(gpio_dev->pctrl)) { dev_err(&pdev->dev, "Couldn't register pinctrl driver\n"); return PTR_ERR(gpio_dev->pctrl); } ret = gpiochip_add_data(&gpio_dev->gc, gpio_dev); if (ret) goto out1; ret = gpiochip_add_pin_range(&gpio_dev->gc, dev_name(&pdev->dev), 0, 0, TOTAL_NUMBER_OF_PINS); if (ret) { dev_err(&pdev->dev, "Failed to add pin range\n"); goto out2; } ret = gpiochip_irqchip_add(&gpio_dev->gc, &amd_gpio_irqchip, 0, handle_simple_irq, IRQ_TYPE_NONE); if (ret) { dev_err(&pdev->dev, "could not add irqchip\n"); ret = -ENODEV; goto out2; } gpiochip_set_chained_irqchip(&gpio_dev->gc, &amd_gpio_irqchip, irq_base, amd_gpio_irq_handler); platform_set_drvdata(pdev, gpio_dev); dev_dbg(&pdev->dev, "amd gpio driver loaded\n"); return ret; out2: gpiochip_remove(&gpio_dev->gc); out1: pinctrl_unregister(gpio_dev->pctrl); return ret; } CWE ID: CWE-415 Target: 1 Example 2: Code: local void gf2_matrix_square(unsigned long *square, unsigned long *mat) { int n; for (n = 0; n < 32; n++) square[n] = gf2_matrix_times(mat, mat[n]); } CWE ID: CWE-22 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool ldm_parse_vblk (const u8 *buf, int len, struct vblk *vb) { bool result = false; int r_objid; BUG_ON (!buf || !vb); r_objid = ldm_relative (buf, len, 0x18, 0); if (r_objid < 0) { ldm_error ("VBLK header is corrupt."); return false; } vb->flags = buf[0x12]; vb->type = buf[0x13]; vb->obj_id = ldm_get_vnum (buf + 0x18); ldm_get_vstr (buf+0x18+r_objid, vb->name, sizeof (vb->name)); switch (vb->type) { case VBLK_CMP3: result = ldm_parse_cmp3 (buf, len, vb); break; case VBLK_DSK3: result = ldm_parse_dsk3 (buf, len, vb); break; case VBLK_DSK4: result = ldm_parse_dsk4 (buf, len, vb); break; case VBLK_DGR3: result = ldm_parse_dgr3 (buf, len, vb); break; case VBLK_DGR4: result = ldm_parse_dgr4 (buf, len, vb); break; case VBLK_PRT3: result = ldm_parse_prt3 (buf, len, vb); break; case VBLK_VOL5: result = ldm_parse_vol5 (buf, len, vb); break; } if (result) ldm_debug ("Parsed VBLK 0x%llx (type: 0x%02x) ok.", (unsigned long long) vb->obj_id, vb->type); else ldm_error ("Failed to parse VBLK 0x%llx (type: 0x%02x).", (unsigned long long) vb->obj_id, vb->type); return result; } 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* Track::GetCodecId() const { return m_info.codecId; } CWE ID: CWE-119 Target: 1 Example 2: Code: bool ContentSecurityPolicy::Subsumes(const ContentSecurityPolicy& other) const { if (!policies_.size() || !other.policies_.size()) return !policies_.size(); if (policies_.size() != 1) return false; CSPDirectiveListVector other_vector; for (const auto& policy : other.policies_) { if (!policy->IsReportOnly()) other_vector.push_back(policy); } return policies_[0]->Subsumes(other_vector); } 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 FLTIsBinaryComparisonFilterType(const char *pszValue) { if (pszValue) { if (strcasecmp(pszValue, "PropertyIsEqualTo") == 0 || strcasecmp(pszValue, "PropertyIsNotEqualTo") == 0 || strcasecmp(pszValue, "PropertyIsLessThan") == 0 || strcasecmp(pszValue, "PropertyIsGreaterThan") == 0 || strcasecmp(pszValue, "PropertyIsLessThanOrEqualTo") == 0 || strcasecmp(pszValue, "PropertyIsGreaterThanOrEqualTo") == 0) return MS_TRUE; } return MS_FALSE; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void InstallablePaymentAppCrawler::OnPaymentMethodManifestParsed( const GURL& method_manifest_url, const std::vector<GURL>& default_applications, const std::vector<url::Origin>& supported_origins, bool all_origins_supported) { number_of_payment_method_manifest_to_parse_--; if (web_contents() == nullptr) return; content::PermissionManager* permission_manager = web_contents()->GetBrowserContext()->GetPermissionManager(); if (permission_manager == nullptr) return; for (const auto& url : default_applications) { if (downloaded_web_app_manifests_.find(url) != downloaded_web_app_manifests_.end()) { continue; } if (permission_manager->GetPermissionStatus( content::PermissionType::PAYMENT_HANDLER, url.GetOrigin(), url.GetOrigin()) != blink::mojom::PermissionStatus::GRANTED) { continue; } number_of_web_app_manifest_to_download_++; downloaded_web_app_manifests_.insert(url); downloader_->DownloadWebAppManifest( url, base::BindOnce( &InstallablePaymentAppCrawler::OnPaymentWebAppManifestDownloaded, weak_ptr_factory_.GetWeakPtr(), method_manifest_url, url)); } FinishCrawlingPaymentAppsIfReady(); } CWE ID: Target: 1 Example 2: Code: int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { int i, j, bits, ret = 0, wstart, wend, window, wvalue; int start = 1; BIGNUM *d, *r; const BIGNUM *aa; /* Table of variables obtained from 'ctx' */ BIGNUM *val[TABLE_SIZE]; BN_MONT_CTX *mont = NULL; if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) { return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont); } bn_check_top(a); bn_check_top(p); bn_check_top(m); if (!BN_is_odd(m)) { BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS); return (0); } bits = BN_num_bits(p); if (bits == 0) { /* x**0 mod 1 is still zero. */ if (BN_is_one(m)) { ret = 1; BN_zero(rr); } else { ret = BN_one(rr); } return ret; } BN_CTX_start(ctx); d = BN_CTX_get(ctx); r = BN_CTX_get(ctx); val[0] = BN_CTX_get(ctx); if (!d || !r || !val[0]) goto err; /* * If this is not done, things will break in the montgomery part */ if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } if (a->neg || BN_ucmp(a, m) >= 0) { if (!BN_nnmod(val[0], a, m, ctx)) goto err; aa = val[0]; } else aa = a; if (BN_is_zero(aa)) { BN_zero(rr); ret = 1; goto err; } if (!BN_to_montgomery(val[0], aa, mont, ctx)) goto err; /* 1 */ window = BN_window_bits_for_exponent_size(bits); if (window > 1) { if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) goto err; /* 2 */ j = 1 << (window - 1); for (i = 1; i < j; i++) { if (((val[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx)) goto err; } } start = 1; /* This is used to avoid multiplication etc * when there is only the value '1' in the * buffer. */ wvalue = 0; /* The 'value' of the window */ wstart = bits - 1; /* The top bit of the window */ wend = 0; /* The bottom bit of the window */ #if 1 /* by Shay Gueron's suggestion */ j = m->top; /* borrow j */ if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) { if (bn_wexpand(r, j) == NULL) goto err; /* 2^(top*BN_BITS2) - m */ r->d[0] = (0 - m->d[0]) & BN_MASK2; for (i = 1; i < j; i++) r->d[i] = (~m->d[i]) & BN_MASK2; r->top = j; /* * Upper words will be zero if the corresponding words of 'm' were * 0xfff[...], so decrement r->top accordingly. */ bn_correct_top(r); } else #endif if (!BN_to_montgomery(r, BN_value_one(), mont, ctx)) goto err; for (;;) { if (BN_is_bit_set(p, wstart) == 0) { if (!start) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } if (wstart == 0) break; wstart--; continue; } /* * We now have wstart on a 'set' bit, we now need to work out how bit * a window to do. To do this we need to scan forward until the last * set bit before the end of the window */ j = wstart; wvalue = 1; wend = 0; for (i = 1; i < window; i++) { if (wstart - i < 0) break; if (BN_is_bit_set(p, wstart - i)) { wvalue <<= (i - wend); wvalue |= 1; wend = i; } } /* wend is the size of the current window */ j = wend + 1; /* add the 'bytes above' */ if (!start) for (i = 0; i < j; i++) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } /* wvalue will be an odd number < 2^window */ if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx)) goto err; /* move the 'window' down further */ wstart -= wend + 1; wvalue = 0; start = 0; if (wstart < 0) break; } #if defined(SPARC_T4_MONT) if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) { j = mont->N.top; /* borrow j */ val[0]->d[0] = 1; /* borrow val[0] */ for (i = 1; i < j; i++) val[0]->d[i] = 0; val[0]->top = j; if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx)) goto err; } else #endif if (!BN_from_montgomery(rr, r, mont, ctx)) goto err; ret = 1; err: if ((in_mont == NULL) && (mont != NULL)) BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); return (ret); } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode) { struct sshbuf *b = NULL; struct sshcomp *comp; struct sshenc *enc; struct sshmac *mac; struct newkeys *newkey = NULL; size_t keylen, ivlen, maclen; int r; if ((newkey = calloc(1, sizeof(*newkey))) == NULL) { r = SSH_ERR_ALLOC_FAIL; goto out; } if ((r = sshbuf_froms(m, &b)) != 0) goto out; #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif enc = &newkey->enc; mac = &newkey->mac; comp = &newkey->comp; if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 || (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 || (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 || (r = sshbuf_get_u32(b, &enc->block_size)) != 0 || (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 || (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0) goto out; if (cipher_authlen(enc->cipher) == 0) { if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0) goto out; if ((r = mac_setup(mac, mac->name)) != 0) goto out; if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 || (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0) goto out; if (maclen > mac->key_len) { r = SSH_ERR_INVALID_FORMAT; goto out; } mac->key_len = maclen; } if ((r = sshbuf_get_u32(b, &comp->type)) != 0 || (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 || (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0) goto out; if (enc->name == NULL || cipher_by_name(enc->name) != enc->cipher) { r = SSH_ERR_INVALID_FORMAT; goto out; } if (sshbuf_len(b) != 0) { r = SSH_ERR_INVALID_FORMAT; goto out; } enc->key_len = keylen; enc->iv_len = ivlen; ssh->kex->newkeys[mode] = newkey; newkey = NULL; r = 0; out: free(newkey); sshbuf_free(b); return r; } 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: bool AXListBoxOption::isEnabled() const { if (!getNode()) return false; if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true")) return false; if (toElement(getNode())->hasAttribute(disabledAttr)) return false; return true; } CWE ID: CWE-254 Target: 1 Example 2: Code: static int uv__process_open_stream(uv_stdio_container_t* container, int pipefds[2], int writable) { int flags; if (!(container->flags & UV_CREATE_PIPE) || pipefds[0] < 0) return 0; if (uv__close(pipefds[1])) if (errno != EINTR && errno != EINPROGRESS) abort(); pipefds[1] = -1; uv__nonblock(pipefds[0], 1); if (container->data.stream->type == UV_NAMED_PIPE && ((uv_pipe_t*)container->data.stream)->ipc) flags = UV_STREAM_READABLE | UV_STREAM_WRITABLE; else if (writable) flags = UV_STREAM_WRITABLE; else flags = UV_STREAM_READABLE; return uv__stream_open(container->data.stream, pipefds[0], flags); } 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: TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams( int version, size_t start, size_t end, const std::string& selection, const std::string& content, const std::string& base_page_url, const std::string& encoding, int now_on_tap_version) : version(version), start(start), end(end), selection(selection), content(content), base_page_url(base_page_url), encoding(encoding), now_on_tap_version(now_on_tap_version) {} 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 MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image) { MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t depth, packet_size; ssize_t y; unsigned char *colormap, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); /* Allocate colormap. */ if (IsPaletteImage(image,&image->exception) == MagickFalse) (void) SetImageType(image,PaletteType); depth=GetImageQuantumDepth(image,MagickTrue); packet_size=(size_t) (depth/8); pixels=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*pixels)); packet_size=(size_t) (image->colors > 256 ? 6UL : 3UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors,packet_size* sizeof(*colormap)); if ((pixels == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Write colormap to file. */ q=colormap; q=colormap; if (image->colors <= 256) for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].red); *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].green); *q++=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue); } else for (i=0; i < (ssize_t) image->colors; i++) { *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].red) & 0xff); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].green) & 0xff);; *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8); *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff); } (void) WriteBlob(image,packet_size*image->colors,colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); /* Write image pixels to file. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); q=pixels; for (x=0; x < (ssize_t) image->columns; x++) { if (image->colors > 256) *q++=(unsigned char) ((size_t) GetPixelIndex(indexes+x) >> 8); *q++=(unsigned char) GetPixelIndex(indexes+x); } (void) WriteBlob(image,(size_t) (q-pixels),pixels); } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(status); } CWE ID: CWE-772 Target: 1 Example 2: Code: void dir_scan(char *parent_name, unsigned int start_block, unsigned int offset, struct pathnames *paths) { unsigned int type; char *name; struct pathnames *new; struct inode *i; struct dir *dir = s_ops.squashfs_opendir(start_block, offset, &i); if(dir == NULL) { ERROR("dir_scan: failed to read directory %s, skipping\n", parent_name); return; } if(lsonly || info) print_filename(parent_name, i); if(!lsonly) { /* * Make directory with default User rwx permissions rather than * the permissions from the filesystem, as these may not have * write/execute permission. These are fixed up later in * set_attributes(). */ int res = mkdir(parent_name, S_IRUSR|S_IWUSR|S_IXUSR); if(res == -1) { /* * Skip directory if mkdir fails, unless we're * forcing and the error is -EEXIST */ if(!force || errno != EEXIST) { ERROR("dir_scan: failed to make directory %s, " "because %s\n", parent_name, strerror(errno)); squashfs_closedir(dir); FAILED = TRUE; return; } /* * Try to change permissions of existing directory so * that we can write to it */ res = chmod(parent_name, S_IRUSR|S_IWUSR|S_IXUSR); if (res == -1) ERROR("dir_scan: failed to change permissions " "for directory %s, because %s\n", parent_name, strerror(errno)); } } while(squashfs_readdir(dir, &name, &start_block, &offset, &type)) { char *pathname; int res; TRACE("dir_scan: name %s, start_block %d, offset %d, type %d\n", name, start_block, offset, type); if(!matches(paths, name, &new)) continue; res = asprintf(&pathname, "%s/%s", parent_name, name); if(res == -1) EXIT_UNSQUASH("asprintf failed in dir_scan\n"); if(type == SQUASHFS_DIR_TYPE) { dir_scan(pathname, start_block, offset, new); free(pathname); } else if(new == NULL) { update_info(pathname); i = s_ops.read_inode(start_block, offset); if(lsonly || info) print_filename(pathname, i); if(!lsonly) create_inode(pathname, i); if(i->type == SQUASHFS_SYMLINK_TYPE || i->type == SQUASHFS_LSYMLINK_TYPE) free(i->symlink); } else free(pathname); free_subdir(new); } if(!lsonly) queue_dir(parent_name, dir); squashfs_closedir(dir); dir_count ++; } 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: ExclusiveAccessContext* TestBrowserWindow::GetExclusiveAccessContext() { return nullptr; } 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: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); version_ = GET_PARAM(2); // 0: high precision forward transform } CWE ID: CWE-119 Target: 1 Example 2: Code: DomainReliabilityClearMode last_clear_mode() const { return last_clear_mode_; } 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 void StrokeRectOnCanvas(const FloatRect& rect, PaintCanvas* canvas, const PaintFlags* flags) { DCHECK_EQ(flags->getStyle(), PaintFlags::kStroke_Style); if ((rect.Width() > 0) != (rect.Height() > 0)) { SkPath path; path.moveTo(rect.X(), rect.Y()); path.lineTo(rect.MaxX(), rect.MaxY()); path.close(); canvas->drawPath(path, *flags); return; } canvas->drawRect(rect, *flags); } 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: long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg) { int nid; long ret; nid = OBJ_obj2nid(p7->type); switch (cmd) { case PKCS7_OP_SET_DETACHED_SIGNATURE: if (nid == NID_pkcs7_signed) { ret = p7->detached = (int)larg; ASN1_OCTET_STRING *os; os = p7->d.sign->contents->d.data; ASN1_OCTET_STRING_free(os); p7->d.sign->contents->d.data = NULL; } } else { PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE); ret = 0; } break; case PKCS7_OP_GET_DETACHED_SIGNATURE: if (nid == NID_pkcs7_signed) { if (!p7->d.sign || !p7->d.sign->contents->d.ptr) ret = 1; else ret = 0; p7->detached = ret; } else { PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE); ret = 0; } break; default: PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_UNKNOWN_OPERATION); ret = 0; } CWE ID: Target: 1 Example 2: Code: CStarter::publishPreScriptUpdateAd( ClassAd* ad ) { if( pre_script && pre_script->PublishUpdateAd(ad) ) { return true; } return 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: ExprResolveMod(struct xkb_context *ctx, const ExprDef *def, enum mod_type mod_type, const struct xkb_mod_set *mods, xkb_mod_index_t *ndx_rtrn) { xkb_mod_index_t ndx; xkb_atom_t name; if (def->expr.op != EXPR_IDENT) { log_err(ctx, "Cannot resolve virtual modifier: " "found %s where a virtual modifier name was expected\n", expr_op_type_to_string(def->expr.op)); return false; } name = def->ident.ident; ndx = XkbModNameToIndex(mods, name, mod_type); if (ndx == XKB_MOD_INVALID) { log_err(ctx, "Cannot resolve virtual modifier: " "\"%s\" was not previously declared\n", xkb_atom_text(ctx, name)); return false; } *ndx_rtrn = ndx; 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: void smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; SMP_TRACE_DEBUG("%s", __func__); STREAM_TO_ARRAY(p_cb->ltk, p, BT_OCTET16_LEN); smp_key_distribution(p_cb, NULL); } CWE ID: CWE-200 Target: 1 Example 2: Code: void PostOnOwnerThread(const scoped_refptr<PrintJobWorkerOwner>& owner, const PrintingContext::PrintSettingsCallback& callback, PrintingContext::Result result) { owner->PostTask(FROM_HERE, base::Bind(&HoldRefCallback, owner, base::Bind(callback, result))); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len) { struct net *net = sock_net(sk); struct sctp_sock *sp = sctp_sk(sk); struct sctp_endpoint *ep = sp->ep; struct sctp_bind_addr *bp = &ep->base.bind_addr; struct sctp_af *af; unsigned short snum; int ret = 0; /* Common sockaddr verification. */ af = sctp_sockaddr_af(sp, addr, len); if (!af) { pr_debug("%s: sk:%p, newaddr:%p, len:%d EINVAL\n", __func__, sk, addr, len); return -EINVAL; } snum = ntohs(addr->v4.sin_port); pr_debug("%s: sk:%p, new addr:%pISc, port:%d, new port:%d, len:%d\n", __func__, sk, &addr->sa, bp->port, snum, len); /* PF specific bind() address verification. */ if (!sp->pf->bind_verify(sp, addr)) return -EADDRNOTAVAIL; /* We must either be unbound, or bind to the same port. * It's OK to allow 0 ports if we are already bound. * We'll just inhert an already bound port in this case */ if (bp->port) { if (!snum) snum = bp->port; else if (snum != bp->port) { pr_debug("%s: new port %d doesn't match existing port " "%d\n", __func__, snum, bp->port); return -EINVAL; } } if (snum && snum < PROT_SOCK && !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) return -EACCES; /* See if the address matches any of the addresses we may have * already bound before checking against other endpoints. */ if (sctp_bind_addr_match(bp, addr, sp)) return -EINVAL; /* Make sure we are allowed to bind here. * The function sctp_get_port_local() does duplicate address * detection. */ addr->v4.sin_port = htons(snum); if ((ret = sctp_get_port_local(sk, addr))) { return -EADDRINUSE; } /* Refresh ephemeral port. */ if (!bp->port) bp->port = inet_sk(sk)->inet_num; /* Add the address to the bind address list. * Use GFP_ATOMIC since BHs will be disabled. */ ret = sctp_add_bind_addr(bp, addr, af->sockaddr_len, SCTP_ADDR_SRC, GFP_ATOMIC); /* Copy back into socket for getsockname() use. */ if (!ret) { inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num); sp->pf->to_sk_saddr(addr, sk); } return ret; } CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Response DOMHandler::SetFileInputFiles( std::unique_ptr<protocol::Array<std::string>> files, Maybe<DOM::NodeId> node_id, Maybe<DOM::BackendNodeId> backend_node_id, Maybe<String> in_object_id) { if (host_) { for (size_t i = 0; i < files->length(); i++) { #if defined(OS_WIN) ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( host_->GetProcess()->GetID(), base::FilePath(base::UTF8ToUTF16(files->get(i)))); #else ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( host_->GetProcess()->GetID(), base::FilePath(files->get(i))); #endif // OS_WIN } } return Response::FallThrough(); } CWE ID: CWE-254 Target: 1 Example 2: Code: void ClickShelfItemForWindow(ShelfView* shelf_view, aura::Window* window) { ShelfViewTestAPI test_api(shelf_view); test_api.SetAnimationDuration(1); test_api.RunMessageLoopUntilAnimationsDone(); ShelfID shelf_id = ShelfID::Deserialize(window->GetProperty(kShelfIDKey)); DCHECK(!shelf_id.IsNull()); int index = Shell::Get()->shelf_model()->ItemIndexByID(shelf_id); DCHECK_GE(index, 0); gfx::Rect bounds = test_api.GetButton(index)->GetBoundsInScreen(); ui::test::EventGenerator& event_generator = GetEventGenerator(); event_generator.MoveMouseTo(bounds.CenterPoint()); event_generator.ClickLeftButton(); test_api.RunMessageLoopUntilAnimationsDone(); } 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: blink::WebSpeechRecognizer* RenderViewImpl::SpeechRecognizer() { if (!speech_recognition_dispatcher_) speech_recognition_dispatcher_ = new SpeechRecognitionDispatcher(this); return speech_recognition_dispatcher_; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int sc_asn1_read_tag(const u8 ** buf, size_t buflen, unsigned int *cla_out, unsigned int *tag_out, size_t *taglen) { const u8 *p = *buf; size_t left = buflen, len; unsigned int cla, tag, i; if (left < 2) return SC_ERROR_INVALID_ASN1_OBJECT; *buf = NULL; if (*p == 0xff || *p == 0) { /* end of data reached */ *taglen = 0; *tag_out = SC_ASN1_TAG_EOC; return SC_SUCCESS; } /* parse tag byte(s) * Resulted tag is presented by integer that has not to be * confused with the 'tag number' part of ASN.1 tag. */ cla = (*p & SC_ASN1_TAG_CLASS) | (*p & SC_ASN1_TAG_CONSTRUCTED); tag = *p & SC_ASN1_TAG_PRIMITIVE; p++; left--; if (tag == SC_ASN1_TAG_PRIMITIVE) { /* high tag number */ size_t n = SC_ASN1_TAGNUM_SIZE - 1; /* search the last tag octet */ while (left-- != 0 && n != 0) { tag <<= 8; tag |= *p; if ((*p++ & 0x80) == 0) break; n--; } if (left == 0 || n == 0) /* either an invalid tag or it doesn't fit in * unsigned int */ return SC_ERROR_INVALID_ASN1_OBJECT; } /* parse length byte(s) */ len = *p & 0x7f; if (*p++ & 0x80) { unsigned int a = 0; if (len > 4 || len > left) return SC_ERROR_INVALID_ASN1_OBJECT; left -= len; for (i = 0; i < len; i++) { a <<= 8; a |= *p; p++; } len = a; } *cla_out = cla; *tag_out = tag; *taglen = len; *buf = p; if (len > left) return SC_ERROR_ASN1_END_OF_CONTENTS; return SC_SUCCESS; } CWE ID: CWE-125 Target: 1 Example 2: Code: int fix_log_file_owner(uid_t uid, gid_t gid) { int r1 = 0, r2 = 0; if (!(log_fp = open_log_file())) return -1; r1 = fchown(fileno(log_fp), uid, gid); if (open_debug_log() != OK) return -1; if (debug_file_fp) r2 = fchown(fileno(debug_file_fp), uid, gid); /* return 0 if both are 0 and otherwise < 0 */ return r1 < r2 ? r1 : r2; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long Chapters::Edition::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) // Atom ID { status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: my_object_many_stringify (MyObject *obj, GHashTable /* char * -> GValue * */ *vals, GHashTable /* char * -> GValue * */ **ret, GError **error) { *ret = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, unset_and_free_gvalue); g_hash_table_foreach (vals, hash_foreach_stringify, *ret); return TRUE; } CWE ID: CWE-264 Target: 1 Example 2: Code: GF_Err stsh_Size(GF_Box *s) { GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s; ptr->size += 4 + (8 * gf_list_count(ptr->entries)); 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: void BindDiscardableMemoryRequestOnIO( discardable_memory::mojom::DiscardableSharedMemoryManagerRequest request, discardable_memory::DiscardableSharedMemoryManager* manager) { DCHECK_CURRENTLY_ON(BrowserThread::IO); service_manager::BindSourceInfo source_info; manager->Bind(std::move(request), source_info); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void scsi_write_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode != SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_write_complete(r, -EINVAL); return; } n = r->iov.iov_len / 512; if (n) { if (s->tray_open) { scsi_write_complete(r, -ENOMEDIUM); } qemu_iovec_init_external(&r->qiov, &r->iov, 1); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_WRITE); r->req.aiocb = bdrv_aio_writev(s->bs, r->sector, &r->qiov, n, scsi_write_complete, r); if (r->req.aiocb == NULL) { scsi_write_complete(r, -ENOMEM); } } else { /* Invoke completion routine to fetch data from host. */ scsi_write_complete(r, 0); } } CWE ID: CWE-119 Target: 1 Example 2: Code: int ipv6_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { int err; if (level == SOL_IP && sk->sk_type != SOCK_RAW) return udp_prot.setsockopt(sk, level, optname, optval, optlen); if (level != SOL_IPV6) return -ENOPROTOOPT; err = do_ipv6_setsockopt(sk, level, optname, optval, optlen); #ifdef CONFIG_NETFILTER /* we need to exclude all possible ENOPROTOOPTs except default case */ if (err == -ENOPROTOOPT && optname != IPV6_IPSEC_POLICY && optname != IPV6_XFRM_POLICY) { lock_sock(sk); err = nf_setsockopt(sk, PF_INET6, optname, optval, optlen); release_sock(sk); } #endif return err; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DelegatedFrameHost::OnCompositingStarted(ui::Compositor* compositor, base::TimeTicks start_time) { last_draw_ended_ = start_time; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool HeapAllocator::backingExpand(void* address, size_t newSize) { if (!address) return false; ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return false; ASSERT(!state->isInGC()); ASSERT(state->isAllocationAllowed()); DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return false; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); ASSERT(header->checkHeader()); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); bool succeed = arena->expandObject(header, newSize); if (succeed) state->allocationPointAdjusted(arena->arenaIndex()); return succeed; } CWE ID: CWE-119 Target: 1 Example 2: Code: static inline uint64_t virtio_net_supported_guest_offloads(VirtIONet *n) { VirtIODevice *vdev = VIRTIO_DEVICE(n); return virtio_net_guest_offloads_by_features(vdev->guest_features); } 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 __net_init xt_net_init(struct net *net) { int i; for (i = 0; i < NFPROTO_NUMPROTO; i++) INIT_LIST_HEAD(&net->xt.tables[i]); return 0; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void runTest() { if (m_settings.enableCompositorThread) CCLayerTreeHostTest::runTest(); } CWE ID: CWE-119 Target: 1 Example 2: Code: sshpkt_fatal(struct ssh *ssh, const char *tag, int r) { switch (r) { case SSH_ERR_CONN_CLOSED: logit("Connection closed by %.200s", ssh_remote_ipaddr(ssh)); cleanup_exit(255); case SSH_ERR_CONN_TIMEOUT: logit("Connection to %.200s timed out", ssh_remote_ipaddr(ssh)); cleanup_exit(255); case SSH_ERR_DISCONNECTED: logit("Disconnected from %.200s", ssh_remote_ipaddr(ssh)); cleanup_exit(255); case SSH_ERR_SYSTEM_ERROR: if (errno == ECONNRESET) { logit("Connection reset by %.200s", ssh_remote_ipaddr(ssh)); cleanup_exit(255); } /* FALLTHROUGH */ case SSH_ERR_NO_CIPHER_ALG_MATCH: case SSH_ERR_NO_MAC_ALG_MATCH: case SSH_ERR_NO_COMPRESS_ALG_MATCH: case SSH_ERR_NO_KEX_ALG_MATCH: case SSH_ERR_NO_HOSTKEY_ALG_MATCH: if (ssh && ssh->kex && ssh->kex->failed_choice) { fatal("Unable to negotiate with %.200s: %s. " "Their offer: %s", ssh_remote_ipaddr(ssh), ssh_err(r), ssh->kex->failed_choice); } /* FALLTHROUGH */ default: fatal("%s%sConnection to %.200s: %s", tag != NULL ? tag : "", tag != NULL ? ": " : "", ssh_remote_ipaddr(ssh), ssh_err(r)); } } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameImpl::WillReleaseScriptContext(v8::Local<v8::Context> context, int world_id) { for (auto& observer : observers_) observer.WillReleaseScriptContext(context, world_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: static int xfrm6_tunnel_rcv(struct sk_buff *skb) { struct ipv6hdr *iph = ipv6_hdr(skb); __be32 spi; spi = xfrm6_tunnel_spi_lookup((xfrm_address_t *)&iph->saddr); return xfrm6_rcv_spi(skb, spi); } CWE ID: CWE-399 Target: 1 Example 2: Code: static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev, struct net_device *adj_dev, struct list_head *dev_list) { return (dev_list == &dev->adj_list.upper || dev_list == &dev->adj_list.lower) && net_eq(dev_net(dev), dev_net(adj_dev)); } CWE ID: CWE-400 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CapturerMac::CgBlit(const VideoFrameBuffer& buffer, const InvalidRects& rects) { if (last_buffer_) memcpy(buffer.ptr(), last_buffer_, buffer.bytes_per_row() * buffer.size().height()); last_buffer_ = buffer.ptr(); CGDirectDisplayID main_display = CGMainDisplayID(); uint8* display_base_address = reinterpret_cast<uint8*>(CGDisplayBaseAddress(main_display)); int src_bytes_per_row = CGDisplayBytesPerRow(main_display); int src_bytes_per_pixel = CGDisplayBitsPerPixel(main_display) / 8; for (InvalidRects::iterator i = rects.begin(); i != rects.end(); ++i) { int src_row_offset = i->x() * src_bytes_per_pixel; int dst_row_offset = i->x() * sizeof(uint32_t); int rect_width_in_bytes = i->width() * src_bytes_per_pixel; int ymax = i->height() + i->y(); for (int y = i->y(); y < ymax; ++y) { memcpy(buffer.ptr() + y * buffer.bytes_per_row() + dst_row_offset, display_base_address + y * src_bytes_per_row + src_row_offset, rect_width_in_bytes); } } } 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 ChromeExtensionsDispatcherDelegate::RegisterNativeHandlers( extensions::Dispatcher* dispatcher, extensions::ModuleSystem* module_system, extensions::ScriptContext* context) { module_system->RegisterNativeHandler( "app", std::unique_ptr<NativeHandler>( new extensions::AppBindings(dispatcher, context))); module_system->RegisterNativeHandler( "sync_file_system", std::unique_ptr<NativeHandler>( new extensions::SyncFileSystemCustomBindings(context))); module_system->RegisterNativeHandler( "file_browser_handler", std::unique_ptr<NativeHandler>( new extensions::FileBrowserHandlerCustomBindings(context))); module_system->RegisterNativeHandler( "file_manager_private", std::unique_ptr<NativeHandler>( new extensions::FileManagerPrivateCustomBindings(context))); module_system->RegisterNativeHandler( "notifications_private", std::unique_ptr<NativeHandler>( new extensions::NotificationsNativeHandler(context))); module_system->RegisterNativeHandler( "mediaGalleries", std::unique_ptr<NativeHandler>( new extensions::MediaGalleriesCustomBindings(context))); module_system->RegisterNativeHandler( "page_capture", std::unique_ptr<NativeHandler>( new extensions::PageCaptureCustomBindings(context))); module_system->RegisterNativeHandler( "platform_keys_natives", std::unique_ptr<NativeHandler>( new extensions::PlatformKeysNatives(context))); module_system->RegisterNativeHandler( "tabs", std::unique_ptr<NativeHandler>( new extensions::TabsCustomBindings(context))); module_system->RegisterNativeHandler( "webstore", std::unique_ptr<NativeHandler>( new extensions::WebstoreBindings(context))); #if defined(ENABLE_WEBRTC) module_system->RegisterNativeHandler( "cast_streaming_natives", std::unique_ptr<NativeHandler>( new extensions::CastStreamingNativeHandler(context))); #endif module_system->RegisterNativeHandler( "automationInternal", std::unique_ptr<NativeHandler>( new extensions::AutomationInternalCustomBindings(context))); } CWE ID: CWE-284 Target: 1 Example 2: Code: void DevToolsWindow::SetWindowBounds(int x, int y, int width, int height) { if (!IsDocked()) browser_->window()->SetBounds(gfx::Rect(x, y, width, height)); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static HB_Error Load_PosClassRule( HB_ContextPosFormat2* cpf2, HB_PosClassRule* pcr, HB_Stream stream ) { HB_Error error; HB_UShort n, count; HB_UShort* c; HB_PosLookupRecord* plr; if ( ACCESS_Frame( 4L ) ) return error; pcr->GlyphCount = GET_UShort(); pcr->PosCount = GET_UShort(); FORGET_Frame(); if ( pcr->GlyphCount > cpf2->MaxContextLength ) cpf2->MaxContextLength = pcr->GlyphCount; pcr->Class = NULL; count = pcr->GlyphCount - 1; /* only GlyphCount - 1 elements */ if ( ALLOC_ARRAY( pcr->Class, count, HB_UShort ) ) return error; c = pcr->Class; if ( ACCESS_Frame( count * 2L ) ) goto Fail2; for ( n = 0; n < count; n++ ) c[n] = GET_UShort(); FORGET_Frame(); pcr->PosLookupRecord = NULL; count = pcr->PosCount; if ( ALLOC_ARRAY( pcr->PosLookupRecord, count, HB_PosLookupRecord ) ) goto Fail2; plr = pcr->PosLookupRecord; if ( ACCESS_Frame( count * 4L ) ) goto Fail1; for ( n = 0; n < count; n++ ) { plr[n].SequenceIndex = GET_UShort(); plr[n].LookupListIndex = GET_UShort(); } FORGET_Frame(); return HB_Err_Ok; Fail1: FREE( plr ); Fail2: FREE( c ); return error; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: DidStartNavigationToPendingEntry(const GURL& url, content::ReloadType reload_type) { devtools_bindings_->frontend_host_.reset( content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, base::Unretained(devtools_bindings_)))); } CWE ID: CWE-200 Target: 1 Example 2: Code: static void deprecatedStaticAttrAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8SetReturnValueInt(info, TestObject::deprecatedStaticAttr()); } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void stroke_loglevel(private_stroke_socket_t *this, stroke_msg_t *msg, FILE *out) { debug_t group; pop_string(msg, &(msg->loglevel.type)); DBG1(DBG_CFG, "received stroke: loglevel %d for %s", msg->loglevel.level, msg->loglevel.type); if (this->prevent_loglevel_changes) { DBG1(DBG_CFG, "prevented log level change"); fprintf(out, "command not allowed!\n"); return; } if (!enum_from_name(debug_names, msg->loglevel.type, &group)) { fprintf(out, "unknown type '%s'!\n", msg->loglevel.type); return; } charon->set_level(charon, group, msg->loglevel.level); } CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: Cluster::Cluster( Segment* pSegment, long idx, long long element_start /* long long element_size */ ) : m_pSegment(pSegment), m_element_start(element_start), m_index(idx), m_pos(element_start), m_element_size(-1 /* element_size */ ), m_timecode(-1), m_entries(NULL), m_entries_size(0), m_entries_count(-1) //means "has not been parsed yet" { } CWE ID: CWE-119 Target: 1 Example 2: Code: void WebContentsImpl::CreateNewWidget(int32_t render_process_id, int32_t route_id, mojom::WidgetPtr widget, blink::WebPopupType popup_type) { CreateNewWidget(render_process_id, route_id, false, std::move(widget), popup_type); } 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 cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void tcp_illinois_info(struct sock *sk, u32 ext, struct sk_buff *skb) { const struct illinois *ca = inet_csk_ca(sk); if (ext & (1 << (INET_DIAG_VEGASINFO - 1))) { struct tcpvegas_info info = { .tcpv_enabled = 1, .tcpv_rttcnt = ca->cnt_rtt, .tcpv_minrtt = ca->base_rtt, }; u64 t = ca->sum_rtt; do_div(t, ca->cnt_rtt); info.tcpv_rtt = t; nla_put(skb, INET_DIAG_VEGASINFO, sizeof(info), &info); } } CWE ID: CWE-189 Target: 1 Example 2: Code: struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid, nodemask_t *nmask) { gfp_t gfp_mask = htlb_alloc_mask(h); spin_lock(&hugetlb_lock); if (h->free_huge_pages - h->resv_huge_pages > 0) { struct page *page; page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask); if (page) { spin_unlock(&hugetlb_lock); return page; } } spin_unlock(&hugetlb_lock); /* No reservations, try to overcommit */ return __alloc_buddy_huge_page(h, gfp_mask, preferred_nid, nmask); } 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: sshpkt_putb(struct ssh *ssh, const struct sshbuf *b) { return sshbuf_putb(ssh->state->outgoing_packet, b); } 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 _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC) { zend_hash_destroy(&pglobals->ht_rc); } CWE ID: CWE-415 Target: 1 Example 2: Code: void TestRenderFrame::SetHTMLOverrideForNextNavigation( const std::string& html) { next_navigation_html_override_ = html; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int flv_write_header(AVFormatContext *s) { int i; AVIOContext *pb = s->pb; FLVContext *flv = s->priv_data; for (i = 0; i < s->nb_streams; i++) { AVCodecParameters *par = s->streams[i]->codecpar; FLVStreamContext *sc; switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: if (s->streams[i]->avg_frame_rate.den && s->streams[i]->avg_frame_rate.num) { flv->framerate = av_q2d(s->streams[i]->avg_frame_rate); } if (flv->video_par) { av_log(s, AV_LOG_ERROR, "at most one video stream is supported in flv\n"); return AVERROR(EINVAL); } flv->video_par = par; if (!ff_codec_get_tag(flv_video_codec_ids, par->codec_id)) return unsupported_codec(s, "Video", par->codec_id); if (par->codec_id == AV_CODEC_ID_MPEG4 || par->codec_id == AV_CODEC_ID_H263) { int error = s->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL; av_log(s, error ? AV_LOG_ERROR : AV_LOG_WARNING, "Codec %s is not supported in the official FLV specification,\n", avcodec_get_name(par->codec_id)); if (error) { av_log(s, AV_LOG_ERROR, "use vstrict=-1 / -strict -1 to use it anyway.\n"); return AVERROR(EINVAL); } } else if (par->codec_id == AV_CODEC_ID_VP6) { av_log(s, AV_LOG_WARNING, "Muxing VP6 in flv will produce flipped video on playback.\n"); } break; case AVMEDIA_TYPE_AUDIO: if (flv->audio_par) { av_log(s, AV_LOG_ERROR, "at most one audio stream is supported in flv\n"); return AVERROR(EINVAL); } flv->audio_par = par; if (get_audio_flags(s, par) < 0) return unsupported_codec(s, "Audio", par->codec_id); if (par->codec_id == AV_CODEC_ID_PCM_S16BE) av_log(s, AV_LOG_WARNING, "16-bit big-endian audio in flv is valid but most likely unplayable (hardware dependent); use s16le\n"); break; case AVMEDIA_TYPE_DATA: if (par->codec_id != AV_CODEC_ID_TEXT && par->codec_id != AV_CODEC_ID_NONE) return unsupported_codec(s, "Data", par->codec_id); flv->data_par = par; break; case AVMEDIA_TYPE_SUBTITLE: if (par->codec_id != AV_CODEC_ID_TEXT) { av_log(s, AV_LOG_ERROR, "Subtitle codec '%s' for stream %d is not compatible with FLV\n", avcodec_get_name(par->codec_id), i); return AVERROR_INVALIDDATA; } flv->data_par = par; break; default: av_log(s, AV_LOG_ERROR, "Codec type '%s' for stream %d is not compatible with FLV\n", av_get_media_type_string(par->codec_type), i); return AVERROR(EINVAL); } avpriv_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */ sc = av_mallocz(sizeof(FLVStreamContext)); if (!sc) return AVERROR(ENOMEM); s->streams[i]->priv_data = sc; sc->last_ts = -1; } flv->delay = AV_NOPTS_VALUE; avio_write(pb, "FLV", 3); avio_w8(pb, 1); avio_w8(pb, FLV_HEADER_FLAG_HASAUDIO * !!flv->audio_par + FLV_HEADER_FLAG_HASVIDEO * !!flv->video_par); avio_wb32(pb, 9); avio_wb32(pb, 0); for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->codecpar->codec_tag == 5) { avio_w8(pb, 8); // message type avio_wb24(pb, 0); // include flags avio_wb24(pb, 0); // time stamp avio_wb32(pb, 0); // reserved avio_wb32(pb, 11); // size flv->reserved = 5; } if (flv->flags & FLV_NO_METADATA) { pb->seekable = 0; } else { write_metadata(s, 0); } for (i = 0; i < s->nb_streams; i++) { flv_write_codec_header(s, s->streams[i]->codecpar, 0); } flv->datastart_offset = avio_tell(pb); return 0; } CWE ID: CWE-617 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: AccessControlStatus ScriptResource::CalculateAccessControlStatus() const { if (GetCORSStatus() == CORSStatus::kServiceWorkerOpaque) return kOpaqueResource; if (IsSameOriginOrCORSSuccessful()) return kSharableCrossOrigin; return kNotSharableCrossOrigin; } CWE ID: CWE-200 Target: 1 Example 2: Code: void PwnMessageHelper::FileSystemWrite(RenderProcessHost* process, int request_id, GURL file_path, std::string blob_uuid, int64_t position) { TestFileapiOperationWaiter waiter( process->GetStoragePartition()->GetFileSystemContext()); IPC::IpcSecurityTestUtil::PwnMessageReceived( process->GetChannel(), FileSystemHostMsg_Write(request_id, file_path, blob_uuid, position)); if (waiter.did_start_update()) waiter.WaitForEndUpdate(); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual ~InlineLoginUIOAuth2Delegate() {} 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 ResourceDispatcherHostImpl::PauseRequest(int child_id, int request_id, bool pause) { GlobalRequestID global_id(child_id, request_id); PendingRequestList::iterator i = pending_requests_.find(global_id); if (i == pending_requests_.end()) { DVLOG(1) << "Pausing a request that wasn't found"; return; } ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(i->second); int pause_count = info->pause_count() + (pause ? 1 : -1); if (pause_count < 0) { NOTREACHED(); // Unbalanced call to pause. return; } info->set_pause_count(pause_count); VLOG(1) << "To pause (" << pause << "): " << i->second->url().spec(); if (info->pause_count() == 0) { MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &ResourceDispatcherHostImpl::ResumeRequest, weak_factory_.GetWeakPtr(), global_id)); } } CWE ID: CWE-119 Target: 1 Example 2: Code: static int parse_username(char *rawuser, struct parsed_mount_info *parsed_info) { char *user, *password, slash; int rc = 0; /* everything after first % sign is a password */ password = strchr(rawuser, '%'); if (password) { rc = set_password(parsed_info, password + 1); if (rc) return rc; *password = '\0'; } /* everything after first '/' or '\' is a username */ user = strchr(rawuser, '/'); if (!user) user = strchr(rawuser, '\\'); /* everything before that slash is a domain */ if (user) { slash = *user; *user = '\0'; strlcpy(parsed_info->domain, rawuser, sizeof(parsed_info->domain)); *(user++) = slash; } else { user = rawuser; } strlcpy(parsed_info->username, user, sizeof(parsed_info->username)); parsed_info->got_user = 1; if (password) *password = '%'; return 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool vma_shareable(struct vm_area_struct *vma, unsigned long addr) { unsigned long base = addr & PUD_MASK; unsigned long end = base + PUD_SIZE; /* * check on proper vm_flags and page table alignment */ if (vma->vm_flags & VM_MAYSHARE && range_in_vma(vma, base, end)) return true; return false; } 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: WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec) { dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm; dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; WORD32 j; UWORD8 u1_buf_mode; struct MMCParams *ps_mmc_params; UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst; ps_slice->u1_mmco_equalto5 = 0; { if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) { ps_slice->u1_no_output_of_prior_pics_flag = ih264d_get_bit_h264(ps_bitstrm); COPYTHECONTEXT("SH: no_output_of_prior_pics_flag", ps_slice->u1_no_output_of_prior_pics_flag); ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264( ps_bitstrm); COPYTHECONTEXT("SH: long_term_reference_flag", ps_slice->u1_long_term_reference_flag); ps_dpb_cmds->u1_idr_pic = 1; ps_dpb_cmds->u1_no_output_of_prior_pics_flag = ps_slice->u1_no_output_of_prior_pics_flag; ps_dpb_cmds->u1_long_term_reference_flag = ps_slice->u1_long_term_reference_flag; } else { u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary COPYTHECONTEXT("SH: adaptive_ref_pic_buffering_flag", u1_buf_mode); ps_dpb_cmds->u1_buf_mode = u1_buf_mode; j = 0; if(u1_buf_mode == 1) { UWORD32 u4_mmco; UWORD32 u4_diff_pic_num; UWORD32 u4_lt_idx, u4_max_lt_idx; u4_mmco = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); while(u4_mmco != END_OF_MMCO) { if (j >= MAX_REF_BUFS) { #ifdef __ANDROID__ ALOGE("b/25818142"); android_errorWriteLog(0x534e4554, "25818142"); #endif ps_dpb_cmds->u1_num_of_commands = 0; return -1; } ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j]; ps_mmc_params->u4_mmco = u4_mmco; switch(u4_mmco) { case MARK_ST_PICNUM_AS_NONREF: u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; break; case MARK_LT_INDEX_AS_NONREF: u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; case MARK_ST_PICNUM_AS_LT_INDEX: u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; case SET_MAX_LT_INDEX: { u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx; break; } case RESET_REF_PICTURES: { ps_slice->u1_mmco_equalto5 = 1; break; } case SET_LT_INDEX: u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); ps_mmc_params->u4_lt_idx = u4_lt_idx; break; default: break; } u4_mmco = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); j++; } ps_dpb_cmds->u1_num_of_commands = j; } } ps_dpb_cmds->u1_dpb_commands_read = 1; ps_dpb_cmds->u1_dpb_commands_read_slc = 1; } u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst; return u4_bit_ofst; } CWE ID: CWE-20 Target: 1 Example 2: Code: acpi_os_install_interrupt_handler(u32 gsi, acpi_osd_handler handler, void *context) { unsigned int irq; acpi_irq_stats_init(); /* * ACPI interrupts different from the SCI in our copy of the FADT are * not supported. */ if (gsi != acpi_gbl_FADT.sci_interrupt) return AE_BAD_PARAMETER; if (acpi_irq_handler) return AE_ALREADY_ACQUIRED; if (acpi_gsi_to_irq(gsi, &irq) < 0) { printk(KERN_ERR PREFIX "SCI (ACPI GSI %d) not registered\n", gsi); return AE_OK; } acpi_irq_handler = handler; acpi_irq_context = context; if (request_irq(irq, acpi_irq, IRQF_SHARED, "acpi", acpi_irq)) { printk(KERN_ERR PREFIX "SCI (IRQ%d) allocation failed\n", irq); acpi_irq_handler = NULL; return AE_NOT_ACQUIRED; } acpi_sci_irq = irq; return AE_OK; } 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 GetURLAndTitleToBookmark(content::WebContents* web_contents, GURL* url, base::string16* title) { *url = GetURLToBookmark(web_contents); *title = web_contents->GetTitle(); } CWE ID: CWE-79 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al) { #ifndef OPENSSL_NO_EC unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; EVP_PKEY *ckey = NULL, *skey = NULL; skey = s->s3->peer_tmp; if (skey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); return 0; } ckey = ssl_generate_pkey(skey); if (ssl_derive(s, ckey, skey) == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB); goto err; } /* Generate encoding of client key */ encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint); if (encoded_pt_len == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB); goto err; } EVP_PKEY_free(ckey); ckey = NULL; *len = encoded_pt_len; /* length of encoded point */ **p = *len; *p += 1; /* copy the point */ memcpy(*p, encodedPoint, *len); /* increment len to account for length field */ *len += 1; OPENSSL_free(encodedPoint); return 1; err: EVP_PKEY_free(ckey); return 0; #else SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); *al = SSL_AD_INTERNAL_ERROR; return 0; #endif } CWE ID: CWE-476 Target: 1 Example 2: Code: SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb, struct io_event __user *, result) { struct kioctx *ctx; struct kiocb *kiocb; u32 key; int ret; ret = get_user(key, &iocb->aio_key); if (unlikely(ret)) return -EFAULT; ctx = lookup_ioctx(ctx_id); if (unlikely(!ctx)) return -EINVAL; spin_lock_irq(&ctx->ctx_lock); kiocb = lookup_kiocb(ctx, iocb, key); if (kiocb) ret = kiocb_cancel(ctx, kiocb); else ret = -EINVAL; spin_unlock_irq(&ctx->ctx_lock); if (!ret) { /* * The result argument is no longer used - the io_event is * always delivered via the ring buffer. -EINPROGRESS indicates * cancellation is progress: */ ret = -EINPROGRESS; } percpu_ref_put(&ctx->users); 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: wait_for_completion_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int x25_negotiate_facilities(struct sk_buff *skb, struct sock *sk, struct x25_facilities *new, struct x25_dte_facilities *dte) { struct x25_sock *x25 = x25_sk(sk); struct x25_facilities *ours = &x25->facilities; struct x25_facilities theirs; int len; memset(&theirs, 0, sizeof(theirs)); memcpy(new, ours, sizeof(*new)); len = x25_parse_facilities(skb, &theirs, dte, &x25->vc_facil_mask); if (len < 0) return len; /* * They want reverse charging, we won't accept it. */ if ((theirs.reverse & 0x01 ) && (ours->reverse & 0x01)) { SOCK_DEBUG(sk, "X.25: rejecting reverse charging request\n"); return -1; } new->reverse = theirs.reverse; if (theirs.throughput) { int theirs_in = theirs.throughput & 0x0f; int theirs_out = theirs.throughput & 0xf0; int ours_in = ours->throughput & 0x0f; int ours_out = ours->throughput & 0xf0; if (!ours_in || theirs_in < ours_in) { SOCK_DEBUG(sk, "X.25: inbound throughput negotiated\n"); new->throughput = (new->throughput & 0xf0) | theirs_in; } if (!ours_out || theirs_out < ours_out) { SOCK_DEBUG(sk, "X.25: outbound throughput negotiated\n"); new->throughput = (new->throughput & 0x0f) | theirs_out; } } if (theirs.pacsize_in && theirs.pacsize_out) { if (theirs.pacsize_in < ours->pacsize_in) { SOCK_DEBUG(sk, "X.25: packet size inwards negotiated down\n"); new->pacsize_in = theirs.pacsize_in; } if (theirs.pacsize_out < ours->pacsize_out) { SOCK_DEBUG(sk, "X.25: packet size outwards negotiated down\n"); new->pacsize_out = theirs.pacsize_out; } } if (theirs.winsize_in && theirs.winsize_out) { if (theirs.winsize_in < ours->winsize_in) { SOCK_DEBUG(sk, "X.25: window size inwards negotiated down\n"); new->winsize_in = theirs.winsize_in; } if (theirs.winsize_out < ours->winsize_out) { SOCK_DEBUG(sk, "X.25: window size outwards negotiated down\n"); new->winsize_out = theirs.winsize_out; } } return len; } CWE ID: CWE-200 Target: 1 Example 2: Code: bool AutofillDialogViews::SectionContainer::OnMousePressed( const ui::MouseEvent& event) { if (!ShouldForwardEvent(event)) return false; return proxy_button_->OnMousePressed(ProxyEvent(event)); } 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: _asn1_get_indefinite_length_string (const unsigned char *der, int der_len, int *len) { int len2, len3, counter, indefinite; int result; unsigned long tag; unsigned char class; counter = indefinite = 0; while (1) { if (HAVE_TWO(der_len) && (der[counter] == 0) && (der[counter + 1] == 0)) { counter += 2; DECR_LEN(der_len, 2); indefinite--; if (indefinite <= 0) break; else continue; } if (asn1_get_tag_der (der + counter, der_len, &class, &len2, &tag) != ASN1_SUCCESS) return ASN1_DER_ERROR; DECR_LEN(der_len, len2); counter += len2; len2 = asn1_get_length_der (der + counter, der_len, &len3); if (len2 < -1) return ASN1_DER_ERROR; if (len2 == -1) { indefinite++; counter += 1; DECR_LEN(der_len, 1); } else { counter += len2 + len3; DECR_LEN(der_len, len2+len3); } } *len = counter; return ASN1_SUCCESS; cleanup: return result; } 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: virtual InputMethodDescriptors* GetSupportedInputMethods() { if (!initialized_successfully_) { InputMethodDescriptors* result = new InputMethodDescriptors; result->push_back(input_method::GetFallbackInputMethodDescriptor()); return result; } return chromeos::GetSupportedInputMethodDescriptors(); } CWE ID: CWE-399 Target: 1 Example 2: Code: void WebMediaPlayerImpl::OnCdmAttached(bool success) { DVLOG(1) << __func__ << ": success = " << success; DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK(pending_cdm_context_ref_); if (success) { media_log_->SetBooleanProperty("has_cdm", true); cdm_context_ref_ = std::move(pending_cdm_context_ref_); if (set_cdm_result_) { set_cdm_result_->Complete(); set_cdm_result_.reset(); } return; } pending_cdm_context_ref_.reset(); if (set_cdm_result_) { set_cdm_result_->CompleteWithError( blink::kWebContentDecryptionModuleExceptionNotSupportedError, 0, "Unable to set ContentDecryptionModule object"); set_cdm_result_.reset(); } } 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 ieee80211_fragment(struct ieee80211_tx_data *tx, struct sk_buff *skb, int hdrlen, int frag_threshold) { struct ieee80211_local *local = tx->local; struct ieee80211_tx_info *info; struct sk_buff *tmp; int per_fragm = frag_threshold - hdrlen - FCS_LEN; int pos = hdrlen + per_fragm; int rem = skb->len - hdrlen - per_fragm; if (WARN_ON(rem < 0)) return -EINVAL; /* first fragment was already added to queue by caller */ while (rem) { int fraglen = per_fragm; if (fraglen > rem) fraglen = rem; rem -= fraglen; tmp = dev_alloc_skb(local->tx_headroom + frag_threshold + tx->sdata->encrypt_headroom + IEEE80211_ENCRYPT_TAILROOM); if (!tmp) return -ENOMEM; __skb_queue_tail(&tx->skbs, tmp); skb_reserve(tmp, local->tx_headroom + tx->sdata->encrypt_headroom); /* copy control information */ memcpy(tmp->cb, skb->cb, sizeof(tmp->cb)); info = IEEE80211_SKB_CB(tmp); info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT | IEEE80211_TX_CTL_FIRST_FRAGMENT); if (rem) info->flags |= IEEE80211_TX_CTL_MORE_FRAMES; skb_copy_queue_mapping(tmp, skb); tmp->priority = skb->priority; tmp->dev = skb->dev; /* copy header and data */ memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen); memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen); pos += fraglen; } /* adjust first fragment's length */ skb->len = hdrlen + per_fragm; return 0; } CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void cp2112_gpio_set(struct gpio_chip *chip, unsigned offset, int value) { struct cp2112_device *dev = gpiochip_get_data(chip); struct hid_device *hdev = dev->hdev; u8 *buf = dev->in_out_buffer; unsigned long flags; int ret; spin_lock_irqsave(&dev->lock, flags); buf[0] = CP2112_GPIO_SET; buf[1] = value ? 0xff : 0; buf[2] = 1 << offset; ret = hid_hw_raw_request(hdev, CP2112_GPIO_SET, buf, CP2112_GPIO_SET_LENGTH, HID_FEATURE_REPORT, HID_REQ_SET_REPORT); if (ret < 0) hid_err(hdev, "error setting GPIO values: %d\n", ret); spin_unlock_irqrestore(&dev->lock, flags); } CWE ID: CWE-404 Target: 1 Example 2: Code: struct domain_device *sas_find_dev_by_rphy(struct sas_rphy *rphy) { struct Scsi_Host *shost = dev_to_shost(rphy->dev.parent); struct sas_ha_struct *ha = SHOST_TO_SAS_HA(shost); struct domain_device *found_dev = NULL; int i; unsigned long flags; spin_lock_irqsave(&ha->phy_port_lock, flags); for (i = 0; i < ha->num_phys; i++) { struct asd_sas_port *port = ha->sas_port[i]; struct domain_device *dev; spin_lock(&port->dev_list_lock); list_for_each_entry(dev, &port->dev_list, dev_list_node) { if (rphy == dev->rphy) { found_dev = dev; spin_unlock(&port->dev_list_lock); goto found; } } spin_unlock(&port->dev_list_lock); } found: spin_unlock_irqrestore(&ha->phy_port_lock, flags); return found_dev; } 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: telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print) { int i, x; u_int c; const u_char *osp, *p; #define FETCH(c, sp, length) \ do { \ if (length < 1) \ goto pktend; \ ND_TCHECK(*sp); \ c = *sp++; \ length--; \ } while (0) osp = sp; FETCH(c, sp, length); if (c != IAC) goto pktend; FETCH(c, sp, length); if (c == IAC) { /* <IAC><IAC>! */ if (print) ND_PRINT((ndo, "IAC IAC")); goto done; } i = c - TELCMD_FIRST; if (i < 0 || i > IAC - TELCMD_FIRST) goto pktend; switch (c) { case DONT: case DO: case WONT: case WILL: case SB: /* DONT/DO/WONT/WILL x */ FETCH(x, sp, length); if (x >= 0 && x < NTELOPTS) { if (print) ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x])); } else { if (print) ND_PRINT((ndo, "%s %#x", telcmds[i], x)); } if (c != SB) break; /* IAC SB .... IAC SE */ p = sp; while (length > (u_int)(p + 1 - sp)) { ND_TCHECK2(*p, 2); if (p[0] == IAC && p[1] == SE) break; p++; } if (*p != IAC) goto pktend; switch (x) { case TELOPT_AUTHENTICATION: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd))); if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype))); break; case TELOPT_ENCRYPT: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd))); if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype))); break; default: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds))); break; } while (p > sp) { FETCH(x, sp, length); if (print) ND_PRINT((ndo, " %#x", x)); } /* terminating IAC SE */ if (print) ND_PRINT((ndo, " SE")); sp += 2; break; default: if (print) ND_PRINT((ndo, "%s", telcmds[i])); goto done; } done: return sp - osp; trunc: ND_PRINT((ndo, "%s", tstr)); pktend: return -1; #undef FETCH } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool IsAllowed(const scoped_refptr<const Extension>& extension, const GURL& url, PermittedFeature feature, int tab_id) { const PermissionsData* permissions_data = extension->permissions_data(); bool script = permissions_data->CanAccessPage(extension.get(), url, tab_id, nullptr) && permissions_data->CanRunContentScriptOnPage( extension.get(), url, tab_id, nullptr); bool capture = HasTabsPermission(extension, tab_id) && permissions_data->CanCaptureVisiblePage(tab_id, NULL); switch (feature) { case PERMITTED_SCRIPT_ONLY: return script && !capture; case PERMITTED_CAPTURE_ONLY: return capture && !script; case PERMITTED_BOTH: return script && capture; case PERMITTED_NONE: return !script && !capture; } NOTREACHED(); return false; } CWE ID: CWE-20 Target: 1 Example 2: Code: void EditorClientBlackBerry::showSpellingUI(bool) { notImplemented(); } 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 ExternalProtocolHandler::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(prefs::kExcludedSchemes); } 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 struct page *alloc_huge_page(struct vm_area_struct *vma, unsigned long addr, int avoid_reserve) { struct hstate *h = hstate_vma(vma); struct page *page; struct address_space *mapping = vma->vm_file->f_mapping; struct inode *inode = mapping->host; long chg; /* * Processes that did not create the mapping will have no reserves and * will not have accounted against quota. Check that the quota can be * made before satisfying the allocation * MAP_NORESERVE mappings may also need pages and quota allocated * if no reserve mapping overlaps. */ chg = vma_needs_reservation(h, vma, addr); if (chg < 0) return ERR_PTR(-VM_FAULT_OOM); if (chg) if (hugetlb_get_quota(inode->i_mapping, chg)) return ERR_PTR(-VM_FAULT_SIGBUS); spin_lock(&hugetlb_lock); page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve); spin_unlock(&hugetlb_lock); if (!page) { page = alloc_buddy_huge_page(h, NUMA_NO_NODE); if (!page) { hugetlb_put_quota(inode->i_mapping, chg); return ERR_PTR(-VM_FAULT_SIGBUS); } } set_page_private(page, (unsigned long) mapping); vma_commit_reservation(h, vma, addr); return page; } CWE ID: CWE-399 Target: 1 Example 2: Code: static void intel_pmu_cpu_dying(int cpu) { struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu); struct intel_percore *pc = cpuc->per_core; if (pc) { if (pc->core_id == -1 || --pc->refcnt == 0) kfree(pc); cpuc->per_core = NULL; } fini_debug_store_on_cpu(cpu); } 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: BooleanHistogram::BooleanHistogram(const std::string& name, const BucketRanges* ranges) : LinearHistogram(name, 1, 2, ranges) {} 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: void StorageHandler::ClearDataForOrigin( const std::string& origin, const std::string& storage_types, std::unique_ptr<ClearDataForOriginCallback> callback) { if (!process_) return callback->sendFailure(Response::InternalError()); StoragePartition* partition = process_->GetStoragePartition(); std::vector<std::string> types = base::SplitString( storage_types, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); std::unordered_set<std::string> set(types.begin(), types.end()); uint32_t remove_mask = 0; if (set.count(Storage::StorageTypeEnum::Appcache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_APPCACHE; if (set.count(Storage::StorageTypeEnum::Cookies)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES; if (set.count(Storage::StorageTypeEnum::File_systems)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS; if (set.count(Storage::StorageTypeEnum::Indexeddb)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB; if (set.count(Storage::StorageTypeEnum::Local_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE; if (set.count(Storage::StorageTypeEnum::Shader_cache)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE; if (set.count(Storage::StorageTypeEnum::Websql)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL; if (set.count(Storage::StorageTypeEnum::Service_workers)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS; if (set.count(Storage::StorageTypeEnum::Cache_storage)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE; if (set.count(Storage::StorageTypeEnum::All)) remove_mask |= StoragePartition::REMOVE_DATA_MASK_ALL; if (!remove_mask) { return callback->sendFailure( Response::InvalidParams("No valid storage type specified")); } partition->ClearData(remove_mask, StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(origin), StoragePartition::OriginMatcherFunction(), base::Time(), base::Time::Max(), base::BindOnce(&ClearDataForOriginCallback::sendSuccess, std::move(callback))); } CWE ID: CWE-20 Target: 1 Example 2: Code: std::unique_ptr<BlobDataHandle> BlobStorageContext::AddFinishedBlob( const BlobDataBuilder& external_builder) { TRACE_EVENT0("Blob", "Context::AddFinishedBlob"); return BuildBlob(external_builder, TransportAllowedCallback()); } 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: OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) { if (buffer == 0) { return NULL; } Mutex::Autolock autoLock(mBufferIDLock); ssize_t index = mBufferIDToBufferHeader.indexOfKey(buffer); if (index < 0) { CLOGW("findBufferHeader: buffer %u not found", buffer); return NULL; } return mBufferIDToBufferHeader.valueAt(index); } 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: RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "OnDocumentElementCreated", base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated, base::Unretained(this))); } CWE ID: Target: 1 Example 2: Code: static void sd_print_sense_hdr(struct scsi_disk *sdkp, struct scsi_sense_hdr *sshdr) { sd_printk(KERN_INFO, sdkp, " "); scsi_show_sense_hdr(sshdr); sd_printk(KERN_INFO, sdkp, " "); scsi_show_extd_sense(sshdr->asc, sshdr->ascq); } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int prctl_set_mm(int opt, unsigned long addr, unsigned long arg4, unsigned long arg5) { unsigned long rlim = rlimit(RLIMIT_DATA); unsigned long vm_req_flags; unsigned long vm_bad_flags; struct vm_area_struct *vma; int error = 0; struct mm_struct *mm = current->mm; if (arg4 | arg5) return -EINVAL; if (!capable(CAP_SYS_RESOURCE)) return -EPERM; if (addr >= TASK_SIZE) return -EINVAL; down_read(&mm->mmap_sem); vma = find_vma(mm, addr); if (opt != PR_SET_MM_START_BRK && opt != PR_SET_MM_BRK) { /* It must be existing VMA */ if (!vma || vma->vm_start > addr) goto out; } error = -EINVAL; switch (opt) { case PR_SET_MM_START_CODE: case PR_SET_MM_END_CODE: vm_req_flags = VM_READ | VM_EXEC; vm_bad_flags = VM_WRITE | VM_MAYSHARE; if ((vma->vm_flags & vm_req_flags) != vm_req_flags || (vma->vm_flags & vm_bad_flags)) goto out; if (opt == PR_SET_MM_START_CODE) mm->start_code = addr; else mm->end_code = addr; break; case PR_SET_MM_START_DATA: case PR_SET_MM_END_DATA: vm_req_flags = VM_READ | VM_WRITE; vm_bad_flags = VM_EXEC | VM_MAYSHARE; if ((vma->vm_flags & vm_req_flags) != vm_req_flags || (vma->vm_flags & vm_bad_flags)) goto out; if (opt == PR_SET_MM_START_DATA) mm->start_data = addr; else mm->end_data = addr; break; case PR_SET_MM_START_STACK: #ifdef CONFIG_STACK_GROWSUP vm_req_flags = VM_READ | VM_WRITE | VM_GROWSUP; #else vm_req_flags = VM_READ | VM_WRITE | VM_GROWSDOWN; #endif if ((vma->vm_flags & vm_req_flags) != vm_req_flags) goto out; mm->start_stack = addr; break; case PR_SET_MM_START_BRK: if (addr <= mm->end_data) goto out; if (rlim < RLIM_INFINITY && (mm->brk - addr) + (mm->end_data - mm->start_data) > rlim) goto out; mm->start_brk = addr; break; case PR_SET_MM_BRK: if (addr <= mm->end_data) goto out; if (rlim < RLIM_INFINITY && (addr - mm->start_brk) + (mm->end_data - mm->start_data) > rlim) goto out; mm->brk = addr; break; default: error = -EINVAL; goto out; } error = 0; out: up_read(&mm->mmap_sem); return error; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xsltCopyOf(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemCopyOfPtr comp = (xsltStyleItemCopyOfPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xmlXPathObjectPtr res = NULL; xmlNodeSetPtr list = NULL; int i; xmlDocPtr oldXPContextDoc; xmlNsPtr *oldXPNamespaces; xmlNodePtr oldXPContextNode; int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; xmlXPathContextPtr xpctxt; if ((ctxt == NULL) || (node == NULL) || (inst == NULL)) return; if ((comp == NULL) || (comp->select == NULL) || (comp->comp == NULL)) { xsltTransformError(ctxt, NULL, inst, "xsl:copy-of : compilation failed\n"); return; } /* * SPEC XSLT 1.0: * "The xsl:copy-of element can be used to insert a result tree * fragment into the result tree, without first converting it to * a string as xsl:value-of does (see [7.6.1 Generating Text with * xsl:value-of]). The required select attribute contains an * expression. When the result of evaluating the expression is a * result tree fragment, the complete fragment is copied into the * result tree. When the result is a node-set, all the nodes in the * set are copied in document order into the result tree; copying * an element node copies the attribute nodes, namespace nodes and * children of the element node as well as the element node itself; * a root node is copied by copying its children. When the result * is neither a node-set nor a result tree fragment, the result is * converted to a string and then inserted into the result tree, * as with xsl:value-of. */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: select %s\n", comp->select)); #endif /* * Evaluate the "select" expression. */ xpctxt = ctxt->xpathCtxt; oldXPContextDoc = xpctxt->doc; oldXPContextNode = xpctxt->node; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; oldXPNsNr = xpctxt->nsNr; oldXPNamespaces = xpctxt->namespaces; xpctxt->node = node; if (comp != NULL) { #ifdef XSLT_REFACTORED if (comp->inScopeNs != NULL) { xpctxt->namespaces = comp->inScopeNs->list; xpctxt->nsNr = comp->inScopeNs->xpathNumber; } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } #else xpctxt->namespaces = comp->nsList; xpctxt->nsNr = comp->nsNr; #endif } else { xpctxt->namespaces = NULL; xpctxt->nsNr = 0; } res = xmlXPathCompiledEval(comp->comp, xpctxt); xpctxt->doc = oldXPContextDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->nsNr = oldXPNsNr; xpctxt->namespaces = oldXPNamespaces; if (res != NULL) { if (res->type == XPATH_NODESET) { /* * Node-set * -------- */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result is a node set\n")); #endif list = res->nodesetval; if (list != NULL) { xmlNodePtr cur; /* * The list is already sorted in document order by XPath. * Append everything in this order under ctxt->insert. */ for (i = 0;i < list->nodeNr;i++) { cur = list->nodeTab[i]; if (cur == NULL) continue; if ((cur->type == XML_DOCUMENT_NODE) || (cur->type == XML_HTML_DOCUMENT_NODE)) { xsltCopyTreeList(ctxt, inst, cur->children, ctxt->insert, 0, 0); } else if (cur->type == XML_ATTRIBUTE_NODE) { xsltShallowCopyAttr(ctxt, inst, ctxt->insert, (xmlAttrPtr) cur); } else { xsltCopyTreeInternal(ctxt, inst, cur, ctxt->insert, 0, 0); } } } } else if (res->type == XPATH_XSLT_TREE) { /* * Result tree fragment * -------------------- * E.g. via <xsl:variable ...><foo/></xsl:variable> * Note that the root node of such trees is an xmlDocPtr in Libxslt. */ #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result is a result tree fragment\n")); #endif list = res->nodesetval; if ((list != NULL) && (list->nodeTab != NULL) && (list->nodeTab[0] != NULL) && (IS_XSLT_REAL_NODE(list->nodeTab[0]))) { xsltCopyTreeList(ctxt, inst, list->nodeTab[0]->children, ctxt->insert, 0, 0); } } else { xmlChar *value = NULL; /* * Convert to a string. */ value = xmlXPathCastToString(res); if (value == NULL) { xsltTransformError(ctxt, NULL, inst, "Internal error in xsltCopyOf(): " "failed to cast an XPath object to string.\n"); ctxt->state = XSLT_STATE_STOPPED; } else { if (value[0] != 0) { /* * Append content as text node. */ xsltCopyTextString(ctxt, ctxt->insert, value, 0); } xmlFree(value); #ifdef WITH_XSLT_DEBUG_PROCESS XSLT_TRACE(ctxt,XSLT_TRACE_COPY_OF,xsltGenericDebug(xsltGenericDebugContext, "xsltCopyOf: result %s\n", res->stringval)); #endif } } } else { ctxt->state = XSLT_STATE_STOPPED; } if (res != NULL) xmlXPathFreeObject(res); } CWE ID: CWE-119 Target: 1 Example 2: Code: bool Extension::ParsePermissions(const char* key, string16* error, APIPermissionSet* api_permissions, URLPatternSet* host_permissions) { if (manifest_->HasKey(key)) { ListValue* permissions = NULL; if (!manifest_->GetList(key, &permissions)) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidPermissions, ""); return false; } std::vector<std::string> host_data; if (!APIPermissionSet::ParseFromJSON(permissions, api_permissions, error, &host_data)) return false; std::vector<APIPermission::ID> to_remove; FeatureProvider* permission_features = BaseFeatureProvider::GetPermissionFeatures(); for (APIPermissionSet::const_iterator it = api_permissions->begin(); it != api_permissions->end(); ++it) { extensions::Feature* feature = permission_features->GetFeature(it->name()); CHECK(feature); Feature::Availability availability = feature->IsAvailableToManifest( id(), GetType(), Feature::ConvertLocation(location()), manifest_version()); if (!availability.is_available()) { install_warnings_.push_back(InstallWarning(InstallWarning::FORMAT_TEXT, availability.message())); to_remove.push_back(it->id()); continue; } if (it->id() == APIPermission::kExperimental) { if (!CanSpecifyExperimentalPermission()) { *error = ASCIIToUTF16(errors::kExperimentalFlagRequired); return false; } } } for (std::vector<APIPermission::ID>::const_iterator it = to_remove.begin(); it != to_remove.end(); ++it) { api_permissions->erase(*it); } const int kAllowedSchemes = CanExecuteScriptEverywhere() ? URLPattern::SCHEME_ALL : kValidHostPermissionSchemes; for (std::vector<std::string>::const_iterator it = host_data.begin(); it != host_data.end(); ++it) { const std::string& permission_str = *it; URLPattern pattern = URLPattern(kAllowedSchemes); URLPattern::ParseResult parse_result = pattern.Parse(permission_str); if (parse_result == URLPattern::PARSE_SUCCESS) { if (!CanSpecifyHostPermission(pattern, *api_permissions)) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidPermissionScheme, permission_str); return false; } pattern.SetPath("/*"); if (pattern.MatchesScheme(chrome::kFileScheme) && !CanExecuteScriptEverywhere()) { wants_file_access_ = true; if (!(creation_flags_ & ALLOW_FILE_ACCESS)) { pattern.SetValidSchemes( pattern.valid_schemes() & ~URLPattern::SCHEME_FILE); } } host_permissions->AddPattern(pattern); continue; } install_warnings_.push_back(InstallWarning( InstallWarning::FORMAT_TEXT, base::StringPrintf( "Permission '%s' is unknown or URL pattern is malformed.", permission_str.c_str()))); } } return true; } CWE ID: CWE-264 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from, int offset, size_t count) { int len = iov_length(from, count) - offset; int copy = skb_headlen(skb); int size, offset1 = 0; int i = 0; /* Skip over from offset */ while (count && (offset >= from->iov_len)) { offset -= from->iov_len; ++from; --count; } /* copy up to skb headlen */ while (count && (copy > 0)) { size = min_t(unsigned int, copy, from->iov_len - offset); if (copy_from_user(skb->data + offset1, from->iov_base + offset, size)) return -EFAULT; if (copy > size) { ++from; --count; offset = 0; } else offset += size; copy -= size; offset1 += size; } if (len == offset1) return 0; while (count--) { struct page *page[MAX_SKB_FRAGS]; int num_pages; unsigned long base; unsigned long truesize; len = from->iov_len - offset; if (!len) { offset = 0; ++from; continue; } base = (unsigned long)from->iov_base + offset; size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT; num_pages = get_user_pages_fast(base, size, 0, &page[i]); if ((num_pages != size) || (num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags)) { for (i = 0; i < num_pages; i++) put_page(page[i]); return -EFAULT; } truesize = size * PAGE_SIZE; skb->data_len += len; skb->len += len; skb->truesize += truesize; atomic_add(truesize, &skb->sk->sk_wmem_alloc); while (len) { int off = base & ~PAGE_MASK; int size = min_t(int, len, PAGE_SIZE - off); __skb_fill_page_desc(skb, i, page[i], off, size); skb_shinfo(skb)->nr_frags++; /* increase sk_wmem_alloc */ base += size; len -= size; i++; } offset = 0; ++from; } return 0; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: header_put_byte (SF_PRIVATE *psf, char x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 1) psf->header [psf->headindex++] = x ; } /* header_put_byte */ CWE ID: CWE-119 Target: 1 Example 2: Code: xdr_mpol_arg(XDR *xdrs, mpol_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!_xdr_kadm5_policy_ent_rec(xdrs, &objp->rec, objp->api_version)) { return (FALSE); } if (!xdr_long(xdrs, &objp->mask)) { return (FALSE); } return (TRUE); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int use_append( const char * /* method */, const char *path ) { return attr_list_has_file( ATTR_APPEND_FILES, path ); } CWE ID: CWE-134 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit = -1, rightLimit; int i, restoreAlphaBlending = 0; if (border < 0) { /* Refuse to fill to a non-solid border */ return; } if (!im->trueColor) { if ((color > (im->colorsTotal - 1)) || (border > (im->colorsTotal - 1)) || (color < 0)) { return; } } restoreAlphaBlending = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (x >= im->sx) { x = im->sx - 1; } else if (x < 0) { x = 0; } if (y >= im->sy) { y = im->sy - 1; } else if (y < 0) { y = 0; } for (i = x; i >= 0; i--) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); leftLimit = i; } if (leftLimit == -1) { im->alphaBlendingFlag = restoreAlphaBlending; return; } /* Seek right */ rightLimit = x; for (i = (x + 1); i < im->sx; i++) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } im->alphaBlendingFlag = restoreAlphaBlending; } CWE ID: CWE-119 Target: 1 Example 2: Code: void ImageLoader::imageNotifyFinished(ImageResourceContent* resource) { RESOURCE_LOADING_DVLOG(1) << "ImageLoader::imageNotifyFinished " << this << "; m_hasPendingLoadEvent=" << m_hasPendingLoadEvent; DCHECK(m_failedLoadURL.isEmpty()); DCHECK_EQ(resource, m_image.get()); m_imageComplete = true; if (m_image) m_image->updateImageAnimationPolicy(); updateLayoutObject(); if (m_image && m_image->getImage() && m_image->getImage()->isSVGImage()) toSVGImage(m_image->getImage())->updateUseCounters(element()->document()); if (!m_hasPendingLoadEvent) return; if (resource->errorOccurred()) { loadEventSender().cancelEvent(this); m_hasPendingLoadEvent = false; if (resource->resourceError().isAccessCheck()) { crossSiteOrCSPViolationOccurred( AtomicString(resource->resourceError().failingURL())); } if (!m_suppressErrorEvents) dispatchErrorEvent(); updatedHasPendingEvent(); return; } loadEventSender().dispatchEventSoon(this); } 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: le64addr_string(netdissect_options *ndo, const u_char *ep) { const unsigned int len = 8; register u_int i; register char *cp; register struct enamemem *tp; char buf[BUFSIZE]; tp = lookup_bytestring(ndo, ep, len); if (tp->e_name) return (tp->e_name); cp = buf; for (i = len; i > 0 ; --i) { *cp++ = hex[*(ep + i - 1) >> 4]; *cp++ = hex[*(ep + i - 1) & 0xf]; *cp++ = ':'; } cp --; *cp = '\0'; tp->e_name = strdup(buf); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "le64addr_string: strdup(buf)"); return (tp->e_name); } CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DisconnectWindowLinux::Show(remoting::ChromotingHost* host, const std::string& username) { NOTIMPLEMENTED(); } CWE ID: CWE-399 Target: 1 Example 2: Code: Tags::Tags(Segment* pSegment, long long payload_start, long long payload_size, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(payload_start), m_size(payload_size), m_element_start(element_start), m_element_size(element_size), m_tags(NULL), m_tags_size(0), m_tags_count(0) {} CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool retry_instruction(struct x86_emulate_ctxt *ctxt, unsigned long cr2, int emulation_type) { struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt); unsigned long last_retry_eip, last_retry_addr, gpa = cr2; last_retry_eip = vcpu->arch.last_retry_eip; last_retry_addr = vcpu->arch.last_retry_addr; /* * If the emulation is caused by #PF and it is non-page_table * writing instruction, it means the VM-EXIT is caused by shadow * page protected, we can zap the shadow page and retry this * instruction directly. * * Note: if the guest uses a non-page-table modifying instruction * on the PDE that points to the instruction, then we will unmap * the instruction and go to an infinite loop. So, we cache the * last retried eip and the last fault address, if we meet the eip * and the address again, we can break out of the potential infinite * loop. */ vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0; if (!(emulation_type & EMULTYPE_RETRY)) return false; if (x86_page_table_writing_insn(ctxt)) return false; if (ctxt->eip == last_retry_eip && last_retry_addr == cr2) return false; vcpu->arch.last_retry_eip = ctxt->eip; vcpu->arch.last_retry_addr = cr2; if (!vcpu->arch.mmu.direct_map) gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL); kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa)); return true; } CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: NeXTDecode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s) { static const char module[] = "NeXTDecode"; unsigned char *bp, *op; tmsize_t cc; uint8* row; tmsize_t scanline, n; (void) s; /* * Each scanline is assumed to start off as all * white (we assume a PhotometricInterpretation * of ``min-is-black''). */ for (op = (unsigned char*) buf, cc = occ; cc-- > 0;) *op++ = 0xff; bp = (unsigned char *)tif->tif_rawcp; cc = tif->tif_rawcc; scanline = tif->tif_scanlinesize; if (occ % scanline) { TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read"); return (0); } for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) { n = *bp++, cc--; switch (n) { case LITERALROW: /* * The entire scanline is given as literal values. */ if (cc < scanline) goto bad; _TIFFmemcpy(row, bp, scanline); bp += scanline; cc -= scanline; break; case LITERALSPAN: { tmsize_t off; /* * The scanline has a literal span that begins at some * offset. */ if( cc < 4 ) goto bad; off = (bp[0] * 256) + bp[1]; n = (bp[2] * 256) + bp[3]; if (cc < 4+n || off+n > scanline) goto bad; _TIFFmemcpy(row+off, bp+4, n); bp += 4+n; cc -= 4+n; break; } default: { uint32 npixels = 0, grey; uint32 imagewidth = tif->tif_dir.td_imagewidth; if( isTiled(tif) ) imagewidth = tif->tif_dir.td_tilewidth; /* * The scanline is composed of a sequence of constant * color ``runs''. We shift into ``run mode'' and * interpret bytes as codes of the form * <color><npixels> until we've filled the scanline. */ op = row; for (;;) { grey = (uint32)((n>>6) & 0x3); n &= 0x3f; /* * Ensure the run does not exceed the scanline * bounds, potentially resulting in a security * issue. */ while (n-- > 0 && npixels < imagewidth) SETPIXEL(op, grey); if (npixels >= imagewidth) break; if (cc == 0) goto bad; n = *bp++, cc--; } break; } } } tif->tif_rawcp = (uint8*) bp; tif->tif_rawcc = cc; return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "Not enough data for scanline %ld", (long) tif->tif_row); return (0); } CWE ID: CWE-119 Target: 1 Example 2: Code: smb_ofile_getcred(smb_ofile_t *of) { return (of->f_cr); } 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: horizontalDifference8(unsigned char *ip, int n, int stride, unsigned short *wp, uint16 *From8) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; #undef CLAMP #define CLAMP(v) (From8[(v)]) mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1; wp += 3; ip += 3; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1; wp += 4; ip += 4; } } else { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } } 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: int ip6_mroute_getsockopt(struct sock *sk, int optname, char __user *optval, int __user *optlen) { int olr; int val; struct net *net = sock_net(sk); struct mr6_table *mrt; mrt = ip6mr_get_table(net, raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); if (!mrt) return -ENOENT; switch (optname) { case MRT6_VERSION: val = 0x0305; break; #ifdef CONFIG_IPV6_PIMSM_V2 case MRT6_PIM: val = mrt->mroute_do_pim; break; #endif case MRT6_ASSERT: val = mrt->mroute_do_assert; break; default: return -ENOPROTOOPT; } if (get_user(olr, optlen)) return -EFAULT; olr = min_t(int, olr, sizeof(int)); if (olr < 0) return -EINVAL; if (put_user(olr, optlen)) return -EFAULT; if (copy_to_user(optval, &val, olr)) return -EFAULT; return 0; } CWE ID: CWE-20 Target: 1 Example 2: Code: gfx::Size BrowserView::GetResizeCornerSize() const { return ResizeCorner::GetSize(); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int pfkey_send_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = x ? xs_net(x) : c->net; struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); if (atomic_read(&net_pfkey->socks_nr) == 0) return 0; switch (c->event) { case XFRM_MSG_EXPIRE: return key_notify_sa_expire(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_NEWSA: case XFRM_MSG_UPDSA: return key_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return key_notify_sa_flush(c); case XFRM_MSG_NEWAE: /* not yet supported */ break; default: pr_err("pfkey: Unknown SA event %d\n", c->event); break; } return 0; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct usb_serial_port *wport; wport = serial->port[1]; tty_port_tty_set(&wport->port, tty); return usb_serial_generic_open(tty, port); } CWE ID: CWE-404 Target: 1 Example 2: Code: bool ExtensionApiTest::StartWebSocketServer( const base::FilePath& root_directory, bool enable_basic_auth) { websocket_server_.reset(new net::SpawnedTestServer( net::SpawnedTestServer::TYPE_WS, root_directory)); websocket_server_->set_websocket_basic_auth(enable_basic_auth); if (!websocket_server_->Start()) return false; test_config_->SetInteger(kTestWebSocketPort, websocket_server_->host_port_pair().port()); return true; } CWE ID: CWE-200 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: BufferMeta(size_t size) : mSize(size), mIsBackup(false) { } 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: dhcpv6_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint16_t type, optlen; i = 0; while (i < length) { tlv = cp + i; type = EXTRACT_16BITS(tlv); optlen = EXTRACT_16BITS(tlv + 2); value = tlv + 4; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 4 )); switch (type) { case DH6OPT_DNS_SERVERS: case DH6OPT_SNTP_SERVERS: { if (optlen % 16 != 0) { ND_PRINT((ndo, " %s", istr)); return -1; } for (t = 0; t < optlen; t += 16) ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t))); } break; case DH6OPT_DOMAIN_LIST: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 4 + optlen; } return 0; } CWE ID: CWE-125 Target: 1 Example 2: Code: ExtensionNavigationThrottle::~ExtensionNavigationThrottle() {} 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: ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg, int /* flags */) { if (msg->iov_length != 1) return -1; msg->ndesc_length = 0; // Messages with descriptors aren't supported yet. return static_cast<ssize_t>( ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base), msg->iov[0].length)); } 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 sk_sp<SkImage> flipSkImageVertically(SkImage* input, AlphaDisposition alphaOp) { size_t width = static_cast<size_t>(input->width()); size_t height = static_cast<size_t>(input->height()); SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(), (alphaOp == PremultiplyAlpha) ? kPremul_SkAlphaType : kUnpremul_SkAlphaType); size_t imageRowBytes = width * info.bytesPerPixel(); RefPtr<Uint8Array> imagePixels = copySkImageData(input, info); if (!imagePixels) return nullptr; for (size_t i = 0; i < height / 2; i++) { size_t topFirstElement = i * imageRowBytes; size_t topLastElement = (i + 1) * imageRowBytes; size_t bottomFirstElement = (height - 1 - i) * imageRowBytes; std::swap_ranges(imagePixels->data() + topFirstElement, imagePixels->data() + topLastElement, imagePixels->data() + bottomFirstElement); } return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes); } CWE ID: CWE-787 Target: 1 Example 2: Code: static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data) { u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges; if (!mtrr_valid(vcpu, msr, data)) return 1; if (msr == MSR_MTRRdefType) { vcpu->arch.mtrr_state.def_type = data; vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10; } else if (msr == MSR_MTRRfix64K_00000) p[0] = data; else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000) p[1 + msr - MSR_MTRRfix16K_80000] = data; else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000) p[3 + msr - MSR_MTRRfix4K_C0000] = data; else if (msr == MSR_IA32_CR_PAT) vcpu->arch.pat = data; else { /* Variable MTRRs */ int idx, is_mtrr_mask; u64 *pt; idx = (msr - 0x200) / 2; is_mtrr_mask = msr - 0x200 - 2 * idx; if (!is_mtrr_mask) pt = (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo; else pt = (u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo; *pt = data; } kvm_mmu_reset_context(vcpu); return 0; } CWE ID: CWE-399 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void perf_event_exit_task_context(struct task_struct *child, int ctxn) { struct perf_event *child_event, *tmp; struct perf_event_context *child_ctx; unsigned long flags; if (likely(!child->perf_event_ctxp[ctxn])) { perf_event_task(child, NULL, 0); return; } local_irq_save(flags); /* * We can't reschedule here because interrupts are disabled, * and either child is current or it is a task that can't be * scheduled, so we are now safe from rescheduling changing * our context. */ child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]); /* * Take the context lock here so that if find_get_context is * reading child->perf_event_ctxp, we wait until it has * incremented the context's refcount before we do put_ctx below. */ raw_spin_lock(&child_ctx->lock); task_ctx_sched_out(child_ctx); child->perf_event_ctxp[ctxn] = NULL; /* * If this context is a clone; unclone it so it can't get * swapped to another process while we're removing all * the events from it. */ unclone_ctx(child_ctx); update_context_time(child_ctx); raw_spin_unlock_irqrestore(&child_ctx->lock, flags); /* * Report the task dead after unscheduling the events so that we * won't get any samples after PERF_RECORD_EXIT. We can however still * get a few PERF_RECORD_READ events. */ perf_event_task(child, child_ctx, 0); /* * We can recurse on the same lock type through: * * __perf_event_exit_task() * sync_child_event() * fput(parent_event->filp) * perf_release() * mutex_lock(&ctx->mutex) * * But since its the parent context it won't be the same instance. */ mutex_lock(&child_ctx->mutex); again: list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups, group_entry) __perf_event_exit_task(child_event, child_ctx, child); list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups, group_entry) __perf_event_exit_task(child_event, child_ctx, child); /* * If the last event was a group event, it will have appended all * its siblings to the list, but we obtained 'tmp' before that which * will still point to the list head terminating the iteration. */ if (!list_empty(&child_ctx->pinned_groups) || !list_empty(&child_ctx->flexible_groups)) goto again; mutex_unlock(&child_ctx->mutex); put_ctx(child_ctx); } CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ChromotingInstance::Init(uint32_t argc, const char* argn[], const char* argv[]) { CHECK(!initialized_); initialized_ = true; VLOG(1) << "Started ChromotingInstance::Init"; if (!media::IsMediaLibraryInitialized()) { LOG(ERROR) << "Media library not initialized."; return false; } net::EnableSSLServerSockets(); context_.Start(); scoped_refptr<FrameConsumerProxy> consumer_proxy = new FrameConsumerProxy(plugin_task_runner_); rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(), context_.decode_task_runner(), consumer_proxy); view_.reset(new PepperView(this, &context_, rectangle_decoder_.get())); consumer_proxy->Attach(view_->AsWeakPtr()); return true; } CWE ID: Target: 1 Example 2: Code: char *rds_ib_wc_status_str(enum ib_wc_status status) { return rds_str_array(rds_ib_wc_status_strings, ARRAY_SIZE(rds_ib_wc_status_strings), status); } CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void gx_ttfReader__Read(ttfReader *self, void *p, int n) { gx_ttfReader *r = (gx_ttfReader *)self; const byte *q; if (!r->error) { if (r->extra_glyph_index != -1) { q = r->glyph_data.bits.data + r->pos; r->error = (r->glyph_data.bits.size - r->pos < n ? gs_note_error(gs_error_invalidfont) : 0); if (r->error == 0) memcpy(p, q, n); unsigned int cnt; for (cnt = 0; cnt < (uint)n; cnt += r->error) { r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q); if (r->error < 0) break; else if ( r->error == 0) { memcpy((char *)p + cnt, q, n - cnt); break; } else { memcpy((char *)p + cnt, q, r->error); } } } } if (r->error) { memset(p, 0, n); return; } r->pos += n; } 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 void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp) { ns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT; shm_rmid(ns, shp); shm_unlock(shp); if (!is_file_hugepages(shp->shm_file)) shmem_lock(shp->shm_file, 0, shp->mlock_user); else if (shp->mlock_user) user_shm_unlock(file_inode(shp->shm_file)->i_size, shp->mlock_user); fput (shp->shm_file); ipc_rcu_putref(shp, shm_rcu_free); } CWE ID: CWE-362 Target: 1 Example 2: Code: gfx::Rect RenderWidgetHostViewAura::GetCaretBounds() { const gfx::Rect rect = gfx::UnionRects(selection_start_rect_, selection_end_rect_); return ConvertRectToScreen(rect); } 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 Image *ReadSCTImage(const ImageInfo *image_info,ExceptionInfo *exception) { char magick[2]; Image *image; MagickBooleanType status; MagickRealType height, width; Quantum pixel; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; ssize_t count, y; unsigned char buffer[768]; size_t separations, separations_mask, units; /* 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); } /* Read control block. */ count=ReadBlob(image,80,buffer); (void) count; count=ReadBlob(image,2,(unsigned char *) magick); if ((LocaleNCompare((char *) magick,"CT",2) != 0) && (LocaleNCompare((char *) magick,"LW",2) != 0) && (LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"PG",2) != 0) && (LocaleNCompare((char *) magick,"TX",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((LocaleNCompare((char *) magick,"LW",2) == 0) || (LocaleNCompare((char *) magick,"BM",2) == 0) || (LocaleNCompare((char *) magick,"PG",2) == 0) || (LocaleNCompare((char *) magick,"TX",2) == 0)) ThrowReaderException(CoderError,"OnlyContinuousTonePictureSupported"); count=ReadBlob(image,174,buffer); count=ReadBlob(image,768,buffer); /* Read paramter block. */ units=1UL*ReadBlobByte(image); if (units == 0) image->units=PixelsPerCentimeterResolution; separations=1UL*ReadBlobByte(image); separations_mask=ReadBlobMSBShort(image); count=ReadBlob(image,14,buffer); buffer[14]='\0'; height=StringToDouble((char *) buffer,(char **) NULL); count=ReadBlob(image,14,buffer); width=StringToDouble((char *) buffer,(char **) NULL); count=ReadBlob(image,12,buffer); buffer[12]='\0'; image->rows=StringToUnsignedLong((char *) buffer); count=ReadBlob(image,12,buffer); image->columns=StringToUnsignedLong((char *) buffer); count=ReadBlob(image,200,buffer); count=ReadBlob(image,768,buffer); if (separations_mask == 0x0f) SetImageColorspace(image,CMYKColorspace); image->x_resolution=1.0*image->columns/width; image->y_resolution=1.0*image->rows/height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert SCT raster image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { for (i=0; i < (ssize_t) separations; i++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { pixel=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); if (image->colorspace == CMYKColorspace) pixel=(Quantum) (QuantumRange-pixel); switch (i) { case 0: { SetPixelRed(q,pixel); SetPixelGreen(q,pixel); SetPixelBlue(q,pixel); break; } case 1: { SetPixelGreen(q,pixel); break; } case 2: { SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(indexes+x,pixel); break; } } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if ((image->columns % 2) != 0) (void) ReadBlobByte(image); /* pad */ } status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } 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: off_t HFSForkReadStream::Seek(off_t offset, int whence) { DCHECK_EQ(SEEK_SET, whence); DCHECK_GE(offset, 0); DCHECK_LT(static_cast<uint64_t>(offset), fork_.logicalSize); size_t target_block = offset / hfs_->block_size(); size_t block_count = 0; for (size_t i = 0; i < arraysize(fork_.extents); ++i) { const HFSPlusExtentDescriptor* extent = &fork_.extents[i]; if (extent->startBlock == 0 && extent->blockCount == 0) break; base::CheckedNumeric<size_t> new_block_count(block_count); new_block_count += extent->blockCount; if (!new_block_count.IsValid()) { DLOG(ERROR) << "Seek offset block count overflows"; return false; } if (target_block < new_block_count.ValueOrDie()) { if (current_extent_ != i) { read_current_extent_ = false; current_extent_ = i; } auto iterator_block_offset = base::CheckedNumeric<size_t>(block_count) * hfs_->block_size(); if (!iterator_block_offset.IsValid()) { DLOG(ERROR) << "Seek block offset overflows"; return false; } fork_logical_offset_ = offset; return offset; } block_count = new_block_count.ValueOrDie(); } return -1; } CWE ID: Target: 1 Example 2: Code: R_API void r_bin_java_annotation_free(void /*RBinJavaAnnotation*/ *a) { RBinJavaAnnotation *annotation = a; if (annotation) { r_list_free (annotation->element_value_pairs); free (annotation); } } 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: cifs_writev_complete(struct work_struct *work) { struct cifs_writedata *wdata = container_of(work, struct cifs_writedata, work); struct inode *inode = wdata->cfile->dentry->d_inode; int i = 0; if (wdata->result == 0) { cifs_update_eof(CIFS_I(inode), wdata->offset, wdata->bytes); cifs_stats_bytes_written(tlink_tcon(wdata->cfile->tlink), wdata->bytes); } else if (wdata->sync_mode == WB_SYNC_ALL && wdata->result == -EAGAIN) return cifs_writev_requeue(wdata); for (i = 0; i < wdata->nr_pages; i++) { struct page *page = wdata->pages[i]; if (wdata->result == -EAGAIN) __set_page_dirty_nobuffers(page); else if (wdata->result < 0) SetPageError(page); end_page_writeback(page); page_cache_release(page); } if (wdata->result != -EAGAIN) mapping_set_error(inode->i_mapping, wdata->result); kref_put(&wdata->refcount, cifs_writedata_release); } 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: nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_getdeviceinfo *gdev) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops = nfsd4_layout_ops[gdev->gd_layout_type]; u32 starting_len = xdr->buf->len, needed_len; __be32 *p; dprintk("%s: err %d\n", __func__, be32_to_cpu(nfserr)); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = cpu_to_be32(gdev->gd_layout_type); /* If maxcount is 0 then just update notifications */ if (gdev->gd_maxcount != 0) { nfserr = ops->encode_getdeviceinfo(xdr, gdev); if (nfserr) { /* * We don't bother to burden the layout drivers with * enforcing gd_maxcount, just tell the client to * come back with a bigger buffer if it's not enough. */ if (xdr->buf->len + 4 > gdev->gd_maxcount) goto toosmall; goto out; } } nfserr = nfserr_resource; if (gdev->gd_notify_types) { p = xdr_reserve_space(xdr, 4 + 4); if (!p) goto out; *p++ = cpu_to_be32(1); /* bitmap length */ *p++ = cpu_to_be32(gdev->gd_notify_types); } else { p = xdr_reserve_space(xdr, 4); if (!p) goto out; *p++ = 0; } nfserr = 0; out: kfree(gdev->gd_device); dprintk("%s: done: %d\n", __func__, be32_to_cpu(nfserr)); return nfserr; toosmall: dprintk("%s: maxcount too small\n", __func__); needed_len = xdr->buf->len + 4 /* notifications */; xdr_truncate_encode(xdr, starting_len); p = xdr_reserve_space(xdr, 4); if (!p) { nfserr = nfserr_resource; } else { *p++ = cpu_to_be32(needed_len); nfserr = nfserr_toosmall; } goto out; } CWE ID: CWE-404 Target: 1 Example 2: Code: copy_node_opt_info(OptNode* to, OptNode* from) { *to = *from; } 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 vfat_hash(const struct dentry *dentry, const struct inode *inode, struct qstr *qstr) { qstr->hash = full_name_hash(qstr->name, vfat_striptail_len(qstr)); return 0; } CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("options_page")); GURL omnibox(chrome::kChromeUIOmniboxURL); ui_test_utils::NavigateToURL(browser(), omnibox); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(omnibox, tab1->GetURL()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetMainFrame()->GetProcess(), rph1); GURL extension_url("chrome-extension://" + extension->id()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); ::ShowSingletonTab(browser(), extension_url); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetMainFrame()->GetProcess(); EXPECT_EQ(tab1->GetURL(), extension_url); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } CWE ID: CWE-285 Target: 1 Example 2: Code: void InspectorClientImpl::overrideDeviceMetrics(int width, int height, float deviceScaleFactor, bool emulateViewport, bool fitWindow) { if (WebDevToolsAgentImpl* agent = devToolsAgent()) agent->overrideDeviceMetrics(width, height, deviceScaleFactor, emulateViewport, fitWindow); } 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 btrfs_destroy_inode(struct inode *inode) { struct btrfs_ordered_extent *ordered; struct btrfs_root *root = BTRFS_I(inode)->root; WARN_ON(!hlist_empty(&inode->i_dentry)); WARN_ON(inode->i_data.nrpages); WARN_ON(BTRFS_I(inode)->outstanding_extents); WARN_ON(BTRFS_I(inode)->reserved_extents); WARN_ON(BTRFS_I(inode)->delalloc_bytes); WARN_ON(BTRFS_I(inode)->csum_bytes); /* * This can happen where we create an inode, but somebody else also * created the same inode and we need to destroy the one we already * created. */ if (!root) goto free; /* * Make sure we're properly removed from the ordered operation * lists. */ smp_mb(); if (!list_empty(&BTRFS_I(inode)->ordered_operations)) { spin_lock(&root->fs_info->ordered_extent_lock); list_del_init(&BTRFS_I(inode)->ordered_operations); spin_unlock(&root->fs_info->ordered_extent_lock); } if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) { printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n", (unsigned long long)btrfs_ino(inode)); atomic_dec(&root->orphan_inodes); } while (1) { ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1); if (!ordered) break; else { printk(KERN_ERR "btrfs found ordered " "extent %llu %llu on inode cleanup\n", (unsigned long long)ordered->file_offset, (unsigned long long)ordered->len); btrfs_remove_ordered_extent(inode, ordered); btrfs_put_ordered_extent(ordered); btrfs_put_ordered_extent(ordered); } } inode_tree_del(inode); btrfs_drop_extent_cache(inode, 0, (u64)-1, 0); free: btrfs_remove_delayed_node(inode); call_rcu(&inode->i_rcu, btrfs_i_callback); } 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: PHP_FUNCTION(locale_lookup) { char* fallback_loc = NULL; int fallback_loc_len = 0; const char* loc_range = NULL; int loc_range_len = 0; zval* arr = NULL; HashTable* hash_arr = NULL; zend_bool boolCanonical = 0; char* result =NULL; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "as|bs", &arr, &loc_range, &loc_range_len, &boolCanonical, &fallback_loc, &fallback_loc_len) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_lookup: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_range_len == 0) { loc_range = intl_locale_get_default(TSRMLS_C); } hash_arr = HASH_OF(arr); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) { RETURN_EMPTY_STRING(); } result = lookup_loc_range(loc_range, hash_arr, boolCanonical TSRMLS_CC); if(result == NULL || result[0] == '\0') { if( fallback_loc ) { result = estrndup(fallback_loc, fallback_loc_len); } else { RETURN_EMPTY_STRING(); } } RETVAL_STRINGL(result, strlen(result), 0); } CWE ID: CWE-125 Target: 1 Example 2: Code: void SessionService::SetSelectedTabInWindow(const SessionID& window_id, int index) { if (!ShouldTrackChangesToWindow(window_id)) return; ScheduleCommand(CreateSetSelectedTabInWindow(window_id, index)); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: virtual void commitCompleteOnCCThread(CCLayerTreeHostImpl*) { } 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 decode_level3_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int header_len; if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) { return 0; } if (!extend_raw_data(header, stream, LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) { return 0; } header_len = lha_decode_uint32(&RAW_DATA(header, 24)); if (header_len > LEVEL_3_MAX_HEADER_LEN) { return 0; } if (!extend_raw_data(header, stream, header_len - RAW_DATA_LEN(header))) { return 0; } memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; (*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7)); (*header)->length = lha_decode_uint32(&RAW_DATA(header, 11)); (*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15)); (*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21)); (*header)->os_type = RAW_DATA(header, 23); if (!decode_extended_headers(header, 28)) { return 0; } return 1; } CWE ID: CWE-190 Target: 1 Example 2: Code: static int ip6_tnl_xmit2(struct sk_buff *skb, struct net_device *dev, __u8 dsfield, struct flowi *fl, int encap_limit, __u32 *pmtu) { struct net *net = dev_net(dev); struct ip6_tnl *t = netdev_priv(dev); struct net_device_stats *stats = &t->dev->stats; struct ipv6hdr *ipv6h = ipv6_hdr(skb); struct ipv6_tel_txoption opt; struct dst_entry *dst; struct net_device *tdev; int mtu; unsigned int max_headroom = sizeof(struct ipv6hdr); u8 proto; int err = -1; int pkt_len; if ((dst = ip6_tnl_dst_check(t)) != NULL) dst_hold(dst); else { dst = ip6_route_output(net, NULL, fl); if (dst->error || xfrm_lookup(net, &dst, fl, NULL, 0) < 0) goto tx_err_link_failure; } tdev = dst->dev; if (tdev == dev) { stats->collisions++; if (net_ratelimit()) printk(KERN_WARNING "%s: Local routing loop detected!\n", t->parms.name); goto tx_err_dst_release; } mtu = dst_mtu(dst) - sizeof (*ipv6h); if (encap_limit >= 0) { max_headroom += 8; mtu -= 8; } if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; if (skb_dst(skb)) skb_dst(skb)->ops->update_pmtu(skb_dst(skb), mtu); if (skb->len > mtu) { *pmtu = mtu; err = -EMSGSIZE; goto tx_err_dst_release; } /* * Okay, now see if we can stuff it in the buffer as-is. */ max_headroom += LL_RESERVED_SPACE(tdev); if (skb_headroom(skb) < max_headroom || skb_shared(skb) || (skb_cloned(skb) && !skb_clone_writable(skb, 0))) { struct sk_buff *new_skb; if (!(new_skb = skb_realloc_headroom(skb, max_headroom))) goto tx_err_dst_release; if (skb->sk) skb_set_owner_w(new_skb, skb->sk); kfree_skb(skb); skb = new_skb; } skb_dst_drop(skb); skb_dst_set(skb, dst_clone(dst)); skb->transport_header = skb->network_header; proto = fl->proto; if (encap_limit >= 0) { init_tel_txopt(&opt, encap_limit); ipv6_push_nfrag_opts(skb, &opt.ops, &proto, NULL); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); ipv6h = ipv6_hdr(skb); *(__be32*)ipv6h = fl->fl6_flowlabel | htonl(0x60000000); dsfield = INET_ECN_encapsulate(0, dsfield); ipv6_change_dsfield(ipv6h, ~INET_ECN_MASK, dsfield); ipv6h->hop_limit = t->parms.hop_limit; ipv6h->nexthdr = proto; ipv6_addr_copy(&ipv6h->saddr, &fl->fl6_src); ipv6_addr_copy(&ipv6h->daddr, &fl->fl6_dst); nf_reset(skb); pkt_len = skb->len; err = ip6_local_out(skb); if (net_xmit_eval(err) == 0) { stats->tx_bytes += pkt_len; stats->tx_packets++; } else { stats->tx_errors++; stats->tx_aborted_errors++; } ip6_tnl_dst_store(t, dst); return 0; tx_err_link_failure: stats->tx_carrier_errors++; dst_link_failure(skb); tx_err_dst_release: dst_release(dst); return err; } CWE ID: CWE-362 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) { s->avctx->profile = get_bits(gb, 4); s->avctx->level = get_bits(gb, 4); if (s->avctx->profile == 0 && s->avctx->level == 8) { s->avctx->level = 0; } return 0; } CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RenderFrameObserverNatives::OnDocumentElementCreated( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK(args.Length() == 2); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsFunction()); int frame_id = args[0]->Int32Value(); content::RenderFrame* frame = content::RenderFrame::FromRoutingID(frame_id); if (!frame) { LOG(WARNING) << "No render frame found to register LoadWatcher."; return; } new LoadWatcher(context(), frame, args[1].As<v8::Function>()); args.GetReturnValue().Set(true); } CWE ID: Target: 1 Example 2: Code: static GF_Err gf_isom_dump_svg_track(GF_ISOFile *the_file, u32 track, FILE *dump) { char nhmlFileName[1024]; FILE *nhmlFile; u32 i, count, di, ts, cur_frame; u64 start, end; GF_BitStream *bs; GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, track); if (!trak) return GF_BAD_PARAM; switch (trak->Media->handler->handlerType) { case GF_ISOM_MEDIA_TEXT: case GF_ISOM_MEDIA_SUBT: break; default: return GF_BAD_PARAM; } strcpy(nhmlFileName, the_file->fileName); strcat(nhmlFileName, ".nhml"); nhmlFile = gf_fopen(nhmlFileName, "wt"); fprintf(nhmlFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); fprintf(nhmlFile, "<NHNTStream streamType=\"3\" objectTypeIndication=\"10\" timeScale=\"%d\" baseMediaFile=\"file.svg\" inRootOD=\"yes\">\n", trak->Media->mediaHeader->timeScale); fprintf(nhmlFile, "<NHNTSample isRAP=\"yes\" DTS=\"0\" xmlFrom=\"doc.start\" xmlTo=\"text_1.start\"/>\n"); ts = trak->Media->mediaHeader->timeScale; cur_frame = 0; end = 0; fprintf(dump, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); fprintf(dump, "<svg version=\"1.2\" baseProfile=\"tiny\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"%d\" height=\"%d\" fill=\"black\">\n", trak->Header->width >> 16 , trak->Header->height >> 16); fprintf(dump, "<g transform=\"translate(%d, %d)\" text-anchor=\"middle\">\n", (trak->Header->width >> 16)/2 , (trak->Header->height >> 16)/2); count = gf_isom_get_sample_count(the_file, track); for (i=0; i<count; i++) { GF_TextSample *txt; GF_ISOSample *s = gf_isom_get_sample(the_file, track, i+1, &di); if (!s) continue; start = s->DTS; if (s->dataLength==2) { gf_isom_sample_del(&s); continue; } if (i+1<count) { GF_ISOSample *next = gf_isom_get_sample_info(the_file, track, i+2, NULL, NULL); if (next) { end = next->DTS; gf_isom_sample_del(&next); } } cur_frame++; bs = gf_bs_new(s->data, s->dataLength, GF_BITSTREAM_READ); txt = gf_isom_parse_texte_sample(bs); gf_bs_del(bs); if (!txt->len) continue; fprintf(dump, " <text id=\"text_%d\" display=\"none\">%s\n", cur_frame, txt->text); fprintf(dump, " <set attributeName=\"display\" to=\"inline\" begin=\"%g\" end=\"%g\"/>\n", ((s64)start*1.0)/ts, ((s64)end*1.0)/ts); fprintf(dump, " <discard begin=\"%g\"/>\n", ((s64)end*1.0)/ts); fprintf(dump, " </text>\n"); gf_isom_sample_del(&s); gf_isom_delete_text_sample(txt); fprintf(dump, "\n"); gf_set_progress("SRT Extract", i, count); if (i == count - 2) { fprintf(nhmlFile, "<NHNTSample isRAP=\"no\" DTS=\"%f\" xmlFrom=\"text_%d.start\" xmlTo=\"doc.end\"/>\n", ((s64)start*1.0), cur_frame); } else { fprintf(nhmlFile, "<NHNTSample isRAP=\"no\" DTS=\"%f\" xmlFrom=\"text_%d.start\" xmlTo=\"text_%d.start\"/>\n", ((s64)start*1.0), cur_frame, cur_frame+1); } } fprintf(dump, "</g>\n"); fprintf(dump, "</svg>\n"); fprintf(nhmlFile, "</NHNTStream>\n"); gf_fclose(nhmlFile); if (count) gf_set_progress("SRT Extract", i, count); return GF_OK; } CWE ID: CWE-125 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: EncodedJSValue JSC_HOST_CALL jsTestCustomNamedGetterPrototypeFunctionAnotherFunction(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestCustomNamedGetter::s_info)) return throwVMTypeError(exec); JSTestCustomNamedGetter* castedThis = jsCast<JSTestCustomNamedGetter*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestCustomNamedGetter::s_info); TestCustomNamedGetter* impl = static_cast<TestCustomNamedGetter*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); const String& str(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->anotherFunction(str); 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: void OnZipAnalysisFinished(const zip_analyzer::Results& results) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(ClientDownloadRequest::ZIPPED_EXECUTABLE, type_); if (!service_) return; if (results.success) { zipped_executable_ = results.has_executable; archived_binary_.CopyFrom(results.archived_binary); DVLOG(1) << "Zip analysis finished for " << item_->GetFullPath().value() << ", has_executable=" << results.has_executable << " has_archive=" << results.has_archive; } else { DVLOG(1) << "Zip analysis failed for " << item_->GetFullPath().value(); } UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasExecutable", zipped_executable_); UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasArchiveButNoExecutable", results.has_archive && !zipped_executable_); UMA_HISTOGRAM_TIMES("SBClientDownload.ExtractZipFeaturesTime", base::TimeTicks::Now() - zip_analysis_start_time_); for (const auto& file_extension : results.archived_archive_filetypes) RecordArchivedArchiveFileExtensionType(file_extension); if (!zipped_executable_ && !results.has_archive) { PostFinishTask(UNKNOWN, REASON_ARCHIVE_WITHOUT_BINARIES); return; } if (!zipped_executable_ && results.has_archive) type_ = ClientDownloadRequest::ZIPPED_ARCHIVE; OnFileFeatureExtractionDone(); } CWE ID: Target: 1 Example 2: Code: DataReductionProxyConfig::GetProxyConnectionToProbe() const { DCHECK(thread_checker_.CalledOnValidThread()); const std::vector<DataReductionProxyServer>& proxies = DataReductionProxyConfig::GetProxiesForHttp(); for (const DataReductionProxyServer& proxy_server : proxies) { bool is_secure_proxy = proxy_server.IsSecureProxy(); bool is_core_proxy = proxy_server.IsCoreProxy(); if (!network_properties_manager_->HasWarmupURLProbeFailed(is_secure_proxy, is_core_proxy) && network_properties_manager_->ShouldFetchWarmupProbeURL(is_secure_proxy, is_core_proxy)) { return proxy_server; } } for (const DataReductionProxyServer& proxy_server : proxies) { bool is_secure_proxy = proxy_server.IsSecureProxy(); bool is_core_proxy = proxy_server.IsCoreProxy(); if (network_properties_manager_->ShouldFetchWarmupProbeURL(is_secure_proxy, is_core_proxy)) { return proxy_server; } } return base::nullopt; } CWE ID: CWE-416 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DevToolsAgentHostImpl::ForceDetachAllClients() { scoped_refptr<DevToolsAgentHostImpl> protect(this); while (!session_by_client_.empty()) { DevToolsAgentHostClient* client = session_by_client_.begin()->first; InnerDetachClient(client); client->AgentHostClosed(this); } } 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 UnloadController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedImpl(old_contents); TabAttachedImpl(new_contents->web_contents()); } CWE ID: CWE-20 Target: 1 Example 2: Code: FileFunction(flock) /* }}} */ /* {{{ proto bool SplFileObject::fflush() 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 WebMediaPlayerMS::HasSingleSecurityOrigin() const { DCHECK(thread_checker_.CalledOnValidThread()); return true; } 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: struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns, struct user_namespace *user_ns, struct fs_struct *new_fs) { struct mnt_namespace *new_ns; struct vfsmount *rootmnt = NULL, *pwdmnt = NULL; struct mount *p, *q; struct mount *old; struct mount *new; int copy_flags; BUG_ON(!ns); if (likely(!(flags & CLONE_NEWNS))) { get_mnt_ns(ns); return ns; } old = ns->root; new_ns = alloc_mnt_ns(user_ns); if (IS_ERR(new_ns)) return new_ns; namespace_lock(); /* First pass: copy the tree topology */ copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE; if (user_ns != ns->user_ns) copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED; new = copy_tree(old, old->mnt.mnt_root, copy_flags); if (IS_ERR(new)) { namespace_unlock(); free_mnt_ns(new_ns); return ERR_CAST(new); } new_ns->root = new; list_add_tail(&new_ns->list, &new->mnt_list); /* * Second pass: switch the tsk->fs->* elements and mark new vfsmounts * as belonging to new namespace. We have already acquired a private * fs_struct, so tsk->fs->lock is not needed. */ p = old; q = new; while (p) { q->mnt_ns = new_ns; if (new_fs) { if (&p->mnt == new_fs->root.mnt) { new_fs->root.mnt = mntget(&q->mnt); rootmnt = &p->mnt; } if (&p->mnt == new_fs->pwd.mnt) { new_fs->pwd.mnt = mntget(&q->mnt); pwdmnt = &p->mnt; } } p = next_mnt(p, old); q = next_mnt(q, new); if (!q) break; while (p->mnt.mnt_root != q->mnt.mnt_root) p = next_mnt(p, old); } namespace_unlock(); if (rootmnt) mntput(rootmnt); if (pwdmnt) mntput(pwdmnt); return new_ns; } CWE ID: CWE-400 Target: 1 Example 2: Code: PHP_FUNCTION(snmpgetnext) { php_snmp(INTERNAL_FUNCTION_PARAM_PASSTHRU, SNMP_CMD_GETNEXT, SNMP_VERSION_1); } 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: SelectionInDOMTree ConvertToSelectionInDOMTree( const SelectionInFlatTree& selection_in_flat_tree) { return SelectionInDOMTree::Builder() .SetAffinity(selection_in_flat_tree.Affinity()) .SetBaseAndExtent(ToPositionInDOMTree(selection_in_flat_tree.Base()), ToPositionInDOMTree(selection_in_flat_tree.Extent())) .SetIsDirectional(selection_in_flat_tree.IsDirectional()) .SetIsHandleVisible(selection_in_flat_tree.IsHandleVisible()) .Build(); } 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: int __glXDispSwap_CreateContext(__GLXclientState *cl, GLbyte *pc) { xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc; __GLX_DECLARE_SWAP_VARIABLES; __GLX_SWAP_SHORT(&req->length); __GLX_SWAP_INT(&req->context); __GLX_SWAP_INT(&req->visual); return __glXDisp_CreateContext(cl, pc); } CWE ID: CWE-20 Target: 1 Example 2: Code: BaseAudioContext::BaseAudioContext(Document* document, enum ContextType context_type) : PausableObject(document), destination_node_(nullptr), is_cleared_(false), is_resolving_resume_promises_(false), has_posted_cleanup_task_(false), user_gesture_required_(false), connection_count_(0), deferred_task_handler_(DeferredTaskHandler::Create()), context_state_(kSuspended), closed_context_sample_rate_(-1), periodic_wave_sine_(nullptr), periodic_wave_square_(nullptr), periodic_wave_sawtooth_(nullptr), periodic_wave_triangle_(nullptr), output_position_() { switch (context_type) { case kRealtimeContext: switch (GetAutoplayPolicy()) { case AutoplayPolicy::Type::kNoUserGestureRequired: break; case AutoplayPolicy::Type::kUserGestureRequired: case AutoplayPolicy::Type::kUserGestureRequiredForCrossOrigin: if (document->GetFrame() && document->GetFrame()->IsCrossOriginSubframe()) { autoplay_status_ = AutoplayStatus::kAutoplayStatusFailed; user_gesture_required_ = true; } break; case AutoplayPolicy::Type::kDocumentUserActivationRequired: autoplay_status_ = AutoplayStatus::kAutoplayStatusFailed; user_gesture_required_ = true; break; } break; case kOfflineContext: break; default: NOTREACHED(); break; } } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int asepcos_card_reader_lock_obtained(sc_card_t *card, int was_reset) { int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); if (was_reset > 0 && card->type == SC_CARD_TYPE_ASEPCOS_JAVA) { /* in case of a Java card try to select the ASEPCOS applet */ r = asepcos_select_asepcos_applet(card); } LOG_FUNC_RETURN(card->ctx, r); } 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: ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, struct ext2_xattr_header *header) { struct super_block *sb = inode->i_sb; struct buffer_head *new_bh = NULL; int error; if (header) { new_bh = ext2_xattr_cache_find(inode, header); if (new_bh) { /* We found an identical block in the cache. */ if (new_bh == old_bh) { ea_bdebug(new_bh, "keeping this block"); } else { /* The old block is released after updating the inode. */ ea_bdebug(new_bh, "reusing block"); error = dquot_alloc_block(inode, 1); if (error) { unlock_buffer(new_bh); goto cleanup; } le32_add_cpu(&HDR(new_bh)->h_refcount, 1); ea_bdebug(new_bh, "refcount now=%d", le32_to_cpu(HDR(new_bh)->h_refcount)); } unlock_buffer(new_bh); } else if (old_bh && header == HDR(old_bh)) { /* Keep this block. No need to lock the block as we don't need to change the reference count. */ new_bh = old_bh; get_bh(new_bh); ext2_xattr_cache_insert(new_bh); } else { /* We need to allocate a new block */ ext2_fsblk_t goal = ext2_group_first_block_no(sb, EXT2_I(inode)->i_block_group); int block = ext2_new_block(inode, goal, &error); if (error) goto cleanup; ea_idebug(inode, "creating block %d", block); new_bh = sb_getblk(sb, block); if (unlikely(!new_bh)) { ext2_free_blocks(inode, block, 1); mark_inode_dirty(inode); error = -ENOMEM; goto cleanup; } lock_buffer(new_bh); memcpy(new_bh->b_data, header, new_bh->b_size); set_buffer_uptodate(new_bh); unlock_buffer(new_bh); ext2_xattr_cache_insert(new_bh); ext2_xattr_update_super_block(sb); } mark_buffer_dirty(new_bh); if (IS_SYNC(inode)) { sync_dirty_buffer(new_bh); error = -EIO; if (buffer_req(new_bh) && !buffer_uptodate(new_bh)) goto cleanup; } } /* Update the inode. */ EXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0; inode->i_ctime = CURRENT_TIME_SEC; if (IS_SYNC(inode)) { error = sync_inode_metadata(inode, 1); /* In case sync failed due to ENOSPC the inode was actually * written (only some dirty data were not) so we just proceed * as if nothing happened and cleanup the unused block */ if (error && error != -ENOSPC) { if (new_bh && new_bh != old_bh) { dquot_free_block_nodirty(inode, 1); mark_inode_dirty(inode); } goto cleanup; } } else mark_inode_dirty(inode); error = 0; if (old_bh && old_bh != new_bh) { struct mb_cache_entry *ce; /* * If there was an old block and we are no longer using it, * release the old block. */ ce = mb_cache_entry_get(ext2_xattr_cache, old_bh->b_bdev, old_bh->b_blocknr); lock_buffer(old_bh); if (HDR(old_bh)->h_refcount == cpu_to_le32(1)) { /* Free the old block. */ if (ce) mb_cache_entry_free(ce); ea_bdebug(old_bh, "freeing"); ext2_free_blocks(inode, old_bh->b_blocknr, 1); mark_inode_dirty(inode); /* We let our caller release old_bh, so we * need to duplicate the buffer before. */ get_bh(old_bh); bforget(old_bh); } else { /* Decrement the refcount only. */ le32_add_cpu(&HDR(old_bh)->h_refcount, -1); if (ce) mb_cache_entry_release(ce); dquot_free_block_nodirty(inode, 1); mark_inode_dirty(inode); mark_buffer_dirty(old_bh); ea_bdebug(old_bh, "refcount now=%d", le32_to_cpu(HDR(old_bh)->h_refcount)); } unlock_buffer(old_bh); } cleanup: brelse(new_bh); return error; } CWE ID: CWE-19 Target: 1 Example 2: Code: GLvoid StubGLUniform1fv(GLint location, GLsizei count, const GLfloat* v) { glUniform1fv(location, count, v); } 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: fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, "fpDiff", "%s", "(cc%(bps*stride))!=0"); return 0; } if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: my_object_emit_frobnicate (MyObject *obj, GError **error) { g_signal_emit (obj, signals[FROBNICATE], 0, 42); return TRUE; } CWE ID: CWE-264 Target: 1 Example 2: Code: void CWebServer::Do_Work() { bool exception_thrown = false; while (!m_bDoStop) { exception_thrown = false; try { if (m_pWebEm) { m_pWebEm->Run(); } } catch (std::exception& e) { _log.Log(LOG_ERROR, "WebServer(%s) exception occurred : '%s'", m_server_alias.c_str(), e.what()); exception_thrown = true; } catch (...) { _log.Log(LOG_ERROR, "WebServer(%s) unknown exception occurred", m_server_alias.c_str()); exception_thrown = true; } if (exception_thrown) { _log.Log(LOG_STATUS, "WebServer(%s) restart server in 5 seconds", m_server_alias.c_str()); sleep_milliseconds(5000); // prevents from an exception flood continue; } break; } _log.Log(LOG_STATUS, "WebServer(%s) stopped", m_server_alias.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: void LockContentsView::RemoveUser(bool is_primary) { if (Shell::Get()->login_screen_controller()->IsAuthenticating()) return; LoginBigUserView* to_remove = is_primary ? primary_big_view_ : opt_secondary_big_view_; DCHECK(to_remove->GetCurrentUser()->can_remove); AccountId user = to_remove->GetCurrentUser()->basic_user_info->account_id; Shell::Get()->login_screen_controller()->RemoveUser(user); std::vector<mojom::LoginUserInfoPtr> new_users; if (!is_primary) new_users.push_back(primary_big_view_->GetCurrentUser()->Clone()); if (is_primary && opt_secondary_big_view_) new_users.push_back(opt_secondary_big_view_->GetCurrentUser()->Clone()); if (users_list_) { for (int i = 0; i < users_list_->user_count(); ++i) { new_users.push_back( users_list_->user_view_at(i)->current_user()->Clone()); } } data_dispatcher_->NotifyUsers(new_users); } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CCLayerTreeHostTest::doBeginTest() { ASSERT(isMainThread()); ASSERT(!m_running); m_running = true; m_client = MockLayerTreeHostClient::create(this); RefPtr<LayerChromium> rootLayer = LayerChromium::create(0); m_layerTreeHost = MockLayerTreeHost::create(this, m_client.get(), rootLayer, m_settings); ASSERT(m_layerTreeHost); m_beginning = true; beginTest(); m_beginning = false; if (m_endWhenBeginReturns) onEndTest(static_cast<void*>(this)); } CWE ID: CWE-119 Target: 1 Example 2: Code: MATCHER(IsBackgroundDump, "") { return arg.level_of_detail == MemoryDumpLevelOfDetail::BACKGROUND; } CWE ID: CWE-269 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void InspectorResourceAgent::frameClearedScheduledNavigation(LocalFrame* frame) { m_frameNavigationInitiatorMap.remove(m_pageAgent->frameId(frame)); } 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: u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport) { struct keydata *keyptr = get_keyptr(); u32 hash[4]; /* * Pick a unique starting offset for each ephemeral port search * (saddr, daddr, dport) and 48bits of random data. */ hash[0] = (__force u32)saddr; hash[1] = (__force u32)daddr; hash[2] = (__force u32)dport ^ keyptr->secret[10]; hash[3] = keyptr->secret[11]; return half_md4_transform(hash, keyptr->secret); } CWE ID: Target: 1 Example 2: Code: static int netmasklen(struct in_addr addr) { int masklen; for (masklen = 0; masklen < 32; masklen++) { if (ntohl(addr.s_addr) >= (0xffffffff << masklen)) break; } return 32 - masklen; } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RilSapSocket::initSapSocket(const char *socketName, RIL_RadioFunctions *uimFuncs) { if (strcmp(socketName, "sap_uim_socket1") == 0) { if(!SocketExists(socketName)) { addSocketToList(socketName, RIL_SOCKET_1, uimFuncs); } } #if (SIM_COUNT >= 2) if (strcmp(socketName, "sap_uim_socket2") == 0) { if(!SocketExists(socketName)) { addSocketToList(socketName, RIL_SOCKET_2, uimFuncs); } } #endif #if (SIM_COUNT >= 3) if (strcmp(socketName, "sap_uim_socket3") == 0) { if(!SocketExists(socketName)) { addSocketToList(socketName, RIL_SOCKET_3, uimFuncs); } } #endif #if (SIM_COUNT >= 4) if (strcmp(socketName, "sap_uim_socket4") == 0) { if(!SocketExists(socketName)) { addSocketToList(socketName, RIL_SOCKET_4, uimFuncs); } } #endif } 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 GM2TabStyle::PaintTabBackground(gfx::Canvas* canvas, bool active, int fill_id, int y_inset, const SkPath* clip) const { DCHECK(!y_inset || fill_id); const SkColor active_color = tab_->controller()->GetTabBackgroundColor(TAB_ACTIVE); const SkColor inactive_color = tab_->GetThemeProvider()->GetDisplayProperty( ThemeProperties::SHOULD_FILL_BACKGROUND_TAB_COLOR) ? tab_->controller()->GetTabBackgroundColor(TAB_INACTIVE) : SK_ColorTRANSPARENT; const SkColor stroke_color = tab_->controller()->GetToolbarTopSeparatorColor(); const bool paint_hover_effect = !active && IsHoverActive(); const float stroke_thickness = GetStrokeThickness(active); PaintTabBackgroundFill(canvas, active, paint_hover_effect, active_color, inactive_color, fill_id, y_inset); if (stroke_thickness > 0) { gfx::ScopedCanvas scoped_canvas(clip ? canvas : nullptr); if (clip) canvas->sk_canvas()->clipPath(*clip, SkClipOp::kDifference, true); PaintBackgroundStroke(canvas, active, stroke_color); } PaintSeparators(canvas); } CWE ID: CWE-20 Target: 1 Example 2: Code: xsltFormatNumberPreSuffix(xsltDecimalFormatPtr self, xmlChar **format, xsltFormatNumberInfoPtr info) { int count=0; /* will hold total length of prefix/suffix */ int len; while (1) { /* * prefix / suffix ends at end of string or at * first 'special' character */ if (**format == 0) return count; /* if next character 'escaped' just count it */ if (**format == SYMBOL_QUOTE) { if (*++(*format) == 0) return -1; } else if (IS_SPECIAL(self, *format)) return count; /* * else treat percent/per-mille as special cases, * depending on whether +ve or -ve */ else { /* * for +ve prefix/suffix, allow only a * single occurence of either */ if (xsltUTF8Charcmp(*format, self->percent) == 0) { if (info->is_multiplier_set) return -1; info->multiplier = 100; info->is_multiplier_set = TRUE; } else if (xsltUTF8Charcmp(*format, self->permille) == 0) { if (info->is_multiplier_set) return -1; info->multiplier = 1000; info->is_multiplier_set = TRUE; } } if ((len=xsltUTF8Size(*format)) < 1) return -1; count += len; *format += len; } } CWE ID: CWE-119 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebMediaPlayerImpl::ReportMemoryUsage() { DCHECK(main_task_runner_->BelongsToCurrentThread()); if (demuxer_ && !IsNetworkStateError(network_state_)) { base::PostTaskAndReplyWithResult( media_task_runner_.get(), FROM_HERE, base::Bind(&Demuxer::GetMemoryUsage, base::Unretained(demuxer_.get())), base::Bind(&WebMediaPlayerImpl::FinishMemoryUsageReport, AsWeakPtr())); } else { FinishMemoryUsageReport(0); } } CWE ID: CWE-732 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: begin_softmask(fz_context *ctx, pdf_run_processor *pr, softmask_save *save) { pdf_gstate *gstate = pr->gstate + pr->gtop; pdf_xobject *softmask = gstate->softmask; fz_rect mask_bbox; fz_matrix tos_save[2], save_ctm; fz_matrix mask_matrix; fz_colorspace *mask_colorspace; save->softmask = softmask; if (softmask == NULL) return gstate; save->page_resources = gstate->softmask_resources; save->ctm = gstate->softmask_ctm; save_ctm = gstate->ctm; pdf_xobject_bbox(ctx, softmask, &mask_bbox); pdf_xobject_matrix(ctx, softmask, &mask_matrix); pdf_tos_save(ctx, &pr->tos, tos_save); if (gstate->luminosity) mask_bbox = fz_infinite_rect; else { fz_transform_rect(&mask_bbox, &mask_matrix); fz_transform_rect(&mask_bbox, &gstate->softmask_ctm); } gstate->softmask = NULL; gstate->softmask_resources = NULL; gstate->ctm = gstate->softmask_ctm; mask_colorspace = pdf_xobject_colorspace(ctx, softmask); if (gstate->luminosity && !mask_colorspace) mask_colorspace = fz_device_gray(ctx); fz_try(ctx) { fz_begin_mask(ctx, pr->dev, &mask_bbox, gstate->luminosity, mask_colorspace, gstate->softmask_bc, &gstate->fill.color_params); pdf_run_xobject(ctx, pr, softmask, save->page_resources, &fz_identity, 1); } fz_always(ctx) fz_drop_colorspace(ctx, mask_colorspace); fz_catch(ctx) { fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); /* FIXME: Ignore error - nasty, but if we throw from * here the clip stack would be messed up. */ /* TODO: pass cookie here to increase the cookie error count */ } fz_end_mask(ctx, pr->dev); pdf_tos_restore(ctx, &pr->tos, tos_save); gstate = pr->gstate + pr->gtop; gstate->ctm = save_ctm; return gstate; } CWE ID: CWE-416 Target: 1 Example 2: Code: void ath_tx_aggr_stop(struct ath_softc *sc, struct ieee80211_sta *sta, u16 tid) { struct ath_node *an = (struct ath_node *)sta->drv_priv; struct ath_atx_tid *txtid = ATH_AN_2_TID(an, tid); struct ath_txq *txq = txtid->ac->txq; ath_txq_lock(sc, txq); txtid->active = false; txtid->paused = false; ath_tx_flush_tid(sc, txtid); ath_tx_tid_change_state(sc, txtid); ath_txq_unlock_complete(sc, txq); } 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: std::unique_ptr<base::DictionaryValue> CreateInvalidParamResponse( int command_id, const std::string& param) { return CreateErrorResponse( command_id, kErrorInvalidParam, base::StringPrintf("Missing or invalid '%s' parameter", param.c_str())); } 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: int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg, void *buf, int peekonly) { struct tmComResBusInfo *bus = &dev->bus; u32 bytes_to_read, write_distance, curr_grp, curr_gwp, new_grp, buf_size, space_rem; struct tmComResInfo msg_tmp; int ret = SAA_ERR_BAD_PARAMETER; saa7164_bus_verify(dev); if (msg == NULL) return ret; if (msg->size > dev->bus.m_wMaxReqSize) { printk(KERN_ERR "%s() Exceeded dev->bus.m_wMaxReqSize\n", __func__); return ret; } if ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) { printk(KERN_ERR "%s() Missing msg buf, size should be %d bytes\n", __func__, msg->size); return ret; } mutex_lock(&bus->lock); /* Peek the bus to see if a msg exists, if it's not what we're expecting * then return cleanly else read the message from the bus. */ curr_gwp = saa7164_readl(bus->m_dwGetWritePos); curr_grp = saa7164_readl(bus->m_dwGetReadPos); if (curr_gwp == curr_grp) { ret = SAA_ERR_EMPTY; goto out; } bytes_to_read = sizeof(*msg); /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR "%s() No message/response found\n", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem); memcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing, bytes_to_read - space_rem); } else { /* No wrapping */ memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read); } /* Convert from little endian to CPU */ msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size); msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command); msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector); /* No need to update the read positions, because this was a peek */ /* If the caller specifically want to peek, return */ if (peekonly) { memcpy(msg, &msg_tmp, sizeof(*msg)); goto peekout; } /* Check if the command/response matches what is expected */ if ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) || (msg_tmp.controlselector != msg->controlselector) || (msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) { printk(KERN_ERR "%s() Unexpected msg miss-match\n", __func__); saa7164_bus_dumpmsg(dev, msg, buf); saa7164_bus_dumpmsg(dev, &msg_tmp, NULL); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Get the actual command and response from the bus */ buf_size = msg->size; bytes_to_read = sizeof(*msg) + msg->size; /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR "%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\n", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; if (space_rem < sizeof(*msg)) { /* msg wraps around the ring */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem); memcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing, sizeof(*msg) - space_rem); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) - space_rem, buf_size); } else if (space_rem == sizeof(*msg)) { memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing, buf_size); } else { /* Additional data wraps around the ring */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) { memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), space_rem - sizeof(*msg)); memcpy_fromio(buf + space_rem - sizeof(*msg), bus->m_pdwGetRing, bytes_to_read - space_rem); } } } else { /* No wrapping */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), buf_size); } /* Convert from little endian to CPU */ msg->size = le16_to_cpu((__force __le16)msg->size); msg->command = le32_to_cpu((__force __le32)msg->command); msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector); /* Update the read positions, adjusting the ring */ saa7164_writel(bus->m_dwGetReadPos, new_grp); peekout: ret = SAA_OK; out: mutex_unlock(&bus->lock); saa7164_bus_verify(dev); return ret; } CWE ID: CWE-125 Target: 1 Example 2: Code: void RenderWidgetHostImpl::ForwardKeyboardEventWithCommands( const NativeWebKeyboardEvent& key_event, const ui::LatencyInfo& latency, const std::vector<EditCommand>* commands, bool* update_event) { TRACE_EVENT0("input", "RenderWidgetHostImpl::ForwardKeyboardEvent"); if (owner_delegate_ && !owner_delegate_->MayRenderWidgetForwardKeyboardEvent(key_event)) { return; } if (ShouldDropInputEvents()) return; if (!process_->IsInitializedAndNotDead()) return; if (KeyPressListenersHandleEvent(key_event)) { if (key_event.GetType() == WebKeyboardEvent::kRawKeyDown) suppress_events_until_keydown_ = true; return; } if (!WebInputEvent::IsKeyboardEventType(key_event.GetType())) return; if (suppress_events_until_keydown_) { if (key_event.GetType() == WebKeyboardEvent::kKeyUp || key_event.GetType() == WebKeyboardEvent::kChar) return; DCHECK(key_event.GetType() == WebKeyboardEvent::kRawKeyDown || key_event.GetType() == WebKeyboardEvent::kKeyDown); suppress_events_until_keydown_ = false; } bool is_shortcut = false; if (delegate_ && !key_event.skip_in_browser) { if (key_event.GetType() == WebKeyboardEvent::kRawKeyDown) suppress_events_until_keydown_ = true; switch (delegate_->PreHandleKeyboardEvent(key_event)) { case KeyboardEventProcessingResult::HANDLED: return; #if defined(USE_AURA) case KeyboardEventProcessingResult::HANDLED_DONT_UPDATE_EVENT: if (update_event) *update_event = false; return; #endif case KeyboardEventProcessingResult::NOT_HANDLED: break; case KeyboardEventProcessingResult::NOT_HANDLED_IS_SHORTCUT: is_shortcut = true; break; } if (key_event.GetType() == WebKeyboardEvent::kRawKeyDown) suppress_events_until_keydown_ = false; } auto* touch_emulator = GetExistingTouchEmulator(); if (touch_emulator && touch_emulator->HandleKeyboardEvent(key_event)) return; NativeWebKeyboardEventWithLatencyInfo key_event_with_latency(key_event, latency); key_event_with_latency.event.is_browser_shortcut = is_shortcut; DispatchInputEventWithLatencyInfo(key_event, &key_event_with_latency.latency); if (commands && !commands->empty()) { GetWidgetInputHandler()->SetEditCommandsForNextKeyEvent(*commands); } input_router_->SendKeyboardEvent(key_event_with_latency); } 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: monitor_init(void) { struct ssh *ssh = active_state; /* XXX */ struct monitor *mon; mon = xcalloc(1, sizeof(*mon)); monitor_openfds(mon, 1); /* Used to share zlib space across processes */ if (options.compression) { mon->m_zback = mm_create(NULL, MM_MEMSIZE); mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE); /* Compression needs to share state across borders */ ssh_packet_set_compress_hooks(ssh, mon->m_zlib, (ssh_packet_comp_alloc_func *)mm_zalloc, (ssh_packet_comp_free_func *)mm_zfree); } return mon; } 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: FrameImpl::FrameImpl(std::unique_ptr<content::WebContents> web_contents, chromium::web::FrameObserverPtr observer) : web_contents_(std::move(web_contents)), observer_(std::move(observer)) { Observe(web_contents.get()); } CWE ID: CWE-264 Target: 1 Example 2: Code: static int parse_overview_line(char *line, void *data) { struct FetchCtx *fc = data; struct Context *ctx = fc->ctx; struct NntpData *nntp_data = ctx->data; struct Header *hdr = NULL; char *header = NULL, *field = NULL; bool save = true; anum_t anum; if (!line) return 0; /* parse article number */ field = strchr(line, '\t'); if (field) *field++ = '\0'; if (sscanf(line, ANUM, &anum) != 1) return 0; mutt_debug(2, "" ANUM "\n", anum); /* out of bounds */ if (anum < fc->first || anum > fc->last) return 0; /* not in LISTGROUP */ if (!fc->messages[anum - fc->first]) { /* progress */ if (!ctx->quiet) mutt_progress_update(&fc->progress, anum - fc->first + 1, -1); return 0; } /* convert overview line to header */ FILE *fp = mutt_file_mkstemp(); if (!fp) return -1; header = nntp_data->nserv->overview_fmt; while (field) { char *b = field; if (*header) { if (strstr(header, ":full") == NULL && fputs(header, fp) == EOF) { mutt_file_fclose(&fp); return -1; } header = strchr(header, '\0') + 1; } field = strchr(field, '\t'); if (field) *field++ = '\0'; if (fputs(b, fp) == EOF || fputc('\n', fp) == EOF) { mutt_file_fclose(&fp); return -1; } } rewind(fp); /* allocate memory for headers */ if (ctx->msgcount >= ctx->hdrmax) mx_alloc_memory(ctx); /* parse header */ hdr = ctx->hdrs[ctx->msgcount] = mutt_header_new(); hdr->env = mutt_rfc822_read_header(fp, hdr, 0, 0); hdr->env->newsgroups = mutt_str_strdup(nntp_data->group); hdr->received = hdr->date_sent; mutt_file_fclose(&fp); #ifdef USE_HCACHE if (fc->hc) { char buf[16]; /* try to replace with header from cache */ snprintf(buf, sizeof(buf), "%u", anum); void *hdata = mutt_hcache_fetch(fc->hc, buf, strlen(buf)); if (hdata) { mutt_debug(2, "mutt_hcache_fetch %s\n", buf); mutt_header_free(&hdr); ctx->hdrs[ctx->msgcount] = hdr = mutt_hcache_restore(hdata); mutt_hcache_free(fc->hc, &hdata); hdr->data = 0; hdr->read = false; hdr->old = false; /* skip header marked as deleted in cache */ if (hdr->deleted && !fc->restore) { if (nntp_data->bcache) { mutt_debug(2, "mutt_bcache_del %s\n", buf); mutt_bcache_del(nntp_data->bcache, buf); } save = false; } } /* not cached yet, store header */ else { mutt_debug(2, "mutt_hcache_store %s\n", buf); mutt_hcache_store(fc->hc, buf, strlen(buf), hdr, 0); } } #endif if (save) { hdr->index = ctx->msgcount++; hdr->read = false; hdr->old = false; hdr->deleted = false; hdr->data = mutt_mem_calloc(1, sizeof(struct NntpHeaderData)); NHDR(hdr)->article_num = anum; if (fc->restore) hdr->changed = true; else { nntp_article_status(ctx, hdr, NULL, anum); if (!hdr->read) nntp_parse_xref(ctx, hdr); } if (anum > nntp_data->last_loaded) nntp_data->last_loaded = anum; } else mutt_header_free(&hdr); /* progress */ if (!ctx->quiet) mutt_progress_update(&fc->progress, anum - fc->first + 1, -1); return 0; } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GLboolean WebGLRenderingContextBase::isTexture(WebGLTexture* texture) { if (!texture || isContextLost()) return 0; if (!texture->HasEverBeenBound()) return 0; if (texture->IsDeleted()) return 0; return ContextGL()->IsTexture(texture->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: bool asn1_write_GeneralString(struct asn1_data *data, const char *s) { asn1_push_tag(data, ASN1_GENERAL_STRING); asn1_write_LDAPString(data, s); asn1_pop_tag(data); return !data->has_error; } CWE ID: CWE-399 Target: 1 Example 2: Code: static uint32_t NumberOfElementsImpl(JSObject* object, FixedArrayBase* backing_store) { uint32_t length = GetString(object)->length(); return length + BackingStoreAccessor::NumberOfElementsImpl(object, backing_store); } 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: TabGroupData::TabGroupData() { static int next_placeholder_title_number = 1; title_ = base::ASCIIToUTF16( "Group " + base::NumberToString(next_placeholder_title_number)); ++next_placeholder_title_number; static SkRandom rand; stroke_color_ = rand.nextU() | 0xff000000; } 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 DataReductionProxyConfig::InitializeOnIOThread( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, WarmupURLFetcher::CreateCustomProxyConfigCallback create_custom_proxy_config_callback, NetworkPropertiesManager* manager, const std::string& user_agent) { DCHECK(thread_checker_.CalledOnValidThread()); network_properties_manager_ = manager; network_properties_manager_->ResetWarmupURLFetchMetrics(); secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory)); warmup_url_fetcher_.reset(new WarmupURLFetcher( create_custom_proxy_config_callback, base::BindRepeating( &DataReductionProxyConfig::HandleWarmupFetcherResponse, base::Unretained(this)), base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate, base::Unretained(this)), ui_task_runner_, user_agent)); AddDefaultProxyBypassRules(); network_connection_tracker_->AddNetworkConnectionObserver(this); network_connection_tracker_->GetConnectionType( &connection_type_, base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged, weak_factory_.GetWeakPtr())); } CWE ID: CWE-416 Target: 1 Example 2: Code: void PrintRenderFrameHelper::PrintPreviewContext::ClearContext() { prep_frame_view_.reset(); metafile_.reset(); pages_to_render_.clear(); error_ = PREVIEW_ERROR_NONE; } 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 ExtensionSettingsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { RegisterTitle(localized_strings, "extensionSettings", IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE); localized_strings->SetString("extensionSettingsVisitWebsite", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VISIT_WEBSITE)); localized_strings->SetString("extensionSettingsDeveloperMode", l10n_util::GetStringUTF16(IDS_EXTENSIONS_DEVELOPER_MODE_LINK)); localized_strings->SetString("extensionSettingsNoExtensions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_NONE_INSTALLED)); localized_strings->SetString("extensionSettingsSuggestGallery", l10n_util::GetStringFUTF16(IDS_EXTENSIONS_NONE_INSTALLED_SUGGEST_GALLERY, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsGetMoreExtensions", l10n_util::GetStringFUTF16(IDS_GET_MORE_EXTENSIONS, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsExtensionId", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ID)); localized_strings->SetString("extensionSettingsExtensionPath", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PATH)); localized_strings->SetString("extensionSettingsInspectViews", l10n_util::GetStringUTF16(IDS_EXTENSIONS_INSPECT_VIEWS)); localized_strings->SetString("viewIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VIEW_INCOGNITO)); localized_strings->SetString("extensionSettingsEnable", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE)); localized_strings->SetString("extensionSettingsEnabled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLED)); localized_strings->SetString("extensionSettingsRemove", l10n_util::GetStringUTF16(IDS_EXTENSIONS_REMOVE)); localized_strings->SetString("extensionSettingsEnableIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE_INCOGNITO)); localized_strings->SetString("extensionSettingsAllowFileAccess", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ALLOW_FILE_ACCESS)); localized_strings->SetString("extensionSettingsIncognitoWarning", l10n_util::GetStringFUTF16(IDS_EXTENSIONS_INCOGNITO_WARNING, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME))); localized_strings->SetString("extensionSettingsReload", l10n_util::GetStringUTF16(IDS_EXTENSIONS_RELOAD)); localized_strings->SetString("extensionSettingsOptions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS)); localized_strings->SetString("extensionSettingsPolicyControlled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_POLICY_CONTROLLED)); localized_strings->SetString("extensionSettingsShowButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_BUTTON)); localized_strings->SetString("extensionSettingsLoadUnpackedButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON)); localized_strings->SetString("extensionSettingsPackButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PACK_BUTTON)); localized_strings->SetString("extensionSettingsUpdateButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UPDATE_BUTTON)); localized_strings->SetString("extensionSettingsCrashMessage", l10n_util::GetStringUTF16(IDS_EXTENSIONS_CRASHED_EXTENSION)); localized_strings->SetString("extensionSettingsInDevelopment", l10n_util::GetStringUTF16(IDS_EXTENSIONS_IN_DEVELOPMENT)); localized_strings->SetString("extensionSettingsWarningsTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WARNINGS_TITLE)); localized_strings->SetString("extensionSettingsShowDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS)); localized_strings->SetString("extensionSettingsHideDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS)); } 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: sshkey_load_file(int fd, struct sshbuf *blob) { u_char buf[1024]; size_t len; struct stat st; int r; if (fstat(fd, &st) < 0) return SSH_ERR_SYSTEM_ERROR; if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size > MAX_KEY_FILE_SIZE) return SSH_ERR_INVALID_FORMAT; for (;;) { if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) { if (errno == EPIPE) break; r = SSH_ERR_SYSTEM_ERROR; goto out; } if ((r = sshbuf_put(blob, buf, len)) != 0) goto out; if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) { r = SSH_ERR_INVALID_FORMAT; goto out; } } if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 && st.st_size != (off_t)sshbuf_len(blob)) { r = SSH_ERR_FILE_CHANGED; goto out; } r = 0; out: explicit_bzero(buf, sizeof(buf)); if (r != 0) sshbuf_reset(blob); return r; } CWE ID: CWE-320 Target: 1 Example 2: Code: raptor_libxml_entityDecl(void* user_data, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content) { raptor_sax2* sax2 = (raptor_sax2*)user_data; libxml2_entityDecl(sax2->xc, name, type, publicId, systemId, content); } 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 CommandBufferProxyImpl::Echo(const base::Closure& callback) { if (last_state_.error != gpu::error::kNoError) { return false; } if (!Send(new GpuCommandBufferMsg_Echo(route_id_, GpuCommandBufferMsg_EchoAck(route_id_)))) { return false; } echo_tasks_.push(callback); return true; } CWE ID: Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static ssize_t exitcode_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) { char *end, buf[sizeof("nnnnn\0")]; int tmp; if (copy_from_user(buf, buffer, count)) return -EFAULT; tmp = simple_strtol(buf, &end, 0); if ((*end != '\0') && !isspace(*end)) return -EINVAL; uml_exitcode = tmp; return count; } CWE ID: CWE-119 Target: 1 Example 2: Code: ssize_t read_code(struct file *file, unsigned long addr, loff_t pos, size_t len) { ssize_t res = vfs_read(file, (void __user *)addr, len, &pos); if (res > 0) flush_icache_range(addr, addr + len); return res; } 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: long Chapters::Atom::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x00) // Display ID { status = ParseDisplay(pReader, pos, size); if (status < 0) // error return status; } else if (id == 0x1654) // StringUID ID { status = UnserializeString(pReader, pos, size, m_string_uid); if (status < 0) // error return status; } else if (id == 0x33C4) // UID ID { long long val; status = UnserializeInt(pReader, pos, size, val); if (status < 0) // error return status; m_uid = val; } else if (id == 0x11) // TimeStart ID { const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_start_timecode = val; } else if (id == 0x12) // TimeEnd ID { const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_stop_timecode = val; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: UnacceleratedStaticBitmapImage::MakeAccelerated( base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_wrapper) { if (!context_wrapper) return nullptr; // Can happen if the context is lost. GrContext* grcontext = context_wrapper->ContextProvider()->GetGrContext(); if (!grcontext) return nullptr; // Can happen if the context is lost. sk_sp<SkImage> sk_image = paint_image_.GetSkImage(); sk_sp<SkImage> gpu_skimage = sk_image->makeTextureImage(grcontext, sk_image->colorSpace()); if (!gpu_skimage) return nullptr; return AcceleratedStaticBitmapImage::CreateFromSkImage( std::move(gpu_skimage), std::move(context_wrapper)); } CWE ID: CWE-119 Target: 1 Example 2: Code: size_t keyboard_controller_observer_count() const { return keyboard_controller_.observer_count(); } CWE ID: CWE-20 Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool GetWindowFromWindowID(UIThreadExtensionFunction* function, int window_id, WindowController** controller) { if (window_id == extension_misc::kCurrentWindowId) { WindowController* extension_window_controller = function->dispatcher()->delegate()->GetExtensionWindowController(); if (extension_window_controller) { *controller = extension_window_controller; } else { *controller = WindowControllerList::GetInstance()-> CurrentWindowForFunction(function); } if (!(*controller)) { function->SetError(keys::kNoCurrentWindowError); return false; } } else { *controller = WindowControllerList::GetInstance()-> FindWindowForFunctionById(function, window_id); if (!(*controller)) { function->SetError(ErrorUtils::FormatErrorMessage( keys::kWindowNotFoundError, base::IntToString(window_id))); return false; } } return true; } CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: v8::Handle<v8::Value> V8WebKitMutationObserver::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.WebKitMutationObserver.Constructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("DOM object constructor cannot be called as a function."); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); v8::Local<v8::Value> arg = args[0]; if (!arg->IsObject()) return throwError(TYPE_MISMATCH_ERR, args.GetIsolate()); ScriptExecutionContext* context = getScriptExecutionContext(); if (!context) return V8Proxy::throwError(V8Proxy::ReferenceError, "WebKitMutationObserver constructor's associated frame unavailable", args.GetIsolate()); RefPtr<MutationCallback> callback = V8MutationCallback::create(arg, context); RefPtr<WebKitMutationObserver> observer = WebKitMutationObserver::create(callback.release()); V8DOMWrapper::setDOMWrapper(args.Holder(), &info, observer.get()); V8DOMWrapper::setJSWrapperForDOMObject(observer.release(), v8::Persistent<v8::Object>::New(args.Holder())); return args.Holder(); } CWE ID: Target: 1 Example 2: Code: Range* Document::caretRangeFromPoint(int x, int y) { if (GetLayoutViewItem().IsNull()) return nullptr; HitTestResult result = HitTestInDocument(this, x, y); PositionWithAffinity position_with_affinity = result.GetPosition(); if (position_with_affinity.IsNull()) return nullptr; Position range_compliant_position = position_with_affinity.GetPosition().ParentAnchoredEquivalent(); return Range::CreateAdjustedToTreeScope(*this, range_compliant_position); } 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: int ahash_mcryptd_update(struct ahash_request *desc) { /* alignment is to be done by multi-buffer crypto algorithm if needed */ return crypto_ahash_update(desc); } 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: void AddChunk(const TransformPaintPropertyNode* t, const ClipPaintPropertyNode* c, const EffectPaintPropertyNode* e, const FloatRect& bounds = FloatRect(0, 0, 100, 100)) { auto record = sk_make_sp<PaintRecord>(); record->push<cc::DrawRectOp>(bounds, cc::PaintFlags()); AddChunk(std::move(record), t, c, e, bounds); } CWE ID: Target: 1 Example 2: Code: OxideQQuickWebView::RestoreType OxideQQuickWebView::restoreType() const { Q_D(const OxideQQuickWebView); return RestoreLastSessionExitedCleanly; } 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: PHP_MINFO_FUNCTION(gd) { php_info_print_table_start(); php_info_print_table_row(2, "GD Support", "enabled"); /* need to use a PHPAPI function here because it is external module in windows */ #if defined(HAVE_GD_BUNDLED) php_info_print_table_row(2, "GD Version", PHP_GD_VERSION_STRING); #else php_info_print_table_row(2, "GD headers Version", PHP_GD_VERSION_STRING); #if defined(HAVE_GD_LIBVERSION) php_info_print_table_row(2, "GD library Version", gdVersionString()); #endif #endif #ifdef ENABLE_GD_TTF php_info_print_table_row(2, "FreeType Support", "enabled"); #if HAVE_LIBFREETYPE php_info_print_table_row(2, "FreeType Linkage", "with freetype"); { char tmp[256]; #ifdef FREETYPE_PATCH snprintf(tmp, sizeof(tmp), "%d.%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR, FREETYPE_PATCH); #elif defined(FREETYPE_MAJOR) snprintf(tmp, sizeof(tmp), "%d.%d", FREETYPE_MAJOR, FREETYPE_MINOR); #else snprintf(tmp, sizeof(tmp), "1.x"); #endif php_info_print_table_row(2, "FreeType Version", tmp); } #else php_info_print_table_row(2, "FreeType Linkage", "with unknown library"); #endif #endif #ifdef HAVE_LIBT1 php_info_print_table_row(2, "T1Lib Support", "enabled"); #endif php_info_print_table_row(2, "GIF Read Support", "enabled"); php_info_print_table_row(2, "GIF Create Support", "enabled"); #ifdef HAVE_GD_JPG { php_info_print_table_row(2, "JPEG Support", "enabled"); php_info_print_table_row(2, "libJPEG Version", gdJpegGetVersionString()); } #endif #ifdef HAVE_GD_PNG php_info_print_table_row(2, "PNG Support", "enabled"); php_info_print_table_row(2, "libPNG Version", gdPngGetVersionString()); #endif php_info_print_table_row(2, "WBMP Support", "enabled"); #if defined(HAVE_GD_XPM) php_info_print_table_row(2, "XPM Support", "enabled"); { char tmp[12]; snprintf(tmp, sizeof(tmp), "%d", XpmLibraryVersion()); php_info_print_table_row(2, "libXpm Version", tmp); } #endif php_info_print_table_row(2, "XBM Support", "enabled"); #if defined(USE_GD_JISX0208) php_info_print_table_row(2, "JIS-mapped Japanese Font Support", "enabled"); #endif #ifdef HAVE_GD_WEBP php_info_print_table_row(2, "WebP Support", "enabled"); #endif php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code and CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: findoprnd(ITEM *ptr, int32 *pos) { #ifdef BS_DEBUG elog(DEBUG3, (ptr[*pos].type == OPR) ? "%d %c" : "%d %d", *pos, ptr[*pos].val); #endif if (ptr[*pos].type == VAL) { ptr[*pos].left = 0; (*pos)--; } else if (ptr[*pos].val == (int32) '!') { ptr[*pos].left = -1; (*pos)--; findoprnd(ptr, pos); } else { ITEM *curitem = &ptr[*pos]; int32 tmp = *pos; (*pos)--; findoprnd(ptr, pos); curitem->left = *pos - tmp; findoprnd(ptr, pos); } } CWE ID: CWE-189 Target: 1 Example 2: Code: HFSBTreeIterator::~HFSBTreeIterator() {} CWE ID: Target: 0 Now analyze the following code and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int vlan_dev_fcoe_get_wwn(struct net_device *dev, u64 *wwn, int type) { struct net_device *real_dev = vlan_dev_info(dev)->real_dev; const struct net_device_ops *ops = real_dev->netdev_ops; int rc = -EINVAL; if (ops->ndo_fcoe_get_wwn) rc = ops->ndo_fcoe_get_wwn(real_dev, wwn, type); return rc; } 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: _PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, size_t len, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ uint8_t buf[4]; smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = MIN(len, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); if (descriptor == (smb_iconv_t)-1) { *bytes_consumed = 1; return INVALID_CODEPOINT; } /* * this looks a little strange, but it is needed to cope with * codepoints above 64k (U+1000) which are encoded as per RFC2781. */ olen = 2; outbuf = (char *)buf; smb_iconv(descriptor, &str, &ilen, &outbuf, &olen); if (olen == 2) { olen = 4; outbuf = (char *)buf; smb_iconv(descriptor, &str, &ilen, &outbuf, &olen); if (olen == 4) { /* we didn't convert any bytes */ *bytes_consumed = 1; return INVALID_CODEPOINT; } olen = 4 - olen; } else { olen = 2 - olen; } *bytes_consumed = ilen_orig - ilen; if (olen == 2) { return (codepoint_t)SVAL(buf, 0); } if (olen == 4) { /* decode a 4 byte UTF16 character manually */ return (codepoint_t)0x10000 + (buf[2] | ((buf[3] & 0x3)<<8) | (buf[0]<<10) | ((buf[1] & 0x3)<<18)); } /* no other length is valid */ return INVALID_CODEPOINT; } CWE ID: CWE-200 Target: 1 Example 2: Code: SMB2_logoff(const unsigned int xid, struct cifs_ses *ses) { struct smb2_logoff_req *req; /* response is also trivial struct */ int rc = 0; struct TCP_Server_Info *server; int flags = 0; cifs_dbg(FYI, "disconnect session %p\n", ses); if (ses && (ses->server)) server = ses->server; else return -EIO; /* no need to send SMB logoff if uid already closed due to reconnect */ if (ses->need_reconnect) goto smb2_session_already_dead; rc = small_smb2_init(SMB2_LOGOFF, NULL, (void **) &req); if (rc) return rc; /* since no tcon, smb2_init can not do this, so do here */ req->hdr.sync_hdr.SessionId = ses->Suid; if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) flags |= CIFS_TRANSFORM_REQ; else if (server->sign) req->hdr.sync_hdr.Flags |= SMB2_FLAGS_SIGNED; rc = SendReceiveNoRsp(xid, ses, (char *) req, flags); cifs_small_buf_release(req); /* * No tcon so can't do * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]); */ smb2_session_already_dead: return rc; } 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 void coroutine_fn v9fs_xattrcreate(void *opaque) { int flags; int32_t fid; int64_t size; ssize_t err = 0; V9fsString name; size_t offset = 7; V9fsFidState *file_fidp; V9fsFidState *xattr_fidp; V9fsPDU *pdu = opaque; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags); if (err < 0) { goto out_nofid; } trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags); file_fidp = get_fid(pdu, fid); if (file_fidp == NULL) { err = -EINVAL; goto out_nofid; } /* Make the file fid point to xattr */ xattr_fidp = file_fidp; xattr_fidp->fid_type = P9_FID_XATTR; xattr_fidp->fs.xattr.copied_len = 0; xattr_fidp->fs.xattr.len = size; xattr_fidp->fs.xattr.flags = flags; v9fs_string_init(&xattr_fidp->fs.xattr.name); v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name); xattr_fidp->fs.xattr.value = g_malloc0(size); err = offset; put_fid(pdu, file_fidp); pdu_complete(pdu, err); v9fs_string_free(&name); } CWE ID: CWE-399 Output:
1