Native VBS and CMake builds of the server and every registered suite: protocol and document sync, VBS/compdb providers, stock GCC diagnostics (including in-process default profile preparation), the stock occurrence observer and hover/definition, the bounded Scheduler, C++ module graph, scan and artifact cache with real CMI production, the context-aware symbol index with schema-2 snapshot migration, navigation and guarded rename, reflection provenance with splice-origin extraction, index-backed completion and signature help, live GCC worker control with a registered DAP suite, and the Neovim and VS Code clients. VoidLibrary follows main. The private GCC 16.2.0 frontend is reproduced from the versioned patches and verified stepping reflection/template code with projected values 17/34 and 41/82.
1301 lines
51 KiB
C++
1301 lines
51 KiB
C++
#include "Trace.hpp"
|
|
|
|
#include <Void/Crypto/Crypto.hpp>
|
|
#include <Void/System/Types.hpp>
|
|
#include <Void/Unicode/Utf.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cerrno>
|
|
#include <cstring>
|
|
#include <fcntl.h>
|
|
#include <mutex>
|
|
#include <span>
|
|
#include <sys/stat.h>
|
|
#include <system_error>
|
|
#include <unistd.h>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace vls::gcc {
|
|
namespace {
|
|
|
|
using Protocol::as_array;
|
|
using Protocol::as_bool;
|
|
using Protocol::as_object;
|
|
using Protocol::as_string;
|
|
using Protocol::find_member;
|
|
using Protocol::Json;
|
|
using Void::System::OwnedFd;
|
|
using namespace std::string_view_literals;
|
|
|
|
constexpr auto backend = "gcc-16.2.0/vls-eval-1"sv;
|
|
constexpr std::uint32_t max_events = 4096;
|
|
constexpr std::size_t max_event = 4096; // Includes the compiler's LF.
|
|
constexpr std::size_t max_trace = 1024 * 1024;
|
|
constexpr std::size_t max_source = 1024 * 1024;
|
|
constexpr std::size_t max_diagnostics = 1024 * 1024;
|
|
constexpr std::size_t max_metadata = 1024;
|
|
constexpr std::size_t max_command = 128;
|
|
constexpr std::size_t json_depth = 4;
|
|
|
|
constexpr auto magic = "VLSTRC1\n"sv;
|
|
constexpr auto hex_digits = "0123456789abcdef"sv;
|
|
using Digest = std::array<char, 32>;
|
|
using RecordHeader = std::array<char, 5>;
|
|
|
|
// One manifest, one finish, and at most one command per compiler event.
|
|
constexpr std::size_t max_journal_bytes =
|
|
magic.size() + max_source + max_diagnostics + 2 * (max_metadata + 1) + max_trace +
|
|
max_events * max_command + (2 + 2 * max_events) * (sizeof(RecordHeader) + sizeof(Digest));
|
|
|
|
enum class RecordType : char { manifest = 'M', event = 'E', command = 'C', finish = 'F' };
|
|
|
|
std::size_t payload_limit(RecordType type) {
|
|
switch (type) {
|
|
case RecordType::manifest:
|
|
return max_metadata + 1 + max_source;
|
|
case RecordType::event:
|
|
return max_event - 1;
|
|
case RecordType::command:
|
|
return max_command;
|
|
case RecordType::finish:
|
|
return max_metadata + 1 + max_diagnostics;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
std::string io_error(std::string_view operation) {
|
|
const auto error = std::error_code(errno, std::generic_category());
|
|
return std::string{operation} + ": " + error.message();
|
|
}
|
|
|
|
bool write_all(int fd, std::span<const char> bytes) {
|
|
while (!bytes.empty()) {
|
|
const auto count = ::write(fd, bytes.data(), bytes.size());
|
|
if (count < 0 && errno == EINTR) {
|
|
continue;
|
|
}
|
|
if (count <= 0) {
|
|
if (count == 0) {
|
|
errno = EIO;
|
|
}
|
|
return false;
|
|
}
|
|
bytes = bytes.subspan(static_cast<std::size_t>(count));
|
|
}
|
|
return true;
|
|
}
|
|
|
|
enum class ReadStatus { complete, short_read, error };
|
|
|
|
ReadStatus read_all(int fd, std::span<char> bytes) {
|
|
while (!bytes.empty()) {
|
|
const auto count = ::read(fd, bytes.data(), bytes.size());
|
|
if (count < 0 && errno == EINTR) {
|
|
continue;
|
|
}
|
|
if (count <= 0) {
|
|
return count == 0 ? ReadStatus::short_read : ReadStatus::error;
|
|
}
|
|
bytes = bytes.subspan(static_cast<std::size_t>(count));
|
|
}
|
|
return ReadStatus::complete;
|
|
}
|
|
|
|
bool sync(int fd) {
|
|
int result;
|
|
do {
|
|
result = ::fsync(fd);
|
|
} while (result < 0 && errno == EINTR);
|
|
return result == 0;
|
|
}
|
|
|
|
std::string hex(std::span<const std::byte> bytes) {
|
|
std::string encoded;
|
|
encoded.reserve(bytes.size() * 2);
|
|
for (const auto byte : bytes) {
|
|
const auto value = std::to_integer<unsigned>(byte);
|
|
encoded.push_back(hex_digits[value >> 4u]);
|
|
encoded.push_back(hex_digits[value & 15u]);
|
|
}
|
|
return encoded;
|
|
}
|
|
|
|
bool is_hex(std::string_view text, std::size_t size) {
|
|
return text.size() == size &&
|
|
std::ranges::all_of(text, [](char ch) { return hex_digits.contains(ch); });
|
|
}
|
|
|
|
std::expected<Digest, std::string> record_digest(const Digest &previous, const RecordHeader &header,
|
|
std::string_view payload) {
|
|
auto hasher = Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256);
|
|
if (!hasher || !hasher->update(std::as_bytes(std::span{previous})) ||
|
|
!hasher->update(std::as_bytes(std::span{header})) || !hasher->update(payload)) {
|
|
return std::unexpected{"cannot hash trace record"};
|
|
}
|
|
const auto hashed = hasher->finalize();
|
|
Digest result;
|
|
if (!hashed || hashed->size() != result.size()) {
|
|
return std::unexpected{"cannot finalize trace record hash"};
|
|
}
|
|
std::memcpy(result.data(), hashed->data(), result.size());
|
|
return result;
|
|
}
|
|
|
|
// Magic, then records of type, big-endian u32 length, digest, and exact payload bytes.
|
|
// The digest covers the previous digest (zero for the manifest), type/length, and payload.
|
|
class JournalWriter {
|
|
public:
|
|
explicit JournalWriter(OwnedFd fd) : fd_(std::move(fd)) {}
|
|
|
|
TraceResult append(RecordType type, std::string_view payload) {
|
|
if (failed_) {
|
|
return std::unexpected{"trace journal is unavailable after a write failure"};
|
|
}
|
|
if (payload.empty() || payload.size() > payload_limit(type)) {
|
|
return std::unexpected{"trace journal record is out of bounds"};
|
|
}
|
|
const std::size_t size = payload.size();
|
|
const RecordHeader header{static_cast<char>(type), static_cast<char>(size >> 24u),
|
|
static_cast<char>(size >> 16u), static_cast<char>(size >> 8u),
|
|
static_cast<char>(size)};
|
|
auto digest = record_digest(previous_, header, payload);
|
|
if (!digest) {
|
|
return std::unexpected{std::move(digest.error())};
|
|
}
|
|
if (!write_all(fd_.get(), header) || !write_all(fd_.get(), *digest) ||
|
|
!write_all(fd_.get(), payload) || !sync(fd_.get())) {
|
|
failed_ = true;
|
|
return std::unexpected{io_error("cannot append trace journal")};
|
|
}
|
|
previous_ = *digest;
|
|
return {};
|
|
}
|
|
|
|
private:
|
|
OwnedFd fd_;
|
|
Digest previous_{};
|
|
bool failed_{};
|
|
};
|
|
|
|
bool valid_path(const std::filesystem::path &path) {
|
|
const auto name = path.filename();
|
|
return !name.empty() && name != "." && name != ".." && !path.native().contains('\0');
|
|
}
|
|
|
|
std::expected<JournalWriter, std::string> create_journal(const std::filesystem::path &path,
|
|
std::string_view manifest) {
|
|
if (!valid_path(path)) {
|
|
return std::unexpected{"invalid trace journal path"};
|
|
}
|
|
auto parent = path.parent_path();
|
|
if (parent.empty()) {
|
|
parent = ".";
|
|
}
|
|
const OwnedFd directory{::open(parent.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC)};
|
|
if (!directory) {
|
|
return std::unexpected{io_error("cannot open trace journal directory")};
|
|
}
|
|
OwnedFd fd{::openat(directory.get(), path.filename().c_str(),
|
|
O_WRONLY | O_CREAT | O_EXCL | O_APPEND | O_NOFOLLOW | O_CLOEXEC, 0600)};
|
|
if (!fd) {
|
|
return std::unexpected{io_error("cannot exclusively create trace journal")};
|
|
}
|
|
if (::fchmod(fd.get(), 0600) != 0 || !write_all(fd.get(), magic)) {
|
|
return std::unexpected{io_error("cannot initialize trace journal")};
|
|
}
|
|
JournalWriter journal{std::move(fd)};
|
|
if (auto result = journal.append(RecordType::manifest, manifest); !result) {
|
|
return std::unexpected{std::move(result.error())};
|
|
}
|
|
if (!sync(directory.get())) {
|
|
return std::unexpected{io_error("cannot sync trace journal directory")};
|
|
}
|
|
return journal;
|
|
}
|
|
|
|
struct Record {
|
|
RecordType type;
|
|
std::string payload;
|
|
};
|
|
|
|
struct ReadFailure {
|
|
std::string message;
|
|
bool corrupt;
|
|
};
|
|
|
|
class JournalReader {
|
|
public:
|
|
JournalReader(int fd, std::uintmax_t bytes) : fd_(fd), remaining_(bytes) {}
|
|
|
|
TraceResult read_magic() {
|
|
std::array<char, magic.size()> actual{};
|
|
if (auto result = take(actual); !result) {
|
|
return std::unexpected{std::move(result.error().message)};
|
|
}
|
|
if (std::string_view{actual.data(), actual.size()} != magic) {
|
|
return std::unexpected{"incompatible trace journal header"};
|
|
}
|
|
return {};
|
|
}
|
|
|
|
[[nodiscard]] bool has_remaining() const { return remaining_ != 0; }
|
|
|
|
std::expected<Record, ReadFailure> next() {
|
|
RecordHeader header;
|
|
if (auto result = take(header); !result) {
|
|
return std::unexpected{std::move(result.error())};
|
|
}
|
|
const auto type = static_cast<RecordType>(header[0]);
|
|
std::uint32_t size = 0;
|
|
for (const auto byte : std::span{header}.subspan(1)) {
|
|
size = (size << 8u) | static_cast<unsigned char>(byte);
|
|
}
|
|
if (size == 0 || size > payload_limit(type)) {
|
|
return std::unexpected{
|
|
ReadFailure{"invalid trace journal record type or length", true}};
|
|
}
|
|
Digest stored;
|
|
if (stored.size() + size > remaining_) {
|
|
return std::unexpected{ReadFailure{"truncated trace journal record", false}};
|
|
}
|
|
if (auto result = take(stored); !result) {
|
|
return std::unexpected{std::move(result.error())};
|
|
}
|
|
std::string payload(size, '\0');
|
|
if (auto result = take(payload); !result) {
|
|
return std::unexpected{std::move(result.error())};
|
|
}
|
|
auto actual = record_digest(previous_, header, payload);
|
|
if (!actual) {
|
|
return std::unexpected{ReadFailure{std::move(actual.error()), false}};
|
|
}
|
|
if (*actual != stored) {
|
|
return std::unexpected{ReadFailure{"trace journal record hash mismatch", true}};
|
|
}
|
|
previous_ = stored;
|
|
return Record{type, std::move(payload)};
|
|
}
|
|
|
|
private:
|
|
std::expected<void, ReadFailure> take(std::span<char> bytes) {
|
|
if (bytes.size() > remaining_) {
|
|
return std::unexpected{ReadFailure{"truncated trace journal record", false}};
|
|
}
|
|
if (bytes.size() > budget_) {
|
|
return std::unexpected{ReadFailure{"trace journal exceeds the v1 byte limit", true}};
|
|
}
|
|
const auto status = read_all(fd_, bytes);
|
|
if (status != ReadStatus::complete) {
|
|
return std::unexpected{ReadFailure{status == ReadStatus::short_read
|
|
? "truncated trace journal record"
|
|
: io_error("cannot read trace journal"),
|
|
false}};
|
|
}
|
|
remaining_ -= bytes.size();
|
|
budget_ -= bytes.size();
|
|
return {};
|
|
}
|
|
|
|
int fd_;
|
|
std::uintmax_t remaining_;
|
|
std::size_t budget_ = max_journal_bytes;
|
|
Digest previous_{};
|
|
};
|
|
|
|
std::string_view text(const Json::Object &object, std::string_view name) {
|
|
const auto *string = as_string(find_member(object, name));
|
|
return string ? std::string_view{*string} : std::string_view{};
|
|
}
|
|
|
|
std::optional<std::int64_t> integer(const Json *field) {
|
|
// StrictJson preserves the distinction, even when a decimal rounds to an integer.
|
|
const auto *value = field ? std::get_if<std::int64_t>(&field->value) : nullptr;
|
|
return value ? std::optional{*value} : std::nullopt;
|
|
}
|
|
|
|
std::optional<std::uint32_t> ordinal(const Json::Object &object, std::string_view name) {
|
|
const auto number = integer(find_member(object, name));
|
|
if (!number || !std::in_range<std::uint32_t>(*number)) {
|
|
return std::nullopt;
|
|
}
|
|
return static_cast<std::uint32_t>(*number);
|
|
}
|
|
|
|
bool is_null(const Json *field) {
|
|
return field && std::holds_alternative<std::nullptr_t>(field->value);
|
|
}
|
|
|
|
Json json_text(std::string_view value) { return Json{std::string{value}}; }
|
|
|
|
Json nullable_ordinal(std::optional<std::uint32_t> number) {
|
|
return number ? Json{static_cast<std::int64_t>(*number)} : Json{nullptr};
|
|
}
|
|
|
|
// The source and diagnostics are raw bytes in the journal. Preserve non-UTF-8 input in
|
|
// the JSON projection with an explicit alternate encoding.
|
|
void add_bytes(Json::Object &object, std::string_view name, std::string_view bytes) {
|
|
if (Void::Unicode::validate_utf8(bytes)) {
|
|
object.emplace(name, json_text(bytes));
|
|
} else {
|
|
object.emplace(name, Json{nullptr});
|
|
object.emplace(std::string{name} + "Hex", Json{hex(std::as_bytes(std::span{bytes}))});
|
|
}
|
|
}
|
|
|
|
struct Manifest {
|
|
std::string source;
|
|
std::string source_sha;
|
|
std::string compiler_sha;
|
|
std::string nonce;
|
|
std::int64_t pid;
|
|
};
|
|
|
|
std::expected<std::string, std::string> source_hash(std::string_view source) {
|
|
const auto hashed = Void::Crypto::sha256(source);
|
|
if (!hashed) {
|
|
return std::unexpected{"cannot hash captured source"};
|
|
}
|
|
return hex(*hashed);
|
|
}
|
|
|
|
bool valid_identity(std::string_view compiler_sha, std::string_view nonce, std::int64_t pid) {
|
|
return pid > 0 && std::in_range<pid_t>(pid) && is_hex(nonce, 32) && is_hex(compiler_sha, 64);
|
|
}
|
|
|
|
std::expected<std::string, std::string> with_metadata(Json::Object fields, std::string_view bytes) {
|
|
auto encoded = Protocol::serialize_json(Json{std::move(fields)}, json_depth);
|
|
if (!encoded) {
|
|
return std::unexpected{std::move(encoded.error())};
|
|
}
|
|
if (encoded->size() > max_metadata) {
|
|
return std::unexpected{"trace journal metadata is too large"};
|
|
}
|
|
encoded->push_back('\n');
|
|
encoded->append(bytes);
|
|
return encoded;
|
|
}
|
|
|
|
std::expected<std::pair<Json::Object, std::string_view>, std::string>
|
|
split_metadata(std::string_view payload, std::size_t byte_limit) {
|
|
const auto separator = payload.substr(0, max_metadata + 1).find('\n');
|
|
if (separator == std::string_view::npos || payload.size() - separator - 1 > byte_limit) {
|
|
return std::unexpected{"invalid trace journal metadata size"};
|
|
}
|
|
auto parsed = Protocol::parse_json(payload.substr(0, separator), json_depth);
|
|
if (!parsed || !as_object(&*parsed)) {
|
|
return std::unexpected{"invalid trace journal metadata JSON"};
|
|
}
|
|
return std::pair{std::get<Json::Object>(std::move(parsed->value)),
|
|
payload.substr(separator + 1)};
|
|
}
|
|
|
|
std::expected<Manifest, std::string> read_manifest(std::string_view payload) {
|
|
auto split = split_metadata(payload, max_source);
|
|
if (!split) {
|
|
return std::unexpected{std::move(split.error())};
|
|
}
|
|
const auto &[metadata, source] = *split;
|
|
const auto nonce = text(metadata, "nonce");
|
|
const auto compiler_sha = text(metadata, "compilerSha256");
|
|
const auto source_sha = text(metadata, "sourceSha256");
|
|
const auto pid = integer(find_member(metadata, "pid"));
|
|
if (metadata.size() != 5 || text(metadata, "backend") != backend || !pid ||
|
|
!valid_identity(compiler_sha, nonce, *pid) || !is_hex(source_sha, 64)) {
|
|
return std::unexpected{"invalid trace journal identity"};
|
|
}
|
|
auto actual = source_hash(source);
|
|
if (!actual || *actual != source_sha) {
|
|
return std::unexpected{"captured trace source hash mismatch"};
|
|
}
|
|
return Manifest{std::string{source}, std::move(*actual), std::string{compiler_sha},
|
|
std::string{nonce}, *pid};
|
|
}
|
|
|
|
enum class Kind {
|
|
hello,
|
|
enter,
|
|
body,
|
|
value,
|
|
cached,
|
|
stopped,
|
|
resumed,
|
|
leave,
|
|
terminal,
|
|
frontend_end,
|
|
splice
|
|
};
|
|
|
|
constexpr std::array kind_names{"hello"sv, "enter"sv, "body"sv, "value"sv,
|
|
"cached"sv, "stopped"sv, "resumed"sv, "leave"sv,
|
|
"terminal"sv, "frontendEnd"sv, "splice"sv};
|
|
// Recordings made before splice origins existed keep replaying unchanged.
|
|
constexpr std::array legacy_kind_names{"hello"sv, "enter"sv, "body"sv, "value"sv,
|
|
"cached"sv, "stopped"sv, "resumed"sv, "leave"sv,
|
|
"terminal"sv, "frontendEnd"sv};
|
|
constexpr std::array target_kinds{"declaration"sv, "type"sv, "value"sv};
|
|
constexpr std::array capabilities{"integralReturn"sv, "cooperativeStep"sv};
|
|
constexpr std::array actions{"step"sv, "continue"sv, "cancel"sv};
|
|
constexpr std::array leave_outcomes{"returned"sv, "failed"sv, "overflow"sv, "throw"sv,
|
|
"jump"sv, "void"sv, "constructor"sv};
|
|
constexpr std::array terminal_reasons{"truncated"sv, "cancelled"sv, "controlTimeout"sv,
|
|
"controlEOF"sv, "controlError"sv, "controlLimit"sv};
|
|
constexpr std::array process_outcomes{"completed"sv, "failed"sv, "cancelled"sv, "truncated"sv,
|
|
"expired"sv};
|
|
|
|
// Return the static spelling, so views retained in the state never reference parsed JSON.
|
|
std::string_view known(std::span<const std::string_view> options, std::string_view value) {
|
|
const auto found = std::ranges::find(options, value);
|
|
return found == options.end() ? std::string_view{} : *found;
|
|
}
|
|
|
|
bool matches_set(const Json *value, std::span<const std::string_view> required) {
|
|
const auto *array = as_array(value);
|
|
return array && array->size() == required.size() &&
|
|
std::ranges::all_of(required, [array](std::string_view name) {
|
|
return std::ranges::any_of(*array, [name](const Json &entry) {
|
|
const auto *string = as_string(&entry);
|
|
return string && *string == name;
|
|
});
|
|
});
|
|
}
|
|
|
|
bool nullable_printable(const Json *value) {
|
|
const auto *string = as_string(value);
|
|
return is_null(value) ||
|
|
(string && string->size() <= 512 &&
|
|
std::ranges::all_of(*string, [](char ch) { return ch >= 32 && ch <= 126; }));
|
|
}
|
|
|
|
bool positive_coordinate(const Json::Object &event, std::string_view name) {
|
|
const auto value = integer(find_member(event, name));
|
|
return value && *value > 0 && std::in_range<std::int32_t>(*value);
|
|
}
|
|
|
|
bool valid_value(const Json *value) {
|
|
const auto *object = as_object(value);
|
|
if (!object) {
|
|
return false;
|
|
}
|
|
const auto kind = text(*object, "kind");
|
|
if (kind == "unavailable") {
|
|
return object->size() == 2 && text(*object, "reason") == "unsupportedScalar";
|
|
}
|
|
const auto width = ordinal(*object, "precision");
|
|
const auto bits = text(*object, "bitsHex");
|
|
if (kind != "integer" || object->size() != 4 || !width || *width == 0 || *width > 64 ||
|
|
!as_bool(find_member(*object, "signed")) || !is_hex(bits, (*width + 3) / 4)) {
|
|
return false;
|
|
}
|
|
const auto leading_bits = (*width - 1) % 4 + 1;
|
|
return hex_digits.find(bits.front()) < (1u << leading_bits);
|
|
}
|
|
|
|
struct Frame {
|
|
enum class Phase { entered, body, cached };
|
|
|
|
std::uint32_t id;
|
|
std::optional<std::uint32_t> parent;
|
|
Json::Object declaration;
|
|
Phase phase = Phase::entered;
|
|
std::optional<Json> value{};
|
|
std::string_view outcome{};
|
|
|
|
Json inspect() const {
|
|
auto result = declaration;
|
|
if (phase == Phase::body) {
|
|
result.emplace("body", Json{true});
|
|
} else if (phase == Phase::cached) {
|
|
result.emplace("cached", Json{true});
|
|
}
|
|
if (!outcome.empty()) {
|
|
result.emplace("outcome", json_text(outcome));
|
|
}
|
|
if (value) {
|
|
result.emplace("value", *value);
|
|
result.emplace("valueProvisional", Json{outcome != "returned"});
|
|
}
|
|
return Json{std::move(result)};
|
|
}
|
|
};
|
|
|
|
struct Completion {
|
|
std::string_view outcome;
|
|
int exit_code;
|
|
std::string diagnostics;
|
|
};
|
|
|
|
struct Capture {
|
|
Manifest manifest;
|
|
std::optional<Completion> completion;
|
|
|
|
ReplayMetadata metadata(bool ended, const ReadFailure *failure) const {
|
|
const bool partial =
|
|
failure || !completion || !ended ||
|
|
(completion->outcome != "completed" && completion->outcome != "failed");
|
|
return {backend,
|
|
manifest.nonce,
|
|
manifest.pid,
|
|
manifest.compiler_sha,
|
|
manifest.source_sha,
|
|
partial,
|
|
failure && failure->corrupt,
|
|
failure ? std::optional<std::string_view>{failure->message} : std::nullopt,
|
|
completion ? std::optional{completion->outcome} : std::nullopt,
|
|
completion ? std::optional{completion->exit_code} : std::nullopt};
|
|
}
|
|
};
|
|
|
|
void add_recording_status(Json::Object &cursor, const ReplayMetadata &metadata) {
|
|
cursor.emplace("partial", Json{metadata.partial});
|
|
cursor.emplace("corrupt", Json{metadata.corrupt});
|
|
if (metadata.journal_error) {
|
|
cursor.emplace("journalError", json_text(*metadata.journal_error));
|
|
}
|
|
cursor.emplace("outcome", metadata.outcome ? json_text(*metadata.outcome) : Json{nullptr});
|
|
cursor.emplace("exitCode", metadata.exit_code
|
|
? Json{static_cast<std::int64_t>(*metadata.exit_code)}
|
|
: Json{nullptr});
|
|
}
|
|
|
|
struct SpliceOrigin {
|
|
std::string source;
|
|
std::uint32_t line{}, column{};
|
|
std::string_view target_kind;
|
|
std::string target_name, target_source;
|
|
std::optional<std::uint32_t> target_line, target_column;
|
|
};
|
|
|
|
struct CursorFields {
|
|
std::optional<std::uint32_t> sequence;
|
|
std::optional<std::uint32_t> stop;
|
|
std::string_view pending;
|
|
bool ended;
|
|
std::string_view terminal;
|
|
std::shared_ptr<const std::vector<SpliceOrigin>> origins;
|
|
|
|
Json::Object inspect(const Manifest &manifest, Json::Array frames, Json last_leave) const {
|
|
Json::Object cursor{{"backend", json_text(backend)},
|
|
{"nonce", json_text(manifest.nonce)},
|
|
{"pid", Json{manifest.pid}},
|
|
{"compilerSha256", json_text(manifest.compiler_sha)},
|
|
{"sourceSha256", json_text(manifest.source_sha)},
|
|
{"sequence", nullable_ordinal(sequence)},
|
|
{"stop", nullable_ordinal(stop)},
|
|
{"frames", Json{std::move(frames)}},
|
|
{"lastLeave", std::move(last_leave)},
|
|
{"pendingAction", pending.empty() ? Json{nullptr} : json_text(pending)},
|
|
{"frontendEnded", Json{ended}},
|
|
{"terminal", terminal.empty() ? Json{nullptr} : json_text(terminal)}};
|
|
if (origins) {
|
|
Json::Array array;
|
|
for (const auto &origin : *origins) {
|
|
Json::Object fields{
|
|
{"source", Json{origin.source}},
|
|
{"line", Json{std::int64_t{origin.line}}},
|
|
{"byteColumn", Json{std::int64_t{origin.column}}},
|
|
{"targetKind", Json{std::string{origin.target_kind}}},
|
|
{"targetName", origin.target_name.empty() ? Json{} : Json{origin.target_name}},
|
|
{"targetSource",
|
|
origin.target_source.empty() ? Json{} : Json{origin.target_source}}};
|
|
fields.emplace("targetLine", origin.target_line
|
|
? Json{std::int64_t{*origin.target_line}}
|
|
: Json{});
|
|
fields.emplace("targetByteColumn", origin.target_column
|
|
? Json{std::int64_t{*origin.target_column}}
|
|
: Json{});
|
|
array.push_back(Json{std::move(fields)});
|
|
}
|
|
cursor.emplace("origins", Json{std::move(array)});
|
|
}
|
|
return cursor;
|
|
}
|
|
};
|
|
|
|
// A child keeps the version of its parent observed on entry. Only the innermost frame
|
|
// can change, so saving a phase, value or leave costs one frame regardless of depth.
|
|
struct FrameVersion {
|
|
Json frame;
|
|
std::optional<std::size_t> parent_version;
|
|
};
|
|
|
|
struct FrameRefs {
|
|
std::optional<std::size_t> top;
|
|
std::optional<std::size_t> last_leave;
|
|
};
|
|
|
|
struct IndexedCursor {
|
|
FrameRefs frames;
|
|
CursorFields fields;
|
|
};
|
|
|
|
struct RecordingIndex {
|
|
std::vector<ReplayEvent> events;
|
|
std::vector<IndexedCursor> cursors;
|
|
std::vector<ReplayValuePoint> values;
|
|
std::vector<FrameVersion> versions;
|
|
|
|
FrameRefs last_frames() const { return cursors.empty() ? FrameRefs{} : cursors.back().frames; }
|
|
|
|
std::size_t save(const Frame &frame, std::optional<std::size_t> parent) {
|
|
versions.push_back({frame.inspect(), parent});
|
|
return versions.size() - 1;
|
|
}
|
|
|
|
void record(ReplayEvent event, Kind kind, CursorFields fields, const Frame *top,
|
|
const std::optional<Frame> &last_leave) {
|
|
auto refs = last_frames();
|
|
switch (kind) {
|
|
case Kind::enter:
|
|
refs.top = save(*top, refs.top);
|
|
break;
|
|
case Kind::value:
|
|
if (text(*as_object(&*top->value), "kind") == "integer") {
|
|
values.push_back({event.sequence, std::nullopt});
|
|
}
|
|
[[fallthrough]];
|
|
case Kind::body:
|
|
case Kind::cached:
|
|
refs.top = save(*top, versions[*refs.top].parent_version);
|
|
break;
|
|
case Kind::leave: {
|
|
const auto parent = versions[*refs.top].parent_version;
|
|
refs.last_leave = save(*last_leave, parent);
|
|
refs.top = parent;
|
|
break;
|
|
}
|
|
case Kind::stopped:
|
|
// Timeline requires an immediately preceding integer value on this same frame.
|
|
values.back().stop_sequence = event.sequence;
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
events.push_back(event);
|
|
cursors.push_back({refs, fields});
|
|
}
|
|
|
|
Json inspect(const Manifest &manifest, const IndexedCursor &cursor) const {
|
|
Json::Array frames;
|
|
for (auto top = cursor.frames.top; top; top = versions[*top].parent_version) {
|
|
frames.push_back(versions[*top].frame);
|
|
}
|
|
std::ranges::reverse(frames);
|
|
const auto leave = cursor.frames.last_leave;
|
|
return Json{cursor.fields.inspect(manifest, std::move(frames),
|
|
leave ? versions[*leave].frame : Json{nullptr})};
|
|
}
|
|
};
|
|
|
|
class Timeline {
|
|
public:
|
|
explicit Timeline(Manifest manifest) : capture_{std::move(manifest), std::nullopt} {
|
|
// Append a verified event before making its change visible. Frame pushes then need no
|
|
// allocation once a complete journal record has been committed.
|
|
frames_.reserve(max_events);
|
|
}
|
|
|
|
TraceResult event(std::string_view line, JournalWriter *journal = nullptr,
|
|
RecordingIndex *index = nullptr) {
|
|
if (sequence_ == max_events || line.size() >= max_event || line.contains('\n') ||
|
|
line.size() + 1 > max_trace - trace_bytes_) {
|
|
return std::unexpected{"compiler trace event or stream exceeds wire bounds"};
|
|
}
|
|
auto parsed = Protocol::parse_json(line, json_depth);
|
|
const auto *event = parsed ? as_object(&*parsed) : nullptr;
|
|
if (!event || integer(find_member(*event, "v")) != 1 ||
|
|
text(*event, "nonce") != capture_.manifest.nonce ||
|
|
ordinal(*event, "seq") != sequence_) {
|
|
return std::unexpected{"invalid compiler trace envelope"};
|
|
}
|
|
const auto name = std::ranges::find(kind_names, text(*event, "kind"));
|
|
if (name == kind_names.end()) {
|
|
return std::unexpected{"unknown compiler trace event kind"};
|
|
}
|
|
const auto kind = static_cast<Kind>(name - kind_names.begin());
|
|
if (auto result = validate(*event, kind); !result) {
|
|
return result;
|
|
}
|
|
if (journal) {
|
|
if (auto result = journal->append(RecordType::event, line); !result) {
|
|
return result;
|
|
}
|
|
}
|
|
ReplayEvent summary{};
|
|
if (index) {
|
|
summary = {
|
|
sequence_, *name, ordinal(*event, "frame"), ordinal(*event, "parent"),
|
|
std::nullopt, std::nullopt};
|
|
if (kind == Kind::resumed) {
|
|
// validate_frame matched both echoed fields to this authorization.
|
|
summary.acknowledged_stop = stop_;
|
|
summary.acknowledged_action = pending_;
|
|
}
|
|
}
|
|
apply(std::get<Json::Object>(std::move(parsed->value)), kind);
|
|
trace_bytes_ += line.size() + 1;
|
|
++sequence_;
|
|
if (kind != Kind::splice) {
|
|
last_kind_ = kind;
|
|
}
|
|
if (index) {
|
|
index->record(summary, kind, cursor_fields(),
|
|
frames_.empty() ? nullptr : &frames_.back(), last_leave_);
|
|
}
|
|
return {};
|
|
}
|
|
|
|
TraceResult authorize(std::uint32_t stop, std::string_view requested,
|
|
JournalWriter *journal = nullptr) {
|
|
const auto action = known(actions, requested);
|
|
if (!stopped() || stopped() != stop || action.empty()) {
|
|
return std::unexpected{
|
|
"trace command needs the current unconsumed stop and a supported action"};
|
|
}
|
|
if (journal) {
|
|
auto encoded = Protocol::serialize_json(
|
|
Json{Json::Object{{"action", json_text(action)}, {"stop", nullable_ordinal(stop)}}},
|
|
json_depth);
|
|
if (!encoded) {
|
|
return std::unexpected{std::move(encoded.error())};
|
|
}
|
|
if (auto result = journal->append(RecordType::command, *encoded); !result) {
|
|
return result;
|
|
}
|
|
}
|
|
// One command per verified stop bounds the command count by the event count.
|
|
pending_ = action;
|
|
return {};
|
|
}
|
|
|
|
TraceResult finish(std::string_view requested, int code, std::string_view diagnostics,
|
|
JournalWriter *journal = nullptr) {
|
|
const auto outcome = known(process_outcomes, requested);
|
|
if (capture_.completion || outcome.empty() || diagnostics.size() > max_diagnostics ||
|
|
(outcome == "completed" && (!ended_ || code != 0))) {
|
|
return std::unexpected{"invalid trace process outcome"};
|
|
}
|
|
Completion completion{outcome, code, std::string{diagnostics}};
|
|
if (journal) {
|
|
auto encoded = with_metadata({{"outcome", json_text(outcome)},
|
|
{"exitCode", Json{static_cast<std::int64_t>(code)}}},
|
|
completion.diagnostics);
|
|
if (!encoded) {
|
|
return std::unexpected{std::move(encoded.error())};
|
|
}
|
|
if (auto result = journal->append(RecordType::finish, *encoded); !result) {
|
|
return result;
|
|
}
|
|
}
|
|
capture_.completion = std::move(completion);
|
|
return {};
|
|
}
|
|
|
|
std::optional<std::uint32_t> sequence() const {
|
|
return sequence_ == 0 ? std::nullopt : std::optional{sequence_ - 1};
|
|
}
|
|
|
|
std::optional<std::uint32_t> stopped() const {
|
|
return pending_.empty() && !capture_.completion ? stop_ : std::nullopt;
|
|
}
|
|
|
|
bool ended() const { return ended_; }
|
|
std::string_view terminal() const { return terminal_; }
|
|
|
|
CursorFields cursor_fields() const {
|
|
return {sequence(), stopped(), pending_, ended_, terminal_, origins_};
|
|
}
|
|
|
|
Capture release_capture() && { return std::move(capture_); }
|
|
|
|
Json inspection() const {
|
|
Json::Array frames;
|
|
frames.reserve(frames_.size());
|
|
for (const auto &frame : frames_) {
|
|
frames.push_back(frame.inspect());
|
|
}
|
|
auto cursor = cursor_fields().inspect(capture_.manifest, std::move(frames),
|
|
last_leave_ ? last_leave_->inspect() : Json{nullptr});
|
|
add_recording_status(cursor, capture_.metadata(ended_, nullptr));
|
|
return Json{std::move(cursor)};
|
|
}
|
|
|
|
private:
|
|
static constexpr std::size_t envelope_fields = 4;
|
|
static constexpr std::size_t frame_fields = envelope_fields + 2;
|
|
|
|
TraceResult validate(const Json::Object &event, Kind kind) const {
|
|
if (capture_.completion || ended_ || !terminal_.empty()) {
|
|
return std::unexpected{"compiler trace event after termination"};
|
|
}
|
|
if (sequence_ == 0) {
|
|
if (kind == Kind::hello && event.size() == envelope_fields + 4 &&
|
|
text(event, "backend") == backend &&
|
|
integer(find_member(event, "pid")) == capture_.manifest.pid &&
|
|
matches_set(find_member(event, "capabilities"), capabilities) &&
|
|
(matches_set(find_member(event, "kinds"), kind_names) ||
|
|
matches_set(find_member(event, "kinds"), legacy_kind_names))) {
|
|
return {};
|
|
}
|
|
return std::unexpected{"invalid GCC evaluator handshake"};
|
|
}
|
|
if (stop_ && kind != Kind::resumed && kind != Kind::terminal) {
|
|
return std::unexpected{"compiler moved without acknowledging the stopped command"};
|
|
}
|
|
switch (kind) {
|
|
case Kind::hello:
|
|
return std::unexpected{"duplicate GCC evaluator handshake"};
|
|
case Kind::terminal: {
|
|
const auto reason = known(terminal_reasons, text(event, "reason"));
|
|
if (reason == "truncated" && event.size() == envelope_fields + 1) {
|
|
return {};
|
|
}
|
|
if (!reason.empty() && reason != "truncated" && event.size() == envelope_fields + 2 &&
|
|
stop_ && ordinal(event, "stop") == stop_ &&
|
|
(reason != "cancelled" || pending_ == "cancel")) {
|
|
return {};
|
|
}
|
|
return std::unexpected{"invalid compiler terminal event"};
|
|
}
|
|
case Kind::frontend_end:
|
|
if (event.size() == envelope_fields && frames_.empty()) {
|
|
return {};
|
|
}
|
|
return std::unexpected{"frontendEnd requires a balanced trace"};
|
|
case Kind::splice: {
|
|
if (!declared_splice_) {
|
|
return std::unexpected{"splice origin was not declared in the handshake"};
|
|
}
|
|
const auto target_kind = known(target_kinds, text(event, "targetKind"));
|
|
const bool coordinates = (is_null(find_member(event, "targetLine")) &&
|
|
is_null(find_member(event, "targetByteColumn"))) ||
|
|
(positive_coordinate(event, "targetLine") &&
|
|
positive_coordinate(event, "targetByteColumn"));
|
|
if (event.size() == envelope_fields + 8 && !target_kind.empty() &&
|
|
nullable_printable(find_member(event, "source")) &&
|
|
positive_coordinate(event, "line") && positive_coordinate(event, "byteColumn") &&
|
|
nullable_printable(find_member(event, "targetName")) &&
|
|
nullable_printable(find_member(event, "targetSource")) && coordinates) {
|
|
return {};
|
|
}
|
|
return std::unexpected{"invalid compiler splice origin"};
|
|
}
|
|
default:
|
|
return validate_frame(event, kind);
|
|
}
|
|
}
|
|
|
|
TraceResult validate_frame(const Json::Object &event, Kind kind) const {
|
|
const auto *top = frames_.empty() ? nullptr : &frames_.back();
|
|
const auto id = ordinal(event, "frame");
|
|
const auto parent = kind == Kind::enter ? (top ? std::optional{top->id} : std::nullopt)
|
|
: (top ? top->parent : std::nullopt);
|
|
const bool parent_matches =
|
|
parent ? ordinal(event, "parent") == parent : is_null(find_member(event, "parent"));
|
|
if (!id || !parent_matches ||
|
|
(kind == Kind::enter ? *id != sequence_ : !top || *id != top->id)) {
|
|
return std::unexpected{"invalid compiler trace frame or parent"};
|
|
}
|
|
switch (kind) {
|
|
case Kind::enter: {
|
|
const auto location = text(event, "sourceKind");
|
|
const bool located =
|
|
location == "logicalDeclaration" && event.size() == frame_fields + 5 &&
|
|
nullable_printable(find_member(event, "source")) &&
|
|
positive_coordinate(event, "line") && positive_coordinate(event, "byteColumn");
|
|
if (nullable_printable(find_member(event, "name")) &&
|
|
(located || (location == "unavailable" && event.size() == frame_fields + 2))) {
|
|
return {};
|
|
}
|
|
break;
|
|
}
|
|
case Kind::body:
|
|
case Kind::cached:
|
|
if (event.size() == frame_fields && top->phase == Frame::Phase::entered) {
|
|
return {};
|
|
}
|
|
break;
|
|
case Kind::value:
|
|
if (event.size() == frame_fields + 1 && top->phase == Frame::Phase::body &&
|
|
!top->value && valid_value(find_member(event, "value"))) {
|
|
return {};
|
|
}
|
|
break;
|
|
case Kind::stopped:
|
|
if (event.size() == frame_fields && !disarmed_ && last_kind_ == Kind::value &&
|
|
top->value && text(*as_object(&*top->value), "kind") == "integer") {
|
|
return {};
|
|
}
|
|
break;
|
|
case Kind::resumed:
|
|
if (event.size() == frame_fields + 2 && stop_ && ordinal(event, "stop") == stop_ &&
|
|
(pending_ == "step" || pending_ == "continue") &&
|
|
text(event, "action") == pending_) {
|
|
return {};
|
|
}
|
|
break;
|
|
case Kind::leave:
|
|
if (event.size() == frame_fields + 1 &&
|
|
!known(leave_outcomes, text(event, "outcome")).empty()) {
|
|
return {};
|
|
}
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
return std::unexpected{"invalid compiler trace frame event"};
|
|
}
|
|
|
|
void apply(Json::Object event, Kind kind) {
|
|
switch (kind) {
|
|
case Kind::hello:
|
|
declared_splice_ = matches_set(find_member(event, "kinds"), kind_names);
|
|
break;
|
|
case Kind::enter: {
|
|
const auto parent = ordinal(event, "parent");
|
|
event.erase("v");
|
|
event.erase("seq");
|
|
event.erase("nonce");
|
|
event.erase("kind");
|
|
frames_.push_back(
|
|
Frame{.id = sequence_, .parent = parent, .declaration = std::move(event)});
|
|
break;
|
|
}
|
|
case Kind::body:
|
|
frames_.back().phase = Frame::Phase::body;
|
|
break;
|
|
case Kind::cached:
|
|
frames_.back().phase = Frame::Phase::cached;
|
|
break;
|
|
case Kind::value:
|
|
frames_.back().value = std::move(event.find("value")->second);
|
|
break;
|
|
case Kind::stopped:
|
|
stop_ = sequence_;
|
|
break;
|
|
case Kind::resumed:
|
|
disarmed_ = pending_ == "continue";
|
|
pending_ = {};
|
|
stop_.reset();
|
|
break;
|
|
case Kind::leave:
|
|
frames_.back().outcome = known(leave_outcomes, text(event, "outcome"));
|
|
last_leave_ = std::move(frames_.back());
|
|
frames_.pop_back();
|
|
break;
|
|
case Kind::terminal:
|
|
terminal_ = known(terminal_reasons, text(event, "reason"));
|
|
pending_ = {};
|
|
stop_.reset();
|
|
break;
|
|
case Kind::frontend_end:
|
|
ended_ = true;
|
|
break;
|
|
case Kind::splice: {
|
|
auto next = origins_ ? std::make_shared<std::vector<SpliceOrigin>>(*origins_)
|
|
: std::make_shared<std::vector<SpliceOrigin>>();
|
|
if (next->size() < max_splice_origins) {
|
|
SpliceOrigin origin;
|
|
origin.source = text(event, "source");
|
|
origin.line = static_cast<std::uint32_t>(*ordinal(event, "line"));
|
|
origin.column = static_cast<std::uint32_t>(*ordinal(event, "byteColumn"));
|
|
origin.target_kind = known(target_kinds, text(event, "targetKind"));
|
|
origin.target_name = text(event, "targetName");
|
|
origin.target_source = text(event, "targetSource");
|
|
origin.target_line = ordinal(event, "targetLine");
|
|
origin.target_column = ordinal(event, "targetByteColumn");
|
|
next->push_back(std::move(origin));
|
|
}
|
|
origins_ = std::move(next);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
Capture capture_;
|
|
std::vector<Frame> frames_;
|
|
std::optional<Frame> last_leave_;
|
|
std::optional<std::uint32_t> stop_;
|
|
std::string_view pending_;
|
|
std::string_view terminal_;
|
|
std::size_t trace_bytes_{};
|
|
std::uint32_t sequence_{};
|
|
static constexpr std::size_t max_splice_origins = 256;
|
|
std::shared_ptr<const std::vector<SpliceOrigin>> origins_;
|
|
bool declared_splice_{};
|
|
Kind last_kind_ = Kind::hello;
|
|
bool disarmed_{};
|
|
bool ended_{};
|
|
};
|
|
|
|
TraceResult apply_record(Timeline &timeline, const Record &record, RecordingIndex &index) {
|
|
switch (record.type) {
|
|
case RecordType::event:
|
|
return timeline.event(record.payload, nullptr, &index);
|
|
case RecordType::command: {
|
|
auto parsed = Protocol::parse_json(record.payload, json_depth);
|
|
const auto *command = parsed ? as_object(&*parsed) : nullptr;
|
|
if (!command || command->size() != 2) {
|
|
return std::unexpected{"invalid trace command record"};
|
|
}
|
|
const auto stop = ordinal(*command, "stop");
|
|
if (!stop) {
|
|
return std::unexpected{"invalid recorded trace stop"};
|
|
}
|
|
return timeline.authorize(*stop, text(*command, "action"));
|
|
}
|
|
case RecordType::finish: {
|
|
auto split = split_metadata(record.payload, max_diagnostics);
|
|
if (!split) {
|
|
return std::unexpected{std::move(split.error())};
|
|
}
|
|
const auto &[metadata, diagnostics] = *split;
|
|
const auto exit_code = integer(find_member(metadata, "exitCode"));
|
|
if (metadata.size() != 2 || !exit_code || !std::in_range<int>(*exit_code)) {
|
|
return std::unexpected{"invalid trace exit record"};
|
|
}
|
|
return timeline.finish(text(metadata, "outcome"), static_cast<int>(*exit_code),
|
|
diagnostics);
|
|
}
|
|
case RecordType::manifest:
|
|
return std::unexpected{"duplicate trace journal manifest"};
|
|
}
|
|
return std::unexpected{"unknown trace journal record"};
|
|
}
|
|
|
|
} // namespace
|
|
|
|
struct Trace::State {
|
|
State(Manifest manifest, JournalWriter writer)
|
|
: timeline(std::move(manifest)), journal(std::move(writer)) {}
|
|
|
|
std::mutex mutex;
|
|
Timeline timeline;
|
|
JournalWriter journal;
|
|
};
|
|
|
|
Trace::Trace(std::unique_ptr<State> state) : state_(std::move(state)) {}
|
|
Trace::~Trace() = default;
|
|
|
|
std::expected<std::unique_ptr<Trace>, std::string>
|
|
Trace::create(const std::filesystem::path &output, std::string_view source,
|
|
std::string_view compiler_sha, std::string_view nonce, std::int64_t pid) {
|
|
if (source.size() > max_source || !valid_identity(compiler_sha, nonce, pid)) {
|
|
return std::unexpected{"invalid trace creation identity or source size"};
|
|
}
|
|
auto hash = source_hash(source);
|
|
if (!hash) {
|
|
return std::unexpected{std::move(hash.error())};
|
|
}
|
|
auto payload = with_metadata({{"backend", json_text(backend)},
|
|
{"compilerSha256", json_text(compiler_sha)},
|
|
{"nonce", json_text(nonce)},
|
|
{"pid", Json{pid}},
|
|
{"sourceSha256", Json{*hash}}},
|
|
source);
|
|
if (!payload) {
|
|
return std::unexpected{std::move(payload.error())};
|
|
}
|
|
auto journal = create_journal(output, *payload);
|
|
if (!journal) {
|
|
return std::unexpected{std::move(journal.error())};
|
|
}
|
|
Manifest manifest{std::string{source}, std::move(*hash), std::string{compiler_sha},
|
|
std::string{nonce}, pid};
|
|
return std::unique_ptr<Trace>{
|
|
new Trace{std::make_unique<State>(std::move(manifest), std::move(*journal))}};
|
|
}
|
|
|
|
TraceResult Trace::event(std::string_view line) {
|
|
const std::scoped_lock lock(state_->mutex);
|
|
return state_->timeline.event(line, &state_->journal);
|
|
}
|
|
|
|
TraceResult Trace::authorize(std::uint32_t stop, std::string_view action) {
|
|
const std::scoped_lock lock(state_->mutex);
|
|
return state_->timeline.authorize(stop, action, &state_->journal);
|
|
}
|
|
|
|
std::optional<std::uint32_t> Trace::stopped() const {
|
|
const std::scoped_lock lock(state_->mutex);
|
|
return state_->timeline.stopped();
|
|
}
|
|
|
|
bool Trace::ended() const {
|
|
const std::scoped_lock lock(state_->mutex);
|
|
return state_->timeline.ended();
|
|
}
|
|
|
|
std::string_view Trace::terminal() const {
|
|
const std::scoped_lock lock(state_->mutex);
|
|
return state_->timeline.terminal();
|
|
}
|
|
|
|
Json Trace::inspection() const {
|
|
const std::scoped_lock lock(state_->mutex);
|
|
return state_->timeline.inspection();
|
|
}
|
|
|
|
TraceResult Trace::finish(std::string_view outcome, int code, std::string_view diagnostics) {
|
|
const std::scoped_lock lock(state_->mutex);
|
|
return state_->timeline.finish(outcome, code, diagnostics, &state_->journal);
|
|
}
|
|
|
|
struct ReplayRecording::State {
|
|
Capture capture;
|
|
RecordingIndex index;
|
|
CursorFields final_fields;
|
|
std::optional<ReadFailure> failure;
|
|
};
|
|
|
|
ReplayRecording::ReplayRecording(std::unique_ptr<State> state) : state_(std::move(state)) {}
|
|
ReplayRecording::~ReplayRecording() = default;
|
|
|
|
std::expected<std::shared_ptr<const ReplayRecording>, std::string>
|
|
ReplayRecording::open(const std::filesystem::path &path) {
|
|
if (!path.is_absolute() || !valid_path(path)) {
|
|
return std::unexpected{"trace recording requires an absolute journal file path"};
|
|
}
|
|
const OwnedFd file{
|
|
::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_NOCTTY | O_CLOEXEC)};
|
|
if (!file) {
|
|
return std::unexpected{io_error("cannot open trace journal")};
|
|
}
|
|
struct stat status{};
|
|
if (::fstat(file.get(), &status) != 0 || !S_ISREG(status.st_mode) || status.st_size < 0) {
|
|
return std::unexpected{"trace replay requires a regular file"};
|
|
}
|
|
// Observe a fixed file-length prefix even if a live writer appends while replay runs.
|
|
JournalReader reader{file.get(), static_cast<std::uintmax_t>(status.st_size)};
|
|
if (auto header = reader.read_magic(); !header) {
|
|
return std::unexpected{std::move(header.error())};
|
|
}
|
|
auto first = reader.next();
|
|
if (!first) {
|
|
return std::unexpected{std::move(first.error().message)};
|
|
}
|
|
if (first->type != RecordType::manifest) {
|
|
return std::unexpected{"trace journal does not begin with a manifest"};
|
|
}
|
|
auto manifest = read_manifest(first->payload);
|
|
if (!manifest) {
|
|
return std::unexpected{std::move(manifest.error())};
|
|
}
|
|
Timeline timeline{std::move(*manifest)};
|
|
RecordingIndex index;
|
|
std::optional<ReadFailure> failure;
|
|
while (reader.has_remaining()) {
|
|
auto record = reader.next();
|
|
if (!record) {
|
|
failure = std::move(record.error());
|
|
break;
|
|
}
|
|
if (record->type == RecordType::finish && reader.has_remaining()) {
|
|
failure = ReadFailure{"trace journal has data after its process outcome", true};
|
|
break;
|
|
}
|
|
if (auto applied = apply_record(timeline, *record, index); !applied) {
|
|
failure = ReadFailure{std::move(applied.error()), true};
|
|
break;
|
|
}
|
|
}
|
|
const auto final_fields = timeline.cursor_fields();
|
|
auto state = std::make_unique<State>(std::move(timeline).release_capture(), std::move(index),
|
|
final_fields, std::move(failure));
|
|
return std::shared_ptr<const ReplayRecording>{new ReplayRecording{std::move(state)}};
|
|
}
|
|
|
|
ReplayMetadata ReplayRecording::metadata() const {
|
|
return state_->capture.metadata(state_->final_fields.ended,
|
|
state_->failure ? &*state_->failure : nullptr);
|
|
}
|
|
|
|
std::string_view ReplayRecording::source_bytes() const { return state_->capture.manifest.source; }
|
|
|
|
std::optional<std::string_view> ReplayRecording::diagnostic_bytes() const {
|
|
const auto &completion = state_->capture.completion;
|
|
return completion ? std::optional<std::string_view>{completion->diagnostics} : std::nullopt;
|
|
}
|
|
|
|
std::size_t ReplayRecording::event_count() const { return state_->index.events.size(); }
|
|
|
|
std::expected<std::span<const ReplayEvent>, std::string>
|
|
ReplayRecording::event_page(std::size_t offset, std::size_t count) const {
|
|
if (offset > event_count() || count > max_page_size) {
|
|
return std::unexpected{"requested event page is out of bounds"};
|
|
}
|
|
return std::span{state_->index.events}.subspan(offset, std::min(count, event_count() - offset));
|
|
}
|
|
|
|
std::expected<std::optional<ReplayValuePoint>, std::string>
|
|
ReplayRecording::next_value(std::optional<std::uint32_t> after) const {
|
|
const auto &points = state_->index.values;
|
|
if (after && *after >= event_count()) {
|
|
return std::unexpected{"requested event is outside the verified trace prefix"};
|
|
}
|
|
const auto next =
|
|
after ? std::ranges::upper_bound(points, *after, {}, &ReplayValuePoint::value_sequence)
|
|
: points.begin();
|
|
return next == points.end() ? std::nullopt : std::optional{*next};
|
|
}
|
|
|
|
std::expected<std::optional<ReplayValuePoint>, std::string>
|
|
ReplayRecording::previous_value(std::optional<std::uint32_t> before) const {
|
|
const auto &points = state_->index.values;
|
|
if (before && *before >= event_count()) {
|
|
return std::unexpected{"requested event is outside the verified trace prefix"};
|
|
}
|
|
const auto end_of_point = [](const ReplayValuePoint &point) {
|
|
return point.stop_sequence.value_or(point.value_sequence);
|
|
};
|
|
const auto limit =
|
|
before ? std::ranges::lower_bound(points, *before, {}, end_of_point) : points.end();
|
|
return limit == points.begin() ? std::nullopt : std::optional{*std::prev(limit)};
|
|
}
|
|
|
|
std::expected<Json, std::string> ReplayRecording::cursor_at(std::uint32_t sequence) const {
|
|
if (sequence >= event_count()) {
|
|
return std::unexpected{"requested event is outside the verified trace prefix"};
|
|
}
|
|
return state_->index.inspect(state_->capture.manifest, state_->index.cursors[sequence]);
|
|
}
|
|
|
|
Json ReplayRecording::final_cursor() const {
|
|
return state_->index.inspect(state_->capture.manifest,
|
|
{state_->index.last_frames(), state_->final_fields});
|
|
}
|
|
|
|
std::expected<Json, std::string> replay(const std::filesystem::path &path,
|
|
std::optional<std::uint32_t> sequence) {
|
|
if (!valid_path(path) || (sequence && *sequence >= max_events)) {
|
|
return std::unexpected{"invalid trace replay path or event sequence"};
|
|
}
|
|
std::error_code error;
|
|
const auto absolute = std::filesystem::absolute(path, error);
|
|
if (error) {
|
|
return std::unexpected{error.message()};
|
|
}
|
|
auto opened = ReplayRecording::open(absolute);
|
|
if (!opened) {
|
|
return std::unexpected{std::move(opened.error())};
|
|
}
|
|
const auto &recording = **opened;
|
|
auto cursor = sequence ? recording.cursor_at(*sequence)
|
|
: std::expected<Json, std::string>{recording.final_cursor()};
|
|
if (!cursor) {
|
|
return cursor;
|
|
}
|
|
auto &fields = std::get<Json::Object>(cursor->value);
|
|
add_recording_status(fields, recording.metadata());
|
|
add_bytes(fields, "source", recording.source_bytes());
|
|
if (auto diagnostics = recording.diagnostic_bytes()) {
|
|
add_bytes(fields, "diagnostics", *diagnostics);
|
|
} else {
|
|
fields.emplace("diagnostics", Json{nullptr});
|
|
}
|
|
return cursor;
|
|
}
|
|
|
|
} // namespace vls::gcc
|