#include #include #include #include #include #include #include #include #include #include namespace vls::semantic { namespace fs = std::filesystem; namespace File = Void::LanguageServer::Detail; using Void::System::OwnedFd; using Issue = SourceIssue; // Shared by old and new grant generations. Historical readers keep their own reservations. struct SourceAccounting { std::mutex mutex; std::size_t handles{}, descriptors{}, bytes{}; }; namespace { auto fail(Issue issue, const fs::path &path = {}) { return std::unexpected(SourceError{issue, path.native().size() <= 4095 ? path : fs::path{}}); } struct Reservation { std::shared_ptr account; std::size_t descriptors{}, bytes{}; explicit Reservation(std::shared_ptr account) : account(std::move(account)) {} Reservation(const Reservation &) = delete; ~Reservation() { std::lock_guard lock{account->mutex}; --account->handles; account->descriptors -= descriptors; account->bytes -= bytes; } bool claim(std::size_t fds, std::size_t size) { std::lock_guard lock{account->mutex}; if (fds > 512 - account->descriptors || size > 192 * 1024 * 1024 - account->bytes) return false; account->descriptors += fds; account->bytes += size; descriptors += fds; bytes += size; return true; } }; std::shared_ptr reserve(const std::shared_ptr &account) { std::lock_guard lock{account->mutex}; if (account->handles >= 64) return {}; auto reservation = std::make_shared(account); ++account->handles; return reservation; } bool direct_name(const fs::path &path) { return File::valid_path(path) && path.is_absolute() && path.native() == path.lexically_normal().native() && (path == path.root_path() || path.has_filename()) && std::distance(path.begin(), path.end()) <= 64; } bool below(const fs::path &path, const fs::path &root) { auto [r, p] = std::mismatch(root.begin(), root.end(), path.begin(), path.end()); return r == root.end() && p != path.end(); } struct Pin { OwnedFd fd; struct stat state; }; using Directory = std::shared_ptr; bool same_object(const struct stat &a, const struct stat &b) { return a.st_dev == b.st_dev && a.st_ino == b.st_ino; } OwnedFd open_directory(const fs::path &path) { open_how how{}; how.flags = O_PATH | O_CLOEXEC | O_DIRECTORY; how.resolve = RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS; return OwnedFd{ static_cast(::syscall(SYS_openat2, AT_FDCWD, path.c_str(), &how, sizeof how))}; } std::expected pin_directory(const fs::path &path, Reservation &reservation) { auto fd = open_directory(path); struct stat state{}; if (!fd) return fail(errno == ELOOP || errno == ENOTDIR ? Issue::unsupported_route : Issue::unavailable, path); if (::fstat(fd.get(), &state) != 0) return fail(Issue::unavailable, path); if (!reservation.claim(1, path.native().size())) return fail(Issue::resource_limit, path); return std::make_shared(std::move(fd), state); } bool directory_current(const fs::path &path, const Pin &pin) { auto fd = open_directory(path); struct stat state{}; return fd && ::fstat(fd.get(), &state) == 0 && same_object(pin.state, state); } SourceIssue from_document(const Documents::DocumentError &error) { using K = Documents::DocumentError::Kind; switch (error.kind) { case K::resource_limit: return Issue::resource_limit; case K::stale_read: return Issue::changed; case K::invalid_utf8: return Issue::invalid_text; case K::invalid_uri: return Issue::invalid_path; default: return Issue::unavailable_overlay; } } struct Leaf { Directory parent; fs::path name; OwnedFd object; struct stat state{}; }; bool leaf_current(const Leaf &leaf) { struct stat state{}; if (::fstatat(leaf.parent->fd.get(), leaf.name.c_str(), &state, AT_SYMLINK_NOFOLLOW) != 0) return !leaf.object && errno == ENOENT; return leaf.object && File::same_file_state(leaf.state, state); } } // namespace struct SourceGrant { SourceScope scope; std::shared_ptr reservation; Directory workspace; std::map roots; }; struct SourceEvidence { InstalledSourceGrant grant; std::shared_ptr reservation; Documents::FileOverlayGeneration membership; std::map directories; std::vector> leaves; std::vector observations; std::atomic_bool expired{}; SourceEvidence(InstalledSourceGrant grant, std::shared_ptr reservation, Documents::FileOverlayGeneration membership) : grant(std::move(grant)), reservation(std::move(reservation)), membership(std::move(membership)) {} }; SourceCapture::SourceCapture(std::shared_ptr evidence) : evidence_(std::move(evidence)) {} SourceCatalog::SourceCatalog(const Documents::DocumentStore &documents, std::function before_capture_validation) : documents_(documents), accounting_(std::make_shared()), before_capture_validation_(std::move(before_capture_validation)) {} std::expected SourceCatalog::install(const SourceScope &scope, std::span directories) { std::lock_guard lock{installations_}; installed_.store({}); if (!direct_name(scope.workspace.root) || scope.workspace.session.empty() || scope.workspace.session.size() > 4096 || scope.workspace.session.contains('\0')) return fail(Issue::invalid_path, scope.workspace.root); if (directories.empty() || directories.size() > 32) return fail(Issue::resource_limit); auto reservation = reserve(accounting_); if (!reservation) return fail(Issue::resource_limit); auto workspace = pin_directory(scope.workspace.root, *reservation); if (!workspace) return std::unexpected(workspace.error()); auto grant = std::make_shared(scope, std::move(reservation), *workspace, std::map{}); for (const auto &name : directories) { if (!direct_name(name)) return fail(Issue::invalid_path, name); if (grant->roots.contains(name)) continue; auto pin = name == scope.workspace.root ? workspace : pin_directory(name, *grant->reservation); if (!pin) return std::unexpected(pin.error()); grant->roots.emplace(name, std::move(*pin)); } installed_.store(grant); return grant; } void SourceCatalog::revoke() { std::lock_guard lock{installations_}; installed_.store({}); } namespace { using Roots = std::map; Roots::const_iterator owning_root(const Roots &roots, const fs::path &path) { auto owner = roots.end(); for (auto root = roots.begin(); root != roots.end(); ++root) if (below(path, root->first) && (owner == roots.end() || root->first.native().size() > owner->first.native().size())) owner = root; return owner; } std::expected check_requests(const SourceGrant &grant, std::span requests, const SourceLimits &limits) { if (requests.size() > std::min(limits.files, SourceLimits{}.files)) return fail(Issue::resource_limit); auto remaining = std::min(limits.name_bytes, SourceLimits{}.name_bytes); std::set file_names; for (const auto &[path, allow_missing, lookup_only] : requests) { if (!direct_name(path) || !path.has_filename()) return fail(Issue::invalid_path, path); if (path.native().size() > remaining) return fail(Issue::resource_limit, path); remaining -= path.native().size(); if (owning_root(grant.roots, path) == grant.roots.end() && !(lookup_only && grant.roots.contains(path))) return fail(Issue::outside_scope, path); if (!lookup_only) file_names.insert(path); } for (const auto &request : requests) for (auto p = request.path.parent_path(); p != p.root_path(); p = p.parent_path()) if (file_names.contains(p)) return fail(Issue::conflicting_names, request.path); return {}; } std::expected parent_directory(SourceEvidence &evidence, const fs::path &path, std::size_t max_fds) { const auto root = owning_root(evidence.grant->roots, path); auto name = root->first; auto current = root->second; if (!directory_current(name, *current)) return fail(Issue::changed, name); evidence.directories.try_emplace(name, current); const auto relative = path.lexically_relative(name); for (const auto &part : relative.parent_path()) { name /= part; if (auto i = evidence.directories.find(name); i != evidence.directories.end()) { current = i->second; continue; } OwnedFd fd{::openat(current->fd.get(), part.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)}; if (!fd) return fail(errno == ENOENT ? Issue::missing_parent : Issue::unavailable, name); struct stat state{}; if (::fstat(fd.get(), &state) != 0) return fail(Issue::unavailable, name); if (!S_ISDIR(state.st_mode)) return fail(Issue::unsupported_route, name); if (evidence.reservation->descriptors >= max_fds || !evidence.reservation->claim(1, name.native().size())) return fail(Issue::resource_limit, name); current = std::make_shared(std::move(fd), state); evidence.directories.emplace(name, current); } // A cached intermediate directory may have moved since the previous request. if (!directory_current(name, *current)) return fail(Issue::changed, name); return current; } std::expected bind_leaf(Directory parent, const fs::path &path, Reservation &budget, std::size_t max_fds, bool allow_directory = false) { Leaf leaf{std::move(parent), path.filename(), {}}; leaf.object = OwnedFd{ ::openat(leaf.parent->fd.get(), leaf.name.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)}; if (!leaf.object) { if (errno == ENOENT) return leaf; return fail(Issue::unavailable, path); } if (::fstat(leaf.object.get(), &leaf.state) != 0) return fail(Issue::unavailable, path); if (S_ISLNK(leaf.state.st_mode)) return fail(Issue::unsupported_route, path); if (!S_ISREG(leaf.state.st_mode) && !(allow_directory && S_ISDIR(leaf.state.st_mode))) return fail(Issue::not_regular, path); if (S_ISREG(leaf.state.st_mode) && leaf.state.st_nlink != 1) return fail(Issue::hard_link, path); if (budget.descriptors >= max_fds || !budget.claim(1, 0)) return fail(Issue::resource_limit, path); return leaf; } using Snapshot = std::shared_ptr; std::expected read_source(const Documents::DocumentStore &documents, const Documents::BoundSourceObservation &observation, const Leaf &leaf, const SourceRequest &request, Reservation &budget, std::size_t limit) { const auto &overlay = observation.overlay(); if (!overlay && !leaf.object) { if (!request.allow_missing) return fail(Issue::missing, request.path); return Snapshot{}; } if (!overlay && leaf.state.st_size < 0) return fail(Issue::unavailable, request.path); const auto size = overlay ? overlay->text.size() : static_cast(leaf.state.st_size); if (size > limit || !budget.claim(0, size)) return fail(Issue::resource_limit, request.path); if (overlay) return overlay; std::string bytes; bytes.reserve(size); auto result = File::stream_regular_fd( leaf.object, leaf.state, limit, false, [&](std::span chunk) { bytes.append(reinterpret_cast(chunk.data()), chunk.size()); return true; }); if (!result) return fail(result.error() == File::FileError::changed ? Issue::changed : Issue::unavailable, request.path); auto snapshot = documents.materialize_bound_disk(observation, std::move(bytes)); if (!snapshot) return fail(from_document(snapshot.error()), request.path); return *snapshot; } } // namespace std::expected, SourceError> SourceCatalog::capture(const SourceScope &job, const InstalledSourceGrant &grant, const Documents::FileOverlayInventory &census, std::span requests, SourceLimits limits) const { if (!grant || installed_.load() != grant || job != grant->scope) return fail(Issue::wrong_authority); if (!directory_current(job.workspace.root, *grant->workspace)) return fail(Issue::changed, job.workspace.root); if (auto checked = check_requests(*grant, requests, limits); !checked) return std::unexpected(checked.error()); if (auto checked = documents_.validate_bound_sources(census); !checked) return fail(from_document(checked.error())); auto reservation = reserve(accounting_); if (!reservation) return fail(Issue::resource_limit); auto evidence = std::make_shared(grant, std::move(reservation), census.generation()); std::shared_ptr result{new SourceCapture(evidence)}; auto remaining = std::min(limits.total_bytes, SourceLimits{}.total_bytes); const auto file_limit = std::min(limits.file_bytes, SourceLimits{}.file_bytes); const auto max_fds = std::min(limits.descriptors, SourceLimits{}.descriptors); std::map, fs::path> regular_names; std::set open_names; for (const auto &entry : census.entries()) open_names.insert(entry.identity.canonical_path); for (const auto &request : requests) { const auto &path = request.path; for (auto p = path.parent_path(); p != p.root_path(); p = p.parent_path()) if (open_names.contains(p)) return fail(Issue::conflicting_names, p); auto observed = documents_.observe_bound_source(census, Documents::path_to_file_uri(path), path); if (!observed) return fail(from_document(observed.error()), path); if (!evidence->reservation->claim(0, path.native().size())) return fail(Issue::resource_limit, path); if (auto root = grant->roots.find(path); request.lookup_only && root != grant->roots.end()) { if (observed->overlay()) return fail(Issue::conflicting_names, path); evidence->directories.try_emplace(path, root->second); evidence->observations.push_back(std::move(*observed)); result->entries_.push_back({path, {}, SourceNode::directory}); continue; } auto parent = parent_directory(*evidence, path, max_fds); if (!parent && request.lookup_only && parent.error().issue == Issue::missing_parent) { const auto &first_missing = parent.error().path; auto it = open_names.lower_bound(first_missing); if (it != open_names.end() && (*it == first_missing || below(*it, first_missing))) return fail(Issue::missing_parent, first_missing); auto anchor = evidence->directories.find(first_missing.parent_path()); if (anchor == evidence->directories.end()) return fail(Issue::changed, first_missing); Leaf missing{anchor->second, first_missing.filename(), {}}; evidence->leaves.emplace_back(first_missing, std::move(missing)); evidence->observations.push_back(std::move(*observed)); result->entries_.push_back({path, {}, SourceNode::missing}); continue; } if (!parent) return std::unexpected(parent.error()); auto leaf = bind_leaf(*parent, path, *evidence->reservation, max_fds, request.lookup_only); if (!leaf) return std::unexpected(leaf.error()); if (leaf->object && S_ISDIR(leaf->state.st_mode)) { if (observed->overlay()) return fail(Issue::conflicting_names, path); evidence->directories.try_emplace( path, std::make_shared(std::move(leaf->object), leaf->state)); evidence->observations.push_back(std::move(*observed)); result->entries_.push_back({path, {}, SourceNode::directory}); continue; } if (leaf->object) { auto [it, added] = regular_names.try_emplace({leaf->state.st_dev, leaf->state.st_ino}, path); if (!added && it->second != path) return fail(Issue::conflicting_names, path); } if (installed_.load() != grant) return fail(Issue::wrong_authority); const auto node = leaf->object || observed->overlay() ? SourceNode::regular : SourceNode::missing; if (node == SourceNode::missing) { const auto it = open_names.upper_bound(path); if (it != open_names.end() && below(*it, path)) return fail(Issue::missing_parent, path); } std::expected snapshot{Snapshot{}}; if (!request.lookup_only) snapshot = read_source(documents_, *observed, *leaf, request, *evidence->reservation, std::min(remaining, file_limit)); if (!snapshot) return std::unexpected(snapshot.error()); if (*snapshot) remaining -= (*snapshot)->text.size(); std::optional modified; if (*snapshot) modified = leaf->object ? leaf->state.st_mtim.tv_sec : (*snapshot)->created_at; result->entries_.push_back({path, std::move(*snapshot), node, modified}); evidence->leaves.emplace_back(path, std::move(*leaf)); evidence->observations.push_back(std::move(*observed)); } if (before_capture_validation_) before_capture_validation_(); if (auto checked = validate(job, *result); !checked) return std::unexpected(checked.error()); return result; } std::expected SourceCatalog::validate(const SourceScope &job, const SourceCapture &capture) const { auto &e = *capture.evidence_; if (e.grant != installed_.load() || e.grant->scope != job) return fail(Issue::wrong_authority); auto expire = [&](const fs::path &path) { e.expired = true; return fail(Issue::changed, path); }; if (e.expired || !directory_current(job.workspace.root, *e.grant->workspace)) return expire(job.workspace.root); for (const auto &[path, dir] : e.directories) if (!directory_current(path, *dir)) return expire(path); for (const auto &[path, leaf] : e.leaves) if (!leaf_current(leaf)) return expire(path); if (auto current = documents_.validate_bound_sources(e.membership, e.observations); !current) return expire({}); if (e.grant != installed_.load()) return fail(Issue::wrong_authority); if (e.expired) return fail(Issue::changed); return {}; } } // namespace vls::semantic