#include "Leaf.hpp" #include #ifdef __linux__ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // GNU ELF linkers expose the native executable header, including class, byte order and machine. extern "C" const ElfW(Ehdr) __ehdr_start; namespace vls::gcc { namespace { using Void::System::OwnedFd; namespace File = Void::LanguageServer::Detail; constexpr std::size_t mib = 1024 * 1024; constexpr std::size_t max_image = 256 * mib; constexpr int control_fd = 3; constexpr int events_fd = 4; constexpr int setup_failure = 126; bool lower_hex(std::string_view text, std::size_t size) { return text.size() == size && std::ranges::all_of(text, [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }); } bool pipe_end(int fd, int mode, struct stat &st) { const int flags = ::fcntl(fd, F_GETFL); return flags >= 0 && (flags & (O_ACCMODE | O_PATH)) == mode && ::fstat(fd, &st) == 0 && S_ISFIFO(st.st_mode); } bool same_object(const struct stat &a, const struct stat &b) { return a.st_dev == b.st_dev && a.st_ino == b.st_ino; } int fail(const char *reason, int error = 0) noexcept { // Even an invalid stdio setup must never put diagnostic bytes on the event/control channel. struct stat err{}, other{}; if (!pipe_end(STDERR_FILENO, O_WRONLY, err)) return setup_failure; for (int fd : {STDIN_FILENO, STDOUT_FILENO}) { if (::fstat(fd, &other) == 0 && same_object(err, other)) return setup_failure; } // The supervisor may have already closed or stopped draining its diagnostics pipe. const int flags = ::fcntl(STDERR_FILENO, F_GETFL); if (flags >= 0 && ::fcntl(STDERR_FILENO, F_SETFL, flags | O_NONBLOCK) == 0 && ::signal(SIGPIPE, SIG_IGN) != SIG_ERR) { char message[160]; const int n = error ? std::snprintf(message, sizeof message, "gcc leaf: %s (errno %d)\n", reason, error) : std::snprintf(message, sizeof message, "gcc leaf: %s\n", reason); if (n > 0 && static_cast(n) < sizeof message) (void)::write(STDERR_FILENO, message, static_cast(n)); } return setup_failure; } bool reset_signals() { struct sigaction action{}; action.sa_handler = SIG_DFL; ::sigemptyset(&action.sa_mask); for (int sig : {SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGPIPE, SIGXCPU, SIGXFSZ}) { if (::sigaction(sig, &action, nullptr) != 0) return false; } return ::sigprocmask(SIG_SETMASK, &action.sa_mask, nullptr) == 0; } bool cap_resource(int resource, rlim_t soft, rlim_t hard) { struct rlimit limit{}; if (::getrlimit(resource, &limit) != 0) return false; limit.rlim_cur = std::min(limit.rlim_cur, soft); limit.rlim_max = std::min(limit.rlim_max, hard); return ::setrlimit(resource, &limit) == 0; } bool write_chunk(int fd, std::span bytes) { while (!bytes.empty()) { const ssize_t count = ::write(fd, bytes.data(), bytes.size()); if (count < 0 && errno == EINTR) continue; if (count <= 0) return false; bytes = bytes.subspan(static_cast(count)); } return true; } bool complete_native_elf(std::span image) { const auto fits = [&](std::uint64_t offset, std::uint64_t size) { return offset <= image.size() && size <= image.size() - offset; }; ElfW(Ehdr) header{}; if (image.size() < sizeof header) return false; std::memcpy(&header, image.data(), sizeof header); if (std::memcmp(header.e_ident, __ehdr_start.e_ident, EI_VERSION + 1) != 0 || header.e_machine != __ehdr_start.e_machine || header.e_version != EV_CURRENT || (header.e_type != ET_EXEC && header.e_type != ET_DYN) || header.e_ehsize != sizeof header || header.e_phoff < sizeof header || header.e_phentsize != sizeof(ElfW(Phdr)) || !header.e_phnum || header.e_phnum == PN_XNUM || !fits(header.e_phoff, sizeof(ElfW(Phdr)) * header.e_phnum)) return false; // A truncated section table can leave an otherwise runnable prefix of the file. if (header.e_shoff || header.e_shnum || header.e_shstrndx) { if (header.e_shoff < sizeof header || !header.e_shnum || header.e_shstrndx >= header.e_shnum || header.e_shentsize != sizeof(ElfW(Shdr)) || !fits(header.e_shoff, sizeof(ElfW(Shdr)) * header.e_shnum)) return false; for (unsigned i = 0; i < header.e_shnum; ++i) { ElfW(Shdr) section{}; std::memcpy(§ion, image.data() + header.e_shoff + i * sizeof section, sizeof section); if (section.sh_type != SHT_NOBITS && !fits(section.sh_offset, section.sh_size)) return false; } } bool has_entry = false; for (unsigned i = 0; i < header.e_phnum; ++i) { ElfW(Phdr) segment{}; std::memcpy(&segment, image.data() + header.e_phoff + i * sizeof segment, sizeof segment); if (segment.p_filesz && !fits(segment.p_offset, segment.p_filesz)) return false; if (segment.p_type != PT_LOAD) continue; if (segment.p_filesz > segment.p_memsz) return false; if ((segment.p_flags & PF_X) && header.e_entry >= segment.p_vaddr && header.e_entry - segment.p_vaddr < segment.p_filesz) has_entry = true; } return has_entry; } const char *verify_bytes(std::span image, std::string_view expected) { if (!complete_native_elf(image)) return "incomplete or unsupported native ELF"; const auto digest = Void::Crypto::hash(Void::Crypto::HashAlgorithm::Sha256, image, {.prefer_builtin = true}); if (!digest || digest->size() != 32) return "SHA-256 unavailable"; constexpr std::string_view alphabet = "0123456789abcdef"; for (std::size_t i = 0; i < digest->size(); ++i) { const auto byte = std::to_integer((*digest)[i]); if (expected[2 * i] != alphabet[byte >> 4] || expected[2 * i + 1] != alphabet[byte & 15]) return "compiler SHA-256 mismatch"; } return nullptr; } int prepare_image(int image, const std::filesystem::path &compiler, std::string_view expected) { const open_how how{.flags = O_PATH | O_CLOEXEC, .mode = 0, .resolve = RESOLVE_NO_SYMLINKS}; const OwnedFd source{static_cast(::syscall(SYS_openat2, AT_FDCWD, compiler.c_str(), &how, sizeof how))}; struct stat before{}; if (!source || ::fstat(source.get(), &before) != 0) return fail("cannot open direct compiler path with openat2", errno); if (!S_ISREG(before.st_mode) || before.st_size <= 0 || static_cast(before.st_size) > max_image) return fail("expected a nonempty regular compiler within the image limit"); struct rlimit file_limit{}; if (::getrlimit(RLIMIT_FSIZE, &file_limit) != 0 || static_cast(before.st_size) > file_limit.rlim_cur) return fail("inherited file-size limit cannot hold the compiler"); const auto copied = File::stream_regular_fd(source, before, max_image, true, [&](auto chunk) { return write_chunk(image, chunk); }); if (!copied) return fail("failed to capture stable executable compiler"); constexpr int seals = F_SEAL_WRITE | F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_EXEC | F_SEAL_SEAL; if (::fchmod(image, S_IRUSR | S_IXUSR) != 0 || ::fcntl(image, F_ADD_SEALS, seals) != 0) return fail("kernel refused to seal the compiler memfd", errno); struct stat sealed{}; if (::fstat(image, &sealed) != 0 || sealed.st_size != before.st_size) return fail("sealed compiler size changed"); // Hash the sealed object itself. A concurrent source rewrite or pathname exchange cannot // change the bytes inspected here or the ELF the kernel will load. const auto size = static_cast(sealed.st_size); void *mapping = ::mmap(nullptr, size, PROT_READ, MAP_PRIVATE, image, 0); if (mapping == MAP_FAILED) return fail("cannot map sealed compiler", errno); struct Mapping { void *address; std::size_t size; ~Mapping() { ::munmap(address, size); } } view{mapping, size}; const auto *error = verify_bytes({static_cast(mapping), size}, expected); return error ? fail(error) : 0; } } // namespace int run_leaf(std::filesystem::path compiler, std::string_view expected_sha256, std::string_view nonce, bool stepping) try { struct stat in{}, out{}, err{}; if (!pipe_end(STDIN_FILENO, O_RDONLY, in) || !pipe_end(STDOUT_FILENO, O_WRONLY, out) || !pipe_end(STDERR_FILENO, O_WRONLY, err) || same_object(in, out) || same_object(in, err) || same_object(out, err)) return fail("expected three distinct directed pipes"); if (!lower_hex(nonce, 32) || !lower_hex(expected_sha256, 64)) return fail("invalid nonce or SHA-256"); if (!File::valid_path(compiler) || !compiler.is_absolute()) return fail("expected an absolute compiler path"); const OwnedFd control{::dup2(STDIN_FILENO, control_fd)}; const OwnedFd events{::dup2(STDOUT_FILENO, events_fd)}; if (!control || !events || ::fcntl(STDERR_FILENO, F_SETFD, 0) != 0 || ::close_range(events_fd + 1, UINT_MAX, 0) != 0) return fail("cannot isolate inherited descriptors", errno); const OwnedFd null{::open("/dev/null", O_RDWR | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK)}; struct stat device{}; if (!null || ::fstat(null.get(), &device) != 0 || !S_ISCHR(device.st_mode) || device.st_rdev != makedev(1, 3) || ::dup2(null.get(), STDIN_FILENO) < 0 || ::dup2(null.get(), STDOUT_FILENO) < 0) return fail("cannot isolate raw compiler stdio"); if (!reset_signals() || !cap_resource(RLIMIT_CORE, 0, 0) || !cap_resource(RLIMIT_AS, 768 * mib, 768 * mib) || !cap_resource(RLIMIT_CPU, 15, 20) || !cap_resource(RLIMIT_NOFILE, 32, 32)) return fail("cannot set compiler signals or resource limits", errno); const OwnedFd image{::memfd_create("vls-cc1plus", MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_EXEC)}; if (!image) return fail("executable memfd unsupported or denied", errno); if (const int status = prepare_image(image.get(), compiler, expected_sha256)) return status; if (!cap_resource(RLIMIT_FSIZE, mib, mib)) return fail("cannot set compiler output limit", errno); char nonce_env[] = "VLS_GCC_NONCE=00000000000000000000000000000000"; std::memcpy(nonce_env + sizeof("VLS_GCC_NONCE=") - 1, nonce.data(), nonce.size()); const char *environment[] = {"LC_ALL=C", "PATH=", nonce_env, nullptr}; const char *arguments[] = {"cc1plus", "-quiet", "-std=c++26", "-freflection", "-fsyntax-only", "-nostdinc", "-o", "/dev/null", "-fvls-observe", stepping ? "-fvls-step" : "input.cpp", stepping ? "input.cpp" : nullptr, nullptr}; ::execveat(image.get(), "", const_cast(arguments), const_cast(environment), AT_EMPTY_PATH); return fail("execveat of sealed compiler failed", errno); } catch (...) { return fail("compiler image setup failed"); } } // namespace vls::gcc #else int vls::gcc::run_leaf(std::filesystem::path, std::string_view, std::string_view, bool) { std::fputs("gcc leaf: Linux executable memfd support is required\n", stderr); return 126; } #endif