diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 52967d5015..36a2149aa3 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -119,7 +119,6 @@ When reviewing a diff (your own or a PR), weight these for Hyperlight: * `src/hyperlight_guest_capi/`: guest C library. * `src/hyperlight_host/`: hyperlight-host library. * `src/hyperlight_testing/`: shared test code. -* `schema/`: flatbuffer schemas. * `tests/`: test guest code in C and Rust. * `dev/`: development scripts and tools. * `fuzz/`: fuzzing tests. diff --git a/.github/workflows/DailyArm64.yml b/.github/workflows/DailyArm64.yml index 14a2ab12de..cac2a5ef60 100644 --- a/.github/workflows/DailyArm64.yml +++ b/.github/workflows/DailyArm64.yml @@ -86,7 +86,7 @@ jobs: # Fuzz on aarch64. This coverage was removed from PRs in #1594 to conserve the # limited arm64 runners, and runs here daily instead. The tracing - # fuzzers (fuzz_guest_trace, fuzz_guest_estimate_trace_event) are x86_64-only + # fuzzers (fuzz_guest_trace, fuzz_guest_trace_decode) are x86_64-only fuzzing: needs: build-guests strategy: diff --git a/.github/workflows/Fuzzing.yml b/.github/workflows/Fuzzing.yml index c203bfcc3d..d5946dd281 100644 --- a/.github/workflows/Fuzzing.yml +++ b/.github/workflows/Fuzzing.yml @@ -22,7 +22,7 @@ jobs: strategy: fail-fast: false matrix: - target: ['fuzz_host_print', 'fuzz_guest_call', 'fuzz_host_call', 'fuzz_guest_estimate_trace_event', 'fuzz_guest_trace', 'fuzz_virtq_malformed', 'fuzz_virtq_roundtrip'] + target: ['fuzz_host_print', 'fuzz_guest_call', 'fuzz_host_call', 'fuzz_guest_trace_decode', 'fuzz_guest_trace', 'fuzz_virtq_malformed', 'fuzz_virtq_roundtrip', 'fuzz_control_decode'] uses: ./.github/workflows/dep_fuzzing.yml with: target: ${{ matrix.target }} diff --git a/.github/workflows/ValidatePullRequest.yml b/.github/workflows/ValidatePullRequest.yml index 235fe47793..e6462eaf54 100644 --- a/.github/workflows/ValidatePullRequest.yml +++ b/.github/workflows/ValidatePullRequest.yml @@ -259,7 +259,7 @@ jobs: if: ${{ !cancelled() && !failure() }} strategy: matrix: - target: ['fuzz_host_print', 'fuzz_guest_call', 'fuzz_host_call', 'fuzz_guest_estimate_trace_event', 'fuzz_guest_trace', 'fuzz_virtq_malformed', 'fuzz_virtq_roundtrip'] + target: ['fuzz_host_print', 'fuzz_guest_call', 'fuzz_host_call', 'fuzz_guest_trace_decode', 'fuzz_guest_trace', 'fuzz_virtq_malformed', 'fuzz_virtq_roundtrip', 'fuzz_control_decode'] arch: - X64 # arm64 fuzzing runs on the daily schedule (DailyArm64.yml) instead of on diff --git a/CHANGELOG.md b/CHANGELOG.md index 95fecc54f3..5b9f943b9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added * Add `Sandbox::recreate()`, which rebuilds a sandbox's VM and memory from a snapshot. It recovers unrecoverable sandboxes and keeps configuration, host functions, and interrupt handles by @ludfjig in https://github.com/hyperlight-dev/hyperlight/pull/1751 +### Changed +* **Breaking:** Encode function calls with serde/postcard instead of FlatBuffers. + ### Fixed * Fix restore on WHP not rewinding the guest TSC on hosts with `TSC_ADJUST` support. diff --git a/Cargo.lock b/Cargo.lock index 3cbca23fcf..3eacff6c9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -546,6 +546,15 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -1110,16 +1119,6 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" -[[package]] -name = "flatbuffers" -version = "25.12.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" -dependencies = [ - "bitflags 2.13.2", - "rustc_version", -] - [[package]] name = "flate2" version = "1.1.10" @@ -1698,12 +1697,13 @@ dependencies = [ "bytes", "criterion", "fixedbitset", - "flatbuffers", "hyperlight-testing", "log", "loom", + "postcard", "quickcheck", "rand 0.10.3", + "serde", "smallvec", "spin", "thiserror", @@ -1770,7 +1770,6 @@ name = "hyperlight-guest" version = "0.19.0" dependencies = [ "anyhow", - "flatbuffers", "hyperlight-common", "hyperlight-guest-tracing", "itertools 0.15.0", @@ -1782,7 +1781,6 @@ dependencies = [ name = "hyperlight-guest-bin" version = "0.19.0" dependencies = [ - "flatbuffers", "hyperlight-common", "hyperlight-guest", "hyperlight-guest-macro", @@ -1835,7 +1833,6 @@ dependencies = [ "elfcore", "env_logger", "fallible-iterator", - "flatbuffers", "framehop", "gdbstub", "gdbstub_arch", @@ -1921,7 +1918,6 @@ name = "hyperlight_guest_capi" version = "0.19.0" dependencies = [ "cbindgen", - "flatbuffers", "hyperlight-common", "hyperlight-guest", "hyperlight-guest-bin", @@ -3095,6 +3091,16 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "serde", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -3511,15 +3517,6 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - [[package]] name = "rustix" version = "1.1.4" diff --git a/Justfile b/Justfile index 528fc4df2e..d99881fc39 100644 --- a/Justfile +++ b/Justfile @@ -235,10 +235,11 @@ like-ci config=default-target hypervisor="kvm": just fuzz-like-ci fuzz_host_print {{config}} {{hypervisor}} just fuzz-like-ci fuzz_guest_call {{config}} {{hypervisor}} just fuzz-like-ci fuzz_host_call {{config}} {{hypervisor}} - just fuzz-like-ci fuzz_guest_estimate_trace_event {{config}} {{hypervisor}} + just fuzz-like-ci fuzz_guest_trace_decode {{config}} {{hypervisor}} just fuzz-like-ci fuzz_guest_trace {{config}} {{hypervisor}} just fuzz-like-ci fuzz_virtq_malformed {{config}} {{hypervisor}} just fuzz-like-ci fuzz_virtq_roundtrip {{config}} {{hypervisor}} + just fuzz-like-ci fuzz_control_decode {{config}} {{hypervisor}} @# spelling typos @@ -666,21 +667,6 @@ coverage-ci hypervisor="kvm": (coverage-run hypervisor) cargo +{{nightly-toolchain}} llvm-cov report --lcov --output-path target/coverage/lcov.info cargo +{{nightly-toolchain}} llvm-cov report | tee target/coverage/summary.txt -################### -### FLATBUFFERS ### -################### - -gen-all-fbs-rust-code: - flatc --rust --rust-module-root-file --gen-all -o ./src/hyperlight_common/src/flatbuffers/ ./src/schema/all.fbs - just fmt-apply - -install-vcpkg: - cd .. && git clone https://github.com/Microsoft/vcpkg.git || cd - - cd ../vcpkg && ./bootstrap-vcpkg{{ bin-suffix }} && ./vcpkg integrate install || cd - - -install-flatbuffers-with-vcpkg: install-vcpkg - cd ../vcpkg && ./vcpkg install flatbuffers || cd - - ################################### ### SNAPSHOT GOLDEN HELPERS ### ################################### diff --git a/README.md b/README.md index 5f93525aa3..b7b628e0f5 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,6 @@ Or skip setup entirely with a codespace: | [src/hyperlight_component_macro](./src/hyperlight_component_macro) | Proc macros for WIT-based host/guest bindings | | [src/hyperlight_component_util](./src/hyperlight_component_util) | Shared implementation for WIT binding generation | | [src/hyperlight_testing](./src/hyperlight_testing) | Shared test utilities | -| [src/schema](./src/schema) | FlatBuffer schema definitions | | [src/trace_dump](./src/trace_dump) | Tool for dumping and visualizing trace data | | [src/tests](./src/tests) | Test guest programs (Rust and C) | diff --git a/docs/README.md b/docs/README.md index 918c5e2441..c967e281e7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -38,7 +38,6 @@ This project is composed internally of several components, depicted in the below * [Virtqueue host and guest communication](./virtio-host-guest-communication.md) * [Component wire format](./component-wire-format.md) * [How to debug a Hyperlight guest](./how-to-debug-a-hyperlight-guest.md) -* [How to use Flatbuffers in Hyperlight](./how-to-use-flatbuffers.md) * [How to make a Hyperlight release](./how-to-make-releases.md) * [Getting Hyperlight Metrics, Logs, and Traces](./hyperlight-metrics-logs-and-traces.md) * [Benchmarking Hyperlight](./benchmarking-hyperlight.md) diff --git a/docs/how-to-use-flatbuffers.md b/docs/how-to-use-flatbuffers.md deleted file mode 100644 index c541b0406d..0000000000 --- a/docs/how-to-use-flatbuffers.md +++ /dev/null @@ -1,21 +0,0 @@ -# How to use FlatBuffers - -> Note: the last generation of the flatbuffer code was with done with flatc version 25.9.23 (i.e., the last version as of Oct 2nd, 2025). - -Flatbuffers is used to serialize and deserialize some data structures. - -Schema files are used to define the data structures and are used to generate the code to serialize and deserialize the data structures. - -Those files are located in the [`schema`](../src/schema) directory. - -Code generated from the schema files is checked in to the repository, therefore you only need to generate the code if you change an existing schema file or add a new one. You can find details on how to update schema files [here](https://google.github.io/flatbuffers/flatbuffers_guide_writing_schema.html). - -## Generating code - -We use [flatc](https://google.github.io/flatbuffers/flatbuffers_guide_using_schema_compiler.html) to generate rust code. - -We recommend building `flatc` from source. To generate rust code, use - -```console -just gen-all-fbs-rust-code -``` diff --git a/docs/security-guidance-for-developers.md b/docs/security-guidance-for-developers.md index 559bcaa31e..ef5ebe2587 100644 --- a/docs/security-guidance-for-developers.md +++ b/docs/security-guidance-for-developers.md @@ -9,7 +9,7 @@ This document discusses the security requirements and best practices for service ## Brief Checklist * All host functions that receive parameters from a guest, or operate indirectly on guest data _MUST_ be continuously fuzzed * Host functions _MUST NOT_ call APIs or be used to expose functionality deemed risky in a multi-tenant context -* Guests and host processes _MUST_ use the same version of a FlatBuffer definition +* Guests and host processes _MUST_ use compatible Hyperlight versions More detailed guidance on the requirements and best practices is detailed below. @@ -43,24 +43,13 @@ In a multi-tenant context, the following operations are considered security sens If any of these operations is performed in a host process, a security audit _MUST_ occur. -## Flatbuffers - Guests and host processes _MUST_ use compatible versions of a FlatBuffer definitions +## Guests and host processes _MUST_ use compatible Hyperlight versions -The guests and host processes _MUST_ use the exact same versions of a FlatBuffer definition. I.e., the same .fbs file _MUST_ be used for generating the encoders and decoders. +Host and guest exchange [postcard](https://docs.rs/postcard) messages built from Rust types in `hyperlight-common` with [serde](https://serde.rs). The format has no schema evolution. Guests _MUST_ be built against a `hyperlight-guest` version that matches the host. -## Flatbuffers - If using the same language for development, the guests and host processes _SHOULD_ use the same version of flatc compilers. +## Messages from the guest _MUST_ be copied and validated before use -This can be seen in the header files containing FLATBUFFERS_COMMON_READER_H. For instance: `/* Generated by flatcc 0.6.2 FlatBuffers schema compiler`. -We emit this recommendation because there is a history of compiler bugs, which may affect certain behaviors (encoding, decoding). We emit this recommendation because there is a history of compiler bugs, which may adversely affect certain behaviors (encoding, decoding). - -## Flatbuffers – a verifier should always be called before any decoder. In the case of failed verification, the input _MUST NOT_ be processed. - -For Rust code, if the return code is InvalidFlatBuffer, the input _MUST_ be rejected. - -## Flatbuffers – the host process _MUST NOT_ operate on Flatbuffers from several threads. - -Because of the zero-copy approach that FlatBuffers is using, there is a risk of memory safety issues. Flatbuffers are unsafe to be used in a multithreaded environment. This is explicitly indicated in several parts of the Flatbuffer documentation. - -Additionally, because Flatbuffers tainted data coming from the guests, this is even more critical in a multi-tenant scenario. +The host copies guest data out of shared memory before decoding it. Decoding _MUST_ reject malformed input, trailing bytes, and lengths beyond the received data. Rejected input _MUST NOT_ be processed. ## A rust host process _SHOULD_ handle [panics](https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html) or the service _SHOULD_ restart automatically diff --git a/docs/security.md b/docs/security.md index 32062b2f1e..90b5747e5b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -12,7 +12,7 @@ Hyperlight runs all guest code inside a Virtual Machine, Each VM only has access ### Host-Guest Communication (Serialization and Deserialization) -All communication between the host and the guest is done through a shared memory buffer. Messages are serialized and deserialized using [FlatBuffers](https://flatbuffers.dev/). To minimize attack surface area, we rely on FlatBuffers to formally specify the data structures passed to/from the host and guest, and to generate serialization/deserialization code. Of course, a compromised guest can write arbitrary data to the shared memory buffer, but the host will not accept anything that does not match our strongly typed FlatBuffer [schemas](../src/schema). +All communication between the host and the guest is done through a shared memory buffer. Messages are serialized with [serde](https://serde.rs) into the [postcard](https://docs.rs/postcard) format, using strongly typed Rust definitions in `hyperlight-common`. The host copies guest data out of shared memory before decoding it. Decoding rejects malformed input and trailing bytes. Every length is checked against the received message, so allocations stay proportional to its size. A compromised guest can write arbitrary data to the shared memory buffer, but the host accepts only messages that decode into these types. ### Accessing host functionality from the guest diff --git a/docs/snapshot-versioning.md b/docs/snapshot-versioning.md index 360b557f81..ec30ee4f67 100644 --- a/docs/snapshot-versioning.md +++ b/docs/snapshot-versioning.md @@ -52,6 +52,9 @@ regenerated. ABI 9 removes the heap region from snapshot memory. Earlier snapshots must be regenerated. +ABI 10 encodes control data with postcard and carries its length in a 16-byte +message header. Earlier snapshots must be regenerated. + The `OCI_LAYOUT_VERSION` constant is pinned by the OCI image-layout spec at `1.0.0`. @@ -74,7 +77,7 @@ them. ## Enforcement -The format is large and easy to change by accident. Two mechanisms +The format is large and easy to change by accident. Three mechanisms catch a change to it so reviewers do not have to spot every break by eye, and so a developer who breaks the format unintentionally finds out at build time rather than in production. @@ -87,6 +90,12 @@ OCI layout version, the `HyperlightPEB` size, every `OutBAction` and `VmAction` discriminant, and `BASE_ADDRESS`. If the source value drifts from the copy in `tripwires.rs`, the crate fails to compile. +Wire format tests in +[src/hyperlight_common/src/flatbuffer_wrappers/abi_tests.rs](../src/hyperlight_common/src/flatbuffer_wrappers/abi_tests.rs) +pin the encoded bytes of every host-guest message: the message header, +function calls and results, guest logs and trace events. Snapshots +contain guest code built against these encodings. + The snapshot golden verify test (`cargo test -p hyperlight-host --test snapshot_goldens`) loads snapshots from a local directory (populated by `just snapshot-goldens-pull`, diff --git a/docs/virtio-host-guest-communication.md b/docs/virtio-host-guest-communication.md index 64d293e650..c894796042 100644 --- a/docs/virtio-host-guest-communication.md +++ b/docs/virtio-host-guest-communication.md @@ -185,8 +185,8 @@ Every logical message has this byte layout: ```text +----------------+-----------------------------+---------------------+ - | MsgHeader | size-prefixed FlatBuffer | external byte data | - | 12 bytes | control data | zero or more values | + | MsgHeader | postcard control data | external byte data | + | 16 bytes | control_len bytes | zero or more values | +----------------+-----------------------------+---------------------+ ``` @@ -196,8 +196,12 @@ Every logical message has this byte layout: * three reserved zero bytes * `cid: u32` * `payload_len: u32` +* `control_len: u32` -`payload_len` covers the control data and all external bytes. RPC correlation +`payload_len` covers the control data and all external bytes. `control_len` +covers the control data and never exceeds `payload_len`. The host reads it +first so it can copy exactly the control data out of guest memory in one read +before parsing. RPC correlation IDs are nonzero. Responses echo the request ID. Logs and snapshot checkpoints use ID zero. @@ -208,8 +212,10 @@ The active message kinds are: * `Log` * `SnapshotCheckpoint` -The FlatBuffer holds the typed function call or result and the lengths of -external byte values. External bytes follow it in the same logical message. +The control data holds the typed function call or result and the lengths of +external byte values. It is one [postcard](https://docs.rs/postcard) value. +Decoding rejects trailing bytes. External bytes follow it in the same logical +message. A logical message may span several descriptors or several H2G receive buffers. The guest reads control data directly when it occupies one segment. It copies @@ -218,22 +224,20 @@ control data out of guest writable scratch. ### Choosing a value type -* `String`: UTF-8 text, encoded inside the FlatBuffer. +* `String`: UTF-8 text, encoded inside the control data. * `VecBytes`: small binary values, or a receiver that needs a contiguous `Vec`. * `ByteChunks`: large binary data or data already held in chunks. For small `String` or `VecBytes` values, aim to fit the complete guest-sent G2H -message in 256 bytes. The payload budget is `256 - 12 - envelope_overhead`. -The 12-byte header is fixed. FlatBuffer overhead includes its size prefix -and metadata, and varies with the call. This is a sizing guideline, not a +message in 256 bytes. The payload budget is `256 - 16 - envelope_overhead`. +The 16-byte header is fixed. Control data overhead varies with the call. This is a sizing guideline, not a limit on the value types. ### External byte values -`VecBytes` and `ByteChunks` payloads stay outside the FlatBuffer. It contains the -total logical value length and whether the value is chunked. The encoder can -then reference the caller's byte slices directly without first copying them into -one contiguous FlatBuffer. +`VecBytes` and `ByteChunks` payloads stay outside the control data. It contains +the total logical value length and whether the value is chunked. The encoder +references the caller's byte slices directly. `ExternalValueSource` is implemented by `RecvChain` for host decoding and by `Segments` for guest decoding. @@ -262,8 +266,8 @@ records one total length, not each source chunk length. The receiver sees the logical byte sequence split where it intersects transport buffers. Each payload letter represents 1 KiB. Metadata size varies with the call. -It combines the fixed 12-byte message header and the size-prefixed -FlatBuffer. This example uses 1 KiB of metadata. +It combines the fixed 16-byte message header and the control data. This +example uses 1 KiB of metadata. ```text Sender chunks: [AB] [CDEFG] [HIJ] 2 + 5 + 3 KiB @@ -274,8 +278,8 @@ Guest ByteChunks: [ABC] [DEFG] [HIJ] 3 + 4 + 3 KiB Guest chunks exclude the metadata and unused space. H2G chunking follows the preposted H2G slot size. G2H responses returned to -the guest follow the G2H writable slot size. The message header and FlatBuffer -can consume part of the first slot. The final slot can also be partial. +the guest follow the G2H writable slot size. The message header and control +data can consume part of the first slot. The final slot can also be partial. #### Example: keeping a payload in one chunk @@ -409,7 +413,7 @@ freed virtual ranges bounds page-table growth by the alias high-water mark. ### Trust boundary -The host treats guest rings, descriptors, headers, FlatBuffers, and payload +The host treats guest rings, descriptors, headers, control data, and payload lengths as untrusted. * Rings and payloads use checked copies and atomics within mapped scratch. diff --git a/flake.nix b/flake.nix index 8d1fe33daa..43dd8348d7 100644 --- a/flake.nix +++ b/flake.nix @@ -296,7 +296,6 @@ zlib cargo-hyperlight typos - flatbuffers cargo-fuzz ] ++ (if system == "x86_64-linux" || system == "aarch64-linux" then [ valgrind ] diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index eeaa7ef2a2..12862a96aa 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -14,8 +14,8 @@ hyperlight-host = { workspace = true, default-features = true, features = ["fuzz hyperlight-common = {workspace = true} [[bin]] -name = "fuzz_guest_estimate_trace_event" -path = "fuzz_targets/guest_estimate_trace_event.rs" +name = "fuzz_guest_trace_decode" +path = "fuzz_targets/guest_trace_decode.rs" test = false doc = false bench = false @@ -62,6 +62,13 @@ test = false doc = false bench = false +[[bin]] +name = "fuzz_control_decode" +path = "fuzz_targets/control_decode.rs" +test = false +doc = false +bench = false + [features] default = [] trace = ["hyperlight-host/trace_guest", "hyperlight-common/trace_guest"] diff --git a/fuzz/README.md b/fuzz/README.md index c34425b78f..2ec2ed5be3 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -50,6 +50,16 @@ The malformed target shares the memory backend and covers malformed descriptors. just fuzz-timed fuzz_virtq_roundtrip 60 ``` +## Control data decoding + +`fuzz_control_decode` decodes untrusted function calls, results, and logs. The +first two input bytes select the control length. The remaining +bytes are external values. Decode errors are accepted. Panics fail the run. + +```sh +just fuzz-timed fuzz_control_decode 60 +``` + ## On Failure If you encounter a failure, you can re-run an entire seed (i.e., group of inputs) with: diff --git a/fuzz/fuzz_targets/control_decode.rs b/fuzz/fuzz_targets/control_decode.rs new file mode 100644 index 0000000000..a18ceba549 --- /dev/null +++ b/fuzz/fuzz_targets/control_decode.rs @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 The Hyperlight Authors. + +//! Decodes arbitrary function calls, results and logs from untrusted control +//! data and external bytes. + +#![no_main] + +use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall; +use hyperlight_common::flatbuffer_wrappers::function_types::{Bytes, FunctionCallResult}; +use hyperlight_common::flatbuffer_wrappers::guest_log_data::GuestLogData; +use hyperlight_common::virtq::Segments; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + let Some((split, rest)) = data.split_first_chunk::<2>() else { + return; + }; + let split = usize::from(u16::from_le_bytes(*split)).min(rest.len()); + let (control, external) = rest.split_at(split); + + let mut source = Segments::single(Bytes::copy_from_slice(external)); + let _ = FunctionCall::decode(control, &mut source); + + let mut source = Segments::single(Bytes::copy_from_slice(external)); + let _ = FunctionCallResult::decode(control, &mut source); + + let _ = GuestLogData::try_from(control); +}); diff --git a/fuzz/fuzz_targets/guest_estimate_trace_event.rs b/fuzz/fuzz_targets/guest_trace_decode.rs similarity index 59% rename from fuzz/fuzz_targets/guest_estimate_trace_event.rs rename to fuzz/fuzz_targets/guest_trace_decode.rs index 158baca379..182fd069e6 100644 --- a/fuzz/fuzz_targets/guest_estimate_trace_event.rs +++ b/fuzz/fuzz_targets/guest_trace_decode.rs @@ -3,11 +3,11 @@ #![no_main] #[cfg(not(feature = "trace"))] -compile_error!("feature `trace` must be enabled to fuzz guest trace event estimation"); +compile_error!("feature `trace` must be enabled to fuzz guest trace decoding"); use hyperlight_common::flatbuffer_wrappers::guest_trace_data::{ EventKeyValue, EventsBatchDecoder, EventsBatchEncoder, EventsDecoder, EventsEncoder, - GuestEvent, estimate_event, + GuestEvent, MAX_TRACE_DATA_SIZE, }; use libfuzzer_sys::arbitrary::{Arbitrary, Result as FuzzResult, Unstructured}; use libfuzzer_sys::fuzz_target; @@ -15,18 +15,14 @@ use libfuzzer_sys::fuzz_target; const MAX_STRING_LEN: usize = 1 << 10; // 1024 bytes const MAX_FIELDS: usize = 32; -/// Wrapper around GuestEvent to implement Arbitrary +/// An event to round trip and raw bytes to decode as a batch. #[derive(Debug)] -struct EventInput(GuestEvent); - -impl EventInput { - /// Consumes the wrapper and returns the inner GuestEvent - fn into_inner(self) -> GuestEvent { - self.0 - } +struct Input<'a> { + event: GuestEvent, + raw: &'a [u8], } -impl<'a> Arbitrary<'a> for EventInput { +impl<'a> Arbitrary<'a> for Input<'a> { fn arbitrary(u: &mut Unstructured<'a>) -> FuzzResult { // Choose a variant of GuestEvent to generate let discriminator = u.arbitrary::()? % 5; @@ -60,7 +56,10 @@ impl<'a> Arbitrary<'a> for EventInput { }, }; - Ok(EventInput(event)) + Ok(Input { + event, + raw: u.arbitrary()?, + }) } } @@ -99,59 +98,14 @@ fn arbitrary_fields(u: &mut Unstructured<'_>) -> FuzzResult> Ok(fields) } -/// Encodes a GuestEvent into a byte vector -fn encode(event: &GuestEvent) -> Vec { - // Use the estimate plus some slack to avoid reallocation during encoding - let mut encoder = EventsBatchEncoder::new(estimate_event(event).saturating_add(256), |_| {}); - encoder.encode(event); - encoder.finish().to_vec() -} - -/// Decodes a byte slice into a GuestEvent -fn decode(data: &[u8]) -> Option { - let decoder = EventsBatchDecoder {}; - let mut events = decoder.decode(data).ok()?; - - if events.len() == 1 { - events.pop() - } else { - None - } -} - -/// Asserts that the estimated size is within acceptable bounds of the actual size -/// Allows for a 10% slack or minimum of 128 bytes -fn assert_estimate_bounds(actual: usize, estimate: usize) { - assert!( - estimate >= actual, - "estimate {} smaller than actual {}", - estimate, - actual, - ); - - let slack = (actual / 10).max(128); - let upper_bound = actual + slack; - assert!( - estimate <= upper_bound, - "estimate {} larger than allowable upper bound {} (actual {})", - estimate, - upper_bound, - actual, - ); -} - -fuzz_target!(|input: EventInput| { - let event = input.into_inner(); - - // Get the size estimate - let estimate = estimate_event(&event); - // Encode the event - let encoded_data = encode(&event); - // Assert that the estimate is within bounds - assert_estimate_bounds(encoded_data.len(), estimate); +fuzz_target!(|input: Input<'_>| { + // Arbitrary batches must decode or fail without panicking. + let _ = EventsBatchDecoder.decode(input.raw); - // Decode the event back - let decoded = decode(&encoded_data).expect("decoding failed"); - // Assert that the decoded event matches the original - assert_eq!(event, decoded); + let mut encoder = EventsBatchEncoder::new(MAX_TRACE_DATA_SIZE, |_| {}); + encoder.encode(&input.event); + let decoded = EventsBatchDecoder + .decode(encoder.finish()) + .expect("decoding failed"); + assert_eq!(decoded, [input.event]); }); diff --git a/src/hyperlight_common/Cargo.toml b/src/hyperlight_common/Cargo.toml index 3ea678ecf5..85c3bffdbe 100644 --- a/src/hyperlight_common/Cargo.toml +++ b/src/hyperlight_common/Cargo.toml @@ -21,8 +21,9 @@ bitflags = "2.13.0" bytemuck = { version = "1.24", features = ["derive"] } bytes = { version = "1", default-features = false } fixedbitset = { version = "0.5.7", default-features = false } -flatbuffers = { version = "25.12.19", default-features = false } log = "0.4.32" +postcard = { version = "1.1.3", default-features = false } +serde = { version = "1.0.229", default-features = false, features = ["alloc", "derive"] } smallvec = "1.15.1" spin = "0.12.0" thiserror = { version = "2.0.18", default-features = false } diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/abi_tests.rs b/src/hyperlight_common/src/flatbuffer_wrappers/abi_tests.rs new file mode 100644 index 0000000000..30f020c60a --- /dev/null +++ b/src/hyperlight_common/src/flatbuffer_wrappers/abi_tests.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 The Hyperlight Authors. + +//! Tests that pin the wire format of host-guest messages. +//! +//! Snapshots contain guest code built against this format, so a failure means +//! the new encoding breaks existing snapshots. Keep the old encoding, or bump +//! `SNAPSHOT_ABI_VERSION` and the goldens version as described in +//! `docs/snapshot-versioning.md`. + +use alloc::string::ToString; +use alloc::vec; +use alloc::vec::Vec; + +use super::function_call::{FunctionCall, FunctionCallType}; +use super::function_types::{FunctionCallResult, ParameterValue, ReturnType, ReturnValue}; +use super::guest_error::{ErrorCode, GuestError}; +use super::guest_log_data::GuestLogData; +use super::guest_log_level::LogLevel; +use super::wire::WireValue; +use crate::transport::{ExternalValues, MsgHeader, MsgKind}; + +#[track_caller] +fn assert_wire_bytes(what: &str, actual: &[u8], expected: &[u8]) { + assert_eq!( + actual, expected, + "wire format of {what} changed. This breaks existing snapshots. Keep the old \ + encoding, or bump SNAPSHOT_ABI_VERSION and the goldens version. See \ + docs/snapshot-versioning.md." + ); +} + +fn encode(value: &T) -> Vec { + postcard::to_extend(value, Vec::new()).unwrap() +} + +#[test] +fn message_header() { + let header = MsgHeader::new(MsgKind::Response, 0x1234_5678, 4096, 16); + + #[rustfmt::skip] + let expected = [ + 0x02, 0, 0, 0, // kind, reserved + 0x78, 0x56, 0x34, 0x12, // cid + 0, 0x10, 0, 0, // payload_len + 16, 0, 0, 0, // control_len + ]; + assert_wire_bytes("MsgHeader", header.as_bytes(), &expected); + assert_eq!(MsgHeader::from_bytes(header.as_bytes()), Some(header)); +} + +#[test] +fn function_call() { + let call = FunctionCall::new( + "add".to_string(), + Some(vec![ + ParameterValue::Int(-1), + ParameterValue::String("hi".to_string()), + ParameterValue::VecBytes(vec![1, 2, 3]), + ]), + FunctionCallType::Host, + ReturnType::Long, + ); + let mut buffer = Vec::new(); + let mut external_values = ExternalValues::new(); + let encoded = call.encode(&mut buffer, &mut external_values).unwrap(); + + #[rustfmt::skip] + let expected = [ + 3, b'a', b'd', b'd', // name + 1, // host + 2, // ReturnType::Long + 3, // parameter count + 0, 1, // Int(-1), zigzag varint + 6, 2, b'h', b'i', // String("hi") + 9, 3, 0, // ExternalBytes { length: 3, chunked: false } + ]; + assert_wire_bytes("FunctionCall", encoded, &expected); + assert_eq!(external_values.total_len(), 3); +} + +#[test] +fn function_result() { + let mut buffer = Vec::new(); + let mut external_values = ExternalValues::new(); + + let ok = FunctionCallResult::new(Ok(ReturnValue::UInt(300))); + let encoded = ok.encode(&mut buffer, &mut external_values).unwrap(); + // Ok, UInt, varint 300. + assert_wire_bytes("FunctionCallResult::Ok", encoded, &[0, 1, 0xac, 0x02]); + + let err = FunctionCallResult::new(Err(GuestError::new( + ErrorCode::GuestFunctionNotFound, + "no".to_string(), + ))); + let encoded = err.encode(&mut buffer, &mut external_values).unwrap(); + // Err, code 4, message "no". + assert_wire_bytes("FunctionCallResult::Err", encoded, &[1, 4, 2, b'n', b'o']); + assert_eq!(external_values.total_len(), 0); +} + +#[test] +fn value_tags() { + let cases = [ + (WireValue::Int(0), 0u8), + (WireValue::UInt(0), 1), + (WireValue::Long(0), 2), + (WireValue::ULong(0), 3), + (WireValue::Float(0.0), 4), + (WireValue::Double(0.0), 5), + (WireValue::String(""), 6), + (WireValue::Bool(false), 7), + (WireValue::Void, 8), + ( + WireValue::ExternalBytes { + length: 0, + chunked: false, + }, + 9, + ), + ]; + for (value, tag) in cases { + let what = alloc::format!("{value:?}"); + assert_wire_bytes(&what, &encode(&value)[..1], &[tag]); + } +} + +#[test] +fn return_type_tags() { + let types = [ + ReturnType::Int, + ReturnType::UInt, + ReturnType::Long, + ReturnType::ULong, + ReturnType::Float, + ReturnType::Double, + ReturnType::String, + ReturnType::Bool, + ReturnType::Void, + ReturnType::VecBytes, + ReturnType::ByteChunks, + ]; + for (tag, value) in types.into_iter().enumerate() { + let what = alloc::format!("ReturnType::{value:?}"); + assert_wire_bytes(&what, &encode(&value), &[tag as u8]); + assert_eq!( + postcard::from_bytes::(&[tag as u8]).unwrap(), + value + ); + } + assert!(postcard::from_bytes::(&[types.len() as u8]).is_err()); +} + +#[test] +fn float_bits() { + // Little-endian IEEE 754 after the tag. + assert_wire_bytes( + "Float", + &encode(&WireValue::Float(-0.0)), + &[4, 0, 0, 0, 0x80], + ); + assert_wire_bytes( + "Double", + &encode(&WireValue::Double(-0.0)), + &[5, 0, 0, 0, 0, 0, 0, 0, 0x80], + ); +} + +#[test] +fn error_codes() { + let codes = [ + (ErrorCode::NoError, 0), + (ErrorCode::UnsupportedParameterType, 2), + (ErrorCode::GuestFunctionNameNotProvided, 3), + (ErrorCode::GuestFunctionNotFound, 4), + (ErrorCode::GuestFunctionIncorrecNoOfParameters, 5), + (ErrorCode::GispatchFunctionPointerNotSet, 6), + (ErrorCode::OutbError, 7), + (ErrorCode::UnknownError, 8), + (ErrorCode::GsCheckFailed, 10), + (ErrorCode::TooManyGuestFunctions, 11), + (ErrorCode::FailureInDlmalloc, 12), + (ErrorCode::MallocFailed, 13), + (ErrorCode::GuestFunctionParameterTypeMismatch, 14), + (ErrorCode::GuestError, 15), + (ErrorCode::ArrayLengthParamIsMissing, 16), + (ErrorCode::HostFunctionError, 17), + ]; + for (code, value) in codes { + let what = alloc::format!("ErrorCode::{code:?}"); + assert_wire_bytes( + &what, + &u64::from(code).to_le_bytes(), + &u64::to_le_bytes(value), + ); + assert_eq!(ErrorCode::from(value), code); + } + for unknown in [1, 9, 18, u64::MAX] { + assert_eq!(ErrorCode::from(unknown), ErrorCode::UnknownError); + } +} + +#[test] +fn guest_log() { + let log = GuestLogData::new( + "m".to_string(), + "s".to_string(), + LogLevel::Warning, + "c".to_string(), + "f".to_string(), + 300, + ); + let encoded: Vec = log.try_into().unwrap(); + + #[rustfmt::skip] + let expected = [ + 1, b'm', // message + 1, b's', // source + 3, // LogLevel::Warning + 1, b'c', // caller + 1, b'f', // source_file + 0xac, 2, // line, varint 300 + ]; + assert_wire_bytes("GuestLogData", &encoded, &expected); +} + +#[test] +fn log_level_tags() { + let levels = [ + LogLevel::Trace, + LogLevel::Debug, + LogLevel::Information, + LogLevel::Warning, + LogLevel::Error, + LogLevel::Critical, + LogLevel::None, + ]; + for (tag, level) in levels.into_iter().enumerate() { + let what = alloc::format!("LogLevel::{level:?}"); + assert_wire_bytes(&what, &encode(&level), &[tag as u8]); + assert_eq!( + postcard::from_bytes::(&[tag as u8]).unwrap(), + level + ); + } + assert!(postcard::from_bytes::(&[levels.len() as u8]).is_err()); +} + +#[cfg(feature = "trace_guest")] +#[test] +fn trace_events() { + use super::guest_trace_data::{EventKeyValue, GuestEvent}; + + let field = || EventKeyValue { + key: "k".to_string(), + value: "v".to_string(), + }; + #[rustfmt::skip] + let cases: [(GuestEvent, &[u8]); 5] = [ + ( + GuestEvent::OpenSpan { + id: 2, + parent_id: Some(1), + name: "n".to_string(), + target: "t".to_string(), + tsc: 300, + fields: vec![field()], + }, + &[0, 2, 1, 1, 1, b'n', 1, b't', 0xac, 2, 1, 1, b'k', 1, b'v'], + ), + (GuestEvent::CloseSpan { id: 2, tsc: 3 }, &[1, 2, 3]), + ( + GuestEvent::LogEvent { + parent_id: 2, + name: "n".to_string(), + tsc: 3, + fields: vec![], + }, + &[2, 2, 1, b'n', 3, 0], + ), + ( + GuestEvent::EditSpan { id: 2, fields: vec![field()] }, + &[3, 2, 1, 1, b'k', 1, b'v'], + ), + (GuestEvent::GuestStart { tsc: 1 }, &[4, 1]), + ]; + + for (event, expected) in cases { + let what = alloc::format!("{event:?}"); + assert_wire_bytes(&what, &encode(&event), expected); + } +} diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/codec.rs b/src/hyperlight_common/src/flatbuffer_wrappers/codec.rs index c59e759a0f..09b68ffb5a 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/codec.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/codec.rs @@ -6,7 +6,7 @@ use alloc::vec::Vec; use anyhow::Result; use bytes::Bytes; -/// Receives external byte values while their FlatBuffer metadata is encoded. +/// Receives external byte values while their control data is encoded. /// /// Values are delivered in their logical order without flattening chunked /// values. The value lifetime allows a sink to retain references until the @@ -19,7 +19,7 @@ pub trait ExternalValueSink<'a> { fn push_chunks(&mut self, value: &'a [Bytes]) -> Result<()>; } -/// Supplies complete external byte values while a FlatBuffer is decoded. +/// Supplies complete external byte values while control data is decoded. /// /// [`RecvChain`](crate::virtq::RecvChain) copies values out of shared memory. /// [`Segments`](crate::virtq::Segments) retains existing chunk owners. diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs b/src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs index 849820f52d..b3bdc193a7 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/function_call.rs @@ -4,21 +4,14 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; -use anyhow::{Result, bail}; -use flatbuffers::{FlatBufferBuilder, WIPOffset, size_prefixed_root}; +use anyhow::Result; #[cfg(feature = "tracing")] use tracing::{Span, instrument}; use super::codec::{ExternalValueSink, ExternalValueSource}; use super::function_types::{ParameterValue, ReturnType, decode_parameter_value}; use super::util::try_byte_chunks_len; -use crate::flatbuffers::hyperlight::generated::{ - FunctionCall as FbFunctionCall, FunctionCallArgs as FbFunctionCallArgs, - FunctionCallType as FbFunctionCallType, Parameter, ParameterArgs, - ParameterValue as FbParameterValue, hlbool, hlboolArgs, hldouble, hldoubleArgs, - hlexternalbytes, hlexternalbytesArgs, hlfloat, hlfloatArgs, hlint, hlintArgs, hllong, - hllongArgs, hlstring, hlstringArgs, hluint, hluintArgs, hlulong, hlulongArgs, -}; +use super::wire::{ParamsIn, ParamsOut, WireCall, decode_value, encode_value}; /// The type of function call. #[derive(Debug, Clone, PartialEq, Eq)] @@ -65,179 +58,41 @@ impl FunctionCall { /// Encode control data and collect byte parameters as external values. pub fn encode<'a, 'b, S>( &'a self, - builder: &'b mut FlatBufferBuilder, + buffer: &'b mut Vec, external_values: &mut S, ) -> Result<&'b [u8]> where S: ExternalValueSink<'a> + ?Sized, { - let function_name = builder.create_string(&self.function_name); - - let function_call_type = match self.function_call_type { - FunctionCallType::Guest => FbFunctionCallType::guest, - FunctionCallType::Host => FbFunctionCallType::host, - }; - - let expected_return_type = self.expected_return_type.into(); - - let parameters = match &self.parameters { - Some(parameters) if !parameters.is_empty() => { - let parameter_offsets: Vec> = parameters - .iter() - .map(|parameter| -> Result> { - let parameter = match parameter { - ParameterValue::Int(value) => { - let value = hlint::create(builder, &hlintArgs { value: *value }); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hlint, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::UInt(value) => { - let value = hluint::create(builder, &hluintArgs { value: *value }); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hluint, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::Long(value) => { - let value = hllong::create(builder, &hllongArgs { value: *value }); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hllong, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::ULong(value) => { - let value = - hlulong::create(builder, &hlulongArgs { value: *value }); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hlulong, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::Float(value) => { - let value = - hlfloat::create(builder, &hlfloatArgs { value: *value }); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hlfloat, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::Double(value) => { - let value = - hldouble::create(builder, &hldoubleArgs { value: *value }); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hldouble, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::Bool(value) => { - let value = hlbool::create(builder, &hlboolArgs { value: *value }); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hlbool, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::String(value) => { - let value = builder.create_string(value.as_str()); - let value = - hlstring::create(builder, &hlstringArgs { value: Some(value) }); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hlstring, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::VecBytes(value) => { - let length = u64::try_from(value.len()).map_err(|_| { - anyhow::anyhow!( - "External VecBytes parameter length does not fit in u64" - ) - })?; - external_values.push_bytes(value)?; - let value = hlexternalbytes::create( - builder, - &hlexternalbytesArgs { - length, - chunked: false, - }, - ); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hlexternalbytes, - value: Some(value.as_union_value()), - }, - ) - } - ParameterValue::ByteChunks(value) => { - let length = try_byte_chunks_len(value).ok_or_else(|| { - anyhow::anyhow!("External ByteChunks parameter length overflow") - })?; - let length = u64::try_from(length).map_err(|_| { - anyhow::anyhow!( - "External ByteChunks parameter length does not fit in u64" - ) - })?; - external_values.push_chunks(value)?; - let value = hlexternalbytes::create( - builder, - &hlexternalbytesArgs { - length, - chunked: true, - }, - ); - Parameter::create( - builder, - &ParameterArgs { - value_type: FbParameterValue::hlexternalbytes, - value: Some(value.as_union_value()), - }, - ) - } - }; - Ok(parameter) - }) - .collect::>>()?; - Some(builder.create_vector(¶meter_offsets)) + let parameters = self.parameters.as_deref().unwrap_or_default(); + for parameter in parameters { + match parameter { + ParameterValue::VecBytes(value) => { + u64::try_from(value.len()).map_err(|_| { + anyhow::anyhow!("External VecBytes parameter length does not fit in u64") + })?; + external_values.push_bytes(value)?; + } + ParameterValue::ByteChunks(value) => { + let length = try_byte_chunks_len(value).ok_or_else(|| { + anyhow::anyhow!("External ByteChunks parameter length overflow") + })?; + u64::try_from(length).map_err(|_| { + anyhow::anyhow!("External ByteChunks parameter length does not fit in u64") + })?; + external_values.push_chunks(value)?; + } + _ => {} } - _ => None, - }; + } - let function_call = FbFunctionCall::create( - builder, - &FbFunctionCallArgs { - function_name: Some(function_name), - parameters, - function_call_type, - expected_return_type, - }, - ); - builder.finish_size_prefixed(function_call, None); - Ok(builder.finished_data()) + let call = WireCall { + name: &self.function_name, + host: self.function_call_type == FunctionCallType::Host, + return_type: self.expected_return_type, + params: ParamsOut(parameters), + }; + encode_value(&call, buffer) } /// Decode control data and consume external byte parameters. @@ -245,34 +100,31 @@ impl FunctionCall { where S: ExternalValueSource + ?Sized, { - let function_call_fb = size_prefixed_root::(value) - .map_err(|e| anyhow::anyhow!("Error reading function call buffer: {:?}", e))?; - let function_name = function_call_fb.function_name(); - let function_call_type = match function_call_fb.function_call_type() { - FbFunctionCallType::guest => FunctionCallType::Guest, - FbFunctionCallType::host => FunctionCallType::Host, - other => { - bail!("Invalid function call type: {:?}", other); - } + let call: WireCall<'_, ParamsIn<'_>> = decode_value(value)?; + let function_call_type = if call.host { + FunctionCallType::Host + } else { + FunctionCallType::Guest + }; + + let parameters = if call.params.0.is_empty() { + None + } else { + Some( + call.params + .0 + .into_iter() + .map(|value| decode_parameter_value(value, external_values)) + .collect::>>()?, + ) }; - let expected_return_type = function_call_fb.expected_return_type().try_into()?; - - let parameters = function_call_fb - .parameters() - .map(|parameters| { - parameters - .iter() - .map(|parameter| decode_parameter_value(parameter, external_values)) - .collect::>>() - }) - .transpose()?; external_values.finish()?; Ok(Self { - function_name: function_name.to_string(), + function_name: call.name.to_string(), parameters, function_call_type, - expected_return_type, + expected_return_type: call.return_type, }) } } @@ -284,6 +136,7 @@ mod tests { use super::*; use crate::flatbuffer_wrappers::function_types::{Bytes, ReturnType}; + use crate::flatbuffer_wrappers::wire::WireValue; #[derive(Debug, Clone, PartialEq)] enum TestExternalValue { @@ -349,8 +202,8 @@ mod tests { } #[test] - fn read_from_flatbuffer() -> Result<()> { - let mut builder = FlatBufferBuilder::new(); + fn twelve_parameters_round_trip() -> Result<()> { + let mut buffer = Vec::new(); let mut external_values = TestExternalValues::default(); let test_data = FunctionCall::new( "PrintTwelveArgs".to_string(), @@ -371,7 +224,7 @@ mod tests { FunctionCallType::Guest, ReturnType::Int, ) - .encode(&mut builder, &mut external_values)?; + .encode(&mut buffer, &mut external_values)?; let function_call = FunctionCall::decode(test_data, &mut external_values)?; assert_eq!(function_call.function_name, "PrintTwelveArgs"); @@ -400,7 +253,7 @@ mod tests { #[test] fn byte_parameters_round_trip_in_external_value_order() { - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let expected_parameters = vec![ ParameterValue::Int(7), ParameterValue::UInt(8), @@ -425,7 +278,7 @@ mod tests { ReturnType::ByteChunks, ); let mut external_values = TestExternalValues::default(); - let encoded = call.encode(&mut builder, &mut external_values).unwrap(); + let encoded = call.encode(&mut buffer, &mut external_values).unwrap(); assert!(encoded.len() < 4096); assert_eq!( @@ -441,19 +294,17 @@ mod tests { ]) ); - let encoded_call = size_prefixed_root::(encoded).unwrap(); - let encoded_parameters = encoded_call.parameters().unwrap(); + let encoded_call: WireCall<'_, ParamsIn<'_>> = decode_value(encoded).unwrap(); for (index, length, chunked) in [ (7, 4096, false), (9, 17, true), (10, 0, false), (11, 0, true), ] { - let parameter = encoded_parameters.get(index); - assert_eq!(parameter.value_type(), FbParameterValue::hlexternalbytes); - let metadata = parameter.value_as_hlexternalbytes().unwrap(); - assert_eq!(metadata.length(), length); - assert_eq!(metadata.chunked(), chunked); + assert_eq!( + encoded_call.params.0[index], + WireValue::ExternalBytes { length, chunked } + ); } let decoded = FunctionCall::decode(encoded, &mut external_values).unwrap(); @@ -475,9 +326,9 @@ mod tests { FunctionCallType::Guest, ReturnType::Bool, ); - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = TestExternalValues::default(); - let encoded = call.encode(&mut builder, &mut external_values).unwrap(); + let encoded = call.encode(&mut buffer, &mut external_values).unwrap(); assert!(external_values.values.is_empty()); let decoded = FunctionCall::decode(encoded, &mut external_values).unwrap(); @@ -486,7 +337,7 @@ mod tests { #[test] fn external_parameter_decoder_rejects_invalid_value_sequences() { - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let call = FunctionCall::new( "external_bytes".to_string(), Some(vec![ParameterValue::VecBytes(vec![1, 2, 3])]), @@ -494,7 +345,7 @@ mod tests { ReturnType::Void, ); let mut encoded_values = TestExternalValues::default(); - let encoded = call.encode(&mut builder, &mut encoded_values).unwrap(); + let encoded = call.encode(&mut buffer, &mut encoded_values).unwrap(); let mut missing = TestExternalValues::default(); assert!(FunctionCall::decode(encoded, &mut missing).is_err()); diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/function_types.rs b/src/hyperlight_common/src/flatbuffer_wrappers/function_types.rs index 90cb31587e..b70cd6333d 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/function_types.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/function_types.rs @@ -6,7 +6,7 @@ use alloc::vec::Vec; use anyhow::{Error, Result, anyhow, bail}; pub use bytes::Bytes; -use flatbuffers::size_prefixed_root; +use serde::{Deserialize, Serialize}; #[cfg(feature = "tracing")] use tracing::{Span, instrument}; @@ -15,15 +15,7 @@ use super::guest_error::GuestError; #[cfg(feature = "fuzzing")] use super::util::arbitrary_byte_chunks; use super::util::try_byte_chunks_len; -use crate::flatbuffers::hyperlight::generated::{ - FunctionCallResult as FbFunctionCallResult, FunctionCallResultArgs as FbFunctionCallResultArgs, - FunctionCallResultType, Parameter, ParameterType as FbParameterType, - ParameterValue as FbParameterValue, ReturnType as FbReturnType, ReturnValue as FbReturnValue, - ReturnValueBox, ReturnValueBoxArgs, hlbool, hlboolArgs, hldouble, hldoubleArgs, - hlexternalbytes, hlexternalbytesArgs, hlfloat, hlfloatArgs, hlint, hlintArgs, hllong, - hllongArgs, hlstring, hlstringArgs, hluint, hluintArgs, hlulong, hlulongArgs, hlvoid, - hlvoidArgs, -}; +use super::wire::{WireResult, WireValue, decode_value, encode_value}; pub struct FunctionCallResult(core::result::Result); @@ -31,120 +23,38 @@ impl FunctionCallResult { /// Encode control data and collect a byte return as an external value. pub fn encode<'a, 'b, S>( &'a self, - builder: &'b mut flatbuffers::FlatBufferBuilder, + buffer: &'b mut Vec, external_values: &mut S, ) -> Result<&'b [u8]> where S: ExternalValueSink<'a> + ?Sized, { - match &self.0 { - Ok(rv) => { - // Encode ReturnValue as ReturnValueBox - let (value, value_type) = match rv { - ReturnValue::Int(i) => { - let off = hlint::create(builder, &hlintArgs { value: *i }); - (Some(off.as_union_value()), FbReturnValue::hlint) - } - ReturnValue::UInt(ui) => { - let off = hluint::create(builder, &hluintArgs { value: *ui }); - (Some(off.as_union_value()), FbReturnValue::hluint) - } - ReturnValue::Long(l) => { - let off = hllong::create(builder, &hllongArgs { value: *l }); - (Some(off.as_union_value()), FbReturnValue::hllong) - } - ReturnValue::ULong(ul) => { - let off = hlulong::create(builder, &hlulongArgs { value: *ul }); - (Some(off.as_union_value()), FbReturnValue::hlulong) - } - ReturnValue::Float(f) => { - let off = hlfloat::create(builder, &hlfloatArgs { value: *f }); - (Some(off.as_union_value()), FbReturnValue::hlfloat) - } - ReturnValue::Double(d) => { - let off = hldouble::create(builder, &hldoubleArgs { value: *d }); - (Some(off.as_union_value()), FbReturnValue::hldouble) - } - ReturnValue::Bool(b) => { - let off = hlbool::create(builder, &hlboolArgs { value: *b }); - (Some(off.as_union_value()), FbReturnValue::hlbool) - } - ReturnValue::String(s) => { - let val = builder.create_string(s.as_str()); - let off = hlstring::create(builder, &hlstringArgs { value: Some(val) }); - (Some(off.as_union_value()), FbReturnValue::hlstring) - } + let result = match &self.0 { + Ok(value) => { + match value { ReturnValue::VecBytes(v) => { - let length = u64::try_from(v.len()) + u64::try_from(v.len()) .map_err(|_| anyhow!("External VecBytes length does not fit in u64"))?; - external_values.push_bytes(v)?; - let off = hlexternalbytes::create( - builder, - &hlexternalbytesArgs { - length, - chunked: false, - }, - ); - (Some(off.as_union_value()), FbReturnValue::hlexternalbytes) } ReturnValue::ByteChunks(v) => { let length = try_byte_chunks_len(v) .ok_or_else(|| anyhow!("External ByteChunks length overflow"))?; - - let length = u64::try_from(length).map_err(|_| { + u64::try_from(length).map_err(|_| { anyhow!("External ByteChunks length does not fit in u64") })?; - external_values.push_chunks(v)?; - let off = hlexternalbytes::create( - builder, - &hlexternalbytesArgs { - length, - chunked: true, - }, - ); - (Some(off.as_union_value()), FbReturnValue::hlexternalbytes) - } - ReturnValue::Void(()) => { - let off = hlvoid::create(builder, &hlvoidArgs {}); - (Some(off.as_union_value()), FbReturnValue::hlvoid) } - }; - let rv_box = - ReturnValueBox::create(builder, &ReturnValueBoxArgs { value, value_type }); - let fcr = FbFunctionCallResult::create( - builder, - &FbFunctionCallResultArgs { - result: Some(rv_box.as_union_value()), - result_type: FunctionCallResultType::ReturnValueBox, - }, - ); - builder.finish_size_prefixed(fcr, None); - Ok(builder.finished_data()) - } - Err(ge) => { - // Encode GuestError - let code: crate::flatbuffers::hyperlight::generated::ErrorCode = ge.code.into(); - let msg = builder.create_string(&ge.message); - let guest_error = crate::flatbuffers::hyperlight::generated::GuestError::create( - builder, - &crate::flatbuffers::hyperlight::generated::GuestErrorArgs { - code, - message: Some(msg), - }, - ); - let fcr = FbFunctionCallResult::create( - builder, - &FbFunctionCallResultArgs { - result: Some(guest_error.as_union_value()), - result_type: FunctionCallResultType::GuestError, - }, - ); - builder.finish_size_prefixed(fcr, None); - Ok(builder.finished_data()) + _ => {} + } + WireResult::Ok(WireValue::from_return(value)) } - } + Err(error) => WireResult::Err { + code: error.code.into(), + message: &error.message, + }, + }; + encode_value(&result, buffer) } pub fn new(value: core::result::Result) -> Self { @@ -160,31 +70,10 @@ impl FunctionCallResult { where S: ExternalValueSource + ?Sized, { - let function_call_result_fb = size_prefixed_root::(value) - .map_err(|e| anyhow!("Failed to get FunctionCallResult from bytes: {:?}", e))?; - - let result = match function_call_result_fb.result_type() { - FunctionCallResultType::ReturnValueBox => { - let boxed = function_call_result_fb - .result_as_return_value_box() - .ok_or_else(|| { - anyhow!("Failed to get ReturnValueBox from function call result") - })?; - Ok(decode_return_value(boxed, external_values)?) - } - FunctionCallResultType::GuestError => { - let guest_error_table = function_call_result_fb - .result_as_guest_error() - .ok_or_else(|| anyhow!("Failed to get GuestError from function call result"))?; - let code = guest_error_table.code(); - let message = guest_error_table - .message() - .map(|s| s.to_string()) - .unwrap_or_default(); - Err(GuestError::new(code.into(), message)) - } - other => { - bail!("Unexpected function call result type: {:?}", other) + let result = match decode_value(value)? { + WireResult::Ok(value) => Ok(decode_return_value(value, external_values)?), + WireResult::Err { code, message } => { + Err(GuestError::new(code.into(), message.to_string())) } }; @@ -280,9 +169,9 @@ pub enum ReturnValue { ByteChunks(Vec), } -/// Supported return types from function calling. +/// Supported return types from function calling. Variant order is the wire tag. #[cfg_attr(feature = "fuzzing", derive(arbitrary::Arbitrary))] -#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] #[repr(C)] pub enum ReturnType { /// i32 @@ -316,22 +205,19 @@ enum DecodedExternalBytes { } fn decode_external_bytes( - metadata: hlexternalbytes<'_>, + length: u64, + chunked: bool, externals: &mut S, ) -> Result where S: ExternalValueSource + ?Sized, { // The length delimits this value in the ordered external payload stream. - let length = usize::try_from(metadata.length()).map_err(|_| { - anyhow!( - "External byte length {} does not fit in usize", - metadata.length() - ) - })?; + let length = usize::try_from(length) + .map_err(|_| anyhow!("External byte length {length} does not fit in usize"))?; // `chunked` selects the logical API type. Sources define chunk boundaries. - if metadata.chunked() { + if chunked { let value = externals.take_chunks(length)?; let actual = try_byte_chunks_len(&value) .ok_or_else(|| anyhow!("External ByteChunks length overflow"))?; @@ -351,48 +237,53 @@ where } } -pub(crate) fn decode_parameter_value( - param: Parameter<'_>, +pub(super) fn decode_parameter_value( + value: WireValue<'_>, externals: &mut S, ) -> Result where S: ExternalValueSource + ?Sized, { - match param.value_type() { - FbParameterValue::hlexternalbytes => { - let Some(metadata) = param.value_as_hlexternalbytes() else { - bail!("External byte parameter metadata is missing"); - }; - - match decode_external_bytes(metadata, externals)? { - DecodedExternalBytes::VecBytes(value) => Ok(ParameterValue::VecBytes(value)), - DecodedExternalBytes::ByteChunks(value) => Ok(ParameterValue::ByteChunks(value)), - } - } - _ => param.try_into(), - } -} - -fn decode_return_value( - return_value: ReturnValueBox<'_>, - externals: &mut S, -) -> Result + Ok(match value { + WireValue::Int(v) => ParameterValue::Int(v), + WireValue::UInt(v) => ParameterValue::UInt(v), + WireValue::Long(v) => ParameterValue::Long(v), + WireValue::ULong(v) => ParameterValue::ULong(v), + WireValue::Float(v) => ParameterValue::Float(v), + WireValue::Double(v) => ParameterValue::Double(v), + WireValue::String(v) => ParameterValue::String(v.to_string()), + WireValue::Bool(v) => ParameterValue::Bool(v), + WireValue::Void => bail!("Void is not a valid parameter value"), + WireValue::ExternalBytes { length, chunked } => { + match decode_external_bytes(length, chunked, externals)? { + DecodedExternalBytes::VecBytes(v) => ParameterValue::VecBytes(v), + DecodedExternalBytes::ByteChunks(v) => ParameterValue::ByteChunks(v), + } + } + }) +} + +fn decode_return_value(value: WireValue<'_>, externals: &mut S) -> Result where S: ExternalValueSource + ?Sized, { - match return_value.value_type() { - FbReturnValue::hlexternalbytes => { - let Some(metadata) = return_value.value_as_hlexternalbytes() else { - bail!("External byte parameter metadata is missing"); - }; - - match decode_external_bytes(metadata, externals)? { - DecodedExternalBytes::VecBytes(value) => Ok(ReturnValue::VecBytes(value)), - DecodedExternalBytes::ByteChunks(value) => Ok(ReturnValue::ByteChunks(value)), + Ok(match value { + WireValue::Int(v) => ReturnValue::Int(v), + WireValue::UInt(v) => ReturnValue::UInt(v), + WireValue::Long(v) => ReturnValue::Long(v), + WireValue::ULong(v) => ReturnValue::ULong(v), + WireValue::Float(v) => ReturnValue::Float(v), + WireValue::Double(v) => ReturnValue::Double(v), + WireValue::String(v) => ReturnValue::String(v.to_string()), + WireValue::Bool(v) => ReturnValue::Bool(v), + WireValue::Void => ReturnValue::Void(()), + WireValue::ExternalBytes { length, chunked } => { + match decode_external_bytes(length, chunked, externals)? { + DecodedExternalBytes::VecBytes(v) => ReturnValue::VecBytes(v), + DecodedExternalBytes::ByteChunks(v) => ReturnValue::ByteChunks(v), } } - _ => return_value.try_into(), - } + }) } impl From<&ParameterValue> for ParameterType { @@ -413,130 +304,6 @@ impl From<&ParameterValue> for ParameterType { } } -impl TryFrom> for ParameterValue { - type Error = Error; - - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(param: Parameter<'_>) -> Result { - let value = param.value_type(); - let result = match value { - FbParameterValue::hlint => param - .value_as_hlint() - .map(|hlint| ParameterValue::Int(hlint.value())), - FbParameterValue::hluint => param - .value_as_hluint() - .map(|hluint| ParameterValue::UInt(hluint.value())), - FbParameterValue::hllong => param - .value_as_hllong() - .map(|hllong| ParameterValue::Long(hllong.value())), - FbParameterValue::hlulong => param - .value_as_hlulong() - .map(|hlulong| ParameterValue::ULong(hlulong.value())), - FbParameterValue::hlfloat => param - .value_as_hlfloat() - .map(|hlfloat| ParameterValue::Float(hlfloat.value())), - FbParameterValue::hldouble => param - .value_as_hldouble() - .map(|hldouble| ParameterValue::Double(hldouble.value())), - FbParameterValue::hlbool => param - .value_as_hlbool() - .map(|hlbool| ParameterValue::Bool(hlbool.value())), - FbParameterValue::hlstring => param.value_as_hlstring().map(|hlstring| { - ParameterValue::String(hlstring.value().unwrap_or_default().to_string()) - }), - FbParameterValue::hlexternalbytes => { - bail!("External byte parameter requires an external value source") - } - other => { - bail!("Unexpected flatbuffer parameter value type: {:?}", other); - } - }; - result.ok_or_else(|| anyhow!("Failed to get parameter value")) - } -} - -impl From for FbParameterType { - #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))] - fn from(value: ParameterType) -> Self { - match value { - ParameterType::Int => FbParameterType::hlint, - ParameterType::UInt => FbParameterType::hluint, - ParameterType::Long => FbParameterType::hllong, - ParameterType::ULong => FbParameterType::hlulong, - ParameterType::Float => FbParameterType::hlfloat, - ParameterType::Double => FbParameterType::hldouble, - ParameterType::String => FbParameterType::hlstring, - ParameterType::Bool => FbParameterType::hlbool, - ParameterType::VecBytes => FbParameterType::hlvecbytes, - ParameterType::ByteChunks => FbParameterType::hlbytechunks, - } - } -} - -impl From for FbReturnType { - #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))] - fn from(value: ReturnType) -> Self { - match value { - ReturnType::Int => FbReturnType::hlint, - ReturnType::UInt => FbReturnType::hluint, - ReturnType::Long => FbReturnType::hllong, - ReturnType::ULong => FbReturnType::hlulong, - ReturnType::Float => FbReturnType::hlfloat, - ReturnType::Double => FbReturnType::hldouble, - ReturnType::String => FbReturnType::hlstring, - ReturnType::Bool => FbReturnType::hlbool, - ReturnType::Void => FbReturnType::hlvoid, - ReturnType::VecBytes => FbReturnType::hlsizeprefixedbuffer, - ReturnType::ByteChunks => FbReturnType::hlbytechunks, - } - } -} - -impl TryFrom for ParameterType { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(value: FbParameterType) -> Result { - match value { - FbParameterType::hlint => Ok(ParameterType::Int), - FbParameterType::hluint => Ok(ParameterType::UInt), - FbParameterType::hllong => Ok(ParameterType::Long), - FbParameterType::hlulong => Ok(ParameterType::ULong), - FbParameterType::hlfloat => Ok(ParameterType::Float), - FbParameterType::hldouble => Ok(ParameterType::Double), - FbParameterType::hlstring => Ok(ParameterType::String), - FbParameterType::hlbool => Ok(ParameterType::Bool), - FbParameterType::hlvecbytes => Ok(ParameterType::VecBytes), - FbParameterType::hlbytechunks => Ok(ParameterType::ByteChunks), - _ => { - bail!("Unexpected flatbuffer parameter type: {:?}", value) - } - } - } -} - -impl TryFrom for ReturnType { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(value: FbReturnType) -> Result { - match value { - FbReturnType::hlint => Ok(ReturnType::Int), - FbReturnType::hluint => Ok(ReturnType::UInt), - FbReturnType::hllong => Ok(ReturnType::Long), - FbReturnType::hlulong => Ok(ReturnType::ULong), - FbReturnType::hlfloat => Ok(ReturnType::Float), - FbReturnType::hldouble => Ok(ReturnType::Double), - FbReturnType::hlstring => Ok(ReturnType::String), - FbReturnType::hlbool => Ok(ReturnType::Bool), - FbReturnType::hlvoid => Ok(ReturnType::Void), - FbReturnType::hlsizeprefixedbuffer => Ok(ReturnType::VecBytes), - FbReturnType::hlbytechunks => Ok(ReturnType::ByteChunks), - _ => { - bail!("Unexpected flatbuffer return type: {:?}", value) - } - } - } -} - impl TryFrom for i32 { type Error = Error; #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] @@ -806,83 +573,13 @@ impl TryFrom for () { } } -impl TryFrom> for ReturnValue { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(return_value_box: ReturnValueBox<'_>) -> Result { - match return_value_box.value_type() { - FbReturnValue::hlint => { - let hlint = return_value_box - .value_as_hlint() - .ok_or_else(|| anyhow!("Failed to get hlint from return value"))?; - Ok(ReturnValue::Int(hlint.value())) - } - FbReturnValue::hluint => { - let hluint = return_value_box - .value_as_hluint() - .ok_or_else(|| anyhow!("Failed to get hluint from return value"))?; - Ok(ReturnValue::UInt(hluint.value())) - } - FbReturnValue::hllong => { - let hllong = return_value_box - .value_as_hllong() - .ok_or_else(|| anyhow!("Failed to get hllong from return value"))?; - Ok(ReturnValue::Long(hllong.value())) - } - FbReturnValue::hlulong => { - let hlulong = return_value_box - .value_as_hlulong() - .ok_or_else(|| anyhow!("Failed to get hlulong from return value"))?; - Ok(ReturnValue::ULong(hlulong.value())) - } - FbReturnValue::hlfloat => { - let hlfloat = return_value_box - .value_as_hlfloat() - .ok_or_else(|| anyhow!("Failed to get hlfloat from return value"))?; - Ok(ReturnValue::Float(hlfloat.value())) - } - FbReturnValue::hldouble => { - let hldouble = return_value_box - .value_as_hldouble() - .ok_or_else(|| anyhow!("Failed to get hldouble from return value"))?; - Ok(ReturnValue::Double(hldouble.value())) - } - FbReturnValue::hlbool => { - let hlbool = return_value_box - .value_as_hlbool() - .ok_or_else(|| anyhow!("Failed to get hlbool from return value"))?; - Ok(ReturnValue::Bool(hlbool.value())) - } - FbReturnValue::hlstring => { - let hlstring = match return_value_box.value_as_hlstring() { - Some(hlstring) => hlstring.value().map(|v| v.to_string()), - None => None, - }; - Ok(ReturnValue::String(hlstring.unwrap_or("".to_string()))) - } - FbReturnValue::hlvoid => Ok(ReturnValue::Void(())), - FbReturnValue::hlexternalbytes => { - bail!("External byte return requires an external value source") - } - other => { - bail!("Unexpected flatbuffer return value type: {:?}", other) - } - } - } -} - #[cfg(test)] mod tests { use alloc::collections::VecDeque; use alloc::vec; - use flatbuffers::FlatBufferBuilder; - use super::super::guest_error::ErrorCode; use super::*; - use crate::flatbuffers::hyperlight::generated::{ - ParameterArgs, hlexternalbytes, hlexternalbytesArgs, - }; #[derive(Debug, Clone, PartialEq)] enum TestExternalValue { @@ -947,111 +644,13 @@ mod tests { } } - #[test] - fn parameter_value_wire_tags_are_stable() { - let tags = [ - FbParameterValue::NONE, - FbParameterValue::hlint, - FbParameterValue::hluint, - FbParameterValue::hllong, - FbParameterValue::hlulong, - FbParameterValue::hlfloat, - FbParameterValue::hldouble, - FbParameterValue::hlstring, - FbParameterValue::hlbool, - FbParameterValue::hlexternalbytes, - ]; - - // Tag 9 is reserved for embedded byte vectors. - assert_eq!(tags.map(|tag| tag.0), [0, 1, 2, 3, 4, 5, 6, 7, 8, 10]); - } - - #[test] - fn return_value_wire_tags_are_stable() { - let tags = [ - FbReturnValue::NONE, - FbReturnValue::hlint, - FbReturnValue::hluint, - FbReturnValue::hllong, - FbReturnValue::hlulong, - FbReturnValue::hlfloat, - FbReturnValue::hldouble, - FbReturnValue::hlstring, - FbReturnValue::hlbool, - FbReturnValue::hlvoid, - FbReturnValue::hlexternalbytes, - ]; - - // Tag 10 is reserved for embedded size-prefixed buffers. - assert_eq!(tags.map(|tag| tag.0), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]); - } - - #[test] - fn logical_byte_type_tags_are_stable() { - assert_eq!(FbParameterType::from(ParameterType::VecBytes).0, 8); - assert_eq!(FbParameterType::from(ParameterType::ByteChunks).0, 9); - assert_eq!(FbReturnType::from(ReturnType::VecBytes).0, 9); - assert_eq!(FbReturnType::from(ReturnType::ByteChunks).0, 10); - } - - #[test] - fn embedded_parameter_tag_is_reserved_and_rejected() { - let mut builder = FlatBufferBuilder::new(); - let bytes = builder.create_vector(&[1u8, 2, 3]); - - // Build the retired byte-vector table without its generated type. - let start = builder.start_table(); - builder.push_slot_always(4, bytes); - let value = builder.end_table(start); - let parameter = Parameter::create( - &mut builder, - &ParameterArgs { - value_type: FbParameterValue(9), - value: Some(value.as_union_value()), - }, - ); - builder.finish(parameter, None); - - let parameter = flatbuffers::root::(builder.finished_data()).unwrap(); - let mut externals = TestExternalValues::default(); - assert!(decode_parameter_value(parameter, &mut externals).is_err()); - assert!(ParameterValue::try_from(parameter).is_err()); - assert_eq!(FbParameterValue(9).variant_name(), None); - } - - #[test] - fn embedded_return_tag_is_reserved_and_rejected() { - let mut builder = FlatBufferBuilder::new(); - let bytes = builder.create_vector(&[1u8, 2, 3]); - - // Build the retired size-prefixed table without its generated type. - let start = builder.start_table(); - builder.push_slot_always(6, bytes); - builder.push_slot::(4, 3, 0); - let value = builder.end_table(start); - let return_value = ReturnValueBox::create( - &mut builder, - &ReturnValueBoxArgs { - value_type: FbReturnValue(10), - value: Some(value.as_union_value()), - }, - ); - builder.finish(return_value, None); - - let return_value = flatbuffers::root::(builder.finished_data()).unwrap(); - let mut externals = TestExternalValues::default(); - assert!(decode_return_value(return_value, &mut externals).is_err()); - assert!(ReturnValue::try_from(return_value).is_err()); - assert_eq!(FbReturnValue(10).variant_name(), None); - } - #[test] fn encode_success_result() { - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = TestExternalValues::default(); let test_data = FunctionCallResult::new(Ok(ReturnValue::Int(42))) - .encode(&mut builder, &mut external_values) + .encode(&mut buffer, &mut external_values) .unwrap(); let function_call_result = @@ -1063,7 +662,7 @@ mod tests { #[test] fn encode_error_result() { - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let test_error = GuestError::new( ErrorCode::GuestFunctionNotFound, "Function not found".to_string(), @@ -1071,7 +670,7 @@ mod tests { let mut external_values = TestExternalValues::default(); let test_data = FunctionCallResult::new(Err(test_error.clone())) - .encode(&mut builder, &mut external_values) + .encode(&mut buffer, &mut external_values) .unwrap(); let function_call_result = @@ -1082,28 +681,6 @@ mod tests { assert_eq!(error.message, test_error.message); } - #[test] - fn external_bytes_marks_chunked_values_only() { - fn round_trip(chunked: bool) -> bool { - let mut builder = FlatBufferBuilder::new(); - let value = hlexternalbytes::create( - &mut builder, - &hlexternalbytesArgs { - length: 42, - chunked, - }, - ); - builder.finish(value, None); - let value = flatbuffers::root::(builder.finished_data()).unwrap(); - - assert_eq!(value.length(), 42); - value.chunked() - } - - assert!(!round_trip(false)); - assert!(round_trip(true)); - } - #[test] fn byte_returns_round_trip_as_external_values() { for expected in [ @@ -1115,28 +692,26 @@ mod tests { ReturnValue::VecBytes(Vec::new()), ReturnValue::ByteChunks(Vec::new()), ] { - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = TestExternalValues::default(); let encoded = FunctionCallResult::new(Ok(expected.clone())) - .encode(&mut builder, &mut external_values) + .encode(&mut buffer, &mut external_values) .unwrap(); assert!(encoded.len() < 4096); - let encoded_result = size_prefixed_root::(encoded).unwrap(); - let return_value = encoded_result.result_as_return_value_box().unwrap(); - - assert_eq!(return_value.value_type(), FbReturnValue::hlexternalbytes); - - let metadata = return_value.value_as_hlexternalbytes().unwrap(); let (length, chunked) = match &expected { ReturnValue::VecBytes(value) => (value.len(), false), ReturnValue::ByteChunks(value) => (try_byte_chunks_len(value).unwrap(), true), _ => unreachable!(), }; - - assert_eq!(metadata.length(), length as u64); - assert_eq!(metadata.chunked(), chunked); + assert_eq!( + decode_value::(encoded).unwrap(), + WireResult::Ok(WireValue::ExternalBytes { + length: length as u64, + chunked, + }) + ); let decoded = FunctionCallResult::decode(encoded, &mut external_values) .unwrap() @@ -1150,13 +725,13 @@ mod tests { #[test] fn external_return_decoder_rejects_invalid_values() { - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut encoded_values = TestExternalValues::default(); let encoded = FunctionCallResult::new(Ok(ReturnValue::ByteChunks(vec![Bytes::from_static( b"123", )]))) - .encode(&mut builder, &mut encoded_values) + .encode(&mut buffer, &mut encoded_values) .unwrap(); let mut missing = TestExternalValues::default(); @@ -1178,9 +753,9 @@ mod tests { #[test] fn external_result_decoder_rejects_unused_values() { let result = FunctionCallResult::new(Ok(ReturnValue::Int(42))); - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = TestExternalValues::default(); - let encoded = result.encode(&mut builder, &mut external_values).unwrap(); + let encoded = result.encode(&mut buffer, &mut external_values).unwrap(); assert!(external_values.values.is_empty()); external_values diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/guest_error.rs b/src/hyperlight_common/src/flatbuffer_wrappers/guest_error.rs index 3098016212..f601483822 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/guest_error.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/guest_error.rs @@ -1,15 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2025 The Hyperlight Authors. -extern crate flatbuffers; - use alloc::string::{String, ToString}; #[cfg(feature = "tracing")] use tracing::{Span, instrument}; -use crate::flatbuffers::hyperlight::generated::ErrorCode as FbErrorCode; - #[derive(Debug, Clone, Copy, Eq, PartialEq)] #[repr(C)] /// `ErrorCode` represents an error that occurred in the Hyperlight Guest. @@ -32,60 +28,6 @@ pub enum ErrorCode { HostFunctionError = 17, } -impl From for FbErrorCode { - fn from(error_code: ErrorCode) -> Self { - match error_code { - ErrorCode::NoError => Self::NoError, - ErrorCode::UnsupportedParameterType => Self::UnsupportedParameterType, - ErrorCode::GuestFunctionNameNotProvided => Self::GuestFunctionNameNotProvided, - ErrorCode::GuestFunctionNotFound => Self::GuestFunctionNotFound, - ErrorCode::GuestFunctionIncorrecNoOfParameters => { - Self::GuestFunctionIncorrecNoOfParameters - } - ErrorCode::GispatchFunctionPointerNotSet => Self::GispatchFunctionPointerNotSet, - ErrorCode::OutbError => Self::OutbError, - ErrorCode::UnknownError => Self::UnknownError, - ErrorCode::GsCheckFailed => Self::GsCheckFailed, - ErrorCode::TooManyGuestFunctions => Self::TooManyGuestFunctions, - ErrorCode::FailureInDlmalloc => Self::FailureInDlmalloc, - ErrorCode::MallocFailed => Self::MallocFailed, - ErrorCode::GuestFunctionParameterTypeMismatch => { - Self::GuestFunctionParameterTypeMismatch - } - ErrorCode::GuestError => Self::GuestError, - ErrorCode::ArrayLengthParamIsMissing => Self::ArrayLengthParamIsMissing, - ErrorCode::HostFunctionError => Self::HostError, - } - } -} - -impl From for ErrorCode { - fn from(error_code: FbErrorCode) -> Self { - match error_code { - FbErrorCode::NoError => Self::NoError, - FbErrorCode::UnsupportedParameterType => Self::UnsupportedParameterType, - FbErrorCode::GuestFunctionNameNotProvided => Self::GuestFunctionNameNotProvided, - FbErrorCode::GuestFunctionNotFound => Self::GuestFunctionNotFound, - FbErrorCode::GuestFunctionIncorrecNoOfParameters => { - Self::GuestFunctionIncorrecNoOfParameters - } - FbErrorCode::GispatchFunctionPointerNotSet => Self::GispatchFunctionPointerNotSet, - FbErrorCode::OutbError => Self::OutbError, - FbErrorCode::GsCheckFailed => Self::GsCheckFailed, - FbErrorCode::TooManyGuestFunctions => Self::TooManyGuestFunctions, - FbErrorCode::FailureInDlmalloc => Self::FailureInDlmalloc, - FbErrorCode::MallocFailed => Self::MallocFailed, - FbErrorCode::GuestFunctionParameterTypeMismatch => { - Self::GuestFunctionParameterTypeMismatch - } - FbErrorCode::GuestError => Self::GuestError, - FbErrorCode::ArrayLengthParamIsMissing => Self::ArrayLengthParamIsMissing, - FbErrorCode::HostError => Self::HostFunctionError, - _ => Self::UnknownError, - } - } -} - impl From for ErrorCode { fn from(error_code: u64) -> Self { match error_code { diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_data.rs b/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_data.rs index 8e70bb2128..7c22d1c663 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_data.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_data.rs @@ -1,21 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2025 The Hyperlight Authors. -use alloc::string::{String, ToString}; +use alloc::string::String; use alloc::vec::Vec; -use anyhow::{Error, Result, anyhow}; -use flatbuffers::size_prefixed_root; +use anyhow::{Error, Result}; +use serde::{Deserialize, Serialize}; #[cfg(feature = "tracing")] use tracing::{Span, instrument}; use super::guest_log_level::LogLevel; -use crate::flatbuffers::hyperlight::generated::{ - GuestLogData as FbGuestLogData, GuestLogDataArgs as FbGuestLogDataArgs, LogLevel as FbLogLevel, -}; +use super::wire::{decode_value, encode_value}; /// The guest log data for a VM sandbox -#[derive(Eq, PartialEq, Debug, Clone)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)] #[allow(missing_docs)] pub struct GuestLogData { pub message: String, @@ -51,23 +49,7 @@ impl TryFrom<&[u8]> for GuestLogData { type Error = Error; #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] fn try_from(raw_bytes: &[u8]) -> Result { - let gld_gen = size_prefixed_root::(raw_bytes) - .map_err(|e| anyhow!("Error while reading GuestLogData: {:?}", e))?; - let message = convert_generated_option("message", gld_gen.message())?; - let source = convert_generated_option("source", gld_gen.source())?; - let level = LogLevel::try_from(&gld_gen.level())?; - let caller = convert_generated_option("caller", gld_gen.caller())?; - let source_file = convert_generated_option("source file", gld_gen.source_file())?; - let line = gld_gen.line(); - - Ok(GuestLogData { - message, - source, - level, - caller, - source_file, - line, - }) + decode_value(raw_bytes) } } @@ -75,28 +57,9 @@ impl TryFrom<&GuestLogData> for Vec { type Error = Error; #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] fn try_from(value: &GuestLogData) -> Result> { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let message = builder.create_string(&value.message); - let source = builder.create_string(&value.source); - let caller = builder.create_string(&value.caller); - let source_file = builder.create_string(&value.source_file); - let level = FbLogLevel::from(&value.level); - - let guest_log_data_fb = FbGuestLogData::create( - &mut builder, - &FbGuestLogDataArgs { - message: Some(message), - source: Some(source), - level, - caller: Some(caller), - source_file: Some(source_file), - line: value.line, - }, - ); - builder.finish_size_prefixed(guest_log_data_fb, None); - let res = builder.finished_data().to_vec(); - - Ok(res) + let mut buffer = Vec::new(); + encode_value(value, &mut buffer)?; + Ok(buffer) } } @@ -108,8 +71,23 @@ impl TryFrom for Vec { } } -#[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] -fn convert_generated_option(field_name: &str, opt: Option<&str>) -> Result { - opt.map(|s| s.to_string()) - .ok_or_else(|| anyhow!("Missing field: {}", field_name)) +#[cfg(test)] +mod tests { + use alloc::string::ToString; + + use super::*; + + #[test] + fn round_trips() { + let log = GuestLogData::new( + "message".to_string(), + "source".to_string(), + LogLevel::Warning, + "caller".to_string(), + "file.rs".to_string(), + 42, + ); + let encoded: Vec = (&log).try_into().unwrap(); + assert_eq!(GuestLogData::try_from(encoded.as_slice()).unwrap(), log); + } } diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_level.rs b/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_level.rs index e6edb4c7c3..730a339d8f 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_level.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/guest_log_level.rs @@ -1,15 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2025 The Hyperlight Authors. -use anyhow::{Error, Result, bail}; use log::Level; +use serde::{Deserialize, Serialize}; #[cfg(feature = "tracing")] use tracing::{Span, instrument}; -use crate::flatbuffers::hyperlight::generated::LogLevel as FbLogLevel; - +/// Variant order is the wire tag. #[repr(u8)] -#[derive(Copy, Clone, Eq, PartialEq, Debug)] +#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum LogLevel { Trace = 0, Debug = 1, @@ -35,40 +34,6 @@ impl From for LogLevel { } } -impl TryFrom<&FbLogLevel> for LogLevel { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(val: &FbLogLevel) -> Result { - match *val { - FbLogLevel::Trace => Ok(LogLevel::Trace), - FbLogLevel::Debug => Ok(LogLevel::Debug), - FbLogLevel::Information => Ok(LogLevel::Information), - FbLogLevel::Warning => Ok(LogLevel::Warning), - FbLogLevel::Error => Ok(LogLevel::Error), - FbLogLevel::Critical => Ok(LogLevel::Critical), - FbLogLevel::None => Ok(LogLevel::None), - _ => { - bail!("Unsupported Flatbuffers log level: {:?}", val); - } - } - } -} - -impl From<&LogLevel> for FbLogLevel { - #[cfg_attr(feature = "tracing", instrument(skip_all, parent = Span::current(), level= "Trace"))] - fn from(val: &LogLevel) -> FbLogLevel { - match val { - LogLevel::Critical => FbLogLevel::Critical, - LogLevel::Debug => FbLogLevel::Debug, - LogLevel::Error => FbLogLevel::Error, - LogLevel::Information => FbLogLevel::Information, - LogLevel::None => FbLogLevel::None, - LogLevel::Trace => FbLogLevel::Trace, - LogLevel::Warning => FbLogLevel::Warning, - } - } -} - impl From<&LogLevel> for Level { // There is a test (sandbox::outb::tests::test_log_emit_guest_log) which emits trace record as logs // which causes a panic when this function is instrumented as the logger is contained in refcell and diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/guest_trace_data.rs b/src/hyperlight_common/src/flatbuffer_wrappers/guest_trace_data.rs index 4cf7a7fcb5..3229db5448 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/guest_trace_data.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/guest_trace_data.rs @@ -1,31 +1,17 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2025 The Hyperlight Authors. -//! Guest trace data structures and (de)serialization logic. -//! This module defines the data structures used for tracing spans and events -//! within a guest environment, along with the logic for serializing and -//! deserializing these structures using FlatBuffers. +//! Guest trace events and their batch encoding. //! -//! Schema definitions can be found in `src/schema/guest_trace_data.fbs`. +//! A batch is a sequence of postcard events. Each event marks its own end. -use alloc::string::{String, ToString}; +use alloc::string::String; use alloc::vec::Vec; use anyhow::{Error, Result, anyhow}; -/// Estimate the serialized byte length for a size-prefixed `GuestEvent` buffer. -pub use estimate::estimate_event; -use flatbuffers::size_prefixed_root; +use serde::{Deserialize, Serialize}; -use crate::flatbuffers::hyperlight::generated::{ - CloseSpanType as FbCloseSpanType, CloseSpanTypeArgs as FbCloseSpanTypeArgs, - EditSpanType as FbEditSpanType, EditSpanTypeArgs as FbEditSpanTypeArgs, - GuestEventEnvelopeType as FbGuestEventEnvelopeType, - GuestEventEnvelopeTypeArgs as FbGuestEventEnvelopeTypeArgs, GuestEventType as FbGuestEventType, - GuestStartType as FbGuestStartType, GuestStartTypeArgs as FbGuestStartTypeArgs, - KeyValue as FbKeyValue, KeyValueArgs as FbKeyValueArgs, LogEventType as FbLogEventType, - LogEventTypeArgs as FbLogEventTypeArgs, OpenSpanType as FbOpenSpanType, - OpenSpanTypeArgs as FbOpenSpanTypeArgs, -}; +use super::wire::encode_value; /// TODO: Change these constant to be configurable at runtime by the guest /// Maybe use a weak symbol that the guest can override at link time? @@ -37,7 +23,7 @@ use crate::flatbuffers::hyperlight::generated::{ pub const MAX_TRACE_DATA_SIZE: usize = 4096; /// Key-Value pair structure used in tracing spans/events -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct EventKeyValue { /// Key of the key-value pair pub key: String, @@ -45,56 +31,9 @@ pub struct EventKeyValue { pub value: String, } -impl From> for EventKeyValue { - fn from(value: FbKeyValue<'_>) -> Self { - let key = value.key().to_string(); - let value = value.value().to_string(); - - EventKeyValue { key, value } - } -} - -impl TryFrom<&[u8]> for EventKeyValue { - type Error = Error; - - fn try_from(value: &[u8]) -> Result { - let gld_gen = size_prefixed_root::(value) - .map_err(|e| anyhow!("Error while reading EventKeyValue: {:?}", e))?; - let key = gld_gen.key().to_string(); - let value = gld_gen.value().to_string(); - - Ok(EventKeyValue { key, value }) - } -} - -impl From<&EventKeyValue> for Vec { - fn from(value: &EventKeyValue) -> Self { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - - let key_offset = builder.create_string(&value.key); - let value_offset = builder.create_string(&value.value); - - let kv_args = FbKeyValueArgs { - key: Some(key_offset), - value: Some(value_offset), - }; - - let kv_fb = FbKeyValue::create(&mut builder, &kv_args); - builder.finish_size_prefixed(kv_fb, None); - - builder.finished_data().to_vec() - } -} - -impl From for Vec { - fn from(value: EventKeyValue) -> Self { - Vec::from(&value) - } -} - /// Enum representing different types of guest events for tracing /// such as opening/closing spans and logging events. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum GuestEvent { /// Event representing the opening of a new tracing span. OpenSpan { @@ -168,152 +107,20 @@ pub trait EventsDecoder { fn decode(&self, buffer: &[u8]) -> Result, Error>; } -impl TryFrom<&[u8]> for GuestEvent { - type Error = Error; - - fn try_from(value: &[u8]) -> Result { - let envelope = size_prefixed_root::(value) - .map_err(|e| anyhow!("Error while reading GuestTraceData: {:?}", e))?; - let event_type = envelope.event_type(); - - // Match on the event type to extract the appropriate event data - let event = match event_type { - FbGuestEventType::OpenSpan => { - // Extract OpenSpanType event data - let ost_fb = envelope - .event_as_open_span() - .ok_or_else(|| anyhow!("Failed to cast to OpenSpanType"))?; - - // Extract fields - let id = ost_fb.id(); - let parent = ost_fb.parent(); - let name = ost_fb.name().to_string(); - let target = ost_fb.target().to_string(); - let tsc = ost_fb.tsc(); - - // Extract key-value fields - let mut fields = Vec::new(); - if let Some(fb_fields) = ost_fb.fields() { - for j in 0..fb_fields.len() { - let kv: EventKeyValue = EventKeyValue::from(fb_fields.get(j)); - fields.push(kv); - } - } - - // Construct OpenSpan event - GuestEvent::OpenSpan { - id, - parent_id: parent, - name, - target, - tsc, - fields, - } - } - FbGuestEventType::CloseSpan => { - // Extract CloseSpanType event data - let cst_fb = envelope - .event_as_close_span() - .ok_or_else(|| anyhow!("Failed to cast to CloseSpanType"))?; - // Extract fields - let id = cst_fb.id(); - let tsc = cst_fb.tsc(); - - // Construct CloseSpan event - GuestEvent::CloseSpan { id, tsc } - } - FbGuestEventType::LogEvent => { - // Extract LogEventType event data - let le_fb = envelope - .event_as_log_event() - .ok_or_else(|| anyhow!("Failed to cast to LogEventType"))?; - - // Extract fields - let parent_id = le_fb.parent_id(); - let name = le_fb.name().to_string(); - let tsc = le_fb.tsc(); - - // Extract key-value fields - let mut fields = Vec::new(); - if let Some(fb_fields) = le_fb.fields() { - for j in 0..fb_fields.len() { - let kv: EventKeyValue = EventKeyValue::from(fb_fields.get(j)); - fields.push(kv); - } - } - - // Construct LogEvent - GuestEvent::LogEvent { - parent_id, - name, - tsc, - fields, - } - } - FbGuestEventType::EditSpan => { - let est_fb = envelope - .event_as_edit_span() - .ok_or_else(|| anyhow!("Failed to cast to EditSpanType"))?; - // Extract fields - let id = est_fb.id(); - let mut fields = Vec::new(); - if let Some(fb_fields) = est_fb.fields() { - for j in 0..fb_fields.len() { - let kv: EventKeyValue = EventKeyValue::from(fb_fields.get(j)); - fields.push(kv); - } - } - - // Construct EditSpan event - GuestEvent::EditSpan { id, fields } - } - FbGuestEventType::GuestStart => { - let gst_fb = envelope - .event_as_guest_start() - .ok_or_else(|| anyhow!("Failed to cast to GuestStartType"))?; - - // Extract fields - let tsc = gst_fb.tsc(); - - // Construct GuestStart event - GuestEvent::GuestStart { tsc } - } - - _ => { - return Err(anyhow!("Unknown GuestEventType={}", event_type.0)); - } - }; - - Ok(event) - } -} - +/// Decodes a batch and rejects truncated events. pub struct EventsBatchDecoder; impl EventsDecoder for EventsBatchDecoder { fn decode(&self, data: &[u8]) -> Result, Error> { - let mut cursor = 0; + let mut rest = data; let mut events = Vec::new(); - while data.len() - cursor >= 4 { - let size_bytes = &data[cursor..cursor + 4]; - // The size_bytes is in little-endian format and the while condition ensures there are - // at least 4 bytes to read. - let payload_size = u32::from_le_bytes(size_bytes.try_into()?) as usize; - let event_size = 4 + payload_size; - if data.len() - cursor < event_size { - return Err(anyhow!( - "The serialized buffer does not contain a full set of events", - )); - } - - let event_slice = &data[cursor..cursor + event_size]; - let event = GuestEvent::try_from(event_slice)?; + while !rest.is_empty() { + let (event, tail) = postcard::take_from_bytes(rest) + .map_err(|e| anyhow!("Failed to decode guest trace event: {e}"))?; events.push(event); - - cursor += event_size; + rest = tail; } - Ok(events) } } @@ -324,17 +131,16 @@ pub type EventsBatchEncoder = EventsBatchEncoderGeneric; /// When the buffer reaches its capacity, the provided `report_full` callback /// is invoked with the current buffer contents. /// -/// This encoder uses FlatBuffers for serialization. /// This encoder is a lossless encoder; no events are dropped. pub struct EventsBatchEncoderGeneric { /// Internal buffer for serialized events buffer: Vec, + /// Reused storage for one serialized event + scratch: Vec, /// Maximum capacity of the buffer capacity: usize, /// Callback function to report when the buffer is full report_full: T, - /// Current used capacity of the buffer - used_capacity: usize, } impl EventsBatchEncoderGeneric { @@ -342,9 +148,9 @@ impl EventsBatchEncoderGeneric { pub fn new(initial_capacity: usize, report_full: T) -> Self { Self { buffer: Vec::with_capacity(initial_capacity), + scratch: Vec::new(), capacity: initial_capacity, report_full, - used_capacity: 0, } } } @@ -355,200 +161,23 @@ impl EventsEncoder for EventsBatchEncoderGeneric { /// `report_full` callback is invoked with the current buffer contents, /// and the buffer is cleared for new data. fn encode(&mut self, event: &GuestEvent) { - // Optimization heuristic that helps minimize reallocations during FlatBuffer building. - // The estimate is not exact but should be an upper bound. - // The following behavior can happen: - // - If the estimate is accurate or slightly over, the builder uses the preallocated - // space. - // - If the estimate is too low, the FlatBuffer builder reallocates as needed. - let estimated_size = estimate::estimate_event(event); - let mut builder = flatbuffers::FlatBufferBuilder::with_capacity(estimated_size); - - // Serialize the event based on its type - let ev = match event { - GuestEvent::OpenSpan { - id, - parent_id, - name, - target, - tsc, - fields, - } => { - // Serialize strings - let name_offset = builder.create_string(name); - let target_offset = builder.create_string(target); - - // Serialize key-value fields - let mut field_offsets = Vec::new(); - for field in fields { - let field_offset: flatbuffers::WIPOffset = { - let key_offset = builder.create_string(&field.key); - let value_offset = builder.create_string(&field.value); - let kv_args = FbKeyValueArgs { - key: Some(key_offset), - value: Some(value_offset), - }; - FbKeyValue::create(&mut builder, &kv_args) - }; - field_offsets.push(field_offset); - } - - // Create fields vector - let fields_vector = if !field_offsets.is_empty() { - Some(builder.create_vector(&field_offsets)) - } else { - None - }; - - let ost_args = FbOpenSpanTypeArgs { - id: *id, - parent: *parent_id, - name: Some(name_offset), - target: Some(target_offset), - tsc: *tsc, - fields: fields_vector, - }; - - // Create the OpenSpanType FlatBuffer object - let ost_fb = FbOpenSpanType::create(&mut builder, &ost_args); - - // Create the GuestEventEnvelopeType - let guest_event_fb = FbGuestEventType::OpenSpan; - let envelope_args = FbGuestEventEnvelopeTypeArgs { - event_type: guest_event_fb, - event: Some(ost_fb.as_union_value()), - }; - - // Create the envelope using the union value - FbGuestEventEnvelopeType::create(&mut builder, &envelope_args) - } - GuestEvent::CloseSpan { id, tsc } => { - // Create CloseSpanType FlatBuffer object - let cst_args = FbCloseSpanTypeArgs { id: *id, tsc: *tsc }; - let cst_fb = FbCloseSpanType::create(&mut builder, &cst_args); - - // Create the GuestEventEnvelopeType - let guest_event_fb = FbGuestEventType::CloseSpan; - let envelope_args = FbGuestEventEnvelopeTypeArgs { - event_type: guest_event_fb, - event: Some(cst_fb.as_union_value()), - }; - // Create the envelope using the union value - FbGuestEventEnvelopeType::create(&mut builder, &envelope_args) - } - GuestEvent::LogEvent { - parent_id, - name, - tsc, - fields, - } => { - // Serialize strings - let name_offset = builder.create_string(name); - - // Serialize key-value fields - let mut field_offsets = Vec::new(); - for field in fields { - let field_offset: flatbuffers::WIPOffset = { - let key_offset = builder.create_string(&field.key); - let value_offset = builder.create_string(&field.value); - let kv_args = FbKeyValueArgs { - key: Some(key_offset), - value: Some(value_offset), - }; - FbKeyValue::create(&mut builder, &kv_args) - }; - field_offsets.push(field_offset); - } - - let fields_vector = if !field_offsets.is_empty() { - Some(builder.create_vector(&field_offsets)) - } else { - None - }; - - let le_args = FbLogEventTypeArgs { - parent_id: *parent_id, - name: Some(name_offset), - tsc: *tsc, - fields: fields_vector, - }; - - let le_fb = FbLogEventType::create(&mut builder, &le_args); - - // Create the GuestEventEnvelopeType - let guest_event_fb = FbGuestEventType::LogEvent; - let envelope_args = FbGuestEventEnvelopeTypeArgs { - event_type: guest_event_fb, - event: Some(le_fb.as_union_value()), - }; - // Create the envelope using the union value - FbGuestEventEnvelopeType::create(&mut builder, &envelope_args) - } - GuestEvent::EditSpan { id, fields } => { - // Serialize key-value fields - let mut field_offsets = Vec::new(); - for field in fields { - let field_offset: flatbuffers::WIPOffset = { - let key_offset = builder.create_string(&field.key); - let value_offset = builder.create_string(&field.value); - let kv_args = FbKeyValueArgs { - key: Some(key_offset), - value: Some(value_offset), - }; - FbKeyValue::create(&mut builder, &kv_args) - }; - field_offsets.push(field_offset); - } - - // Create fields vector - let fields_vector = if !field_offsets.is_empty() { - Some(builder.create_vector(&field_offsets)) - } else { - None - }; - - let est_args = FbEditSpanTypeArgs { - id: *id, - fields: fields_vector, - }; - - let es_fb = FbEditSpanType::create(&mut builder, &est_args); - - // Create the GuestEventEnvelopeType - let guest_event_fb = FbGuestEventType::EditSpan; - let envelope_args = FbGuestEventEnvelopeTypeArgs { - event_type: guest_event_fb, - event: Some(es_fb.as_union_value()), - }; - - FbGuestEventEnvelopeType::create(&mut builder, &envelope_args) - } - GuestEvent::GuestStart { tsc } => { - let gst_args = FbGuestStartTypeArgs { tsc: *tsc }; - let gs_fb = FbGuestStartType::create(&mut builder, &gst_args); - // Create the GuestEventEnvelopeType - let guest_event_fb = FbGuestEventType::GuestStart; - let envelope_args = FbGuestEventEnvelopeTypeArgs { - event_type: guest_event_fb, - event: Some(gs_fb.as_union_value()), - }; + let Self { + buffer, + scratch, + capacity, + report_full, + } = self; - FbGuestEventEnvelopeType::create(&mut builder, &envelope_args) - } + // Encoding into a growable vector does not fail. + let Ok(serialized) = encode_value(event, scratch) else { + return; }; - builder.finish_size_prefixed(ev, None); - let serialized = builder.finished_data(); - - // Check if adding this event would exceed capacity - if self.used_capacity + serialized.len() > self.capacity { - (self.report_full)(&self.buffer); - self.buffer.clear(); - self.used_capacity = 0; + if !buffer.is_empty() && buffer.len() + serialized.len() > *capacity { + report_full(buffer); + buffer.clear(); } - // Append serialized data to buffer - self.buffer.extend_from_slice(serialized); - self.used_capacity += serialized.len(); + buffer.extend_from_slice(serialized); } /// Get a reference to the internal buffer containing serialized events. @@ -565,769 +194,110 @@ impl EventsEncoder for EventsBatchEncoderGeneric { self.reset(); } } + /// Reset the internal buffer, clearing all serialized data. /// This prepares the encoder for new events. fn reset(&mut self) { self.buffer.clear(); - self.used_capacity = 0; - } -} - -mod estimate { - use super::{EventKeyValue, GuestEvent}; - - const SIZE_PREFIX: usize = 4; - const ENVELOPE_TABLE_OVERHEAD: usize = 20; - /// Bytes needed for the data section of the `KeyValue` table (offset + slots). - const KV_TABLE_DATA_BYTES: usize = 12; - /// Vtables are deduplicated by the FlatBuffers builder; pay for it at most once. - const KV_VTABLE_BYTES: usize = 8; - const OPEN_TABLE_OVERHEAD: usize = 72; - const CLOSE_TABLE_OVERHEAD: usize = 32; - const LOG_TABLE_OVERHEAD: usize = 52; - const EDIT_TABLE_OVERHEAD: usize = 40; - const GUEST_START_TABLE_OVERHEAD: usize = 24; - - /// Round up to next multiple of 4. - fn pad4(x: usize) -> usize { - (4 - (x & 3)) & 3 - } - - /// Size of a FlatBuffers string object with `len` UTF-8 bytes. - fn size_str(len: usize) -> usize { - let size = 4 + len + 1; - size + pad4(size) - } - - fn size_kv_entry(k_len: usize, v_len: usize) -> usize { - KV_TABLE_DATA_BYTES + size_str(k_len) + size_str(v_len) - } - - fn size_kv_vec(fields: &[EventKeyValue]) -> usize { - if fields.is_empty() { - return 0; - } - - let head = 4 + 4 * fields.len(); - let entries = fields - .iter() - .map(|kv| size_kv_entry(kv.key.len(), kv.value.len())) - .sum::(); - - // The vtable for `KeyValue` tables is shared across entries, so only account for - // it once even if multiple fields are present. - head + pad4(head) + entries + KV_VTABLE_BYTES - } - - fn base_envelope() -> usize { - SIZE_PREFIX + ENVELOPE_TABLE_OVERHEAD - } - - fn open_span_size(name_len: usize, target_len: usize, fields: &[EventKeyValue]) -> usize { - OPEN_TABLE_OVERHEAD + size_str(name_len) + size_str(target_len) + size_kv_vec(fields) - } - - fn log_event_size(name_len: usize, fields: &[EventKeyValue]) -> usize { - LOG_TABLE_OVERHEAD + size_str(name_len) + size_kv_vec(fields) - } - - fn edit_span_size(fields: &[EventKeyValue]) -> usize { - EDIT_TABLE_OVERHEAD + size_kv_vec(fields) - } - - /// Estimate the serialized byte length for a size-prefixed `GuestEvent` buffer. - /// The estimate is designed to be an upper bound on the actual serialized size, - /// with some reasonable slack to account for FlatBuffers overhead. - /// The maximum slack is approximately 10% of the actual size or 128 bytes, - /// whichever is larger. - /// NOTE: This is only an estimate and may not be exact. - /// The estimation upper bound is not guaranteed to be strict, it has been - /// empirically verified to be reasonable in practice. - pub fn estimate_event(event: &GuestEvent) -> usize { - base_envelope() - + match event { - GuestEvent::OpenSpan { - name, - target, - fields, - .. - } => open_span_size(name.len(), target.len(), fields), - GuestEvent::CloseSpan { .. } => CLOSE_TABLE_OVERHEAD, - GuestEvent::LogEvent { name, fields, .. } => log_event_size(name.len(), fields), - GuestEvent::EditSpan { fields, .. } => edit_span_size(fields), - GuestEvent::GuestStart { .. } => GUEST_START_TABLE_OVERHEAD, - } - } - - #[cfg(test)] - mod tests { - use alloc::string::String; - use alloc::vec::Vec; - use alloc::{format, vec}; - - use super::estimate_event; - use crate::flatbuffer_wrappers::guest_trace_data::{ - EventKeyValue, EventsBatchEncoder, EventsEncoder, GuestEvent, - }; - - fn encoded_size(event: &GuestEvent) -> usize { - let mut encoder = EventsBatchEncoder::new(2048, |_| {}); - encoder.encode(event); - encoder.finish().len() - } - - fn assert_estimate_bounds(actual: usize, estimate: usize) { - assert!( - estimate >= actual, - "estimated size {} must be at least actual {}", - estimate, - actual, - ); - - let slack = (actual / 10).max(128); - let upper_bound = actual + slack; - assert!( - estimate <= upper_bound, - "estimated size {} exceeds reasonable bound {} for actual {}", - estimate, - upper_bound, - actual, - ); - } - - #[test] - fn test_estimate_open_span_reasonable() { - let event = GuestEvent::OpenSpan { - id: 1, - parent_id: None, - name: String::from("span"), - target: String::from("target"), - tsc: 10, - fields: vec![EventKeyValue { - key: String::from("k"), - value: String::from("v"), - }], - }; - - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } - - #[test] - fn test_estimate_open_span_large_payload() { - let long_field_value = "v".repeat(4096); - let long_name = "span".repeat(256); - let event = GuestEvent::OpenSpan { - id: 42, - parent_id: Some(5), - name: long_name.clone(), - target: "target".repeat(256), - tsc: 1234, - fields: vec![EventKeyValue { - key: "key".repeat(64), - value: long_field_value, - }], - }; - - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } - - #[test] - fn test_estimate_close_span_reasonable() { - let event = GuestEvent::CloseSpan { id: 7, tsc: 99 }; - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } - - #[test] - fn test_estimate_log_event_reasonable() { - let event = GuestEvent::LogEvent { - parent_id: 5, - name: String::from("log"), - tsc: 55, - fields: vec![ - EventKeyValue { - key: String::from("kk"), - value: String::from("vv"), - }, - EventKeyValue { - key: String::from("m"), - value: String::from("n"), - }, - ], - }; - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } - - #[test] - fn test_estimate_log_event_many_fields() { - let fields = (0..64) - .map(|i| EventKeyValue { - key: format!("k{}", i), - value: "value".repeat(i + 1), - }) - .collect::>(); - - let event = GuestEvent::LogEvent { - parent_id: 77, - name: "logname".repeat(64), - tsc: 9876, - fields, - }; - - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } - - #[test] - fn test_estimate_edit_span_reasonable() { - let event = GuestEvent::EditSpan { - id: 9, - fields: vec![EventKeyValue { - key: String::from("field"), - value: String::from("value"), - }], - }; - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } - - #[test] - fn test_estimate_guest_start_reasonable() { - let event = GuestEvent::GuestStart { tsc: 0 }; - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } - - #[test] - fn test_estimate_guest_start_corner_cases() { - let very_large = GuestEvent::GuestStart { tsc: u64::MAX }; - let zero = GuestEvent::GuestStart { tsc: 0 }; - - for event in [&very_large, &zero] { - let estimate = estimate_event(event); - let actual = encoded_size(event); - assert_estimate_bounds(actual, estimate); - } - } - - #[test] - fn test_estimate_edit_span_empty_fields() { - let event = GuestEvent::EditSpan { - id: 999, - fields: Vec::new(), - }; - - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } - - #[test] - fn test_estimate_edit_span_large() { - let fields = (0..32) - .map(|i| EventKeyValue { - key: format!("long_key_{}", i).repeat(4), - value: "Z".repeat(8192), - }) - .collect::>(); - - let event = GuestEvent::EditSpan { id: 10, fields }; - let estimate = estimate_event(&event); - let actual = encoded_size(&event); - assert_estimate_bounds(actual, estimate); - } } } #[cfg(test)] mod tests { - use flatbuffers::FlatBufferBuilder; + use alloc::string::ToString; + use alloc::vec; + use core::cell::RefCell; use super::*; - use crate::flatbuffers::hyperlight::generated::{ - GuestEventEnvelopeType as FbGuestEventEnvelopeType, - GuestEventEnvelopeTypeArgs as FbGuestEventEnvelopeTypeArgs, - GuestEventType as FbGuestEventType, - }; - - /// Utility function to check an original GuestTraceData against a deserialized one - fn check_fb_guest_trace_data(orig: &[GuestEvent], deserialized: &[GuestEvent]) { - for (original, deserialized) in orig.iter().zip(deserialized.iter()) { - match (original, deserialized) { - ( - GuestEvent::OpenSpan { - id: oid, - parent_id: opid, - name: oname, - target: otarget, - tsc: otsc, - fields: ofields, - }, - GuestEvent::OpenSpan { - id: did, - parent_id: dpid, - name: dname, - target: dtarget, - tsc: dtsc, - fields: dfields, - }, - ) => { - assert_eq!(oid, did); - assert_eq!(opid, dpid); - assert_eq!(oname, dname); - assert_eq!(otarget, dtarget); - assert_eq!(otsc, dtsc); - assert_eq!(ofields.len(), dfields.len()); - for (o_field, d_field) in ofields.iter().zip(dfields.iter()) { - assert_eq!(o_field.key, d_field.key); - assert_eq!(o_field.value, d_field.value); - } - } - ( - GuestEvent::LogEvent { - parent_id: opid, - name: oname, - tsc: otsc, - fields: ofields, - }, - GuestEvent::LogEvent { - parent_id: dpid, - name: dname, - tsc: dtsc, - fields: dfields, - }, - ) => { - assert_eq!(opid, dpid); - assert_eq!(oname, dname); - assert_eq!(otsc, dtsc); - assert_eq!(ofields.len(), dfields.len()); - for (o_field, d_field) in ofields.iter().zip(dfields.iter()) { - assert_eq!(o_field.key, d_field.key); - assert_eq!(o_field.value, d_field.value); - } - } - ( - GuestEvent::CloseSpan { id: oid, tsc: otsc }, - GuestEvent::CloseSpan { id: did, tsc: dtsc }, - ) => { - assert_eq!(oid, did); - assert_eq!(otsc, dtsc); - } - (GuestEvent::GuestStart { tsc: otsc }, GuestEvent::GuestStart { tsc: dtsc }) => { - assert_eq!(otsc, dtsc); - } - ( - GuestEvent::EditSpan { - id: oid, - fields: ofields, - }, - GuestEvent::EditSpan { - id: did, - fields: dfields, - }, - ) => { - assert_eq!(oid, did); - assert_eq!(ofields.len(), dfields.len()); - for (o_field, d_field) in ofields.iter().zip(dfields.iter()) { - assert_eq!(o_field.key, d_field.key); - assert_eq!(o_field.value, d_field.value); - } - } - _ => panic!("Mismatched event types"), - } - } - } - - #[test] - fn test_fb_key_value_serialization() { - let kv = EventKeyValue { - key: "test_key".to_string(), - value: "test_value".to_string(), - }; - - let serialized: Vec = Vec::from(&kv); - let deserialized: EventKeyValue = - EventKeyValue::try_from(serialized.as_slice()).expect("Deserialization failed"); - - assert_eq!(kv.key, deserialized.key); - assert_eq!(kv.value, deserialized.value); - } - - #[test] - fn test_fb_guest_trace_data_open_span_serialization() { - let mut serializer = EventsBatchEncoder::new(1024, |_| {}); - let kv1 = EventKeyValue { - key: "test_key1".to_string(), - value: "test_value1".to_string(), - }; - let kv2 = EventKeyValue { - key: "test_key1".to_string(), - value: "test_value2".to_string(), - }; - - let events = [ - GuestEvent::GuestStart { tsc: 50 }, - GuestEvent::OpenSpan { - id: 1, - parent_id: None, - name: "span_name".to_string(), - target: "span_target".to_string(), - tsc: 100, - fields: Vec::from([kv1, kv2]), - }, - ]; - - for event in &events { - serializer.encode(event); - } - - let serialized = serializer.finish(); - - let deserialized: Vec = EventsBatchDecoder {} - .decode(serialized) - .expect("Deserialization failed"); - - check_fb_guest_trace_data(&events, &deserialized); - } - #[test] - fn test_fb_guest_trace_data_close_span_serialization() { - let events = [GuestEvent::CloseSpan { id: 1, tsc: 200 }]; - - let mut serializer = EventsBatchEncoder::new(1024, |_| {}); - for event in &events { - serializer.encode(event); - } - let serialized = serializer.finish(); - - let deserialized = EventsBatchDecoder {} - .decode(serialized) - .expect("Deserialization failed"); - - check_fb_guest_trace_data(&events, &deserialized); - } - - #[test] - fn test_fb_guest_trace_data_log_event_serialization() { - let kv1 = EventKeyValue { - key: "log_key1".to_string(), - value: "log_value1".to_string(), - }; - let kv2 = EventKeyValue { - key: "log_key2".to_string(), - value: "log_value2".to_string(), - }; - - let events = [GuestEvent::LogEvent { - parent_id: 2, - name: "log_name".to_string(), - tsc: 300, - fields: Vec::from([kv1, kv2]), - }]; - - let mut serializer = EventsBatchEncoder::new(1024, |_| {}); - for event in &events { - serializer.encode(event); - } - let serialized = serializer.finish(); - - let deserialized = EventsBatchDecoder {} - .decode(serialized) - .expect("Deserialization failed"); - - check_fb_guest_trace_data(&events, &deserialized); - } - - /// Test serialization and deserialization of GuestTraceData with multiple events - /// [OpenSpan, LogEvent, CloseSpan] - #[test] - fn test_fb_guest_trace_data_multiple_events_serialization_0() { - let kv1 = EventKeyValue { - key: "span_field1".to_string(), - value: "span_value1".to_string(), - }; - let kv2 = EventKeyValue { - key: "log_field1".to_string(), - value: "log_value1".to_string(), + fn sample_events() -> Vec { + let field = EventKeyValue { + key: "key".to_string(), + value: "value".to_string(), }; - - let events = [ - GuestEvent::OpenSpan { - id: 1, - parent_id: None, - name: "span_name".to_string(), - target: "span_target".to_string(), - tsc: 100, - fields: Vec::from([kv1]), - }, - GuestEvent::LogEvent { - parent_id: 1, - name: "log_name".to_string(), - tsc: 150, - fields: Vec::from([kv2]), - }, - GuestEvent::CloseSpan { id: 1, tsc: 200 }, - ]; - - let mut serializer = EventsBatchEncoder::new(2048, |_| {}); - for event in &events { - serializer.encode(event); - } - let serialized = serializer.finish(); - let deserialized = EventsBatchDecoder {} - .decode(serialized) - .expect("Deserialization failed"); - - check_fb_guest_trace_data(&events, &deserialized); - } - - /// Test serialization and deserialization of GuestTraceData with multiple events - /// [OpenSpan, LogEvent, OpenSpan, LogEvent, CloseSpan] - #[test] - fn test_fb_guest_trace_data_multiple_events_serialization_1() { - let kv1 = EventKeyValue { - key: "span_field1".to_string(), - value: "span_value1".to_string(), - }; - let kv2 = EventKeyValue { - key: "log_field1".to_string(), - value: "log_value1".to_string(), - }; - - let events = [ - GuestEvent::OpenSpan { - id: 1, - parent_id: None, - name: "span_name_1".to_string(), - target: "span_target_1".to_string(), - tsc: 100, - fields: Vec::from([kv1]), - }, + vec![ + GuestEvent::GuestStart { tsc: 1 }, GuestEvent::OpenSpan { id: 2, parent_id: Some(1), - name: "span_name_2".to_string(), - target: "span_target_2".to_string(), - tsc: 1000, - fields: Vec::from([kv2.clone()]), - }, - GuestEvent::LogEvent { - parent_id: 1, - name: "log_name_1".to_string(), - tsc: 150, - fields: Vec::from([kv2.clone()]), + name: "span".to_string(), + target: "target".to_string(), + tsc: 3, + fields: vec![field.clone()], }, GuestEvent::LogEvent { parent_id: 2, - name: "log_name".to_string(), - tsc: 1050, - fields: Vec::from([kv2]), - }, - GuestEvent::CloseSpan { id: 2, tsc: 2000 }, - ]; - - let mut serializer = EventsBatchEncoder::new(4096, |_| {}); - for event in &events { - serializer.encode(event); - } - let serialized = serializer.finish(); - let deserialized = EventsBatchDecoder {} - .decode(serialized) - .expect("Deserialization failed"); - - check_fb_guest_trace_data(&events, &deserialized); - } - - /// Test serialization and deserialization of GuestTraceData with EditSpan event - #[test] - fn test_fb_guest_trace_data_edit_span_serialization_00() { - let kv1 = EventKeyValue { - key: "edit_key1".to_string(), - value: "edit_value1".to_string(), - }; - let kv2 = EventKeyValue { - key: "edit_key2".to_string(), - value: "edit_value2".to_string(), - }; - let events = [GuestEvent::EditSpan { - id: 1, - fields: Vec::from([kv1, kv2]), - }]; - let mut serializer = EventsBatchEncoder::new(1024, |_| {}); - for event in &events { - serializer.encode(event); - } - let serialized = serializer.finish(); - let deserialized = EventsBatchDecoder {} - .decode(serialized) - .expect("Deserialization failed"); - - check_fb_guest_trace_data(&events, &deserialized); - } - - /// Test serialization and deserialization of GuestTraceData with GuestStart event - /// open span and edit span - #[test] - fn test_fb_guest_trace_data_edit_span_with_guest_start_serialization() { - let kv1 = EventKeyValue { - key: "span_field1".to_string(), - value: "span_value1".to_string(), - }; - let kv2 = EventKeyValue { - key: "edit_key1".to_string(), - value: "edit_value1".to_string(), - }; - let events = [ - GuestEvent::GuestStart { tsc: 50 }, - GuestEvent::OpenSpan { - id: 1, - parent_id: None, - name: "span_name".to_string(), - target: "span_target".to_string(), - tsc: 100, - fields: Vec::from([kv1]), + name: "log".to_string(), + tsc: 4, + fields: vec![field.clone()], }, GuestEvent::EditSpan { - id: 1, - fields: Vec::from([kv2]), + id: 2, + fields: vec![field], }, - ]; - let mut serializer = EventsBatchEncoder::new(2048, |_| {}); - for event in &events { - serializer.encode(event); - } - let serialized = serializer.finish(); - let deserialized = EventsBatchDecoder {} - .decode(serialized) - .expect("Deserialization failed"); - - check_fb_guest_trace_data(&events, &deserialized); + GuestEvent::CloseSpan { id: 2, tsc: 5 }, + ] } - /// Test serialization and deserialization of GuestTraceData with GuestStart event, - /// open span, log event, open span, edit span, and close span #[test] - fn test_fb_guest_trace_data_edit_span_with_others_serialization() { - let kv1 = EventKeyValue { - key: "span_field1".to_string(), - value: "span_value1".to_string(), - }; - let kv2 = EventKeyValue { - key: "log_field1".to_string(), - value: "log_value1".to_string(), - }; - let kv3 = EventKeyValue { - key: "edit_key1".to_string(), - value: "edit_value1".to_string(), - }; - - let events = [ - GuestEvent::GuestStart { tsc: 50 }, - GuestEvent::OpenSpan { - id: 1, - parent_id: None, - name: "span_name".to_string(), - target: "span_target".to_string(), - tsc: 100, - fields: Vec::from([kv1]), - }, - GuestEvent::LogEvent { - parent_id: 1, - name: "log_name".to_string(), - tsc: 150, - fields: Vec::from([kv2]), - }, - GuestEvent::EditSpan { - id: 1, - fields: Vec::from([kv3]), - }, - GuestEvent::CloseSpan { id: 1, tsc: 200 }, - ]; - - let mut serializer = EventsBatchEncoder::new(4096, |_| {}); + fn batch_round_trips() { + let events = sample_events(); + let mut encoder = + EventsBatchEncoderGeneric::new(MAX_TRACE_DATA_SIZE, |_| panic!("batch should fit")); for event in &events { - serializer.encode(event); + encoder.encode(event); } - let serialized = serializer.finish(); - let deserialized = EventsBatchDecoder {} - .decode(serialized) - .expect("Deserialization failed"); - check_fb_guest_trace_data(&events, &deserialized); + let batch = encoder.finish(); + let decoded = EventsBatchDecoder.decode(batch).unwrap(); + assert_eq!(decoded, events); } #[test] - fn test_events_batch_decoder_errors_on_truncated_buffer() { - let events = [GuestEvent::LogEvent { - parent_id: 42, - name: "log".to_string(), - tsc: 9001, - fields: Vec::new(), - }]; - - let mut serializer = EventsBatchEncoder::new(512, |_| {}); - for event in &events { - serializer.encode(event); + fn full_batches_are_reported() { + let reported = RefCell::new(Vec::new()); + let mut encoder = EventsBatchEncoderGeneric::new(32, |batch: &[u8]| { + reported.borrow_mut().push(batch.to_vec()) + }); + for event in sample_events() { + encoder.encode(&event); } - let mut truncated = serializer.finish().to_vec(); - assert!( - truncated.pop().is_some(), - "serialized buffer must be non-empty" - ); + encoder.flush(); - let err = EventsBatchDecoder {} - .decode(&truncated) - .expect_err("Decoder must fail when payload is truncated"); - assert!( - err.to_string() - .contains("The serialized buffer does not contain a full set of events"), - "unexpected error: {}", - err, - ); + let decoded: Vec<_> = reported + .borrow() + .iter() + .flat_map(|batch| { + EventsBatchDecoder + .decode(batch) + .unwrap() + .into_iter() + .map(|event| format!("{event:?}")) + .collect::>() + }) + .collect(); + let expected: Vec<_> = sample_events() + .iter() + .map(|event| format!("{event:?}")) + .collect(); + assert_eq!(decoded, expected); + assert!(reported.borrow().len() > 1); } #[test] - fn test_guest_event_try_from_errors_on_missing_union_payload() { - let mut builder = FlatBufferBuilder::new(); - let envelope = FbGuestEventEnvelopeType::create( - &mut builder, - &FbGuestEventEnvelopeTypeArgs { - event_type: FbGuestEventType::OpenSpan, - event: None, - }, - ); - builder.finish_size_prefixed(envelope, None); - let serialized = builder.finished_data(); + fn decoder_rejects_truncated_and_trailing_data() { + let mut encoder = EventsBatchEncoderGeneric::new(MAX_TRACE_DATA_SIZE, |_| {}); + encoder.encode(&GuestEvent::GuestStart { tsc: 7 }); + let batch = encoder.finish().to_vec(); - let err = GuestEvent::try_from(serialized) - .expect_err("Deserialization must fail when union payload is missing"); assert!( - err.to_string().contains("InconsistentUnion"), - "unexpected error: {}", - err, + EventsBatchDecoder + .decode(&batch[..batch.len() - 1]) + .is_err() ); - } - #[test] - fn test_event_key_value_try_from_rejects_short_buffer() { - let buffer = [0x00_u8, 0x01, 0x02]; - let err = EventKeyValue::try_from(buffer.as_slice()) - .expect_err("Deserialization must fail for undersized buffer"); - assert!( - err.to_string() - .contains("Error while reading EventKeyValue"), - "unexpected error: {}", - err, - ); + let mut trailing = batch.clone(); + trailing.push(0); + assert!(EventsBatchDecoder.decode(&trailing).is_err()); } } diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/host_function_definition.rs b/src/hyperlight_common/src/flatbuffer_wrappers/host_function_definition.rs index 0ade7532c1..801cbf8560 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/host_function_definition.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/host_function_definition.rs @@ -1,19 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2025 The Hyperlight Authors. -use alloc::string::{String, ToString}; +use alloc::string::String; use alloc::vec::Vec; -use anyhow::{Error, Result, anyhow}; -use flatbuffers::{FlatBufferBuilder, WIPOffset}; +use anyhow::{Result, anyhow}; #[cfg(feature = "tracing")] use tracing::{Span, instrument}; use super::function_types::{ParameterType, ReturnType}; -use crate::flatbuffers::hyperlight::generated::{ - HostFunctionDefinition as FbHostFunctionDefinition, - HostFunctionDefinitionArgs as FbHostFunctionDefinitionArgs, ParameterType as FbParameterType, -}; /// The definition of a function exposed from the host to the guest #[derive(Debug, Default, Clone, PartialEq, Eq)] @@ -41,40 +36,6 @@ impl HostFunctionDefinition { } } - /// Convert this `HostFunctionDefinition` into a `WIPOffset`. - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - pub(crate) fn convert_to_flatbuffer_def<'a>( - &self, - builder: &mut FlatBufferBuilder<'a>, - ) -> Result>> { - let host_function_name = builder.create_string(&self.function_name); - let return_value_type = self.return_type.into(); - let vec_parameters = match &self.parameter_types { - Some(vec_pvt) => { - let num_items = vec_pvt.len(); - let mut parameters: Vec = Vec::with_capacity(num_items); - for pvt in vec_pvt { - let fb_pvt = pvt.clone().into(); - parameters.push(fb_pvt); - } - Some(builder.create_vector(¶meters)) - } - None => None, - }; - - let fb_host_function_definition: WIPOffset = - FbHostFunctionDefinition::create( - builder, - &FbHostFunctionDefinitionArgs { - function_name: Some(host_function_name), - return_type: return_value_type, - parameters: vec_parameters, - }, - ); - - Ok(fb_host_function_definition) - } - /// Verify that the function call has the correct parameter types. #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] pub fn verify_equal_parameter_types( @@ -91,57 +52,3 @@ impl HostFunctionDefinition { Ok(()) } } - -impl TryFrom<&FbHostFunctionDefinition<'_>> for HostFunctionDefinition { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(value: &FbHostFunctionDefinition) -> Result { - let function_name = value.function_name().to_string(); - let return_type = value.return_type().try_into().map_err(|_| { - anyhow!( - "Failed to convert return type for function {}", - function_name - ) - })?; - let parameter_types = match value.parameters() { - Some(pvt) => { - let len = pvt.len(); - let mut pv: Vec = Vec::with_capacity(len); - for fb_pvt in pvt { - let pvt: ParameterType = fb_pvt.try_into().map_err(|_| { - anyhow!( - "Failed to convert parameter type for function {}", - function_name - ) - })?; - pv.push(pvt); - } - Some(pv) - } - None => None, - }; - - Ok(Self::new(function_name, parameter_types, return_type)) - } -} - -impl TryFrom<&[u8]> for HostFunctionDefinition { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(value: &[u8]) -> Result { - let fb_host_function_definition = flatbuffers::root::>(value) - .map_err(|e| anyhow!("Error while reading HostFunctionDefinition: {:?}", e))?; - Self::try_from(&fb_host_function_definition) - } -} - -impl TryFrom<&HostFunctionDefinition> for Vec { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(hfd: &HostFunctionDefinition) -> Result> { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let host_function_definition = hfd.convert_to_flatbuffer_def(&mut builder)?; - builder.finish_size_prefixed(host_function_definition, None); - Ok(builder.finished_data().to_vec()) - } -} diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/host_function_details.rs b/src/hyperlight_common/src/flatbuffer_wrappers/host_function_details.rs index e36afcf39e..9181205647 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/host_function_details.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/host_function_details.rs @@ -3,17 +3,7 @@ use alloc::vec::Vec; -use anyhow::{Error, Result}; -use flatbuffers::{WIPOffset, size_prefixed_root}; -#[cfg(feature = "tracing")] -use tracing::{Span, instrument}; - use super::host_function_definition::HostFunctionDefinition; -use crate::flatbuffers::hyperlight::generated::{ - HostFunctionDefinition as FbHostFunctionDefinition, - HostFunctionDetails as FbHostFunctionDetails, - HostFunctionDetailsArgs as FbHostFunctionDetailsArgs, -}; /// `HostFunctionDetails` represents the set of functions that the host exposes to the guest. #[derive(Debug, Default, Clone)] @@ -21,69 +11,3 @@ pub struct HostFunctionDetails { /// The host functions. pub host_functions: Option>, } - -impl TryFrom<&[u8]> for HostFunctionDetails { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(value: &[u8]) -> Result { - let host_function_details_fb = size_prefixed_root::(value) - .map_err(|e| anyhow::anyhow!("Error while reading HostFunctionDetails: {:?}", e))?; - - let host_function_definitions = match host_function_details_fb.functions() { - Some(hfd) => { - let len = hfd.len(); - let mut vec_hfd: Vec = Vec::with_capacity(len); - for i in 0..len { - let fb_host_function_definition = hfd.get(i); - let hfdef = HostFunctionDefinition::try_from(&fb_host_function_definition)?; - vec_hfd.push(hfdef); - } - - Some(vec_hfd) - } - - None => None, - }; - - Ok(Self { - host_functions: host_function_definitions, - }) - } -} - -impl TryFrom<&HostFunctionDetails> for Vec { - type Error = Error; - #[cfg_attr(feature = "tracing", instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace"))] - fn try_from(value: &HostFunctionDetails) -> Result> { - let mut builder = flatbuffers::FlatBufferBuilder::new(); - let vec_host_function_definitions = match &value.host_functions { - Some(vec_hfd) => { - let num_items = vec_hfd.len(); - let mut host_function_definitions: Vec> = - Vec::with_capacity(num_items); - - for hfd in vec_hfd { - let host_function_definition = hfd.convert_to_flatbuffer_def(&mut builder)?; - host_function_definitions.push(host_function_definition); - } - - Some(host_function_definitions) - } - None => None, - }; - - let fb_host_function_definitions = - vec_host_function_definitions.map(|v| builder.create_vector(&v)); - - let host_function_details = FbHostFunctionDetails::create( - &mut builder, - &FbHostFunctionDetailsArgs { - functions: fb_host_function_definitions, - }, - ); - builder.finish_size_prefixed(host_function_details, None); - let res = builder.finished_data().to_vec(); - - Ok(res) - } -} diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/mod.rs b/src/hyperlight_common/src/flatbuffer_wrappers/mod.rs index 4001d600fb..33ffaab27b 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/mod.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/mod.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2025 The Hyperlight Authors. +#[cfg(test)] +mod abi_tests; mod codec; pub mod function_call; pub mod function_types; @@ -17,5 +19,6 @@ pub mod host_function_definition; /// cbindgen:ignore pub mod host_function_details; pub mod util; +mod wire; pub use codec::{ExternalValueSink, ExternalValueSource}; diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/util.rs b/src/hyperlight_common/src/flatbuffer_wrappers/util.rs index ac2b078870..402f6b8bca 100644 --- a/src/hyperlight_common/src/flatbuffer_wrappers/util.rs +++ b/src/hyperlight_common/src/flatbuffer_wrappers/util.rs @@ -6,47 +6,6 @@ use alloc::vec::Vec; use bytes::Bytes; -use crate::flatbuffer_wrappers::function_types::ParameterValue; - -/// Estimate the control-buffer capacity for encoding a function call. -/// -/// The function aims to be lightweight and fast and run in O(1) as long as the number of parameters is limited -/// (which it is since hyperlight only currently supports up to 12). -/// -/// Note: This estimates the capacity needed for the inner vec inside a FlatBufferBuilder. It does not -/// necessarily match the size of the final encoded buffer. The estimation always rounds up to the -/// nearest power of two to match FlatBufferBuilder's allocation strategy. -/// -/// The estimations are numbers used are empirically derived based on the tests below and vaguely based -/// on https://flatbuffers.dev/internals/ and https://github.com/dvidelabs/flatcc/blob/f064cefb2034d1e7407407ce32a6085c322212a7/doc/binary-format.md#flatbuffers-binary-format -#[inline] -pub fn estimate_flatbuffer_capacity(function_name: &str, args: &[ParameterValue]) -> usize { - let mut estimated_capacity = 20; - - // Function name overhead - estimated_capacity += function_name.len() + 12; - - // Parameters vector overhead - estimated_capacity += 12 + args.len() * 6; - - // Per-parameter overhead - for arg in args { - estimated_capacity += 16; // Base parameter structure - estimated_capacity += match arg { - ParameterValue::String(s) => s.len() + 20, - ParameterValue::VecBytes(_) | ParameterValue::ByteChunks(_) => 20, - ParameterValue::Int(_) | ParameterValue::UInt(_) => 16, - ParameterValue::Long(_) | ParameterValue::ULong(_) => 20, - ParameterValue::Float(_) => 16, - ParameterValue::Double(_) => 20, - ParameterValue::Bool(_) => 12, - }; - } - - // match how vec grows - estimated_capacity.next_power_of_two() -} - /// Wrap contiguous bytes as one chunk without copying. pub fn byte_chunks_from_bytes(value: Bytes) -> Vec { if value.is_empty() { @@ -101,327 +60,3 @@ pub(crate) fn arbitrary_byte_chunks( ) -> arbitrary::Result> { as arbitrary::Arbitrary>::arbitrary(input).map(byte_chunks_from_vec) } - -#[cfg(test)] -mod tests { - use alloc::string::ToString; - use alloc::vec; - use alloc::vec::Vec; - - use flatbuffers::FlatBufferBuilder; - - use super::*; - use crate::flatbuffer_wrappers::function_call::{FunctionCall, FunctionCallType}; - use crate::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; - use crate::transport::ExternalValues; - - /// Helper function to check that estimation is within reasonable bounds (±25%) - fn assert_estimation_accuracy( - function_name: &str, - args: Vec, - call_type: FunctionCallType, - return_type: ReturnType, - ) { - let estimated = estimate_flatbuffer_capacity(function_name, &args); - - let fc = FunctionCall::new( - function_name.to_string(), - Some(args), - call_type.clone(), - return_type, - ); - // Important that this FlatBufferBuilder is created with capacity 0 so it grows to its needed capacity - let mut builder = FlatBufferBuilder::new(); - let mut external_values = ExternalValues::new(); - let _buffer = fc.encode(&mut builder, &mut external_values).unwrap(); - let actual = builder.collapse().0.capacity(); - - let lower_bound = (actual as f64 * 0.75) as usize; - let upper_bound = (actual as f64 * 1.25) as usize; - - assert!( - estimated >= lower_bound && estimated <= upper_bound, - "Estimation {} outside bounds [{}, {}] for actual size {} (function: {}, call_type: {:?}, return_type: {:?})", - estimated, - lower_bound, - upper_bound, - actual, - function_name, - call_type, - return_type - ); - } - - #[test] - fn test_estimate_no_parameters() { - assert_estimation_accuracy( - "simple_function", - vec![], - FunctionCallType::Guest, - ReturnType::Void, - ); - } - - #[test] - fn capacity_ignores_external_byte_payload_length() { - let small = [ParameterValue::VecBytes(vec![0])]; - let large = [ParameterValue::VecBytes(vec![0; 1024 * 1024])]; - - assert_eq!( - estimate_flatbuffer_capacity("call", &small), - estimate_flatbuffer_capacity("call", &large) - ); - } - - #[test] - fn test_estimate_single_int_parameter() { - assert_estimation_accuracy( - "add_one", - vec![ParameterValue::Int(42)], - FunctionCallType::Guest, - ReturnType::Int, - ); - } - - #[test] - fn test_estimate_multiple_scalar_parameters() { - assert_estimation_accuracy( - "calculate", - vec![ - ParameterValue::Int(10), - ParameterValue::UInt(20), - ParameterValue::Long(30), - ParameterValue::ULong(40), - ParameterValue::Float(1.5), - ParameterValue::Double(2.5), - ParameterValue::Bool(true), - ], - FunctionCallType::Guest, - ReturnType::Double, - ); - } - - #[test] - fn test_estimate_string_parameters() { - assert_estimation_accuracy( - "process_strings", - vec![ - ParameterValue::String("hello".to_string()), - ParameterValue::String("world".to_string()), - ParameterValue::String("this is a longer string for testing".to_string()), - ], - FunctionCallType::Host, - ReturnType::String, - ); - } - - #[test] - fn test_estimate_very_long_string() { - let long_string = "a".repeat(1000); - assert_estimation_accuracy( - "process_long_string", - vec![ParameterValue::String(long_string)], - FunctionCallType::Guest, - ReturnType::String, - ); - } - - #[test] - fn test_estimate_vector_parameters() { - assert_estimation_accuracy( - "process_vectors", - vec![ - ParameterValue::VecBytes(vec![1, 2, 3, 4, 5]), - ParameterValue::VecBytes(vec![]), - ParameterValue::VecBytes(vec![0; 100]), - ], - FunctionCallType::Host, - ReturnType::VecBytes, - ); - } - - #[test] - fn test_estimate_mixed_parameters() { - assert_estimation_accuracy( - "complex_function", - vec![ - ParameterValue::String("test".to_string()), - ParameterValue::Int(42), - ParameterValue::VecBytes(vec![1, 2, 3, 4, 5]), - ParameterValue::Bool(true), - ParameterValue::Double(553.14159), - ParameterValue::String("another string".to_string()), - ParameterValue::Long(9223372036854775807), - ], - FunctionCallType::Guest, - ReturnType::VecBytes, - ); - } - - #[test] - fn test_estimate_large_function_name() { - let long_name = "very_long_function_name_that_exceeds_normal_lengths_for_testing_purposes"; - assert_estimation_accuracy( - long_name, - vec![ParameterValue::Int(1)], - FunctionCallType::Host, - ReturnType::Long, - ); - } - - #[test] - fn test_estimate_large_vector() { - let large_vector = vec![42u8; 10000]; - assert_estimation_accuracy( - "process_large_data", - vec![ParameterValue::VecBytes(large_vector)], - FunctionCallType::Guest, - ReturnType::Bool, - ); - } - - #[test] - fn test_estimate_all_parameter_types() { - assert_estimation_accuracy( - "comprehensive_test", - vec![ - ParameterValue::Int(i32::MIN), - ParameterValue::UInt(u32::MAX), - ParameterValue::Long(i64::MIN), - ParameterValue::ULong(u64::MAX), - ParameterValue::Float(f32::MIN), - ParameterValue::Double(f64::MAX), - ParameterValue::Bool(false), - ParameterValue::String("test string".to_string()), - ParameterValue::VecBytes(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), - ], - FunctionCallType::Host, - ReturnType::ULong, - ); - } - - #[test] - fn test_different_function_call_types() { - assert_estimation_accuracy( - "guest_function", - vec![ParameterValue::String("guest call".to_string())], - FunctionCallType::Guest, - ReturnType::String, - ); - - assert_estimation_accuracy( - "host_function", - vec![ParameterValue::String("host call".to_string())], - FunctionCallType::Host, - ReturnType::String, - ); - } - - #[test] - fn test_different_return_types() { - let args = vec![ - ParameterValue::Int(42), - ParameterValue::String("test".to_string()), - ]; - - let void_est = estimate_flatbuffer_capacity("test_void", &args); - let int_est = estimate_flatbuffer_capacity("test_int", &args); - let string_est = estimate_flatbuffer_capacity("test_string", &args); - - assert!((void_est as i32 - int_est as i32).abs() < 10); - assert!((int_est as i32 - string_est as i32).abs() < 10); - - assert_estimation_accuracy( - "test_void", - args.clone(), - FunctionCallType::Guest, - ReturnType::Void, - ); - assert_estimation_accuracy( - "test_int", - args.clone(), - FunctionCallType::Guest, - ReturnType::Int, - ); - assert_estimation_accuracy( - "test_string", - args, - FunctionCallType::Guest, - ReturnType::String, - ); - } - - #[test] - fn test_estimate_many_large_vectors_and_strings() { - assert_estimation_accuracy( - "process_bulk_data", - vec![ - ParameterValue::String("Large string data: ".to_string() + &"x".repeat(2000)), - ParameterValue::VecBytes(vec![1u8; 5000]), - ParameterValue::String( - "Another large string with lots of content ".to_string() + &"y".repeat(3000), - ), - ParameterValue::VecBytes(vec![255u8; 7500]), - ParameterValue::String( - "Third massive string parameter ".to_string() + &"z".repeat(1500), - ), - ParameterValue::VecBytes(vec![128u8; 10000]), - ParameterValue::Int(42), - ParameterValue::String("Final large string ".to_string() + &"a".repeat(4000)), - ParameterValue::VecBytes(vec![64u8; 2500]), - ParameterValue::Bool(true), - ], - FunctionCallType::Host, - ReturnType::VecBytes, - ); - } - - #[test] - fn test_estimate_twenty_parameters() { - assert_estimation_accuracy( - "function_with_many_parameters", - vec![ - ParameterValue::Int(1), - ParameterValue::String("param2".to_string()), - ParameterValue::Bool(true), - ParameterValue::Float(3213.14), - ParameterValue::VecBytes(vec![1, 2, 3]), - ParameterValue::Long(1000000), - ParameterValue::Double(322.718), - ParameterValue::UInt(42), - ParameterValue::String("param9".to_string()), - ParameterValue::Bool(false), - ParameterValue::ULong(9999999999), - ParameterValue::VecBytes(vec![4, 5, 6, 7, 8]), - ParameterValue::Int(-100), - ParameterValue::Float(1.414), - ParameterValue::String("param15".to_string()), - ParameterValue::Double(1.732), - ParameterValue::Bool(true), - ParameterValue::VecBytes(vec![9, 10]), - ParameterValue::Long(-5000000), - ParameterValue::UInt(12345), - ], - FunctionCallType::Guest, - ReturnType::Int, - ); - } - - /// When running under Miri, this test takes too long due to large allocations - #[test] - #[cfg_attr(miri, ignore)] - fn test_estimate_megabyte_parameters() { - assert_estimation_accuracy( - "process_megabyte_data", - vec![ - ParameterValue::String("MB String 1: ".to_string() + &"x".repeat(1_048_576)), // 1MB string - ParameterValue::VecBytes(vec![42u8; 2_097_152]), // 2MB vector - ParameterValue::String("MB String 2: ".to_string() + &"y".repeat(1_572_864)), // 1.5MB string - ParameterValue::VecBytes(vec![128u8; 3_145_728]), // 3MB vector - ParameterValue::String("MB String 3: ".to_string() + &"z".repeat(2_097_152)), // 2MB string - ], - FunctionCallType::Host, - ReturnType::VecBytes, - ); - } -} diff --git a/src/hyperlight_common/src/flatbuffer_wrappers/wire.rs b/src/hyperlight_common/src/flatbuffer_wrappers/wire.rs new file mode 100644 index 0000000000..dcf7d567c7 --- /dev/null +++ b/src/hyperlight_common/src/flatbuffer_wrappers/wire.rs @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright 2026 The Hyperlight Authors. + +//! Serde/postcard encoding of function calls and results. +//! +//! Control data is one postcard value. The message header records its length. +//! Byte values travel as external values and the control data carries only +//! their length. + +use alloc::vec::Vec; +use core::fmt; +use core::marker::PhantomData; + +use anyhow::{Result, anyhow, bail}; +use serde::de::{SeqAccess, Visitor}; +use serde::ser::SerializeSeq; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use smallvec::SmallVec; + +use super::function_types::{ParameterValue, ReturnType, ReturnValue}; +use super::util::byte_chunks_len; + +/// One control value. Variant order is the wire tag. +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub(super) enum WireValue<'a> { + Int(i32), + UInt(u32), + Long(i64), + ULong(u64), + Float(f32), + Double(f64), + String(&'a str), + Bool(bool), + Void, + ExternalBytes { length: u64, chunked: bool }, +} + +impl<'a> WireValue<'a> { + /// Byte lengths must have been checked by the caller. + pub(super) fn from_parameter(value: &'a ParameterValue) -> Self { + match value { + ParameterValue::Int(v) => Self::Int(*v), + ParameterValue::UInt(v) => Self::UInt(*v), + ParameterValue::Long(v) => Self::Long(*v), + ParameterValue::ULong(v) => Self::ULong(*v), + ParameterValue::Float(v) => Self::Float(*v), + ParameterValue::Double(v) => Self::Double(*v), + ParameterValue::String(v) => Self::String(v), + ParameterValue::Bool(v) => Self::Bool(*v), + ParameterValue::VecBytes(v) => Self::ExternalBytes { + length: v.len() as u64, + chunked: false, + }, + ParameterValue::ByteChunks(v) => Self::ExternalBytes { + length: byte_chunks_len(v) as u64, + chunked: true, + }, + } + } + + /// Byte lengths must have been checked by the caller. + pub(super) fn from_return(value: &'a ReturnValue) -> Self { + match value { + ReturnValue::Int(v) => Self::Int(*v), + ReturnValue::UInt(v) => Self::UInt(*v), + ReturnValue::Long(v) => Self::Long(*v), + ReturnValue::ULong(v) => Self::ULong(*v), + ReturnValue::Float(v) => Self::Float(*v), + ReturnValue::Double(v) => Self::Double(*v), + ReturnValue::String(v) => Self::String(v), + ReturnValue::Bool(v) => Self::Bool(*v), + ReturnValue::Void(()) => Self::Void, + ReturnValue::VecBytes(v) => Self::ExternalBytes { + length: v.len() as u64, + chunked: false, + }, + ReturnValue::ByteChunks(v) => Self::ExternalBytes { + length: byte_chunks_len(v) as u64, + chunked: true, + }, + } + } +} + +/// Serializes parameters as a sequence without collecting them first. +pub(super) struct ParamsOut<'a>(pub(super) &'a [ParameterValue]); + +impl Serialize for ParamsOut<'_> { + fn serialize(&self, serializer: S) -> core::result::Result { + let mut seq = serializer.serialize_seq(Some(self.0.len()))?; + for value in self.0 { + seq.serialize_element(&WireValue::from_parameter(value))?; + } + seq.end() + } +} + +/// Inline capacity covers the common parameter counts without heap use. +pub(super) struct ParamsIn<'a>(pub(super) SmallVec<[WireValue<'a>; 8]>); + +impl<'de: 'a, 'a> Deserialize<'de> for ParamsIn<'a> { + fn deserialize>(deserializer: D) -> core::result::Result { + struct ParamsVisitor<'a>(PhantomData<&'a ()>); + + impl<'de: 'a, 'a> Visitor<'de> for ParamsVisitor<'a> { + type Value = ParamsIn<'a>; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a parameter sequence") + } + + fn visit_seq>( + self, + mut seq: A, + ) -> core::result::Result { + // The length hint is untrusted, so growth follows decoded elements. + let mut values = SmallVec::new(); + while let Some(value) = seq.next_element()? { + values.push(value); + } + Ok(ParamsIn(values)) + } + } + + deserializer.deserialize_seq(ParamsVisitor(PhantomData)) + } +} + +/// One function call. Senders use [`ParamsOut`] and receivers use +/// [`ParamsIn`]. +#[derive(Serialize, Deserialize)] +pub(super) struct WireCall<'a, P> { + pub(super) name: &'a str, + pub(super) host: bool, + pub(super) return_type: ReturnType, + pub(super) params: P, +} + +#[derive(Debug, PartialEq, Serialize, Deserialize)] +pub(super) enum WireResult<'a> { + #[serde(borrow)] + Ok(WireValue<'a>), + Err { + code: u64, + message: &'a str, + }, +} + +/// Write `value` as control data into `buffer`. +pub(super) fn encode_value<'b, T: Serialize>( + value: &T, + buffer: &'b mut Vec, +) -> Result<&'b [u8]> { + let mut out = core::mem::take(buffer); + out.clear(); + *buffer = postcard::to_extend(value, out).map_err(|e| anyhow!("Encode failed: {e}"))?; + Ok(buffer.as_slice()) +} + +/// Read one postcard value and reject trailing bytes. +pub(super) fn decode_value<'a, T: Deserialize<'a>>(value: &'a [u8]) -> Result { + let (decoded, rest) = + postcard::take_from_bytes(value).map_err(|e| anyhow!("Decode failed: {e}"))?; + if !rest.is_empty() { + bail!("Control data has {} trailing bytes", rest.len()); + } + Ok(decoded) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decoding_rejects_truncated_and_trailing_bytes() { + let mut buffer = Vec::new(); + let encoded = encode_value(&WireValue::String("text"), &mut buffer) + .unwrap() + .to_vec(); + assert_eq!( + decode_value::(&encoded).unwrap(), + WireValue::String("text") + ); + + assert!(decode_value::(&encoded[..encoded.len() - 1]).is_err()); + + let mut trailing = encoded.clone(); + trailing.push(0); + assert!(decode_value::(&trailing).is_err()); + } +} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/close_span_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/close_span_type_generated.rs deleted file mode 100644 index c88f61c635..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/close_span_type_generated.rs +++ /dev/null @@ -1,131 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum CloseSpanTypeOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct CloseSpanType<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for CloseSpanType<'a> { - type Inner = CloseSpanType<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> CloseSpanType<'a> { - pub const VT_ID: flatbuffers::VOffsetT = 4; - pub const VT_TSC: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - CloseSpanType { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args CloseSpanTypeArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = CloseSpanTypeBuilder::new(_fbb); - builder.add_tsc(args.tsc); - builder.add_id(args.id); - builder.finish() - } - - #[inline] - pub fn id(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(CloseSpanType::VT_ID, Some(0)).unwrap() } - } - #[inline] - pub fn tsc(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(CloseSpanType::VT_TSC, Some(0)) - .unwrap() - } - } -} - -impl flatbuffers::Verifiable for CloseSpanType<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("id", Self::VT_ID, false)? - .visit_field::("tsc", Self::VT_TSC, false)? - .finish(); - Ok(()) - } -} -pub struct CloseSpanTypeArgs { - pub id: u64, - pub tsc: u64, -} -impl<'a> Default for CloseSpanTypeArgs { - #[inline] - fn default() -> Self { - CloseSpanTypeArgs { id: 0, tsc: 0 } - } -} - -pub struct CloseSpanTypeBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> CloseSpanTypeBuilder<'a, 'b, A> { - #[inline] - pub fn add_id(&mut self, id: u64) { - self.fbb_.push_slot::(CloseSpanType::VT_ID, id, 0); - } - #[inline] - pub fn add_tsc(&mut self, tsc: u64) { - self.fbb_.push_slot::(CloseSpanType::VT_TSC, tsc, 0); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> CloseSpanTypeBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - CloseSpanTypeBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for CloseSpanType<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("CloseSpanType"); - ds.field("id", &self.id()); - ds.field("tsc", &self.tsc()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/edit_span_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/edit_span_type_generated.rs deleted file mode 100644 index 47e5b0bd8c..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/edit_span_type_generated.rs +++ /dev/null @@ -1,148 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum EditSpanTypeOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct EditSpanType<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for EditSpanType<'a> { - type Inner = EditSpanType<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> EditSpanType<'a> { - pub const VT_ID: flatbuffers::VOffsetT = 4; - pub const VT_FIELDS: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - EditSpanType { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args EditSpanTypeArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = EditSpanTypeBuilder::new(_fbb); - builder.add_id(args.id); - if let Some(x) = args.fields { - builder.add_fields(x); - } - builder.finish() - } - - #[inline] - pub fn id(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(EditSpanType::VT_ID, Some(0)).unwrap() } - } - #[inline] - pub fn fields( - &self, - ) -> Option>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab.get::>, - >>(EditSpanType::VT_FIELDS, None) - } - } -} - -impl flatbuffers::Verifiable for EditSpanType<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("id", Self::VT_ID, false)? - .visit_field::>, - >>("fields", Self::VT_FIELDS, false)? - .finish(); - Ok(()) - } -} -pub struct EditSpanTypeArgs<'a> { - pub id: u64, - pub fields: Option< - flatbuffers::WIPOffset>>>, - >, -} -impl<'a> Default for EditSpanTypeArgs<'a> { - #[inline] - fn default() -> Self { - EditSpanTypeArgs { - id: 0, - fields: None, - } - } -} - -pub struct EditSpanTypeBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> EditSpanTypeBuilder<'a, 'b, A> { - #[inline] - pub fn add_id(&mut self, id: u64) { - self.fbb_.push_slot::(EditSpanType::VT_ID, id, 0); - } - #[inline] - pub fn add_fields( - &mut self, - fields: flatbuffers::WIPOffset< - flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset>>, - >, - ) { - self.fbb_ - .push_slot_always::>(EditSpanType::VT_FIELDS, fields); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> EditSpanTypeBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - EditSpanTypeBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for EditSpanType<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("EditSpanType"); - ds.field("id", &self.id()); - ds.field("fields", &self.fields()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/error_code_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/error_code_generated.rs deleted file mode 100644 index f26d38db00..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/error_code_generated.rs +++ /dev/null @@ -1,167 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_ERROR_CODE: u64 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_ERROR_CODE: u64 = 17; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_ERROR_CODE: [ErrorCode; 16] = [ - ErrorCode::NoError, - ErrorCode::UnsupportedParameterType, - ErrorCode::GuestFunctionNameNotProvided, - ErrorCode::GuestFunctionNotFound, - ErrorCode::GuestFunctionIncorrecNoOfParameters, - ErrorCode::GispatchFunctionPointerNotSet, - ErrorCode::OutbError, - ErrorCode::UnknownError, - ErrorCode::GsCheckFailed, - ErrorCode::TooManyGuestFunctions, - ErrorCode::FailureInDlmalloc, - ErrorCode::MallocFailed, - ErrorCode::GuestFunctionParameterTypeMismatch, - ErrorCode::GuestError, - ErrorCode::ArrayLengthParamIsMissing, - ErrorCode::HostError, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct ErrorCode(pub u64); -#[allow(non_upper_case_globals)] -impl ErrorCode { - pub const NoError: Self = Self(0); - pub const UnsupportedParameterType: Self = Self(2); - pub const GuestFunctionNameNotProvided: Self = Self(3); - pub const GuestFunctionNotFound: Self = Self(4); - pub const GuestFunctionIncorrecNoOfParameters: Self = Self(5); - pub const GispatchFunctionPointerNotSet: Self = Self(6); - pub const OutbError: Self = Self(7); - pub const UnknownError: Self = Self(8); - pub const GsCheckFailed: Self = Self(10); - pub const TooManyGuestFunctions: Self = Self(11); - pub const FailureInDlmalloc: Self = Self(12); - pub const MallocFailed: Self = Self(13); - pub const GuestFunctionParameterTypeMismatch: Self = Self(14); - pub const GuestError: Self = Self(15); - pub const ArrayLengthParamIsMissing: Self = Self(16); - pub const HostError: Self = Self(17); - - pub const ENUM_MIN: u64 = 0; - pub const ENUM_MAX: u64 = 17; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NoError, - Self::UnsupportedParameterType, - Self::GuestFunctionNameNotProvided, - Self::GuestFunctionNotFound, - Self::GuestFunctionIncorrecNoOfParameters, - Self::GispatchFunctionPointerNotSet, - Self::OutbError, - Self::UnknownError, - Self::GsCheckFailed, - Self::TooManyGuestFunctions, - Self::FailureInDlmalloc, - Self::MallocFailed, - Self::GuestFunctionParameterTypeMismatch, - Self::GuestError, - Self::ArrayLengthParamIsMissing, - Self::HostError, - ]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NoError => Some("NoError"), - Self::UnsupportedParameterType => Some("UnsupportedParameterType"), - Self::GuestFunctionNameNotProvided => Some("GuestFunctionNameNotProvided"), - Self::GuestFunctionNotFound => Some("GuestFunctionNotFound"), - Self::GuestFunctionIncorrecNoOfParameters => { - Some("GuestFunctionIncorrecNoOfParameters") - } - Self::GispatchFunctionPointerNotSet => Some("GispatchFunctionPointerNotSet"), - Self::OutbError => Some("OutbError"), - Self::UnknownError => Some("UnknownError"), - Self::GsCheckFailed => Some("GsCheckFailed"), - Self::TooManyGuestFunctions => Some("TooManyGuestFunctions"), - Self::FailureInDlmalloc => Some("FailureInDlmalloc"), - Self::MallocFailed => Some("MallocFailed"), - Self::GuestFunctionParameterTypeMismatch => Some("GuestFunctionParameterTypeMismatch"), - Self::GuestError => Some("GuestError"), - Self::ArrayLengthParamIsMissing => Some("ArrayLengthParamIsMissing"), - Self::HostError => Some("HostError"), - _ => None, - } - } -} -impl core::fmt::Debug for ErrorCode { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for ErrorCode { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for ErrorCode { - type Output = ErrorCode; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for ErrorCode { - type Scalar = u64; - #[inline] - fn to_little_endian(self) -> u64 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u64) -> Self { - let b = u64::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for ErrorCode { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u64::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for ErrorCode {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_generated.rs deleted file mode 100644 index 7ea5b4d637..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_generated.rs +++ /dev/null @@ -1,239 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum FunctionCallOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct FunctionCall<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for FunctionCall<'a> { - type Inner = FunctionCall<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> FunctionCall<'a> { - pub const VT_FUNCTION_NAME: flatbuffers::VOffsetT = 4; - pub const VT_PARAMETERS: flatbuffers::VOffsetT = 6; - pub const VT_FUNCTION_CALL_TYPE: flatbuffers::VOffsetT = 8; - pub const VT_EXPECTED_RETURN_TYPE: flatbuffers::VOffsetT = 10; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - FunctionCall { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args FunctionCallArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = FunctionCallBuilder::new(_fbb); - if let Some(x) = args.parameters { - builder.add_parameters(x); - } - if let Some(x) = args.function_name { - builder.add_function_name(x); - } - builder.add_expected_return_type(args.expected_return_type); - builder.add_function_call_type(args.function_call_type); - builder.finish() - } - - #[inline] - pub fn function_name(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(FunctionCall::VT_FUNCTION_NAME, None) - .unwrap() - } - } - #[inline] - pub fn key_compare_less_than(&self, o: &FunctionCall) -> bool { - self.function_name() < o.function_name() - } - - #[inline] - pub fn key_compare_with_value(&self, val: &str) -> ::core::cmp::Ordering { - let key = self.function_name(); - key.cmp(val) - } - #[inline] - pub fn parameters( - &self, - ) -> Option>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab.get::>, - >>(FunctionCall::VT_PARAMETERS, None) - } - } - #[inline] - pub fn function_call_type(&self) -> FunctionCallType { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::( - FunctionCall::VT_FUNCTION_CALL_TYPE, - Some(FunctionCallType::none), - ) - .unwrap() - } - } - #[inline] - pub fn expected_return_type(&self) -> ReturnType { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::( - FunctionCall::VT_EXPECTED_RETURN_TYPE, - Some(ReturnType::hlint), - ) - .unwrap() - } - } -} - -impl flatbuffers::Verifiable for FunctionCall<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::>( - "function_name", - Self::VT_FUNCTION_NAME, - true, - )? - .visit_field::>, - >>("parameters", Self::VT_PARAMETERS, false)? - .visit_field::( - "function_call_type", - Self::VT_FUNCTION_CALL_TYPE, - false, - )? - .visit_field::( - "expected_return_type", - Self::VT_EXPECTED_RETURN_TYPE, - false, - )? - .finish(); - Ok(()) - } -} -pub struct FunctionCallArgs<'a> { - pub function_name: Option>, - pub parameters: Option< - flatbuffers::WIPOffset< - flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset>>, - >, - >, - pub function_call_type: FunctionCallType, - pub expected_return_type: ReturnType, -} -impl<'a> Default for FunctionCallArgs<'a> { - #[inline] - fn default() -> Self { - FunctionCallArgs { - function_name: None, // required field - parameters: None, - function_call_type: FunctionCallType::none, - expected_return_type: ReturnType::hlint, - } - } -} - -pub struct FunctionCallBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> FunctionCallBuilder<'a, 'b, A> { - #[inline] - pub fn add_function_name(&mut self, function_name: flatbuffers::WIPOffset<&'b str>) { - self.fbb_.push_slot_always::>( - FunctionCall::VT_FUNCTION_NAME, - function_name, - ); - } - #[inline] - pub fn add_parameters( - &mut self, - parameters: flatbuffers::WIPOffset< - flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset>>, - >, - ) { - self.fbb_ - .push_slot_always::>(FunctionCall::VT_PARAMETERS, parameters); - } - #[inline] - pub fn add_function_call_type(&mut self, function_call_type: FunctionCallType) { - self.fbb_.push_slot::( - FunctionCall::VT_FUNCTION_CALL_TYPE, - function_call_type, - FunctionCallType::none, - ); - } - #[inline] - pub fn add_expected_return_type(&mut self, expected_return_type: ReturnType) { - self.fbb_.push_slot::( - FunctionCall::VT_EXPECTED_RETURN_TYPE, - expected_return_type, - ReturnType::hlint, - ); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> FunctionCallBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - FunctionCallBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_ - .required(o, FunctionCall::VT_FUNCTION_NAME, "function_name"); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for FunctionCall<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("FunctionCall"); - ds.field("function_name", &self.function_name()); - ds.field("parameters", &self.parameters()); - ds.field("function_call_type", &self.function_call_type()); - ds.field("expected_return_type", &self.expected_return_type()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_result_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_result_generated.rs deleted file mode 100644 index 7f26e9c003..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_result_generated.rs +++ /dev/null @@ -1,223 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum FunctionCallResultOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct FunctionCallResult<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for FunctionCallResult<'a> { - type Inner = FunctionCallResult<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> FunctionCallResult<'a> { - pub const VT_RESULT_TYPE: flatbuffers::VOffsetT = 4; - pub const VT_RESULT: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - FunctionCallResult { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args FunctionCallResultArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = FunctionCallResultBuilder::new(_fbb); - if let Some(x) = args.result { - builder.add_result(x); - } - builder.add_result_type(args.result_type); - builder.finish() - } - - #[inline] - pub fn result_type(&self) -> FunctionCallResultType { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::( - FunctionCallResult::VT_RESULT_TYPE, - Some(FunctionCallResultType::NONE), - ) - .unwrap() - } - } - #[inline] - pub fn result(&self) -> flatbuffers::Table<'a> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>>( - FunctionCallResult::VT_RESULT, - None, - ) - .unwrap() - } - } - #[inline] - #[allow(non_snake_case)] - pub fn result_as_return_value_box(&self) -> Option> { - if self.result_type() == FunctionCallResultType::ReturnValueBox { - let u = self.result(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { ReturnValueBox::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn result_as_guest_error(&self) -> Option> { - if self.result_type() == FunctionCallResultType::GuestError { - let u = self.result(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { GuestError::init_from_table(u) }) - } else { - None - } - } -} - -impl flatbuffers::Verifiable for FunctionCallResult<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_union::( - "result_type", - Self::VT_RESULT_TYPE, - "result", - Self::VT_RESULT, - true, - |key, v, pos| match key { - FunctionCallResultType::ReturnValueBox => v - .verify_union_variant::>( - "FunctionCallResultType::ReturnValueBox", - pos, - ), - FunctionCallResultType::GuestError => v - .verify_union_variant::>( - "FunctionCallResultType::GuestError", - pos, - ), - _ => Ok(()), - }, - )? - .finish(); - Ok(()) - } -} -pub struct FunctionCallResultArgs { - pub result_type: FunctionCallResultType, - pub result: Option>, -} -impl<'a> Default for FunctionCallResultArgs { - #[inline] - fn default() -> Self { - FunctionCallResultArgs { - result_type: FunctionCallResultType::NONE, - result: None, // required field - } - } -} - -pub struct FunctionCallResultBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> FunctionCallResultBuilder<'a, 'b, A> { - #[inline] - pub fn add_result_type(&mut self, result_type: FunctionCallResultType) { - self.fbb_.push_slot::( - FunctionCallResult::VT_RESULT_TYPE, - result_type, - FunctionCallResultType::NONE, - ); - } - #[inline] - pub fn add_result(&mut self, result: flatbuffers::WIPOffset) { - self.fbb_ - .push_slot_always::>(FunctionCallResult::VT_RESULT, result); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> FunctionCallResultBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - FunctionCallResultBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_ - .required(o, FunctionCallResult::VT_RESULT, "result"); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for FunctionCallResult<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("FunctionCallResult"); - ds.field("result_type", &self.result_type()); - match self.result_type() { - FunctionCallResultType::ReturnValueBox => { - if let Some(x) = self.result_as_return_value_box() { - ds.field("result", &x) - } else { - ds.field( - "result", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - FunctionCallResultType::GuestError => { - if let Some(x) = self.result_as_guest_error() { - ds.field("result", &x) - } else { - ds.field( - "result", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - _ => { - let x: Option<()> = None; - ds.field("result", &x) - } - }; - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_result_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_result_type_generated.rs deleted file mode 100644 index 0c54dfed40..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_result_type_generated.rs +++ /dev/null @@ -1,110 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_FUNCTION_CALL_RESULT_TYPE: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_FUNCTION_CALL_RESULT_TYPE: u8 = 2; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_FUNCTION_CALL_RESULT_TYPE: [FunctionCallResultType; 3] = [ - FunctionCallResultType::NONE, - FunctionCallResultType::ReturnValueBox, - FunctionCallResultType::GuestError, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct FunctionCallResultType(pub u8); -#[allow(non_upper_case_globals)] -impl FunctionCallResultType { - pub const NONE: Self = Self(0); - pub const ReturnValueBox: Self = Self(1); - pub const GuestError: Self = Self(2); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[Self::NONE, Self::ReturnValueBox, Self::GuestError]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::ReturnValueBox => Some("ReturnValueBox"), - Self::GuestError => Some("GuestError"), - _ => None, - } - } -} -impl core::fmt::Debug for FunctionCallResultType { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for FunctionCallResultType { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for FunctionCallResultType { - type Output = FunctionCallResultType; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for FunctionCallResultType { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for FunctionCallResultType { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for FunctionCallResultType {} -pub struct FunctionCallResultTypeUnionTableOffset {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_type_generated.rs deleted file mode 100644 index 84356d89a7..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/function_call_type_generated.rs +++ /dev/null @@ -1,109 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_FUNCTION_CALL_TYPE: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_FUNCTION_CALL_TYPE: u8 = 2; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_FUNCTION_CALL_TYPE: [FunctionCallType; 3] = [ - FunctionCallType::none, - FunctionCallType::guest, - FunctionCallType::host, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct FunctionCallType(pub u8); -#[allow(non_upper_case_globals)] -impl FunctionCallType { - pub const none: Self = Self(0); - pub const guest: Self = Self(1); - pub const host: Self = Self(2); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 2; - pub const ENUM_VALUES: &'static [Self] = &[Self::none, Self::guest, Self::host]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::none => Some("none"), - Self::guest => Some("guest"), - Self::host => Some("host"), - _ => None, - } - } -} -impl core::fmt::Debug for FunctionCallType { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for FunctionCallType { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for FunctionCallType { - type Output = FunctionCallType; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for FunctionCallType { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for FunctionCallType { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for FunctionCallType {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_error_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_error_generated.rs deleted file mode 100644 index 21ef559b60..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_error_generated.rs +++ /dev/null @@ -1,141 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum GuestErrorOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct GuestError<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for GuestError<'a> { - type Inner = GuestError<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> GuestError<'a> { - pub const VT_CODE: flatbuffers::VOffsetT = 4; - pub const VT_MESSAGE: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - GuestError { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args GuestErrorArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = GuestErrorBuilder::new(_fbb); - builder.add_code(args.code); - if let Some(x) = args.message { - builder.add_message(x); - } - builder.finish() - } - - #[inline] - pub fn code(&self) -> ErrorCode { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(GuestError::VT_CODE, Some(ErrorCode::NoError)) - .unwrap() - } - } - #[inline] - pub fn message(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(GuestError::VT_MESSAGE, None) - } - } -} - -impl flatbuffers::Verifiable for GuestError<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("code", Self::VT_CODE, false)? - .visit_field::>("message", Self::VT_MESSAGE, false)? - .finish(); - Ok(()) - } -} -pub struct GuestErrorArgs<'a> { - pub code: ErrorCode, - pub message: Option>, -} -impl<'a> Default for GuestErrorArgs<'a> { - #[inline] - fn default() -> Self { - GuestErrorArgs { - code: ErrorCode::NoError, - message: None, - } - } -} - -pub struct GuestErrorBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> GuestErrorBuilder<'a, 'b, A> { - #[inline] - pub fn add_code(&mut self, code: ErrorCode) { - self.fbb_ - .push_slot::(GuestError::VT_CODE, code, ErrorCode::NoError); - } - #[inline] - pub fn add_message(&mut self, message: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(GuestError::VT_MESSAGE, message); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> GuestErrorBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - GuestErrorBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for GuestError<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("GuestError"); - ds.field("code", &self.code()); - ds.field("message", &self.message()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_envelope_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_envelope_type_generated.rs deleted file mode 100644 index 80e24505a5..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_envelope_type_generated.rs +++ /dev/null @@ -1,312 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum GuestEventEnvelopeTypeOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct GuestEventEnvelopeType<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for GuestEventEnvelopeType<'a> { - type Inner = GuestEventEnvelopeType<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> GuestEventEnvelopeType<'a> { - pub const VT_EVENT_TYPE: flatbuffers::VOffsetT = 4; - pub const VT_EVENT: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - GuestEventEnvelopeType { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args GuestEventEnvelopeTypeArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = GuestEventEnvelopeTypeBuilder::new(_fbb); - if let Some(x) = args.event { - builder.add_event(x); - } - builder.add_event_type(args.event_type); - builder.finish() - } - - #[inline] - pub fn event_type(&self) -> GuestEventType { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::( - GuestEventEnvelopeType::VT_EVENT_TYPE, - Some(GuestEventType::NONE), - ) - .unwrap() - } - } - #[inline] - pub fn event(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>>( - GuestEventEnvelopeType::VT_EVENT, - None, - ) - } - } - #[inline] - #[allow(non_snake_case)] - pub fn event_as_open_span(&self) -> Option> { - if self.event_type() == GuestEventType::OpenSpan { - self.event().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { OpenSpanType::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn event_as_close_span(&self) -> Option> { - if self.event_type() == GuestEventType::CloseSpan { - self.event().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { CloseSpanType::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn event_as_log_event(&self) -> Option> { - if self.event_type() == GuestEventType::LogEvent { - self.event().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { LogEventType::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn event_as_edit_span(&self) -> Option> { - if self.event_type() == GuestEventType::EditSpan { - self.event().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { EditSpanType::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn event_as_guest_start(&self) -> Option> { - if self.event_type() == GuestEventType::GuestStart { - self.event().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { GuestStartType::init_from_table(t) } - }) - } else { - None - } - } -} - -impl flatbuffers::Verifiable for GuestEventEnvelopeType<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_union::( - "event_type", - Self::VT_EVENT_TYPE, - "event", - Self::VT_EVENT, - false, - |key, v, pos| match key { - GuestEventType::OpenSpan => v - .verify_union_variant::>( - "GuestEventType::OpenSpan", - pos, - ), - GuestEventType::CloseSpan => v - .verify_union_variant::>( - "GuestEventType::CloseSpan", - pos, - ), - GuestEventType::LogEvent => v - .verify_union_variant::>( - "GuestEventType::LogEvent", - pos, - ), - GuestEventType::EditSpan => v - .verify_union_variant::>( - "GuestEventType::EditSpan", - pos, - ), - GuestEventType::GuestStart => v - .verify_union_variant::>( - "GuestEventType::GuestStart", - pos, - ), - _ => Ok(()), - }, - )? - .finish(); - Ok(()) - } -} -pub struct GuestEventEnvelopeTypeArgs { - pub event_type: GuestEventType, - pub event: Option>, -} -impl<'a> Default for GuestEventEnvelopeTypeArgs { - #[inline] - fn default() -> Self { - GuestEventEnvelopeTypeArgs { - event_type: GuestEventType::NONE, - event: None, - } - } -} - -pub struct GuestEventEnvelopeTypeBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> GuestEventEnvelopeTypeBuilder<'a, 'b, A> { - #[inline] - pub fn add_event_type(&mut self, event_type: GuestEventType) { - self.fbb_.push_slot::( - GuestEventEnvelopeType::VT_EVENT_TYPE, - event_type, - GuestEventType::NONE, - ); - } - #[inline] - pub fn add_event(&mut self, event: flatbuffers::WIPOffset) { - self.fbb_ - .push_slot_always::>(GuestEventEnvelopeType::VT_EVENT, event); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> GuestEventEnvelopeTypeBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - GuestEventEnvelopeTypeBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for GuestEventEnvelopeType<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("GuestEventEnvelopeType"); - ds.field("event_type", &self.event_type()); - match self.event_type() { - GuestEventType::OpenSpan => { - if let Some(x) = self.event_as_open_span() { - ds.field("event", &x) - } else { - ds.field( - "event", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - GuestEventType::CloseSpan => { - if let Some(x) = self.event_as_close_span() { - ds.field("event", &x) - } else { - ds.field( - "event", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - GuestEventType::LogEvent => { - if let Some(x) = self.event_as_log_event() { - ds.field("event", &x) - } else { - ds.field( - "event", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - GuestEventType::EditSpan => { - if let Some(x) = self.event_as_edit_span() { - ds.field("event", &x) - } else { - ds.field( - "event", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - GuestEventType::GuestStart => { - if let Some(x) = self.event_as_guest_start() { - ds.field("event", &x) - } else { - ds.field( - "event", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - _ => { - let x: Option<()> = None; - ds.field("event", &x) - } - }; - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_generated.rs deleted file mode 100644 index 1d89bd9c7c..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_generated.rs +++ /dev/null @@ -1,249 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum GuestEventOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct GuestEvent<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for GuestEvent<'a> { - type Inner = GuestEvent<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> GuestEvent<'a> { - pub const VT_EVENT_TYPE: flatbuffers::VOffsetT = 4; - pub const VT_EVENT: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - GuestEvent { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args GuestEventArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = GuestEventBuilder::new(_fbb); - if let Some(x) = args.event { - builder.add_event(x); - } - builder.add_event_type(args.event_type); - builder.finish() - } - - #[inline] - pub fn event_type(&self) -> GuestEventType { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(GuestEvent::VT_EVENT_TYPE, Some(GuestEventType::NONE)) - .unwrap() - } - } - #[inline] - pub fn event(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>>( - GuestEvent::VT_EVENT, - None, - ) - } - } - #[inline] - #[allow(non_snake_case)] - pub fn event_as_open_span_type(&self) -> Option> { - if self.event_type() == GuestEventType::OpenSpanType { - self.event().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { OpenSpanType::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn event_as_close_span_type(&self) -> Option> { - if self.event_type() == GuestEventType::CloseSpanType { - self.event().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { CloseSpanType::init_from_table(t) } - }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn event_as_log_event_type(&self) -> Option> { - if self.event_type() == GuestEventType::LogEventType { - self.event().map(|t| { - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - unsafe { LogEventType::init_from_table(t) } - }) - } else { - None - } - } -} - -impl flatbuffers::Verifiable for GuestEvent<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_union::( - "event_type", - Self::VT_EVENT_TYPE, - "event", - Self::VT_EVENT, - false, - |key, v, pos| match key { - GuestEventType::OpenSpanType => v - .verify_union_variant::>( - "GuestEventType::OpenSpanType", - pos, - ), - GuestEventType::CloseSpanType => v - .verify_union_variant::>( - "GuestEventType::CloseSpanType", - pos, - ), - GuestEventType::LogEventType => v - .verify_union_variant::>( - "GuestEventType::LogEventType", - pos, - ), - _ => Ok(()), - }, - )? - .finish(); - Ok(()) - } -} -pub struct GuestEventArgs { - pub event_type: GuestEventType, - pub event: Option>, -} -impl<'a> Default for GuestEventArgs { - #[inline] - fn default() -> Self { - GuestEventArgs { - event_type: GuestEventType::NONE, - event: None, - } - } -} - -pub struct GuestEventBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> GuestEventBuilder<'a, 'b, A> { - #[inline] - pub fn add_event_type(&mut self, event_type: GuestEventType) { - self.fbb_.push_slot::( - GuestEvent::VT_EVENT_TYPE, - event_type, - GuestEventType::NONE, - ); - } - #[inline] - pub fn add_event(&mut self, event: flatbuffers::WIPOffset) { - self.fbb_ - .push_slot_always::>(GuestEvent::VT_EVENT, event); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> GuestEventBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - GuestEventBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for GuestEvent<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("GuestEvent"); - ds.field("event_type", &self.event_type()); - match self.event_type() { - GuestEventType::OpenSpanType => { - if let Some(x) = self.event_as_open_span_type() { - ds.field("event", &x) - } else { - ds.field( - "event", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - GuestEventType::CloseSpanType => { - if let Some(x) = self.event_as_close_span_type() { - ds.field("event", &x) - } else { - ds.field( - "event", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - GuestEventType::LogEventType => { - if let Some(x) = self.event_as_log_event_type() { - ds.field("event", &x) - } else { - ds.field( - "event", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - _ => { - let x: Option<()> = None; - ds.field("event", &x) - } - }; - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_type_generated.rs deleted file mode 100644 index 07a343a300..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_type_generated.rs +++ /dev/null @@ -1,126 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_GUEST_EVENT_TYPE: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_GUEST_EVENT_TYPE: u8 = 5; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_GUEST_EVENT_TYPE: [GuestEventType; 6] = [ - GuestEventType::NONE, - GuestEventType::OpenSpan, - GuestEventType::CloseSpan, - GuestEventType::LogEvent, - GuestEventType::EditSpan, - GuestEventType::GuestStart, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct GuestEventType(pub u8); -#[allow(non_upper_case_globals)] -impl GuestEventType { - pub const NONE: Self = Self(0); - pub const OpenSpan: Self = Self(1); - pub const CloseSpan: Self = Self(2); - pub const LogEvent: Self = Self(3); - pub const EditSpan: Self = Self(4); - pub const GuestStart: Self = Self(5); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 5; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::OpenSpan, - Self::CloseSpan, - Self::LogEvent, - Self::EditSpan, - Self::GuestStart, - ]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::OpenSpan => Some("OpenSpan"), - Self::CloseSpan => Some("CloseSpan"), - Self::LogEvent => Some("LogEvent"), - Self::EditSpan => Some("EditSpan"), - Self::GuestStart => Some("GuestStart"), - _ => None, - } - } -} -impl core::fmt::Debug for GuestEventType { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for GuestEventType { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for GuestEventType { - type Output = GuestEventType; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for GuestEventType { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for GuestEventType { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for GuestEventType {} -pub struct GuestEventTypeUnionTableOffset {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_union_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_union_type_generated.rs deleted file mode 100644 index 211b0ba123..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_event_union_type_generated.rs +++ /dev/null @@ -1,126 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_GUEST_EVENT_UNION_TYPE: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_GUEST_EVENT_UNION_TYPE: u8 = 5; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_GUEST_EVENT_UNION_TYPE: [GuestEventUnionType; 6] = [ - GuestEventUnionType::NONE, - GuestEventUnionType::OpenSpan, - GuestEventUnionType::CloseSpan, - GuestEventUnionType::LogEvent, - GuestEventUnionType::EditSpan, - GuestEventUnionType::GuestStart, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct GuestEventUnionType(pub u8); -#[allow(non_upper_case_globals)] -impl GuestEventUnionType { - pub const NONE: Self = Self(0); - pub const OpenSpan: Self = Self(1); - pub const CloseSpan: Self = Self(2); - pub const LogEvent: Self = Self(3); - pub const EditSpan: Self = Self(4); - pub const GuestStart: Self = Self(5); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 5; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::OpenSpan, - Self::CloseSpan, - Self::LogEvent, - Self::EditSpan, - Self::GuestStart, - ]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::OpenSpan => Some("OpenSpan"), - Self::CloseSpan => Some("CloseSpan"), - Self::LogEvent => Some("LogEvent"), - Self::EditSpan => Some("EditSpan"), - Self::GuestStart => Some("GuestStart"), - _ => None, - } - } -} -impl core::fmt::Debug for GuestEventUnionType { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for GuestEventUnionType { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for GuestEventUnionType { - type Output = GuestEventUnionType; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for GuestEventUnionType { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for GuestEventUnionType { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for GuestEventUnionType {} -pub struct GuestEventUnionTypeUnionTableOffset {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_log_data_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_log_data_generated.rs deleted file mode 100644 index d3de70427c..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_log_data_generated.rs +++ /dev/null @@ -1,237 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum GuestLogDataOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct GuestLogData<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for GuestLogData<'a> { - type Inner = GuestLogData<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> GuestLogData<'a> { - pub const VT_MESSAGE: flatbuffers::VOffsetT = 4; - pub const VT_SOURCE: flatbuffers::VOffsetT = 6; - pub const VT_LEVEL: flatbuffers::VOffsetT = 8; - pub const VT_CALLER: flatbuffers::VOffsetT = 10; - pub const VT_SOURCE_FILE: flatbuffers::VOffsetT = 12; - pub const VT_LINE: flatbuffers::VOffsetT = 14; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - GuestLogData { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args GuestLogDataArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = GuestLogDataBuilder::new(_fbb); - builder.add_line(args.line); - if let Some(x) = args.source_file { - builder.add_source_file(x); - } - if let Some(x) = args.caller { - builder.add_caller(x); - } - if let Some(x) = args.source { - builder.add_source(x); - } - if let Some(x) = args.message { - builder.add_message(x); - } - builder.add_level(args.level); - builder.finish() - } - - #[inline] - pub fn message(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(GuestLogData::VT_MESSAGE, None) - } - } - #[inline] - pub fn source(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(GuestLogData::VT_SOURCE, None) - } - } - #[inline] - pub fn level(&self) -> LogLevel { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(GuestLogData::VT_LEVEL, Some(LogLevel::Trace)) - .unwrap() - } - } - #[inline] - pub fn caller(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(GuestLogData::VT_CALLER, None) - } - } - #[inline] - pub fn source_file(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(GuestLogData::VT_SOURCE_FILE, None) - } - } - #[inline] - pub fn line(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(GuestLogData::VT_LINE, Some(0)) - .unwrap() - } - } -} - -impl flatbuffers::Verifiable for GuestLogData<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::>("message", Self::VT_MESSAGE, false)? - .visit_field::>("source", Self::VT_SOURCE, false)? - .visit_field::("level", Self::VT_LEVEL, false)? - .visit_field::>("caller", Self::VT_CALLER, false)? - .visit_field::>( - "source_file", - Self::VT_SOURCE_FILE, - false, - )? - .visit_field::("line", Self::VT_LINE, false)? - .finish(); - Ok(()) - } -} -pub struct GuestLogDataArgs<'a> { - pub message: Option>, - pub source: Option>, - pub level: LogLevel, - pub caller: Option>, - pub source_file: Option>, - pub line: u32, -} -impl<'a> Default for GuestLogDataArgs<'a> { - #[inline] - fn default() -> Self { - GuestLogDataArgs { - message: None, - source: None, - level: LogLevel::Trace, - caller: None, - source_file: None, - line: 0, - } - } -} - -pub struct GuestLogDataBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> GuestLogDataBuilder<'a, 'b, A> { - #[inline] - pub fn add_message(&mut self, message: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(GuestLogData::VT_MESSAGE, message); - } - #[inline] - pub fn add_source(&mut self, source: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(GuestLogData::VT_SOURCE, source); - } - #[inline] - pub fn add_level(&mut self, level: LogLevel) { - self.fbb_ - .push_slot::(GuestLogData::VT_LEVEL, level, LogLevel::Trace); - } - #[inline] - pub fn add_caller(&mut self, caller: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(GuestLogData::VT_CALLER, caller); - } - #[inline] - pub fn add_source_file(&mut self, source_file: flatbuffers::WIPOffset<&'b str>) { - self.fbb_.push_slot_always::>( - GuestLogData::VT_SOURCE_FILE, - source_file, - ); - } - #[inline] - pub fn add_line(&mut self, line: u32) { - self.fbb_.push_slot::(GuestLogData::VT_LINE, line, 0); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> GuestLogDataBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - GuestLogDataBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for GuestLogData<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("GuestLogData"); - ds.field("message", &self.message()); - ds.field("source", &self.source()); - ds.field("level", &self.level()); - ds.field("caller", &self.caller()); - ds.field("source_file", &self.source_file()); - ds.field("line", &self.line()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_start_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_start_type_generated.rs deleted file mode 100644 index f47a43f1ba..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/guest_start_type_generated.rs +++ /dev/null @@ -1,115 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum GuestStartTypeOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct GuestStartType<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for GuestStartType<'a> { - type Inner = GuestStartType<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> GuestStartType<'a> { - pub const VT_TSC: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - GuestStartType { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args GuestStartTypeArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = GuestStartTypeBuilder::new(_fbb); - builder.add_tsc(args.tsc); - builder.finish() - } - - #[inline] - pub fn tsc(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(GuestStartType::VT_TSC, Some(0)) - .unwrap() - } - } -} - -impl flatbuffers::Verifiable for GuestStartType<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("tsc", Self::VT_TSC, false)? - .finish(); - Ok(()) - } -} -pub struct GuestStartTypeArgs { - pub tsc: u64, -} -impl<'a> Default for GuestStartTypeArgs { - #[inline] - fn default() -> Self { - GuestStartTypeArgs { tsc: 0 } - } -} - -pub struct GuestStartTypeBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> GuestStartTypeBuilder<'a, 'b, A> { - #[inline] - pub fn add_tsc(&mut self, tsc: u64) { - self.fbb_.push_slot::(GuestStartType::VT_TSC, tsc, 0); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> GuestStartTypeBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - GuestStartTypeBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for GuestStartType<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("GuestStartType"); - ds.field("tsc", &self.tsc()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlbool_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlbool_generated.rs deleted file mode 100644 index c4a2b6673f..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlbool_generated.rs +++ /dev/null @@ -1,113 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hlboolOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hlbool<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hlbool<'a> { - type Inner = hlbool<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hlbool<'a> { - pub const VT_VALUE: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hlbool { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hlboolArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hlboolBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() - } - - #[inline] - pub fn value(&self) -> bool { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(hlbool::VT_VALUE, Some(false)) - .unwrap() - } - } -} - -impl flatbuffers::Verifiable for hlbool<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } -} -pub struct hlboolArgs { - pub value: bool, -} -impl<'a> Default for hlboolArgs { - #[inline] - fn default() -> Self { - hlboolArgs { value: false } - } -} - -pub struct hlboolBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hlboolBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: bool) { - self.fbb_.push_slot::(hlbool::VT_VALUE, value, false); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hlboolBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hlboolBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hlbool<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hlbool"); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hldouble_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hldouble_generated.rs deleted file mode 100644 index 0cbabb8b1a..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hldouble_generated.rs +++ /dev/null @@ -1,109 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hldoubleOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hldouble<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hldouble<'a> { - type Inner = hldouble<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hldouble<'a> { - pub const VT_VALUE: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hldouble { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hldoubleArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hldoubleBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() - } - - #[inline] - pub fn value(&self) -> f64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(hldouble::VT_VALUE, Some(0.0)).unwrap() } - } -} - -impl flatbuffers::Verifiable for hldouble<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } -} -pub struct hldoubleArgs { - pub value: f64, -} -impl<'a> Default for hldoubleArgs { - #[inline] - fn default() -> Self { - hldoubleArgs { value: 0.0 } - } -} - -pub struct hldoubleBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hldoubleBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: f64) { - self.fbb_.push_slot::(hldouble::VT_VALUE, value, 0.0); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hldoubleBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hldoubleBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hldouble<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hldouble"); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlexternalbytes_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlexternalbytes_generated.rs deleted file mode 100644 index d984c1bb85..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlexternalbytes_generated.rs +++ /dev/null @@ -1,140 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hlexternalbytesOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hlexternalbytes<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hlexternalbytes<'a> { - type Inner = hlexternalbytes<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hlexternalbytes<'a> { - pub const VT_LENGTH: flatbuffers::VOffsetT = 4; - pub const VT_CHUNKED: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hlexternalbytes { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hlexternalbytesArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hlexternalbytesBuilder::new(_fbb); - builder.add_length(args.length); - builder.add_chunked(args.chunked); - builder.finish() - } - - #[inline] - pub fn length(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(hlexternalbytes::VT_LENGTH, Some(0)) - .unwrap() - } - } - #[inline] - pub fn chunked(&self) -> bool { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(hlexternalbytes::VT_CHUNKED, Some(false)) - .unwrap() - } - } -} - -impl flatbuffers::Verifiable for hlexternalbytes<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("length", Self::VT_LENGTH, false)? - .visit_field::("chunked", Self::VT_CHUNKED, false)? - .finish(); - Ok(()) - } -} -pub struct hlexternalbytesArgs { - pub length: u64, - pub chunked: bool, -} -impl<'a> Default for hlexternalbytesArgs { - #[inline] - fn default() -> Self { - hlexternalbytesArgs { - length: 0, - chunked: false, - } - } -} - -pub struct hlexternalbytesBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hlexternalbytesBuilder<'a, 'b, A> { - #[inline] - pub fn add_length(&mut self, length: u64) { - self.fbb_ - .push_slot::(hlexternalbytes::VT_LENGTH, length, 0); - } - #[inline] - pub fn add_chunked(&mut self, chunked: bool) { - self.fbb_ - .push_slot::(hlexternalbytes::VT_CHUNKED, chunked, false); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> hlexternalbytesBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hlexternalbytesBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hlexternalbytes<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hlexternalbytes"); - ds.field("length", &self.length()); - ds.field("chunked", &self.chunked()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlfloat_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlfloat_generated.rs deleted file mode 100644 index ca59467d49..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlfloat_generated.rs +++ /dev/null @@ -1,109 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hlfloatOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hlfloat<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hlfloat<'a> { - type Inner = hlfloat<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hlfloat<'a> { - pub const VT_VALUE: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hlfloat { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hlfloatArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hlfloatBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() - } - - #[inline] - pub fn value(&self) -> f32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(hlfloat::VT_VALUE, Some(0.0)).unwrap() } - } -} - -impl flatbuffers::Verifiable for hlfloat<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } -} -pub struct hlfloatArgs { - pub value: f32, -} -impl<'a> Default for hlfloatArgs { - #[inline] - fn default() -> Self { - hlfloatArgs { value: 0.0 } - } -} - -pub struct hlfloatBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hlfloatBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: f32) { - self.fbb_.push_slot::(hlfloat::VT_VALUE, value, 0.0); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hlfloatBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hlfloatBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hlfloat<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hlfloat"); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlint_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlint_generated.rs deleted file mode 100644 index 726f3ba29f..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlint_generated.rs +++ /dev/null @@ -1,109 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hlintOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hlint<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hlint<'a> { - type Inner = hlint<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hlint<'a> { - pub const VT_VALUE: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hlint { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hlintArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hlintBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() - } - - #[inline] - pub fn value(&self) -> i32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(hlint::VT_VALUE, Some(0)).unwrap() } - } -} - -impl flatbuffers::Verifiable for hlint<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } -} -pub struct hlintArgs { - pub value: i32, -} -impl<'a> Default for hlintArgs { - #[inline] - fn default() -> Self { - hlintArgs { value: 0 } - } -} - -pub struct hlintBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hlintBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: i32) { - self.fbb_.push_slot::(hlint::VT_VALUE, value, 0); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hlintBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hlintBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hlint<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hlint"); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hllong_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hllong_generated.rs deleted file mode 100644 index 7c088ff8ca..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hllong_generated.rs +++ /dev/null @@ -1,109 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hllongOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hllong<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hllong<'a> { - type Inner = hllong<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hllong<'a> { - pub const VT_VALUE: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hllong { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hllongArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hllongBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() - } - - #[inline] - pub fn value(&self) -> i64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(hllong::VT_VALUE, Some(0)).unwrap() } - } -} - -impl flatbuffers::Verifiable for hllong<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } -} -pub struct hllongArgs { - pub value: i64, -} -impl<'a> Default for hllongArgs { - #[inline] - fn default() -> Self { - hllongArgs { value: 0 } - } -} - -pub struct hllongBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hllongBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: i64) { - self.fbb_.push_slot::(hllong::VT_VALUE, value, 0); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hllongBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hllongBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hllong<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hllong"); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlstring_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlstring_generated.rs deleted file mode 100644 index cb2d7db098..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlstring_generated.rs +++ /dev/null @@ -1,115 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hlstringOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hlstring<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hlstring<'a> { - type Inner = hlstring<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hlstring<'a> { - pub const VT_VALUE: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hlstring { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hlstringArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = hlstringBuilder::new(_fbb); - if let Some(x) = args.value { - builder.add_value(x); - } - builder.finish() - } - - #[inline] - pub fn value(&self) -> Option<&'a str> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(hlstring::VT_VALUE, None) - } - } -} - -impl flatbuffers::Verifiable for hlstring<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::>("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } -} -pub struct hlstringArgs<'a> { - pub value: Option>, -} -impl<'a> Default for hlstringArgs<'a> { - #[inline] - fn default() -> Self { - hlstringArgs { value: None } - } -} - -pub struct hlstringBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hlstringBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(hlstring::VT_VALUE, value); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hlstringBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hlstringBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hlstring<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hlstring"); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hluint_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hluint_generated.rs deleted file mode 100644 index 67f8cbd6d3..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hluint_generated.rs +++ /dev/null @@ -1,109 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hluintOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hluint<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hluint<'a> { - type Inner = hluint<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hluint<'a> { - pub const VT_VALUE: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hluint { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hluintArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hluintBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() - } - - #[inline] - pub fn value(&self) -> u32 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(hluint::VT_VALUE, Some(0)).unwrap() } - } -} - -impl flatbuffers::Verifiable for hluint<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } -} -pub struct hluintArgs { - pub value: u32, -} -impl<'a> Default for hluintArgs { - #[inline] - fn default() -> Self { - hluintArgs { value: 0 } - } -} - -pub struct hluintBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hluintBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: u32) { - self.fbb_.push_slot::(hluint::VT_VALUE, value, 0); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hluintBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hluintBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hluint<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hluint"); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlulong_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlulong_generated.rs deleted file mode 100644 index f701f3d6cd..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlulong_generated.rs +++ /dev/null @@ -1,109 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hlulongOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hlulong<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hlulong<'a> { - type Inner = hlulong<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hlulong<'a> { - pub const VT_VALUE: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hlulong { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args hlulongArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hlulongBuilder::new(_fbb); - builder.add_value(args.value); - builder.finish() - } - - #[inline] - pub fn value(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(hlulong::VT_VALUE, Some(0)).unwrap() } - } -} - -impl flatbuffers::Verifiable for hlulong<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("value", Self::VT_VALUE, false)? - .finish(); - Ok(()) - } -} -pub struct hlulongArgs { - pub value: u64, -} -impl<'a> Default for hlulongArgs { - #[inline] - fn default() -> Self { - hlulongArgs { value: 0 } - } -} - -pub struct hlulongBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hlulongBuilder<'a, 'b, A> { - #[inline] - pub fn add_value(&mut self, value: u64) { - self.fbb_.push_slot::(hlulong::VT_VALUE, value, 0); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hlulongBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hlulongBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hlulong<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hlulong"); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlvoid_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlvoid_generated.rs deleted file mode 100644 index a218c60baa..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/hlvoid_generated.rs +++ /dev/null @@ -1,89 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum hlvoidOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct hlvoid<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for hlvoid<'a> { - type Inner = hlvoid<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> hlvoid<'a> { - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - hlvoid { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - _args: &'args hlvoidArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = hlvoidBuilder::new(_fbb); - builder.finish() - } -} - -impl flatbuffers::Verifiable for hlvoid<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)?.finish(); - Ok(()) - } -} -pub struct hlvoidArgs {} -impl<'a> Default for hlvoidArgs { - #[inline] - fn default() -> Self { - hlvoidArgs {} - } -} - -pub struct hlvoidBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> hlvoidBuilder<'a, 'b, A> { - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> hlvoidBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - hlvoidBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for hlvoid<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("hlvoid"); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/host_function_definition_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/host_function_definition_generated.rs deleted file mode 100644 index 8ffb6f35eb..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/host_function_definition_generated.rs +++ /dev/null @@ -1,204 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum HostFunctionDefinitionOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct HostFunctionDefinition<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for HostFunctionDefinition<'a> { - type Inner = HostFunctionDefinition<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> HostFunctionDefinition<'a> { - pub const VT_FUNCTION_NAME: flatbuffers::VOffsetT = 4; - pub const VT_PARAMETERS: flatbuffers::VOffsetT = 6; - pub const VT_RETURN_TYPE: flatbuffers::VOffsetT = 8; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - HostFunctionDefinition { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args HostFunctionDefinitionArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = HostFunctionDefinitionBuilder::new(_fbb); - if let Some(x) = args.parameters { - builder.add_parameters(x); - } - if let Some(x) = args.function_name { - builder.add_function_name(x); - } - builder.add_return_type(args.return_type); - builder.finish() - } - - #[inline] - pub fn function_name(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>( - HostFunctionDefinition::VT_FUNCTION_NAME, - None, - ) - .unwrap() - } - } - #[inline] - pub fn key_compare_less_than(&self, o: &HostFunctionDefinition) -> bool { - self.function_name() < o.function_name() - } - - #[inline] - pub fn key_compare_with_value(&self, val: &str) -> ::core::cmp::Ordering { - let key = self.function_name(); - key.cmp(val) - } - #[inline] - pub fn parameters(&self) -> Option> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>>( - HostFunctionDefinition::VT_PARAMETERS, - None, - ) - } - } - #[inline] - pub fn return_type(&self) -> ReturnType { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::( - HostFunctionDefinition::VT_RETURN_TYPE, - Some(ReturnType::hlint), - ) - .unwrap() - } - } -} - -impl flatbuffers::Verifiable for HostFunctionDefinition<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::>( - "function_name", - Self::VT_FUNCTION_NAME, - true, - )? - .visit_field::>>( - "parameters", - Self::VT_PARAMETERS, - false, - )? - .visit_field::("return_type", Self::VT_RETURN_TYPE, false)? - .finish(); - Ok(()) - } -} -pub struct HostFunctionDefinitionArgs<'a> { - pub function_name: Option>, - pub parameters: Option>>, - pub return_type: ReturnType, -} -impl<'a> Default for HostFunctionDefinitionArgs<'a> { - #[inline] - fn default() -> Self { - HostFunctionDefinitionArgs { - function_name: None, // required field - parameters: None, - return_type: ReturnType::hlint, - } - } -} - -pub struct HostFunctionDefinitionBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> HostFunctionDefinitionBuilder<'a, 'b, A> { - #[inline] - pub fn add_function_name(&mut self, function_name: flatbuffers::WIPOffset<&'b str>) { - self.fbb_.push_slot_always::>( - HostFunctionDefinition::VT_FUNCTION_NAME, - function_name, - ); - } - #[inline] - pub fn add_parameters( - &mut self, - parameters: flatbuffers::WIPOffset>, - ) { - self.fbb_.push_slot_always::>( - HostFunctionDefinition::VT_PARAMETERS, - parameters, - ); - } - #[inline] - pub fn add_return_type(&mut self, return_type: ReturnType) { - self.fbb_.push_slot::( - HostFunctionDefinition::VT_RETURN_TYPE, - return_type, - ReturnType::hlint, - ); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> HostFunctionDefinitionBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - HostFunctionDefinitionBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_ - .required(o, HostFunctionDefinition::VT_FUNCTION_NAME, "function_name"); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for HostFunctionDefinition<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("HostFunctionDefinition"); - ds.field("function_name", &self.function_name()); - ds.field("parameters", &self.parameters()); - ds.field("return_type", &self.return_type()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/host_function_details_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/host_function_details_generated.rs deleted file mode 100644 index 54cf45c736..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/host_function_details_generated.rs +++ /dev/null @@ -1,134 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum HostFunctionDetailsOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct HostFunctionDetails<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for HostFunctionDetails<'a> { - type Inner = HostFunctionDetails<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> HostFunctionDetails<'a> { - pub const VT_FUNCTIONS: flatbuffers::VOffsetT = 4; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - HostFunctionDetails { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args HostFunctionDetailsArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = HostFunctionDetailsBuilder::new(_fbb); - if let Some(x) = args.functions { - builder.add_functions(x); - } - builder.finish() - } - - #[inline] - pub fn functions( - &self, - ) -> Option>>> - { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab.get::>, - >>(HostFunctionDetails::VT_FUNCTIONS, None) - } - } -} - -impl flatbuffers::Verifiable for HostFunctionDetails<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::>, - >>("functions", Self::VT_FUNCTIONS, false)? - .finish(); - Ok(()) - } -} -pub struct HostFunctionDetailsArgs<'a> { - pub functions: Option< - flatbuffers::WIPOffset< - flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset>>, - >, - >, -} -impl<'a> Default for HostFunctionDetailsArgs<'a> { - #[inline] - fn default() -> Self { - HostFunctionDetailsArgs { functions: None } - } -} - -pub struct HostFunctionDetailsBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> HostFunctionDetailsBuilder<'a, 'b, A> { - #[inline] - pub fn add_functions( - &mut self, - functions: flatbuffers::WIPOffset< - flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset>>, - >, - ) { - self.fbb_.push_slot_always::>( - HostFunctionDetails::VT_FUNCTIONS, - functions, - ); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> HostFunctionDetailsBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - HostFunctionDetailsBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for HostFunctionDetails<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("HostFunctionDetails"); - ds.field("functions", &self.functions()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/key_value_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/key_value_generated.rs deleted file mode 100644 index 06516b4a6e..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/key_value_generated.rs +++ /dev/null @@ -1,144 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum KeyValueOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct KeyValue<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for KeyValue<'a> { - type Inner = KeyValue<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> KeyValue<'a> { - pub const VT_KEY: flatbuffers::VOffsetT = 4; - pub const VT_VALUE: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - KeyValue { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args KeyValueArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = KeyValueBuilder::new(_fbb); - if let Some(x) = args.value { - builder.add_value(x); - } - if let Some(x) = args.key { - builder.add_key(x); - } - builder.finish() - } - - #[inline] - pub fn key(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(KeyValue::VT_KEY, None) - .unwrap() - } - } - #[inline] - pub fn value(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(KeyValue::VT_VALUE, None) - .unwrap() - } - } -} - -impl flatbuffers::Verifiable for KeyValue<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::>("key", Self::VT_KEY, true)? - .visit_field::>("value", Self::VT_VALUE, true)? - .finish(); - Ok(()) - } -} -pub struct KeyValueArgs<'a> { - pub key: Option>, - pub value: Option>, -} -impl<'a> Default for KeyValueArgs<'a> { - #[inline] - fn default() -> Self { - KeyValueArgs { - key: None, // required field - value: None, // required field - } - } -} - -pub struct KeyValueBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> KeyValueBuilder<'a, 'b, A> { - #[inline] - pub fn add_key(&mut self, key: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(KeyValue::VT_KEY, key); - } - #[inline] - pub fn add_value(&mut self, value: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(KeyValue::VT_VALUE, value); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> KeyValueBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - KeyValueBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_.required(o, KeyValue::VT_KEY, "key"); - self.fbb_.required(o, KeyValue::VT_VALUE, "value"); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for KeyValue<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("KeyValue"); - ds.field("key", &self.key()); - ds.field("value", &self.value()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/log_event_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/log_event_type_generated.rs deleted file mode 100644 index c78c37a592..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/log_event_type_generated.rs +++ /dev/null @@ -1,195 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum LogEventTypeOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct LogEventType<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for LogEventType<'a> { - type Inner = LogEventType<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> LogEventType<'a> { - pub const VT_PARENT_ID: flatbuffers::VOffsetT = 4; - pub const VT_NAME: flatbuffers::VOffsetT = 6; - pub const VT_TSC: flatbuffers::VOffsetT = 8; - pub const VT_FIELDS: flatbuffers::VOffsetT = 10; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - LogEventType { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args LogEventTypeArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = LogEventTypeBuilder::new(_fbb); - builder.add_tsc(args.tsc); - builder.add_parent_id(args.parent_id); - if let Some(x) = args.fields { - builder.add_fields(x); - } - if let Some(x) = args.name { - builder.add_name(x); - } - builder.finish() - } - - #[inline] - pub fn parent_id(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(LogEventType::VT_PARENT_ID, Some(0)) - .unwrap() - } - } - #[inline] - pub fn name(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(LogEventType::VT_NAME, None) - .unwrap() - } - } - #[inline] - pub fn tsc(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(LogEventType::VT_TSC, Some(0)).unwrap() } - } - #[inline] - pub fn fields( - &self, - ) -> Option>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab.get::>, - >>(LogEventType::VT_FIELDS, None) - } - } -} - -impl flatbuffers::Verifiable for LogEventType<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("parent_id", Self::VT_PARENT_ID, false)? - .visit_field::>("name", Self::VT_NAME, true)? - .visit_field::("tsc", Self::VT_TSC, false)? - .visit_field::>, - >>("fields", Self::VT_FIELDS, false)? - .finish(); - Ok(()) - } -} -pub struct LogEventTypeArgs<'a> { - pub parent_id: u64, - pub name: Option>, - pub tsc: u64, - pub fields: Option< - flatbuffers::WIPOffset>>>, - >, -} -impl<'a> Default for LogEventTypeArgs<'a> { - #[inline] - fn default() -> Self { - LogEventTypeArgs { - parent_id: 0, - name: None, // required field - tsc: 0, - fields: None, - } - } -} - -pub struct LogEventTypeBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> LogEventTypeBuilder<'a, 'b, A> { - #[inline] - pub fn add_parent_id(&mut self, parent_id: u64) { - self.fbb_ - .push_slot::(LogEventType::VT_PARENT_ID, parent_id, 0); - } - #[inline] - pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(LogEventType::VT_NAME, name); - } - #[inline] - pub fn add_tsc(&mut self, tsc: u64) { - self.fbb_.push_slot::(LogEventType::VT_TSC, tsc, 0); - } - #[inline] - pub fn add_fields( - &mut self, - fields: flatbuffers::WIPOffset< - flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset>>, - >, - ) { - self.fbb_ - .push_slot_always::>(LogEventType::VT_FIELDS, fields); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> LogEventTypeBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - LogEventTypeBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_.required(o, LogEventType::VT_NAME, "name"); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for LogEventType<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("LogEventType"); - ds.field("parent_id", &self.parent_id()); - ds.field("name", &self.name()); - ds.field("tsc", &self.tsc()); - ds.field("fields", &self.fields()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/log_level_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/log_level_generated.rs deleted file mode 100644 index 6fb5ce2c62..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/log_level_generated.rs +++ /dev/null @@ -1,129 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_LOG_LEVEL: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_LOG_LEVEL: u8 = 6; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_LOG_LEVEL: [LogLevel; 7] = [ - LogLevel::Trace, - LogLevel::Debug, - LogLevel::Information, - LogLevel::Warning, - LogLevel::Error, - LogLevel::Critical, - LogLevel::None, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct LogLevel(pub u8); -#[allow(non_upper_case_globals)] -impl LogLevel { - pub const Trace: Self = Self(0); - pub const Debug: Self = Self(1); - pub const Information: Self = Self(2); - pub const Warning: Self = Self(3); - pub const Error: Self = Self(4); - pub const Critical: Self = Self(5); - pub const None: Self = Self(6); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 6; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::Trace, - Self::Debug, - Self::Information, - Self::Warning, - Self::Error, - Self::Critical, - Self::None, - ]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::Trace => Some("Trace"), - Self::Debug => Some("Debug"), - Self::Information => Some("Information"), - Self::Warning => Some("Warning"), - Self::Error => Some("Error"), - Self::Critical => Some("Critical"), - Self::None => Some("None"), - _ => None, - } - } -} -impl core::fmt::Debug for LogLevel { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for LogLevel { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for LogLevel { - type Output = LogLevel; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for LogLevel { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for LogLevel { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for LogLevel {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/open_span_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/open_span_type_generated.rs deleted file mode 100644 index d5d9ac8efa..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/open_span_type_generated.rs +++ /dev/null @@ -1,235 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum OpenSpanTypeOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct OpenSpanType<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for OpenSpanType<'a> { - type Inner = OpenSpanType<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> OpenSpanType<'a> { - pub const VT_ID: flatbuffers::VOffsetT = 4; - pub const VT_PARENT: flatbuffers::VOffsetT = 6; - pub const VT_NAME: flatbuffers::VOffsetT = 8; - pub const VT_TARGET: flatbuffers::VOffsetT = 10; - pub const VT_TSC: flatbuffers::VOffsetT = 12; - pub const VT_FIELDS: flatbuffers::VOffsetT = 14; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - OpenSpanType { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args OpenSpanTypeArgs<'args>, - ) -> flatbuffers::WIPOffset> { - let mut builder = OpenSpanTypeBuilder::new(_fbb); - builder.add_tsc(args.tsc); - if let Some(x) = args.parent { - builder.add_parent(x); - } - builder.add_id(args.id); - if let Some(x) = args.fields { - builder.add_fields(x); - } - if let Some(x) = args.target { - builder.add_target(x); - } - if let Some(x) = args.name { - builder.add_name(x); - } - builder.finish() - } - - #[inline] - pub fn id(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(OpenSpanType::VT_ID, Some(0)).unwrap() } - } - #[inline] - pub fn parent(&self) -> Option { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(OpenSpanType::VT_PARENT, None) } - } - #[inline] - pub fn name(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(OpenSpanType::VT_NAME, None) - .unwrap() - } - } - #[inline] - pub fn target(&self) -> &'a str { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>(OpenSpanType::VT_TARGET, None) - .unwrap() - } - } - #[inline] - pub fn tsc(&self) -> u64 { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { self._tab.get::(OpenSpanType::VT_TSC, Some(0)).unwrap() } - } - #[inline] - pub fn fields( - &self, - ) -> Option>>> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab.get::>, - >>(OpenSpanType::VT_FIELDS, None) - } - } -} - -impl flatbuffers::Verifiable for OpenSpanType<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_field::("id", Self::VT_ID, false)? - .visit_field::("parent", Self::VT_PARENT, false)? - .visit_field::>("name", Self::VT_NAME, true)? - .visit_field::>("target", Self::VT_TARGET, true)? - .visit_field::("tsc", Self::VT_TSC, false)? - .visit_field::>, - >>("fields", Self::VT_FIELDS, false)? - .finish(); - Ok(()) - } -} -pub struct OpenSpanTypeArgs<'a> { - pub id: u64, - pub parent: Option, - pub name: Option>, - pub target: Option>, - pub tsc: u64, - pub fields: Option< - flatbuffers::WIPOffset>>>, - >, -} -impl<'a> Default for OpenSpanTypeArgs<'a> { - #[inline] - fn default() -> Self { - OpenSpanTypeArgs { - id: 0, - parent: None, - name: None, // required field - target: None, // required field - tsc: 0, - fields: None, - } - } -} - -pub struct OpenSpanTypeBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> OpenSpanTypeBuilder<'a, 'b, A> { - #[inline] - pub fn add_id(&mut self, id: u64) { - self.fbb_.push_slot::(OpenSpanType::VT_ID, id, 0); - } - #[inline] - pub fn add_parent(&mut self, parent: u64) { - self.fbb_ - .push_slot_always::(OpenSpanType::VT_PARENT, parent); - } - #[inline] - pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(OpenSpanType::VT_NAME, name); - } - #[inline] - pub fn add_target(&mut self, target: flatbuffers::WIPOffset<&'b str>) { - self.fbb_ - .push_slot_always::>(OpenSpanType::VT_TARGET, target); - } - #[inline] - pub fn add_tsc(&mut self, tsc: u64) { - self.fbb_.push_slot::(OpenSpanType::VT_TSC, tsc, 0); - } - #[inline] - pub fn add_fields( - &mut self, - fields: flatbuffers::WIPOffset< - flatbuffers::Vector<'b, flatbuffers::ForwardsUOffset>>, - >, - ) { - self.fbb_ - .push_slot_always::>(OpenSpanType::VT_FIELDS, fields); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> OpenSpanTypeBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - OpenSpanTypeBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_.required(o, OpenSpanType::VT_NAME, "name"); - self.fbb_.required(o, OpenSpanType::VT_TARGET, "target"); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for OpenSpanType<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("OpenSpanType"); - ds.field("id", &self.id()); - ds.field("parent", &self.parent()); - ds.field("name", &self.name()); - ds.field("target", &self.target()); - ds.field("tsc", &self.tsc()); - ds.field("fields", &self.fields()); - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_generated.rs deleted file mode 100644 index ab1beab95f..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_generated.rs +++ /dev/null @@ -1,420 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum ParameterOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct Parameter<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for Parameter<'a> { - type Inner = Parameter<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> Parameter<'a> { - pub const VT_VALUE_TYPE: flatbuffers::VOffsetT = 4; - pub const VT_VALUE: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - Parameter { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args ParameterArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = ParameterBuilder::new(_fbb); - if let Some(x) = args.value { - builder.add_value(x); - } - builder.add_value_type(args.value_type); - builder.finish() - } - - #[inline] - pub fn value_type(&self) -> ParameterValue { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(Parameter::VT_VALUE_TYPE, Some(ParameterValue::NONE)) - .unwrap() - } - } - #[inline] - pub fn value(&self) -> flatbuffers::Table<'a> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>>( - Parameter::VT_VALUE, - None, - ) - .unwrap() - } - } - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlint(&self) -> Option> { - if self.value_type() == ParameterValue::hlint { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlint::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hluint(&self) -> Option> { - if self.value_type() == ParameterValue::hluint { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hluint::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hllong(&self) -> Option> { - if self.value_type() == ParameterValue::hllong { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hllong::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlulong(&self) -> Option> { - if self.value_type() == ParameterValue::hlulong { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlulong::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlfloat(&self) -> Option> { - if self.value_type() == ParameterValue::hlfloat { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlfloat::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hldouble(&self) -> Option> { - if self.value_type() == ParameterValue::hldouble { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hldouble::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlstring(&self) -> Option> { - if self.value_type() == ParameterValue::hlstring { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlstring::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlbool(&self) -> Option> { - if self.value_type() == ParameterValue::hlbool { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlbool::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlexternalbytes(&self) -> Option> { - if self.value_type() == ParameterValue::hlexternalbytes { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlexternalbytes::init_from_table(u) }) - } else { - None - } - } -} - -impl flatbuffers::Verifiable for Parameter<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_union::( - "value_type", - Self::VT_VALUE_TYPE, - "value", - Self::VT_VALUE, - true, - |key, v, pos| match key { - ParameterValue::hlint => v - .verify_union_variant::>( - "ParameterValue::hlint", - pos, - ), - ParameterValue::hluint => v - .verify_union_variant::>( - "ParameterValue::hluint", - pos, - ), - ParameterValue::hllong => v - .verify_union_variant::>( - "ParameterValue::hllong", - pos, - ), - ParameterValue::hlulong => v - .verify_union_variant::>( - "ParameterValue::hlulong", - pos, - ), - ParameterValue::hlfloat => v - .verify_union_variant::>( - "ParameterValue::hlfloat", - pos, - ), - ParameterValue::hldouble => v - .verify_union_variant::>( - "ParameterValue::hldouble", - pos, - ), - ParameterValue::hlstring => v - .verify_union_variant::>( - "ParameterValue::hlstring", - pos, - ), - ParameterValue::hlbool => v - .verify_union_variant::>( - "ParameterValue::hlbool", - pos, - ), - ParameterValue::hlexternalbytes => v - .verify_union_variant::>( - "ParameterValue::hlexternalbytes", - pos, - ), - _ => Ok(()), - }, - )? - .finish(); - Ok(()) - } -} -pub struct ParameterArgs { - pub value_type: ParameterValue, - pub value: Option>, -} -impl<'a> Default for ParameterArgs { - #[inline] - fn default() -> Self { - ParameterArgs { - value_type: ParameterValue::NONE, - value: None, // required field - } - } -} - -pub struct ParameterBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> ParameterBuilder<'a, 'b, A> { - #[inline] - pub fn add_value_type(&mut self, value_type: ParameterValue) { - self.fbb_.push_slot::( - Parameter::VT_VALUE_TYPE, - value_type, - ParameterValue::NONE, - ); - } - #[inline] - pub fn add_value(&mut self, value: flatbuffers::WIPOffset) { - self.fbb_ - .push_slot_always::>(Parameter::VT_VALUE, value); - } - #[inline] - pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> ParameterBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - ParameterBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_.required(o, Parameter::VT_VALUE, "value"); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for Parameter<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("Parameter"); - ds.field("value_type", &self.value_type()); - match self.value_type() { - ParameterValue::hlint => { - if let Some(x) = self.value_as_hlint() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ParameterValue::hluint => { - if let Some(x) = self.value_as_hluint() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ParameterValue::hllong => { - if let Some(x) = self.value_as_hllong() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ParameterValue::hlulong => { - if let Some(x) = self.value_as_hlulong() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ParameterValue::hlfloat => { - if let Some(x) = self.value_as_hlfloat() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ParameterValue::hldouble => { - if let Some(x) = self.value_as_hldouble() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ParameterValue::hlstring => { - if let Some(x) = self.value_as_hlstring() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ParameterValue::hlbool => { - if let Some(x) = self.value_as_hlbool() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ParameterValue::hlexternalbytes => { - if let Some(x) = self.value_as_hlexternalbytes() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - _ => { - let x: Option<()> = None; - ds.field("value", &x) - } - }; - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_type_generated.rs deleted file mode 100644 index cd280599a0..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_type_generated.rs +++ /dev/null @@ -1,141 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_PARAMETER_TYPE: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_PARAMETER_TYPE: u8 = 9; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_PARAMETER_TYPE: [ParameterType; 10] = [ - ParameterType::hlint, - ParameterType::hluint, - ParameterType::hllong, - ParameterType::hlulong, - ParameterType::hlfloat, - ParameterType::hldouble, - ParameterType::hlstring, - ParameterType::hlbool, - ParameterType::hlvecbytes, - ParameterType::hlbytechunks, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct ParameterType(pub u8); -#[allow(non_upper_case_globals)] -impl ParameterType { - pub const hlint: Self = Self(0); - pub const hluint: Self = Self(1); - pub const hllong: Self = Self(2); - pub const hlulong: Self = Self(3); - pub const hlfloat: Self = Self(4); - pub const hldouble: Self = Self(5); - pub const hlstring: Self = Self(6); - pub const hlbool: Self = Self(7); - pub const hlvecbytes: Self = Self(8); - pub const hlbytechunks: Self = Self(9); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 9; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::hlint, - Self::hluint, - Self::hllong, - Self::hlulong, - Self::hlfloat, - Self::hldouble, - Self::hlstring, - Self::hlbool, - Self::hlvecbytes, - Self::hlbytechunks, - ]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::hlint => Some("hlint"), - Self::hluint => Some("hluint"), - Self::hllong => Some("hllong"), - Self::hlulong => Some("hlulong"), - Self::hlfloat => Some("hlfloat"), - Self::hldouble => Some("hldouble"), - Self::hlstring => Some("hlstring"), - Self::hlbool => Some("hlbool"), - Self::hlvecbytes => Some("hlvecbytes"), - Self::hlbytechunks => Some("hlbytechunks"), - _ => None, - } - } -} -impl core::fmt::Debug for ParameterType { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for ParameterType { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for ParameterType { - type Output = ParameterType; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for ParameterType { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for ParameterType { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for ParameterType {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_value_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_value_generated.rs deleted file mode 100644 index 80d03d8e24..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/parameter_value_generated.rs +++ /dev/null @@ -1,142 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_PARAMETER_VALUE: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_PARAMETER_VALUE: u8 = 10; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_PARAMETER_VALUE: [ParameterValue; 10] = [ - ParameterValue::NONE, - ParameterValue::hlint, - ParameterValue::hluint, - ParameterValue::hllong, - ParameterValue::hlulong, - ParameterValue::hlfloat, - ParameterValue::hldouble, - ParameterValue::hlstring, - ParameterValue::hlbool, - ParameterValue::hlexternalbytes, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct ParameterValue(pub u8); -#[allow(non_upper_case_globals)] -impl ParameterValue { - pub const NONE: Self = Self(0); - pub const hlint: Self = Self(1); - pub const hluint: Self = Self(2); - pub const hllong: Self = Self(3); - pub const hlulong: Self = Self(4); - pub const hlfloat: Self = Self(5); - pub const hldouble: Self = Self(6); - pub const hlstring: Self = Self(7); - pub const hlbool: Self = Self(8); - pub const hlexternalbytes: Self = Self(10); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 10; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::hlint, - Self::hluint, - Self::hllong, - Self::hlulong, - Self::hlfloat, - Self::hldouble, - Self::hlstring, - Self::hlbool, - Self::hlexternalbytes, - ]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::hlint => Some("hlint"), - Self::hluint => Some("hluint"), - Self::hllong => Some("hllong"), - Self::hlulong => Some("hlulong"), - Self::hlfloat => Some("hlfloat"), - Self::hldouble => Some("hldouble"), - Self::hlstring => Some("hlstring"), - Self::hlbool => Some("hlbool"), - Self::hlexternalbytes => Some("hlexternalbytes"), - _ => None, - } - } -} -impl core::fmt::Debug for ParameterValue { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for ParameterValue { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for ParameterValue { - type Output = ParameterValue; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for ParameterValue { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for ParameterValue { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for ParameterValue {} -pub struct ParameterValueUnionTableOffset {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_type_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_type_generated.rs deleted file mode 100644 index 06ea93d9c5..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_type_generated.rs +++ /dev/null @@ -1,145 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_RETURN_TYPE: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_RETURN_TYPE: u8 = 10; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_RETURN_TYPE: [ReturnType; 11] = [ - ReturnType::hlint, - ReturnType::hluint, - ReturnType::hllong, - ReturnType::hlulong, - ReturnType::hlfloat, - ReturnType::hldouble, - ReturnType::hlstring, - ReturnType::hlbool, - ReturnType::hlvoid, - ReturnType::hlsizeprefixedbuffer, - ReturnType::hlbytechunks, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct ReturnType(pub u8); -#[allow(non_upper_case_globals)] -impl ReturnType { - pub const hlint: Self = Self(0); - pub const hluint: Self = Self(1); - pub const hllong: Self = Self(2); - pub const hlulong: Self = Self(3); - pub const hlfloat: Self = Self(4); - pub const hldouble: Self = Self(5); - pub const hlstring: Self = Self(6); - pub const hlbool: Self = Self(7); - pub const hlvoid: Self = Self(8); - pub const hlsizeprefixedbuffer: Self = Self(9); - pub const hlbytechunks: Self = Self(10); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 10; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::hlint, - Self::hluint, - Self::hllong, - Self::hlulong, - Self::hlfloat, - Self::hldouble, - Self::hlstring, - Self::hlbool, - Self::hlvoid, - Self::hlsizeprefixedbuffer, - Self::hlbytechunks, - ]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::hlint => Some("hlint"), - Self::hluint => Some("hluint"), - Self::hllong => Some("hllong"), - Self::hlulong => Some("hlulong"), - Self::hlfloat => Some("hlfloat"), - Self::hldouble => Some("hldouble"), - Self::hlstring => Some("hlstring"), - Self::hlbool => Some("hlbool"), - Self::hlvoid => Some("hlvoid"), - Self::hlsizeprefixedbuffer => Some("hlsizeprefixedbuffer"), - Self::hlbytechunks => Some("hlbytechunks"), - _ => None, - } - } -} -impl core::fmt::Debug for ReturnType { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for ReturnType { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for ReturnType { - type Output = ReturnType; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for ReturnType { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for ReturnType { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for ReturnType {} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_value_box_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_value_box_generated.rs deleted file mode 100644 index 170924acdf..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_value_box_generated.rs +++ /dev/null @@ -1,451 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -pub enum ReturnValueBoxOffset {} -#[derive(Copy, Clone, PartialEq)] - -pub struct ReturnValueBox<'a> { - pub _tab: flatbuffers::Table<'a>, -} - -impl<'a> flatbuffers::Follow<'a> for ReturnValueBox<'a> { - type Inner = ReturnValueBox<'a>; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - Self { - _tab: unsafe { flatbuffers::Table::new(buf, loc) }, - } - } -} - -impl<'a> ReturnValueBox<'a> { - pub const VT_VALUE_TYPE: flatbuffers::VOffsetT = 4; - pub const VT_VALUE: flatbuffers::VOffsetT = 6; - - #[inline] - pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { - ReturnValueBox { _tab: table } - } - #[allow(unused_mut)] - pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( - _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, - args: &'args ReturnValueBoxArgs, - ) -> flatbuffers::WIPOffset> { - let mut builder = ReturnValueBoxBuilder::new(_fbb); - if let Some(x) = args.value { - builder.add_value(x); - } - builder.add_value_type(args.value_type); - builder.finish() - } - - #[inline] - pub fn value_type(&self) -> ReturnValue { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::(ReturnValueBox::VT_VALUE_TYPE, Some(ReturnValue::NONE)) - .unwrap() - } - } - #[inline] - pub fn value(&self) -> flatbuffers::Table<'a> { - // Safety: - // Created from valid Table for this object - // which contains a valid value in this slot - unsafe { - self._tab - .get::>>( - ReturnValueBox::VT_VALUE, - None, - ) - .unwrap() - } - } - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlint(&self) -> Option> { - if self.value_type() == ReturnValue::hlint { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlint::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hluint(&self) -> Option> { - if self.value_type() == ReturnValue::hluint { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hluint::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hllong(&self) -> Option> { - if self.value_type() == ReturnValue::hllong { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hllong::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlulong(&self) -> Option> { - if self.value_type() == ReturnValue::hlulong { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlulong::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlfloat(&self) -> Option> { - if self.value_type() == ReturnValue::hlfloat { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlfloat::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hldouble(&self) -> Option> { - if self.value_type() == ReturnValue::hldouble { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hldouble::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlstring(&self) -> Option> { - if self.value_type() == ReturnValue::hlstring { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlstring::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlbool(&self) -> Option> { - if self.value_type() == ReturnValue::hlbool { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlbool::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlvoid(&self) -> Option> { - if self.value_type() == ReturnValue::hlvoid { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlvoid::init_from_table(u) }) - } else { - None - } - } - - #[inline] - #[allow(non_snake_case)] - pub fn value_as_hlexternalbytes(&self) -> Option> { - if self.value_type() == ReturnValue::hlexternalbytes { - let u = self.value(); - // Safety: - // Created from a valid Table for this object - // Which contains a valid union in this slot - Some(unsafe { hlexternalbytes::init_from_table(u) }) - } else { - None - } - } -} - -impl flatbuffers::Verifiable for ReturnValueBox<'_> { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - v.visit_table(pos)? - .visit_union::( - "value_type", - Self::VT_VALUE_TYPE, - "value", - Self::VT_VALUE, - true, - |key, v, pos| match key { - ReturnValue::hlint => v - .verify_union_variant::>( - "ReturnValue::hlint", - pos, - ), - ReturnValue::hluint => v - .verify_union_variant::>( - "ReturnValue::hluint", - pos, - ), - ReturnValue::hllong => v - .verify_union_variant::>( - "ReturnValue::hllong", - pos, - ), - ReturnValue::hlulong => v - .verify_union_variant::>( - "ReturnValue::hlulong", - pos, - ), - ReturnValue::hlfloat => v - .verify_union_variant::>( - "ReturnValue::hlfloat", - pos, - ), - ReturnValue::hldouble => v - .verify_union_variant::>( - "ReturnValue::hldouble", - pos, - ), - ReturnValue::hlstring => v - .verify_union_variant::>( - "ReturnValue::hlstring", - pos, - ), - ReturnValue::hlbool => v - .verify_union_variant::>( - "ReturnValue::hlbool", - pos, - ), - ReturnValue::hlvoid => v - .verify_union_variant::>( - "ReturnValue::hlvoid", - pos, - ), - ReturnValue::hlexternalbytes => v - .verify_union_variant::>( - "ReturnValue::hlexternalbytes", - pos, - ), - _ => Ok(()), - }, - )? - .finish(); - Ok(()) - } -} -pub struct ReturnValueBoxArgs { - pub value_type: ReturnValue, - pub value: Option>, -} -impl<'a> Default for ReturnValueBoxArgs { - #[inline] - fn default() -> Self { - ReturnValueBoxArgs { - value_type: ReturnValue::NONE, - value: None, // required field - } - } -} - -pub struct ReturnValueBoxBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { - fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - start_: flatbuffers::WIPOffset, -} -impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> ReturnValueBoxBuilder<'a, 'b, A> { - #[inline] - pub fn add_value_type(&mut self, value_type: ReturnValue) { - self.fbb_.push_slot::( - ReturnValueBox::VT_VALUE_TYPE, - value_type, - ReturnValue::NONE, - ); - } - #[inline] - pub fn add_value(&mut self, value: flatbuffers::WIPOffset) { - self.fbb_ - .push_slot_always::>(ReturnValueBox::VT_VALUE, value); - } - #[inline] - pub fn new( - _fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, - ) -> ReturnValueBoxBuilder<'a, 'b, A> { - let start = _fbb.start_table(); - ReturnValueBoxBuilder { - fbb_: _fbb, - start_: start, - } - } - #[inline] - pub fn finish(self) -> flatbuffers::WIPOffset> { - let o = self.fbb_.end_table(self.start_); - self.fbb_.required(o, ReturnValueBox::VT_VALUE, "value"); - flatbuffers::WIPOffset::new(o.value()) - } -} - -impl core::fmt::Debug for ReturnValueBox<'_> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let mut ds = f.debug_struct("ReturnValueBox"); - ds.field("value_type", &self.value_type()); - match self.value_type() { - ReturnValue::hlint => { - if let Some(x) = self.value_as_hlint() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hluint => { - if let Some(x) = self.value_as_hluint() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hllong => { - if let Some(x) = self.value_as_hllong() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hlulong => { - if let Some(x) = self.value_as_hlulong() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hlfloat => { - if let Some(x) = self.value_as_hlfloat() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hldouble => { - if let Some(x) = self.value_as_hldouble() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hlstring => { - if let Some(x) = self.value_as_hlstring() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hlbool => { - if let Some(x) = self.value_as_hlbool() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hlvoid => { - if let Some(x) = self.value_as_hlvoid() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - ReturnValue::hlexternalbytes => { - if let Some(x) = self.value_as_hlexternalbytes() { - ds.field("value", &x) - } else { - ds.field( - "value", - &"InvalidFlatbuffer: Union discriminant does not match value.", - ) - } - } - _ => { - let x: Option<()> = None; - ds.field("value", &x) - } - }; - ds.finish() - } -} diff --git a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_value_generated.rs b/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_value_generated.rs deleted file mode 100644 index 9e943036e8..0000000000 --- a/src/hyperlight_common/src/flatbuffers/hyperlight/generated/return_value_generated.rs +++ /dev/null @@ -1,146 +0,0 @@ -// automatically generated by the FlatBuffers compiler, do not modify -// @generated -extern crate alloc; -extern crate flatbuffers; -use alloc::boxed::Box; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; -use core::cmp::Ordering; -use core::mem; - -use self::flatbuffers::{EndianScalar, Follow}; -use super::*; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MIN_RETURN_VALUE: u8 = 0; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -pub const ENUM_MAX_RETURN_VALUE: u8 = 11; -#[deprecated( - since = "2.0.0", - note = "Use associated constants instead. This will no longer be generated in 2021." -)] -#[allow(non_camel_case_types)] -pub const ENUM_VALUES_RETURN_VALUE: [ReturnValue; 11] = [ - ReturnValue::NONE, - ReturnValue::hlint, - ReturnValue::hluint, - ReturnValue::hllong, - ReturnValue::hlulong, - ReturnValue::hlfloat, - ReturnValue::hldouble, - ReturnValue::hlstring, - ReturnValue::hlbool, - ReturnValue::hlvoid, - ReturnValue::hlexternalbytes, -]; - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[repr(transparent)] -pub struct ReturnValue(pub u8); -#[allow(non_upper_case_globals)] -impl ReturnValue { - pub const NONE: Self = Self(0); - pub const hlint: Self = Self(1); - pub const hluint: Self = Self(2); - pub const hllong: Self = Self(3); - pub const hlulong: Self = Self(4); - pub const hlfloat: Self = Self(5); - pub const hldouble: Self = Self(6); - pub const hlstring: Self = Self(7); - pub const hlbool: Self = Self(8); - pub const hlvoid: Self = Self(9); - pub const hlexternalbytes: Self = Self(11); - - pub const ENUM_MIN: u8 = 0; - pub const ENUM_MAX: u8 = 11; - pub const ENUM_VALUES: &'static [Self] = &[ - Self::NONE, - Self::hlint, - Self::hluint, - Self::hllong, - Self::hlulong, - Self::hlfloat, - Self::hldouble, - Self::hlstring, - Self::hlbool, - Self::hlvoid, - Self::hlexternalbytes, - ]; - /// Returns the variant's name or "" if unknown. - pub fn variant_name(self) -> Option<&'static str> { - match self { - Self::NONE => Some("NONE"), - Self::hlint => Some("hlint"), - Self::hluint => Some("hluint"), - Self::hllong => Some("hllong"), - Self::hlulong => Some("hlulong"), - Self::hlfloat => Some("hlfloat"), - Self::hldouble => Some("hldouble"), - Self::hlstring => Some("hlstring"), - Self::hlbool => Some("hlbool"), - Self::hlvoid => Some("hlvoid"), - Self::hlexternalbytes => Some("hlexternalbytes"), - _ => None, - } - } -} -impl core::fmt::Debug for ReturnValue { - fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - if let Some(name) = self.variant_name() { - f.write_str(name) - } else { - f.write_fmt(format_args!("", self.0)) - } - } -} -impl<'a> flatbuffers::Follow<'a> for ReturnValue { - type Inner = Self; - #[inline] - unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { - let b = unsafe { flatbuffers::read_scalar_at::(buf, loc) }; - Self(b) - } -} - -impl flatbuffers::Push for ReturnValue { - type Output = ReturnValue; - #[inline] - unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - unsafe { - flatbuffers::emplace_scalar::(dst, self.0); - } - } -} - -impl flatbuffers::EndianScalar for ReturnValue { - type Scalar = u8; - #[inline] - fn to_little_endian(self) -> u8 { - self.0.to_le() - } - #[inline] - #[allow(clippy::wrong_self_convention)] - fn from_little_endian(v: u8) -> Self { - let b = u8::from_le(v); - Self(b) - } -} - -impl<'a> flatbuffers::Verifiable for ReturnValue { - #[inline] - fn run_verifier( - v: &mut flatbuffers::Verifier, - pos: usize, - ) -> Result<(), flatbuffers::InvalidFlatbuffer> { - use self::flatbuffers::Verifiable; - u8::run_verifier(v, pos) - } -} - -impl flatbuffers::SimpleToVerifyInSlice for ReturnValue {} -pub struct ReturnValueUnionTableOffset {} diff --git a/src/hyperlight_common/src/flatbuffers/mod.rs b/src/hyperlight_common/src/flatbuffers/mod.rs deleted file mode 100644 index 1982b2836b..0000000000 --- a/src/hyperlight_common/src/flatbuffers/mod.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Automatically generated by the Flatbuffers compiler. Do not modify. -// @generated -pub mod hyperlight { - use super::*; - pub mod generated { - use super::*; - mod parameter_value_generated; - pub use self::parameter_value_generated::*; - mod parameter_type_generated; - pub use self::parameter_type_generated::*; - mod return_type_generated; - pub use self::return_type_generated::*; - mod return_value_generated; - pub use self::return_value_generated::*; - mod error_code_generated; - pub use self::error_code_generated::*; - mod function_call_result_type_generated; - pub use self::function_call_result_type_generated::*; - mod function_call_type_generated; - pub use self::function_call_type_generated::*; - mod log_level_generated; - pub use self::log_level_generated::*; - mod guest_event_type_generated; - pub use self::guest_event_type_generated::*; - mod hlint_generated; - pub use self::hlint_generated::*; - mod hluint_generated; - pub use self::hluint_generated::*; - mod hllong_generated; - pub use self::hllong_generated::*; - mod hlulong_generated; - pub use self::hlulong_generated::*; - mod hlfloat_generated; - pub use self::hlfloat_generated::*; - mod hldouble_generated; - pub use self::hldouble_generated::*; - mod hlstring_generated; - pub use self::hlstring_generated::*; - mod hlbool_generated; - pub use self::hlbool_generated::*; - mod hlexternalbytes_generated; - pub use self::hlexternalbytes_generated::*; - mod hlvoid_generated; - pub use self::hlvoid_generated::*; - mod guest_error_generated; - pub use self::guest_error_generated::*; - mod return_value_box_generated; - pub use self::return_value_box_generated::*; - mod function_call_result_generated; - pub use self::function_call_result_generated::*; - mod parameter_generated; - pub use self::parameter_generated::*; - mod function_call_generated; - pub use self::function_call_generated::*; - mod guest_log_data_generated; - pub use self::guest_log_data_generated::*; - mod key_value_generated; - pub use self::key_value_generated::*; - mod open_span_type_generated; - pub use self::open_span_type_generated::*; - mod close_span_type_generated; - pub use self::close_span_type_generated::*; - mod log_event_type_generated; - pub use self::log_event_type_generated::*; - mod edit_span_type_generated; - pub use self::edit_span_type_generated::*; - mod guest_start_type_generated; - pub use self::guest_start_type_generated::*; - mod guest_event_envelope_type_generated; - pub use self::guest_event_envelope_type_generated::*; - mod host_function_definition_generated; - pub use self::host_function_definition_generated::*; - mod host_function_details_generated; - pub use self::host_function_details_generated::*; - } // generated -} // hyperlight diff --git a/src/hyperlight_common/src/lib.rs b/src/hyperlight_common/src/lib.rs index dcf791fec3..383b4342c2 100644 --- a/src/hyperlight_common/src/lib.rs +++ b/src/hyperlight_common/src/lib.rs @@ -14,10 +14,6 @@ extern crate alloc; pub mod component; pub mod flatbuffer_wrappers; -/// cbindgen:ignore -/// FlatBuffers-related utilities and (mostly) generated code -#[allow(clippy::all, warnings)] -mod flatbuffers; // cbindgen:ignore pub mod layout; diff --git a/src/hyperlight_common/src/transport.rs b/src/hyperlight_common/src/transport.rs index 6f7445e148..b76d401e1e 100644 --- a/src/hyperlight_common/src/transport.rs +++ b/src/hyperlight_common/src/transport.rs @@ -15,9 +15,6 @@ use bytes::Bytes; use crate::flatbuffer_wrappers::{ExternalValueSink, ExternalValueSource}; use crate::virtq::{MemOps, RecvChain, Segments, VirtqError, zeroed_vec}; -/// Length of a FlatBuffer size prefix. -pub const SIZE_PREFIX_LEN: usize = core::mem::size_of::(); - /// Message types for the virtqueue wire protocol. #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq, bytemuck::CheckedBitPattern, bytemuck::NoUninit)] @@ -101,18 +98,22 @@ pub struct MsgHeader { pub cid: u32, /// Total number of payload bytes in this logical message. pub payload_len: u32, + /// Number of payload bytes holding control data. External byte values + /// follow it. The host copies exactly this many bytes before decoding. + pub control_len: u32, } impl MsgHeader { pub const SIZE: usize = core::mem::size_of::(); /// Create a message header. - pub const fn new(kind: MsgKind, cid: u32, payload_len: u32) -> Self { + pub const fn new(kind: MsgKind, cid: u32, payload_len: u32, control_len: u32) -> Self { Self { kind, reserved: [0; 3], cid, payload_len, + control_len, } } @@ -124,7 +125,7 @@ impl MsgHeader { /// Parse and validate a wire header. pub fn from_bytes(bytes: &[u8]) -> Option { let header: Self = bytemuck::checked::try_pod_read_unaligned(bytes).ok()?; - (header.reserved == [0; 3]).then_some(header) + (header.reserved == [0; 3] && header.control_len <= header.payload_len).then_some(header) } } @@ -147,10 +148,11 @@ impl<'a> EncodedMessage<'a> { ) -> Option { let payload_len = control.len().checked_add(externals.total_len())?; let payload_len = u32::try_from(payload_len).ok()?; + let control_len = u32::try_from(control.len()).ok()?; let total_len = MsgHeader::SIZE.checked_add(payload_len as usize)?; Some(Self { - header: MsgHeader::new(kind, cid, payload_len), + header: MsgHeader::new(kind, cid, payload_len, control_len), control, externals, total_len, @@ -163,7 +165,7 @@ impl<'a> EncodedMessage<'a> { let externals = ExternalValues::new(); Self { - header: MsgHeader::new(MsgKind::SnapshotCheckpoint, 0, 0), + header: MsgHeader::new(MsgKind::SnapshotCheckpoint, 0, 0, 0), control: &[], externals, total_len, @@ -197,7 +199,7 @@ impl<'a> EncodedMessage<'a> { &self.header } - /// Size-prefixed FlatBuffer control data. + /// Control data. pub const fn control(&self) -> &[u8] { self.control } @@ -307,7 +309,7 @@ impl Buf for EncodedMessageBuf<'_> { } } -/// Borrowed external values collected while encoding a FlatBuffer. +/// Borrowed external values collected while encoding control data. #[derive(Debug, Default)] pub struct ExternalValues<'a> { chunks: Vec<&'a [u8]>, @@ -447,19 +449,6 @@ fn finish_external_values(remaining: usize) -> Result<()> { Ok(()) } -/// Decode a FlatBuffer size prefix. -pub fn size_prefix_payload_len(prefix: &[u8]) -> Option { - // TODO: this is flatbuffer-specific and should be moved probably somewhere else. - let prefix = <[u8; SIZE_PREFIX_LEN]>::try_from(prefix).ok()?; - usize::try_from(u32::from_le_bytes(prefix)).ok() -} - -/// Add the FlatBuffer size prefix to a payload length. -pub const fn size_prefixed_len(payload_len: usize) -> Option { - // TODO: this is flatbuffer-specific and should be moved probably somewhere else. - SIZE_PREFIX_LEN.checked_add(payload_len) -} - #[cfg(test)] mod tests { use bytemuck::checked::try_pod_read_unaligned; @@ -490,24 +479,21 @@ mod tests { #[test] fn header_contains_framing_fields() { - let header = MsgHeader::new(MsgKind::Response, 0x1234_5678, 4096); + let header = MsgHeader::new(MsgKind::Response, 0x1234_5678, 4096, 16); - assert_eq!(MsgHeader::SIZE, 12); + assert_eq!(MsgHeader::SIZE, 16); assert_eq!(header.kind, MsgKind::Response); assert_eq!(header.cid, 0x1234_5678); assert_eq!(header.payload_len, 4096); + assert_eq!(header.control_len, 16); assert_eq!(header.reserved, [0; 3]); - assert_eq!( - header.as_bytes(), - &[0x02, 0, 0, 0, 0x78, 0x56, 0x34, 0x12, 0, 0x10, 0, 0] - ); assert_eq!(MsgHeader::from_bytes(header.as_bytes()), Some(header)); } #[test] fn header_decodes_unaligned_bytes() { - let header = MsgHeader::new(MsgKind::Response, 7, 4096); - let mut storage = [0u32; 4]; + let header = MsgHeader::new(MsgKind::Response, 7, 4096, 16); + let mut storage = [0u32; 5]; let bytes = &mut bytemuck::cast_slice_mut(&mut storage)[1..1 + MsgHeader::SIZE]; bytes.copy_from_slice(header.as_bytes()); @@ -516,10 +502,16 @@ mod tests { #[test] fn rejects_invalid_wire_headers() { - let header = MsgHeader::new(MsgKind::Request, 1, 4); + let header = MsgHeader::new(MsgKind::Request, 1, 4, 4); let mut bytes = [0; MsgHeader::SIZE]; bytes.copy_from_slice(header.as_bytes()); + assert_eq!( + MsgHeader::from_bytes(MsgHeader::new(MsgKind::Request, 1, 4, 5).as_bytes()), + None, + "control data longer than the payload" + ); + for index in 1..4 { bytes[index] = 1; assert_eq!(MsgHeader::from_bytes(&bytes), None); @@ -642,12 +634,4 @@ mod tests { source.finish().unwrap(); } - - #[test] - fn size_prefix_helpers_validate_length() { - assert_eq!(size_prefix_payload_len(&4u32.to_le_bytes()), Some(4)); - assert_eq!(size_prefix_payload_len(&[0; 3]), None); - assert_eq!(size_prefixed_len(4), Some(SIZE_PREFIX_LEN + 4)); - assert_eq!(size_prefixed_len(usize::MAX), None); - } } diff --git a/src/hyperlight_guest/Cargo.toml b/src/hyperlight_guest/Cargo.toml index 95295ca3c8..d0229a0953 100644 --- a/src/hyperlight_guest/Cargo.toml +++ b/src/hyperlight_guest/Cargo.toml @@ -15,7 +15,6 @@ Provides only the essential building blocks for interacting with the host enviro anyhow = { version = "1.0.102", default-features = false } serde_json = { version = "1.0", default-features = false, features = ["alloc"] } hyperlight-common = { workspace = true, default-features = false } -flatbuffers = { version= "25.12.19", default-features = false } tracing = { version = "0.1.44", default-features = false, features = ["attributes"] } itertools = { version = "0.15.0", default-features = false } diff --git a/src/hyperlight_guest/src/transport/codec.rs b/src/hyperlight_guest/src/transport/codec.rs index cdaa32cdac..5d1f86757d 100644 --- a/src/hyperlight_guest/src/transport/codec.rs +++ b/src/hyperlight_guest/src/transport/codec.rs @@ -5,9 +5,7 @@ use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall; use hyperlight_common::flatbuffer_wrappers::function_types::{Bytes, FunctionCallResult}; -use hyperlight_common::transport::{ - Buf, MsgHeader, MsgKind, SIZE_PREFIX_LEN, size_prefix_payload_len, size_prefixed_len, -}; +use hyperlight_common::transport::{MsgHeader, MsgKind}; use hyperlight_common::virtq::Segments; use crate::bail; @@ -17,8 +15,8 @@ use crate::error::{GuestErrorContext, Result}; /// /// Chunked external values retain their H2G slot owners until their final /// [`Bytes`] clone drops. -pub(super) fn decode_request(segments: Segments) -> Result { - let (control, mut external_values) = decode_payload(segments)?; +pub(super) fn decode_request(header: &MsgHeader, segments: Segments) -> Result { + let (control, mut external_values) = decode_payload(header, segments)?; FunctionCall::decode(&control, &mut external_values) .with_context(|| "failed to decode guest function request") } @@ -37,7 +35,7 @@ pub(super) fn decode_response(segments: Segments, cid: u32) -> Result Result<(MsgHeader, Segments)> { } /// Split control data into a contiguous view while retaining external owners. -fn decode_payload(mut segments: Segments) -> Result<(Bytes, Segments)> { - let mut prefix = [0u8; SIZE_PREFIX_LEN]; - segments - .as_buf() - .try_copy_to_slice(&mut prefix) - .context("virtqueue message is missing its size prefix")?; - - let payload_len = - size_prefix_payload_len(&prefix).context("virtqueue message has an invalid prefix")?; - - let control_len = - size_prefixed_len(payload_len).context("virtqueue message control length overflow")?; +fn decode_payload(header: &MsgHeader, mut segments: Segments) -> Result<(Bytes, Segments)> { let control = segments - .split_to(control_len) + .split_to(header.control_len as usize) .context("virtqueue message control data is truncated")? .into_bytes(); @@ -83,24 +70,26 @@ fn decode_payload(mut segments: Segments) -> Result<(Bytes, Segments)> { #[cfg(test)] mod tests { use alloc::vec; + use alloc::vec::Vec; - use flatbuffers::FlatBufferBuilder; use hyperlight_common::flatbuffer_wrappers::ExternalValueSource; use hyperlight_common::flatbuffer_wrappers::function_types::ReturnValue; use hyperlight_common::transport::ExternalValues; use super::*; + fn header(payload_len: u32, control_len: u32) -> MsgHeader { + MsgHeader::new(MsgKind::Request, 1, payload_len, control_len) + } + #[test] fn payload_contiguous_control_reuses_storage() { // Control and external data share one transport allocation. - let bytes = Bytes::from(vec![ - 4, 0, 0, 0, b'c', b't', b'r', b'l', b'd', b'a', b't', b'a', - ]); + let bytes = Bytes::from_static(b"ctrldata"); let ptr = bytes.as_ptr(); - let (control, mut source) = decode_payload(Segments::single(bytes)).unwrap(); + let (control, mut source) = decode_payload(&header(8, 4), Segments::single(bytes)).unwrap(); - assert_eq!(&control[..], b"\x04\0\0\0ctrl"); + assert_eq!(&control[..], b"ctrl"); assert_eq!(control.as_ptr(), ptr); // External data outlives the control view. @@ -108,25 +97,25 @@ mod tests { source.finish().unwrap(); drop(control); assert_eq!(chunks.len(), 1); - assert_eq!(chunks[0].as_ptr(), ptr.wrapping_add(8)); + assert_eq!(chunks[0].as_ptr(), ptr.wrapping_add(4)); assert_eq!(chunks[0].as_ref(), b"data"); } #[test] fn payload_fragmented_control_preserves_external_storage() { - // Both the size prefix and control body cross segment boundaries. - let boundary = Bytes::from(vec![b'r', b'l', b'd', b'a', b't', b'a']); + // The control data crosses segment boundaries. + let boundary = Bytes::from_static(b"rldata"); let ptr = boundary.as_ptr(); let segments = Segments::new([ Bytes::new(), - Bytes::from_static(b"\x04\0"), + Bytes::from_static(b"c"), Bytes::new(), - Bytes::from_static(b"\0\0ct"), + Bytes::from_static(b"t"), boundary, ]); - let (control, mut source) = decode_payload(segments).unwrap(); - assert_eq!(&control[..], b"\x04\0\0\0ctrl"); + let (control, mut source) = decode_payload(&header(8, 4), segments).unwrap(); + assert_eq!(&control[..], b"ctrl"); // Only the control bytes are collected into contiguous storage. let chunks = source.take_chunks(4).unwrap(); @@ -136,20 +125,10 @@ mod tests { assert_eq!(chunks[0].as_ref(), b"data"); } - #[test] - fn payload_rejects_short_size_prefix() { - let prefix = 4u32.to_le_bytes(); - for len in 0..SIZE_PREFIX_LEN { - let segments = Segments::new([Bytes::new(), Bytes::copy_from_slice(&prefix[..len])]); - assert!(decode_payload(segments).is_err(), "prefix length {len}"); - } - } - #[test] fn payload_rejects_truncated_control() { - // The prefix declares four control bytes, but only three follow. - let segments = Segments::single(Bytes::from_static(b"\x04\0\0\0ctr")); - assert!(decode_payload(segments).is_err()); + let segments = Segments::single(Bytes::from_static(b"ctr")); + assert!(decode_payload(&header(4, 4), segments).is_err()); } #[test] @@ -158,13 +137,14 @@ mod tests { let external_ptr = external.as_ptr(); let result = FunctionCallResult::new(Ok(ReturnValue::ByteChunks(vec![external.clone()]))); - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = ExternalValues::new(); - let control = result.encode(&mut builder, &mut external_values).unwrap(); + let control = result.encode(&mut buffer, &mut external_values).unwrap(); + let control_len = u32::try_from(control.len()).unwrap(); let payload_len = u32::try_from(control.len() + external_values.total_len()).unwrap(); - let header = MsgHeader::new(MsgKind::Response, 7, payload_len); + let header = MsgHeader::new(MsgKind::Response, 7, payload_len, control_len); let segments = Segments::new([ Bytes::copy_from_slice(header.as_bytes()), @@ -185,25 +165,38 @@ mod tests { #[test] fn response_rejects_payload_length_mismatch() { let result = FunctionCallResult::new(Ok(ReturnValue::UInt(17))); - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = ExternalValues::new(); - let control = result.encode(&mut builder, &mut external_values).unwrap(); + let control = result.encode(&mut buffer, &mut external_values).unwrap(); - let payload_len = u32::try_from(control.len()).unwrap(); + let len = u32::try_from(control.len()).unwrap(); - let segments = |length| { - let header = MsgHeader::new(MsgKind::Response, 7, length); + let segments = |payload_len, control_len| { + let header = MsgHeader::new(MsgKind::Response, 7, payload_len, control_len); Segments::new([ Bytes::copy_from_slice(header.as_bytes()), Bytes::copy_from_slice(control), ]) }; - - assert!(decode_response(segments(payload_len), 7).is_ok()); - for length in [payload_len - 1, payload_len + 1] { - assert!(decode_response(segments(length), 7).is_err()); + let error = + |payload_len, control_len| match decode_response(segments(payload_len, control_len), 7) + { + Ok(_) => panic!("expected a decode error"), + Err(error) => error.message, + }; + + assert!(decode_response(segments(len, len), 7).is_ok()); + for payload_len in [len - 1, len + 1] { + assert_eq!( + error(payload_len, len - 1), + "Virtqueue message payload length mismatch" + ); } + assert_eq!( + error(len, len + 1), + "Virtqueue message has an invalid header" + ); } #[test] @@ -219,12 +212,14 @@ mod tests { FunctionCallType::Guest, ReturnType::ByteChunks, ); - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = ExternalValues::new(); - let control = call.encode(&mut builder, &mut external_values).unwrap(); + let control = call.encode(&mut buffer, &mut external_values).unwrap(); + let control_len = u32::try_from(control.len()).unwrap(); + let header = MsgHeader::new(MsgKind::Request, 1, control_len + 4, control_len); let segments = Segments::new([Bytes::copy_from_slice(control), external]); - let decoded = decode_request(segments).unwrap(); + let decoded = decode_request(&header, segments).unwrap(); assert_eq!(decoded.function_name, "echo"); let ParameterValue::ByteChunks(chunks) = decoded.parameters.unwrap().into_iter().next().unwrap() diff --git a/src/hyperlight_guest/src/transport/context.rs b/src/hyperlight_guest/src/transport/context.rs index 7c56048c80..ef24151f3a 100644 --- a/src/hyperlight_guest/src/transport/context.rs +++ b/src/hyperlight_guest/src/transport/context.rs @@ -6,12 +6,10 @@ use alloc::vec::Vec; use core::result; -use flatbuffers::FlatBufferBuilder; use hyperlight_common::flatbuffer_wrappers::function_call::{FunctionCall, FunctionCallType}; use hyperlight_common::flatbuffer_wrappers::function_types::{ FunctionCallResult, ParameterValue, ReturnType, ReturnValue, }; -use hyperlight_common::flatbuffer_wrappers::util::estimate_flatbuffer_capacity; use hyperlight_common::layout::scratch_transport_end_gva; use hyperlight_common::outb::OutBAction; use hyperlight_common::transport::{ @@ -173,10 +171,6 @@ impl GuestContext { parameters: Option>, return_type: ReturnType, ) -> Result { - // Encode control data separately from borrowed external byte values. - let params = parameters.as_deref().unwrap_or_default(); - let estimated_capacity = estimate_flatbuffer_capacity(function_name, params); - let fc = FunctionCall::new( function_name.into(), parameters, @@ -184,11 +178,12 @@ impl GuestContext { return_type, ); - let mut builder = FlatBufferBuilder::with_capacity(estimated_capacity); + let mut buffer = Vec::new(); let mut externals = ExternalValues::new(); + // Encode control data separately from borrowed external byte values. let control = fc - .encode(&mut builder, &mut externals) + .encode(&mut buffer, &mut externals) .with_context(|| "failed to encode host function call")?; // Frame the request and include external values in its total length. @@ -310,7 +305,7 @@ impl GuestContext { payload.append(segments); } - let call = codec::decode_request(payload)?; + let call = codec::decode_request(&header, payload)?; Ok(DispatchAction::Call(header.cid, call)) } @@ -321,11 +316,11 @@ impl GuestContext { .with_context(|| "G2H response reclaim failed")?; { - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut externals = ExternalValues::new(); let control = result - .encode(&mut builder, &mut externals) + .encode(&mut buffer, &mut externals) .with_context(|| "failed to encode guest function result")?; let msg = EncodedMessage::new(MsgKind::Response, cid, control, externals) diff --git a/src/hyperlight_guest_bin/Cargo.toml b/src/hyperlight_guest_bin/Cargo.toml index 0b9fe21966..a42cbde923 100644 --- a/src/hyperlight_guest_bin/Cargo.toml +++ b/src/hyperlight_guest_bin/Cargo.toml @@ -29,7 +29,6 @@ talc = { version = "5.1.1", default-features = false } log = { version = "0.4", default-features = false } linkme = { version = "0.3.36", optional = true } spin = "0.12.0" -flatbuffers = { version = "25.12.19", default-features = false } tracing = { version = "0.1.44", default-features = false, features = ["attributes"] } [lints] diff --git a/src/hyperlight_guest_capi/Cargo.toml b/src/hyperlight_guest_capi/Cargo.toml index 46a3fb90fe..1c41c19965 100644 --- a/src/hyperlight_guest_capi/Cargo.toml +++ b/src/hyperlight_guest_capi/Cargo.toml @@ -16,7 +16,6 @@ hyperlight-guest = { workspace = true, default-features = false } hyperlight-guest-bin = { workspace = true, default-features = true } hyperlight-common = { workspace = true, default-features = false } -flatbuffers = { version = "25.12.19", default-features = false } log = { version = "0.4", default-features = false } [build-dependencies] diff --git a/src/hyperlight_host/Cargo.toml b/src/hyperlight_host/Cargo.toml index 2988fd3b1c..10c8f4a7bd 100644 --- a/src/hyperlight_host/Cargo.toml +++ b/src/hyperlight_host/Cargo.toml @@ -27,7 +27,6 @@ goblin = { version = "0.10", default-features = false, features = ["std", "elf32 rand = { version = "0.10" } cfg-if = { version = "1.0.4" } libc = { version = "0.2.186" } -flatbuffers = "25.12.19" framehop = { version = "0.16.0", optional = true } fallible-iterator = { version = "0.3.0", optional = true } blake3 = "1.8.5" diff --git a/src/hyperlight_host/benches/benchmarks.rs b/src/hyperlight_host/benches/benchmarks.rs index c25dd6fccb..ee1f5c7844 100644 --- a/src/hyperlight_host/benches/benchmarks.rs +++ b/src/hyperlight_host/benches/benchmarks.rs @@ -7,11 +7,9 @@ use std::time::{Duration, Instant}; use anyhow::{Result, bail}; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group, criterion_main}; -use flatbuffers::FlatBufferBuilder; use hyperlight_common::flatbuffer_wrappers::ExternalValueSource; use hyperlight_common::flatbuffer_wrappers::function_call::{FunctionCall, FunctionCallType}; use hyperlight_common::flatbuffer_wrappers::function_types::{Bytes, ParameterValue, ReturnType}; -use hyperlight_common::flatbuffer_wrappers::util::estimate_flatbuffer_capacity; use hyperlight_common::transport::ExternalValues; use hyperlight_common::vmem::PAGE_SIZE; use hyperlight_host::func::Registerable; @@ -613,24 +611,20 @@ fn function_call_codec_benchmark(c: &mut Criterion) { for (name, function_call) in [("vec_bytes", &vec_call), ("byte_chunks", &chunk_call)] { group.bench_function(BenchmarkId::new("encode_control", name), |b| { b.iter(|| { - let estimated_capacity = estimate_flatbuffer_capacity( - &function_call.function_name, - function_call.parameters.as_deref().unwrap_or_default(), - ); - let mut builder = FlatBufferBuilder::with_capacity(estimated_capacity); + let mut buffer = Vec::new(); let mut exts = ExternalValues::new(); - let control = function_call.encode(&mut builder, &mut exts).unwrap(); + let control = function_call.encode(&mut buffer, &mut exts).unwrap(); std::hint::black_box((control, exts.total_len())); }); }); } - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = ExternalValues::new(); let vec_control = vec_call - .encode(&mut builder, &mut external_values) + .encode(&mut buffer, &mut external_values) .unwrap() .to_vec(); @@ -642,11 +636,11 @@ fn function_call_codec_benchmark(c: &mut Criterion) { }); }); - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut external_values = ExternalValues::new(); let chunk_control = chunk_call - .encode(&mut builder, &mut external_values) + .encode(&mut buffer, &mut external_values) .unwrap() .to_vec(); diff --git a/src/hyperlight_host/src/error.rs b/src/hyperlight_host/src/error.rs index b7af2033e8..4ecf47b8ec 100644 --- a/src/hyperlight_host/src/error.rs +++ b/src/hyperlight_host/src/error.rs @@ -12,7 +12,6 @@ use std::time::SystemTimeError; #[cfg(target_os = "windows")] use crossbeam_channel::{RecvError, SendError}; -use flatbuffers::InvalidFlatbuffer; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnValue}; use hyperlight_common::flatbuffer_wrappers::guest_error::ErrorCode; use hyperlight_common::virtq::VirtqError; @@ -65,10 +64,6 @@ pub enum HyperlightError { #[error("Execution was cancelled by the host.")] ExecutionCanceledByHost(), - /// Accessing the value of a flatbuffer parameter failed - #[error("Failed to get a value from flat buffer parameter")] - FailedToGetValueFromParameter(), - ///Field Name not found in decoded GuestLogData #[error("Field Name {0} not found in decoded GuestLogData")] FieldIsMissingInGuestLogData(String), @@ -127,10 +122,6 @@ pub enum HyperlightError { #[error("Failed To Convert Size to usize")] IntConversionFailure(#[from] TryFromIntError), - /// The flatbuffer is invalid - #[error("The flatbuffer is invalid")] - InvalidFlatBuffer(#[from] InvalidFlatbuffer), - /// Conversion of str to Json failed #[error("Conversion of str data to json failed")] JsonConversionFailure(#[from] serde_json::Error), @@ -255,12 +246,6 @@ pub enum HyperlightError { #[error("String Conversion of UTF8 data to str failed")] UTF8StringConversionFailure(#[from] FromUtf8Error), - /// The capacity of the vector is incorrect - #[error( - "The capacity of the vector is incorrect. Capacity: {0}, Length: {1}, FlatBuffer Size: {2}" - )] - VectorCapacityIncorrect(usize, usize, i32), - /// vmm sys Error Occurred #[error("vmm sys Error {0:?}")] #[cfg(target_os = "linux")] @@ -345,7 +330,6 @@ impl HyperlightError { | HyperlightError::CheckedAddOverflow(_, _) | HyperlightError::CStringConversionError(_) | HyperlightError::Error(_) - | HyperlightError::FailedToGetValueFromParameter() | HyperlightError::FieldIsMissingInGuestLogData(_) | HyperlightError::GuestBinVersionMismatch { .. } | HyperlightError::GuestError(_, _) @@ -359,7 +343,6 @@ impl HyperlightError { | HyperlightError::HyperlightVmError(HyperlightVmError::UnmapRegion(_)) | HyperlightError::IOError(_) | HyperlightError::IntConversionFailure(_) - | HyperlightError::InvalidFlatBuffer(_) | HyperlightError::JsonConversionFailure(_) | HyperlightError::LockAttemptFailed(_) | HyperlightError::MemoryRequestTooBig(_, _) @@ -381,7 +364,6 @@ impl HyperlightError { | HyperlightError::UnexpectedReturnValueType(_, _) | HyperlightError::UnrecoverableSandbox | HyperlightError::UTF8StringConversionFailure(_) - | HyperlightError::VectorCapacityIncorrect(_, _, _) | HyperlightError::SharedMemory(_) => false, #[cfg(target_os = "windows")] diff --git a/src/hyperlight_host/src/mem/mgr.rs b/src/hyperlight_host/src/mem/mgr.rs index 80b2ee797c..f83585e347 100644 --- a/src/hyperlight_host/src/mem/mgr.rs +++ b/src/hyperlight_host/src/mem/mgr.rs @@ -1,11 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // Copyright 2025 The Hyperlight Authors. -use flatbuffers::FlatBufferBuilder; use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall; use hyperlight_common::flatbuffer_wrappers::function_types::FunctionCallResult; use hyperlight_common::flatbuffer_wrappers::host_function_details::HostFunctionDetails; -use hyperlight_common::flatbuffer_wrappers::util::estimate_flatbuffer_capacity; use hyperlight_common::log_level::GuestLogFilter; use hyperlight_common::transport::{Buf, EncodedMessage, ExternalValues, MailboxValue, MsgKind}; use hyperlight_common::virtq::ReplyChain; @@ -744,13 +742,11 @@ impl SandboxMemoryManager { #[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")] pub(crate) fn write_guest_function_call(&mut self, call: &FunctionCall) -> Result { let cid = self.next_guest_cid; - let params = call.parameters.as_deref().unwrap_or_default(); - let cap = estimate_flatbuffer_capacity(&call.function_name, params); - let mut builder = FlatBufferBuilder::with_capacity(cap); + let mut buffer = Vec::new(); let mut externals = ExternalValues::new(); - let control = call.encode(&mut builder, &mut externals)?; + let control = call.encode(&mut buffer, &mut externals)?; let Some(msg) = EncodedMessage::new(MsgKind::Request, cid, control, externals) else { return Err(new_error!("H2G request exceeds the wire payload limit")); @@ -865,7 +861,7 @@ impl SandboxMemoryManager { )); } - let log = virtq::read_guest_log_data(&mut recv).map_err(|err| { + let log = virtq::read_guest_log_data(&mut recv, &header).map_err(|err| { HyperlightError::TransportError(format!("Failed to read G2H log: {err}")) })?; @@ -884,7 +880,7 @@ impl SandboxMemoryManager { )); } - let result = virtq::read_guest_function_call_result(&mut recv); + let result = virtq::read_guest_function_call_result(&mut recv, &header); consumer.complete(recv, reply).map_err(|err| { HyperlightError::TransportError(format!( "Failed to complete G2H guest function result: {err}" @@ -1310,9 +1306,7 @@ mod tests { use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCallType; use hyperlight_common::flatbuffer_wrappers::function_types::{ParameterValue, ReturnType}; - use hyperlight_common::transport::{ - MsgHeader, SIZE_PREFIX_LEN, size_prefix_payload_len, size_prefixed_len, - }; + use hyperlight_common::transport::MsgHeader; use hyperlight_common::virtq::DescFlags; use hyperlight_common::vmem::{self, BasicMapping, Mapping, MappingKind, PAGE_SIZE}; #[cfg(target_arch = "x86_64")] @@ -1466,12 +1460,7 @@ mod tests { assert_eq!(header.cid, cid); assert_eq!(header.payload_len as usize, wire.len() - MsgHeader::SIZE); - let control = - size_prefix_payload_len(&wire[MsgHeader::SIZE..MsgHeader::SIZE + SIZE_PREFIX_LEN]) - .unwrap(); - - let control_len = size_prefixed_len(control).unwrap(); - let external = &wire[MsgHeader::SIZE + control_len..]; + let external = &wire[MsgHeader::SIZE + header.control_len as usize..]; assert_eq!(external, vec![0xa5; external_len]); let cursor = mgr.h2g_consumer.as_ref().unwrap().avail_cursor(); diff --git a/src/hyperlight_host/src/mem/shared_mem.rs b/src/hyperlight_host/src/mem/shared_mem.rs index 69ef78732f..0d1fddd57f 100644 --- a/src/hyperlight_host/src/mem/shared_mem.rs +++ b/src/hyperlight_host/src/mem/shared_mem.rs @@ -1157,12 +1157,12 @@ impl SharedMemory for GuestSharedMemory { /// racing loads in LLVM return `undef`, as discussed above, we would /// ideally `llvm.freeze` the result of any load out of the sandbox. /// -/// It would furthermore be ideal if we could run the flatbuffers -/// parsing code directly on the guest memory, in order to avoid +/// It would furthermore be ideal if we could run the message +/// decoder directly on the guest memory, in order to avoid /// unnecessary copies. That is unfortunately probably not viable at -/// the present time: because the generated flatbuffers parsing code -/// doesn't use atomic or volatile accesses, it is likely to introduce -/// double-read vulnerabilities. +/// the present time: because the decoder doesn't use atomic or +/// volatile accesses, it is likely to introduce double-read +/// vulnerabilities. /// /// In short, none of the Rust-level operations available to us do the /// right thing, at the Rust spec level or the LLVM spec level. Our diff --git a/src/hyperlight_host/src/mem/virtq/codec.rs b/src/hyperlight_host/src/mem/virtq/codec.rs index a007c7ed77..0e84c0fba8 100644 --- a/src/hyperlight_host/src/mem/virtq/codec.rs +++ b/src/hyperlight_host/src/mem/virtq/codec.rs @@ -4,14 +4,11 @@ //! Host RPC encoding and decoding over virtqueue chains. use anyhow::{Context, bail}; -use flatbuffers::FlatBufferBuilder; use hyperlight_common::flatbuffer_wrappers::ExternalValueSource; use hyperlight_common::flatbuffer_wrappers::function_call::FunctionCall; use hyperlight_common::flatbuffer_wrappers::function_types::FunctionCallResult; use hyperlight_common::flatbuffer_wrappers::guest_log_data::GuestLogData; -use hyperlight_common::transport::{ - EncodedMessage, ExternalValues, MsgHeader, MsgKind, SIZE_PREFIX_LEN, -}; +use hyperlight_common::transport::{EncodedMessage, ExternalValues, MsgHeader, MsgKind}; use hyperlight_common::virtq::{RecvChain, WritableChain}; use super::mem::HostMemOps; @@ -22,8 +19,9 @@ use super::mem::HostMemOps; /// Unconsumed trailing bytes are rejected. pub(crate) fn get_host_function_call( chain: &mut RecvChain, + header: &MsgHeader, ) -> anyhow::Result { - let control = read_control(chain)?; + let control = read_control(chain, header)?; FunctionCall::decode(&control, chain) } @@ -49,8 +47,9 @@ pub(crate) fn read_message_header( /// Decode a guest-function result body after its G2H header. pub(crate) fn read_guest_function_call_result( request: &mut RecvChain, + header: &MsgHeader, ) -> anyhow::Result { - let control = read_control(request)?; + let control = read_control(request, header)?; FunctionCallResult::decode(&control, request) } @@ -62,10 +61,10 @@ pub(crate) fn try_write_response( cid: u32, result: &FunctionCallResult, ) -> anyhow::Result { - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut externals = ExternalValues::new(); - let control = result.encode(&mut builder, &mut externals)?; + let control = result.encode(&mut buffer, &mut externals)?; let msg = EncodedMessage::new(MsgKind::Response, cid, control, externals) .context("Host function response length overflow")?; @@ -83,31 +82,28 @@ pub(crate) fn try_write_response( /// Decode guest log data and reject trailing external bytes. pub(crate) fn read_guest_log_data( chain: &mut RecvChain, + header: &MsgHeader, ) -> anyhow::Result { - let control = read_control(chain)?; + let control = read_control(chain, header)?; chain.finish()?; GuestLogData::try_from(control.as_slice()) } -/// Copy size-prefixed control data and leave external values unread. -fn read_control(request: &mut RecvChain) -> anyhow::Result> { - let mut prefix = [0u8; SIZE_PREFIX_LEN]; - request.read_exact(&mut prefix)?; - - let payload_len = u32::from_le_bytes(prefix) as usize; - if payload_len > request.remaining() { +/// Copy the header's control data and leave external values unread. +fn read_control( + request: &mut RecvChain, + header: &MsgHeader, +) -> anyhow::Result> { + let control_len = header.control_len as usize; + if control_len > request.remaining() { bail!( - "G2H control data declares {payload_len} bytes, only {} remain", + "G2H control data declares {control_len} bytes, only {} remain", request.remaining() ); } - // The prefix and payload fit within the original chain length. - let control_len = SIZE_PREFIX_LEN + payload_len; let mut control = zeroed_vec(control_len, "G2H control data")?; - - control[..SIZE_PREFIX_LEN].copy_from_slice(&prefix); - request.read_exact(&mut control[SIZE_PREFIX_LEN..])?; + request.read_exact(&mut control)?; Ok(control) } @@ -126,7 +122,7 @@ fn zeroed_vec(length: usize, what: &str) -> anyhow::Result> { #[cfg(test)] mod tests { use hyperlight_common::flatbuffer_wrappers::function_types::ReturnValue; - use hyperlight_common::virtq::{BufferChainBuilder, MemOps, RingProducer, VirtqError}; + use hyperlight_common::virtq::{BufferChainBuilder, MemOps, RingProducer}; use super::*; use crate::mem::virtq::tests::TestCase; @@ -156,25 +152,14 @@ mod tests { assert!(zeroed_vec(usize::MAX, "test buffer").is_err()); } - #[test] - fn read_control_rejects_truncated_prefix() { - with_control(b"\x04\0\0", |request| { - let error = read_control(request).unwrap_err(); - assert!(matches!( - error.downcast_ref::(), - Some(VirtqError::ReceiveTooShort { - requested: SIZE_PREFIX_LEN, - remaining: 3, - }) - )); - assert_eq!(request.consumed(), 0); - }); + fn header(payload_len: u32, control_len: u32) -> MsgHeader { + MsgHeader::new(MsgKind::Request, 1, payload_len, control_len) } #[test] fn read_control_rejects_truncated_body() { - with_control(b"\x04\0\0\0ctr", |request| { - let error = read_control(request).unwrap_err(); + with_control(b"ctr", |request| { + let error = read_control(request, &header(4, 4)).unwrap_err(); assert_eq!( error.to_string(), "G2H control data declares 4 bytes, only 3 remain" @@ -183,25 +168,35 @@ mod tests { }); } + #[test] + fn read_message_header_rejects_control_longer_than_payload() { + let mut message = header(3, 4).as_bytes().to_vec(); + message.extend_from_slice(b"ext"); + with_control(&message, |request| { + let error = read_message_header(request).unwrap_err(); + assert_eq!(error.to_string(), "G2H message has an invalid header"); + }); + } + #[test] fn read_control_leaves_external_bytes_unread() { let case = TestCase::new(); let mut producer = RingProducer::new(case.g2h_layout, case.mem.clone()); - let payload = b"\x04\0\0\0ctrlext"; + let payload = b"ctrlext"; let addr = case.g2h_pool_base; case.mem.write(addr, payload).unwrap(); let chain = BufferChainBuilder::new() .readable(addr, 2) - .readable(addr + 2, 5) - .readable(addr + 7, 4) + .readable(addr + 2, 3) + .readable(addr + 5, 2) .build() .unwrap(); producer.submit_available(&chain).unwrap(); let mut consumer = case.g2h_consumer(); let (mut request, reply) = consumer.poll(payload.len()).unwrap().unwrap(); - assert_eq!(read_control(&mut request).unwrap(), b"\x04\0\0\0ctrl"); + assert_eq!(read_control(&mut request, &header(7, 4)).unwrap(), b"ctrl"); assert_eq!(request.remaining(), 3); let mut external = [0; 3]; @@ -221,10 +216,10 @@ mod tests { }; let result = FunctionCallResult::new(Ok(ReturnValue::UInt(17))); - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut externals = ExternalValues::new(); - let control = result.encode(&mut builder, &mut externals).unwrap(); + let control = result.encode(&mut buffer, &mut externals).unwrap(); let message = EncodedMessage::new(MsgKind::Response, 7, control, externals).unwrap(); let prefix = vec![0xa5; reply.capacity() - message.total_len() + 1]; @@ -249,10 +244,10 @@ mod tests { }; let result = FunctionCallResult::new(Ok(ReturnValue::UInt(17))); - let mut builder = FlatBufferBuilder::new(); + let mut buffer = Vec::new(); let mut externals = ExternalValues::new(); - let control = result.encode(&mut builder, &mut externals).unwrap(); + let control = result.encode(&mut buffer, &mut externals).unwrap(); let message = EncodedMessage::new(MsgKind::Response, 7, control, externals).unwrap(); let expected: Vec<_> = message.chunks().flatten().copied().collect(); diff --git a/src/hyperlight_host/src/sandbox/outb.rs b/src/hyperlight_host/src/sandbox/outb.rs index b0f371f481..13477cdf2b 100644 --- a/src/hyperlight_host/src/sandbox/outb.rs +++ b/src/hyperlight_host/src/sandbox/outb.rs @@ -255,7 +255,7 @@ fn outb_virtq_call( )); } - let log = virtq::read_guest_log_data(&mut request) + let log = virtq::read_guest_log_data(&mut request, &header) .map_err(|error| HandleOutbError::ReadHostFunctionCall(error.to_string()))?; emit_guest_log(&log); @@ -286,7 +286,7 @@ fn outb_virtq_call( ) })?; - let call = virtq::get_host_function_call(&mut request) + let call = virtq::get_host_function_call(&mut request, &header) .map_err(|error| HandleOutbError::ReadHostFunctionCall(error.to_string()))?; if call.function_call_type() != FunctionCallType::Host { diff --git a/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs b/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs index 2a98cc3e9f..b43c06e748 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file/media_types.rs @@ -25,7 +25,7 @@ pub(in crate::sandbox::snapshot) const MT_TRANSPORT_CURRENT: &str = MT_TRANSPORT /// ABI version for the snapshot memory blob. Bumped when the /// host-guest contract for the snapshot bytes changes. See /// docs/snapshot-versioning.md. -pub(in crate::sandbox::snapshot) const SNAPSHOT_ABI_VERSION: u32 = 9; +pub(in crate::sandbox::snapshot) const SNAPSHOT_ABI_VERSION: u32 = 10; /// OCI standard annotation key for a manifest's tag inside an image /// index. Set on the manifest descriptor in `index.json`, not on the diff --git a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs index 58bfa19aa5..c3cb64c2e9 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/file_tests.rs @@ -291,7 +291,7 @@ fn layered_writer_preserves_blobs_and_transport_geometry() { manifest["artifactType"], "application/vnd.hyperlight.snapshot.config.v5+json" ); - assert_eq!(config["abi_version"], 9); + assert_eq!(config["abi_version"], 10); let blobs = snapshot.snapshot_memory().blobs().collect::>(); assert_eq!(layers.len(), blobs.len() + 1); for (index, blob) in blobs.iter().enumerate() { @@ -2398,7 +2398,7 @@ fn legacy_config_versions_rejected() { &path, OciTag::new("latest").unwrap(), )); - assert_err_contains(err, "incompatible with snapshot ABI 9"); + assert_err_contains(err, "incompatible with snapshot ABI 10"); } } diff --git a/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs b/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs index f34933d218..663bb273e3 100644 --- a/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs +++ b/src/hyperlight_host/src/sandbox/snapshot/tripwires.rs @@ -9,6 +9,9 @@ //! port numbers, and `BASE_ADDRESS`. A change to any of these breaks //! loading of older snapshots. //! +//! The host-guest message encoding is pinned by tests in +//! `hyperlight_common/src/flatbuffer_wrappers/abi_tests.rs`. +//! //! When an assertion fires, see `docs/snapshot-versioning.md`. use super::file::{ @@ -16,7 +19,7 @@ use super::file::{ SNAPSHOT_ABI_VERSION, }; -const EXPECTED_ABI_VERSION: u32 = 9; +const EXPECTED_ABI_VERSION: u32 = 10; const EXPECTED_MT_CONFIG: &str = "application/vnd.hyperlight.snapshot.config.v5+json"; const EXPECTED_MT_SNAPSHOT: &str = "application/vnd.hyperlight.snapshot.memory.v2"; const EXPECTED_MT_TRANSPORT: &str = "application/vnd.hyperlight.snapshot.transport.v1"; diff --git a/src/hyperlight_host/tests/sandbox_host_tests.rs b/src/hyperlight_host/tests/sandbox_host_tests.rs index bd7dc77de2..4c5f5e90a3 100644 --- a/src/hyperlight_host/tests/sandbox_host_tests.rs +++ b/src/hyperlight_host/tests/sandbox_host_tests.rs @@ -98,11 +98,9 @@ fn float_roundtrip() { for f in doubles.iter() { let res: f64 = sandbox.call("EchoDouble", *f).unwrap(); - // Use == for comparison (handles -0.0 == 0.0) with special case for NaN. - // Note: FlatBuffers doesn't preserve -0.0 (-0.0 round-trips to 0.0) because FlatBuffers skips - // storing values equal to the default (as an optimization), and -0.0 == 0.0 in IEEE 754. - assert!( - (res.is_nan() && f.is_nan()) || res == *f, + assert_eq!( + res.to_bits(), + f.to_bits(), "Expected {:?} but got {:?}", f, res @@ -111,11 +109,9 @@ fn float_roundtrip() { for f in floats.iter() { let res: f32 = sandbox.call("EchoFloat", *f).unwrap(); - // Use == for comparison (handles -0.0 == 0.0) with special case for NaN. - // Note: FlatBuffers doesn't preserve -0.0 (-0.0 round-trips to 0.0) because FlatBuffers skips - // storing values equal to the default (as an optimization), and -0.0 == 0.0 in IEEE 754. - assert!( - (res.is_nan() && f.is_nan()) || res == *f, + assert_eq!( + res.to_bits(), + f.to_bits(), "Expected {:?} but got {:?}", f, res diff --git a/src/hyperlight_host/tests/snapshot_goldens/goldens_version.rs b/src/hyperlight_host/tests/snapshot_goldens/goldens_version.rs index 549feb1b0f..924e351257 100644 --- a/src/hyperlight_host/tests/snapshot_goldens/goldens_version.rs +++ b/src/hyperlight_host/tests/snapshot_goldens/goldens_version.rs @@ -8,7 +8,7 @@ //! publish. See `docs/snapshot-versioning.md`. /// Goldens version, a `vMAJOR.MINOR` string. -pub(crate) const GOLDENS_VERSION: &str = "v9.0"; +pub(crate) const GOLDENS_VERSION: &str = "v10.0"; /// Old majors kept loadable through a compatibility path, verified /// alongside `GOLDENS_VERSION`. A backwards-compatible break (Option 2) diff --git a/src/schema/all.fbs b/src/schema/all.fbs deleted file mode 100644 index 07cebfd8e5..0000000000 --- a/src/schema/all.fbs +++ /dev/null @@ -1,8 +0,0 @@ -include "function_types.fbs"; -include "function_call_result.fbs"; -include "function_call.fbs"; -include "guest_error.fbs"; -include "guest_log_data.fbs"; -include "guest_trace_data.fbs"; -include "host_function_definition.fbs"; -include "host_function_details.fbs"; diff --git a/src/schema/function_call.fbs b/src/schema/function_call.fbs deleted file mode 100644 index 9ad0d8ddf3..0000000000 --- a/src/schema/function_call.fbs +++ /dev/null @@ -1,33 +0,0 @@ -include "function_types.fbs"; - -namespace Hyperlight.Generated; - -enum FunctionCallType : ubyte { - // none is invalid, its the default, its only here to ensure that the type is explicitly set to guest or host as none should fail validation if a buffer using it is written to memory - none, - guest, - host, -} - -// Flatbuffers rust generator doesn't support vectors of unions so we have to wrap them in a table -// see https://github.com/google/flatbuffers/issues/5024 - -table Parameter { - value:ParameterValue(required); -} - -table FunctionCall { - function_name:string(required, key); - parameters:[Parameter]; - function_call_type:FunctionCallType; - // For dynamic calls such as WASM functions we need to know the expected return type - // as these functions are not registered in the guest then there is no way of knowing what the return type is expected to be - // we could register all the WASM functions in the guest by examining the WASM module - // but even if we did this we would still not know the return type of the function as WASM metadata does not contain this information - // so we have to rely on the host to tell us what the return type is - // we can also use this to validate what the host expects where we have a statically registered function. - // If we ultimately adopt WIT for IDL then we might not need this any longer - expected_return_type:ReturnType; -} - -root_type FunctionCall; \ No newline at end of file diff --git a/src/schema/function_call_result.fbs b/src/schema/function_call_result.fbs deleted file mode 100644 index 53ea52b255..0000000000 --- a/src/schema/function_call_result.fbs +++ /dev/null @@ -1,21 +0,0 @@ -include "function_types.fbs"; -include "guest_error.fbs"; - -namespace Hyperlight.Generated; - -// Wrapper so ReturnValue (a union) can be a single union variant -table ReturnValueBox { - value: ReturnValue (required); -} - -// Result-like union -union FunctionCallResultType { - ReturnValueBox, - GuestError -} - -table FunctionCallResult { - result: FunctionCallResultType (required); -} - -root_type FunctionCallResult; \ No newline at end of file diff --git a/src/schema/function_types.fbs b/src/schema/function_types.fbs deleted file mode 100644 index 6bf5791d21..0000000000 --- a/src/schema/function_types.fbs +++ /dev/null @@ -1,123 +0,0 @@ -namespace Hyperlight.Generated; - -// the following tables are used to hold the values of the parameters and return values of functions -// they are named with hl prefix to avoid reserved word clashes in generated code - -// hlint is a 32 bit signed integer - -table hlint { - value:int; -} - -// hluint is a 32 bit unsigned integer - -table hluint { - value:uint; -} - -// hllong is a 64 bit signed integer - -table hllong { - value:long; -} - -// hlulong is a 64 bit unsigned integer - -table hlulong { - value:ulong; -} - -// hlfloat is 32-bit float - -table hlfloat { - value:float; -} - -// hldouble is 64-bit float - -table hldouble { - value:double; -} - -// hlstring is a UTF8 encoded string - -table hlstring{ - value:string; -} - -// hlbool is a C99 boolean - -table hlbool { - value:bool; -} - -// hlexternalbytes declares a logical byte value stored outside the FlatBuffer. -// chunked requests the ByteChunks representation rather than VecBytes. - -table hlexternalbytes { - length:ulong; - chunked:bool; -} - -// hlvoid is a void (used for functions that return nothing) - -table hlvoid { -} - -// This represents a parameter value in a function call - -union ParameterValue { - hlint = 1, - hluint = 2, - hllong = 3, - hlulong = 4, - hlfloat = 5, - hldouble = 6, - hlstring = 7, - hlbool = 8, - // Tag 9 is reserved for embedded byte vectors. - hlexternalbytes = 10, -} - -// This represents a parameter type in a function definition - -enum ParameterType : ubyte { - hlint, - hluint, - hllong, - hlulong, - hlfloat, - hldouble, - hlstring, - hlbool, - hlvecbytes, - hlbytechunks, -} - -enum ReturnType : ubyte { - hlint, - hluint, - hllong, - hlulong, - hlfloat, - hldouble, - hlstring, - hlbool, - hlvoid, - hlsizeprefixedbuffer, - hlbytechunks, -} - -union ReturnValue { - hlint = 1, - hluint = 2, - hllong = 3, - hlulong = 4, - hlfloat = 5, - hldouble = 6, - hlstring = 7, - hlbool = 8, - hlvoid = 9, - // Tag 10 is reserved for embedded size-prefixed buffers. - hlexternalbytes = 11, -} diff --git a/src/schema/guest_error.fbs b/src/schema/guest_error.fbs deleted file mode 100644 index 551dea7647..0000000000 --- a/src/schema/guest_error.fbs +++ /dev/null @@ -1,27 +0,0 @@ -namespace Hyperlight.Generated; - -enum ErrorCode: ulong { - NoError = 0, // The function call was successful - UnsupportedParameterType = 2, // The type of the parameter is not supported by the Guest. - GuestFunctionNameNotProvided = 3, // The Guest function name was not provided by the host. - GuestFunctionNotFound = 4, // The function does not exist in the Guest. - GuestFunctionIncorrecNoOfParameters = 5, // Incorrect number of parameters for the guest function. - GispatchFunctionPointerNotSet = 6, // Host Call Dispatch Function Pointer is not present. - OutbError = 7, // Error in OutB Function - UnknownError = 8, // The guest error is unknown. - GsCheckFailed = 10, // __security_check_cookie failed - TooManyGuestFunctions = 11, // The guest tried to register too many guest functions - FailureInDlmalloc = 12, // this error is set when dlmalloc calls ABORT (e.g. function defined in ABORT (dlmalloc_abort() calls setError with this errorcode) - MallocFailed = 13, // this error is set when malloc returns 0 bytes. - GuestFunctionParameterTypeMismatch = 14, // The function call parameter type was not the expected type. - GuestError = 15, // An error occurred in the guest Guest implementation should use this along with a message when calling setError. - ArrayLengthParamIsMissing = 16, // Expected a int parameter to follow a byte array - HostError = 17 // Guest called Host Function, which errored. -} - -table GuestError { - code: ErrorCode; - message: string; -} - -root_type GuestError; \ No newline at end of file diff --git a/src/schema/guest_log_data.fbs b/src/schema/guest_log_data.fbs deleted file mode 100644 index d9f64c60a3..0000000000 --- a/src/schema/guest_log_data.fbs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Hyperlight.Generated; - -enum LogLevel: uint8 { - Trace = 0, - Debug = 1, - Information = 2, - Warning = 3, - Error = 4, - Critical = 5, - None = 6, -} - -table GuestLogData { - message: string; - source: string; - level: LogLevel; - caller: string; - source_file: string; - line: uint32; -} - -root_type GuestLogData; diff --git a/src/schema/guest_trace_data.fbs b/src/schema/guest_trace_data.fbs deleted file mode 100644 index ebecc8f05d..0000000000 --- a/src/schema/guest_trace_data.fbs +++ /dev/null @@ -1,51 +0,0 @@ -namespace Hyperlight.Generated; - -table KeyValue { - key: string (required); - value: string (required); -} - -table OpenSpanType { - id: ulong; - parent: ulong = null; - name: string (required); - target: string (required); - tsc: ulong; - fields: [KeyValue]; -} - -table CloseSpanType { - id: ulong; - tsc: ulong; -} - -table LogEventType { - parent_id: ulong; - name: string (required); - tsc: ulong; - fields: [KeyValue]; -} - -table EditSpanType { - id: ulong; - fields: [KeyValue]; -} - -table GuestStartType { - tsc: ulong; -} - -// Result-like union -union GuestEventType { - OpenSpan:OpenSpanType, - CloseSpan:CloseSpanType, - LogEvent:LogEventType, - EditSpan:EditSpanType, - GuestStart:GuestStartType, -} - -table GuestEventEnvelopeType { - event: GuestEventType; -} - -root_type GuestEventEnvelopeType; diff --git a/src/schema/host_function_definition.fbs b/src/schema/host_function_definition.fbs deleted file mode 100644 index 2367007b7b..0000000000 --- a/src/schema/host_function_definition.fbs +++ /dev/null @@ -1,11 +0,0 @@ -include "function_types.fbs"; - -namespace Hyperlight.Generated; - -table HostFunctionDefinition { - function_name:string(required, key); - parameters:[ParameterType]; - return_type:ReturnType; -} - -root_type HostFunctionDefinition; \ No newline at end of file diff --git a/src/schema/host_function_details.fbs b/src/schema/host_function_details.fbs deleted file mode 100644 index 5ebd685761..0000000000 --- a/src/schema/host_function_details.fbs +++ /dev/null @@ -1,9 +0,0 @@ -include "host_function_definition.fbs"; - -namespace Hyperlight.Generated; - -table HostFunctionDetails { - functions:[HostFunctionDefinition]; -} - -root_type HostFunctionDetails; \ No newline at end of file diff --git a/src/tests/rust_guests/Cargo.lock b/src/tests/rust_guests/Cargo.lock index 654ea80649..97e78577ee 100644 --- a/src/tests/rust_guests/Cargo.lock +++ b/src/tests/rust_guests/Cargo.lock @@ -117,6 +117,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -203,16 +212,6 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" -[[package]] -name = "flatbuffers" -version = "25.12.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" -dependencies = [ - "bitflags 2.13.1", - "rustc_version", -] - [[package]] name = "foldhash" version = "0.2.0" @@ -239,8 +238,9 @@ dependencies = [ "bytemuck", "bytes", "fixedbitset", - "flatbuffers", "log", + "postcard", + "serde", "smallvec", "spin", "thiserror", @@ -281,7 +281,6 @@ name = "hyperlight-guest" version = "0.19.0" dependencies = [ "anyhow", - "flatbuffers", "hyperlight-common", "hyperlight-guest-tracing", "itertools", @@ -293,7 +292,6 @@ dependencies = [ name = "hyperlight-guest-bin" version = "0.19.0" dependencies = [ - "flatbuffers", "hyperlight-common", "hyperlight-guest", "hyperlight-guest-macro", @@ -480,6 +478,16 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "serde", +] + [[package]] name = "prettyplease" version = "0.3.0" @@ -546,15 +554,6 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - [[package]] name = "scopeguard" version = "1.2.0" @@ -574,6 +573,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]]