Skip to main content

reverie_liteinst/
lib.rs

1#![forbid(unsafe_op_in_unsafe_fn)]
2
3use std::env;
4use std::ffi::OsStr;
5#[cfg(target_arch = "x86_64")]
6use std::ffi::OsString;
7use std::io;
8#[cfg(target_arch = "x86_64")]
9use std::os::unix::ffi::OsStringExt;
10use std::path::PathBuf;
11use std::process::Command;
12
13#[cfg(not(all(
14    target_os = "linux",
15    any(target_arch = "x86_64", target_arch = "aarch64")
16)))]
17compile_error!("reverie-liteinst requires Linux x86-64 or aarch64");
18
19mod allocator_backing;
20
21// This crate's own unit-test binary is a final image too: give it the legacy
22// backing declaration selected_backing() requires at link time.
23#[cfg(test)]
24crate::declare_legacy_tool_backing!();
25#[cfg(feature = "allocator-fixture")]
26#[doc(hidden)]
27pub mod allocator_fixture;
28mod backend;
29#[cfg(feature = "allocator-fixture")]
30#[doc(hidden)]
31pub mod fixed_arena_fixture;
32#[cfg(feature = "allocator-fixture")]
33#[doc(hidden)]
34pub mod generic_fixture;
35#[cfg(feature = "exec-private-init")]
36mod initial_image_stats;
37#[cfg(all(feature = "liteinst", target_arch = "x86_64"))]
38mod interior_entry;
39#[cfg(any(target_arch = "aarch64", test))]
40pub mod lazy_promote;
41#[cfg(all(feature = "liteinst", target_arch = "x86_64"))]
42mod liteinst_census;
43#[cfg(feature = "native-exec-state")]
44pub mod native_exec_state;
45mod patch_alloc;
46#[cfg(feature = "allocator-fixture")]
47#[doc(hidden)]
48pub mod stack_fixture;
49#[cfg(feature = "allocator-fixture")]
50#[doc(hidden)]
51pub mod standalone_fixture;
52mod stats;
53mod straddler;
54mod syscall_fallback;
55
56pub use backend::COORDINATOR_ENV;
57#[cfg(feature = "exec-private-init")]
58pub use backend::InitialImageStatsCollector;
59#[cfg(feature = "exec-private-init")]
60pub use backend::InitialImageStatsServer;
61pub use backend::LiteinstBackend;
62pub use backend::PreloadBootstrap;
63pub use backend::STATS_COORDINATOR_ENV;
64pub use backend::TOOL_PRELOAD_ENV;
65pub use backend::take_preload_bootstrap;
66pub use stats::InheritedEntries;
67pub use stats::LiteinstBackendStatsSnapshot;
68pub use stats::LiteinstBackendStatsSource;
69pub use stats::LiteinstDispatchPath;
70pub use stats::LiteinstPatchDecision;
71pub use stats::guest_stats_enabled;
72pub mod rpc;
73mod runtime;
74mod tool_host;
75
76// AUTONOMOUS-BOT-IMPLEMENTED
77// TODO-HUMAN-REVIEW(PR-252): Review shared reverie-inguest built-in re-exports.
78#[doc(hidden)]
79pub use allocator_backing::AllocatorBackingDescriptor;
80pub use patch_alloc::FixedPrivatePatchAllocator as FixedToolAllocator;
81pub use patch_alloc::PatchAllocator as ScopedToolAllocator;
82pub use patch_alloc::PrivatePatchAllocator as PrivateToolAllocator;
83/// Shared `reverie-inguest` built-in tool enum and getpid spoof constant.
84///
85/// These are re-exported verbatim so LiteInst and e9patch present the same
86/// built-in surface; the same [`BuiltinTool`] value installs the same dispatcher
87/// in both backends via `reverie_inguest::install_builtin`.
88pub use reverie_inguest::BuiltinTool;
89pub use reverie_inguest::SPOOF_PID;
90pub use reverie_inguest::guest::host::CreationHookError;
91pub use reverie_inguest::guest::host::CreationRefusal;
92pub use reverie_inguest::guest::host::PhysicalCreation;
93pub use reverie_inguest::guest::host::PhysicalCreationHook;
94pub use reverie_inguest::guest::host::RefusedChild;
95pub use reverie_inguest::guest::host::set_physical_creation_hook;
96/// The runtime's records of guest calls it refused before any Tool ran (a
97/// signal handler or alternate stack; a fork-like call while process forks
98/// are not allowed). A take returns what was refused in this process since
99/// the last take and clears it.
100pub use reverie_inguest::guest::protect::RefusedProcessCreations;
101pub use reverie_inguest::guest::protect::RefusedSignalControls;
102pub use reverie_inguest::guest::protect::take_refused_process_creations;
103pub use reverie_inguest::guest::protect::take_refused_signal_controls;
104/// Native fixed-stack entry used by the owned standalone leaf.
105///
106/// x86-64 only: on aarch64 this name is not exported (compile-time API
107/// narrowing, recorded in the L0 hand-off) because the inguest entry it
108/// names has no aarch64 body; exporting it would publish a path straight
109/// to `brk #0`.
110#[cfg(target_arch = "x86_64")]
111#[doc(hidden)]
112pub use reverie_inguest::guest::tool_region::constructor_entry;
113// AUTONOMOUS-BOT-IMPLEMENTED
114// TODO-HUMAN-REVIEW(PR-254): Review shared RuntimeConfig alt-stack re-exports.
115/// `REVERIE_LITEINST_ALT_STACK` selector and parser for the shared
116/// `reverie-inguest` `RuntimeConfig` alt-stack knob.
117pub use runtime::ALT_STACK_ENV;
118pub use runtime::IN_GUEST_STAGE_STREAM_ENV;
119pub use runtime::PROCESS_FORK_ENV;
120pub use runtime::SIGALRM_HANDLERS_ENV;
121pub use runtime::SITE_PATCHING_ENV;
122/// `REVERIE_LITEINST_TOOL` values and parser for shared built-in selection.
123pub use runtime::TOOL_PASSTHROUGH;
124pub use runtime::TOOL_SPOOF_GETPID;
125pub use runtime::alt_stack_from_env_value;
126pub use runtime::builtin_tool_from_env_value;
127pub use runtime::reserve_tool_output_fd;
128pub use runtime::site_patching_enabled;
129pub use runtime::site_patching_from_env_value;
130pub use runtime::tool_output_fd;
131pub use straddler::STRADDLER_STALENESS_TICKS_ENV;
132#[cfg(all(feature = "liteinst", target_arch = "x86_64"))]
133pub use straddler::straddler_staleness_from_env_value;
134#[cfg(feature = "exec-private-init")]
135pub use tool_host::InstalledInitialImage;
136#[cfg(feature = "exec-native-injection")]
137pub use tool_host::InstalledSuccessorImage;
138#[cfg(feature = "exec-native-injection")]
139pub use tool_host::NativeSuccessorConsumer;
140#[cfg(feature = "exec-private-init")]
141pub use tool_host::PreparedInitialImage;
142#[cfg(feature = "exec-native-injection")]
143pub use tool_host::PreparedSuccessorImage;
144pub use tool_host::blocking_global_rpc;
145#[cfg(feature = "exec-private-init")]
146pub use tool_host::initialize_initial_image_lifecycle;
147pub use tool_host::install_tool;
148pub use tool_host::install_tool_from_bootstrap;
149pub use tool_host::install_tool_from_bootstrap_with_runtime;
150
151/// Checks that this linked root's allocator uses the runtime's selected Tool
152/// backing. Call during installation, while a dispatch allocation scope is live,
153/// before connecting or publishing a Tool. This grants no installation or
154/// private-image authority.
155pub fn preflight_tool_allocator() -> std::io::Result<()> {
156    patch_alloc::preflight_allocator()
157}
158#[cfg(all(feature = "loader-private-runtime", target_env = "musl"))]
159pub use tool_host::InstalledMappedSuccessorImage;
160#[cfg(all(feature = "loader-private-runtime", target_env = "musl"))]
161pub use tool_host::MappedSuccessorPreparation;
162#[cfg(feature = "loader-private-runtime")]
163pub use tool_host::MappedSuccessorVerifiedDigests;
164#[cfg(all(feature = "loader-private-runtime", target_env = "musl"))]
165pub use tool_host::PreparedMappedSuccessorImage;
166#[cfg(feature = "exec-private-init")]
167pub use tool_host::ValidatedStraddlerStaleness;
168#[cfg(all(feature = "loader-private-runtime", target_env = "musl"))]
169pub use tool_host::initialize_mapped_successor_lifecycle;
170#[cfg(feature = "exec-private-init")]
171pub use tool_host::install_tool_initial_image;
172#[cfg(feature = "exec-native-injection")]
173pub use tool_host::install_tool_initial_image_with_admitted_native_exec;
174#[cfg(feature = "exec-native-injection")]
175pub use tool_host::install_tool_initial_image_with_native_exec;
176#[cfg(all(feature = "loader-private-runtime", target_env = "musl"))]
177pub use tool_host::install_tool_mapped_successor_image;
178pub use tool_host::install_tool_quiescent;
179#[cfg(feature = "exec-native-injection")]
180pub use tool_host::install_tool_successor_image;
181#[cfg(feature = "exec-private-init")]
182pub use tool_host::prepare_tool_initial_image;
183#[cfg(feature = "exec-private-init")]
184pub use tool_host::prepare_tool_initial_image_validated;
185#[cfg(all(feature = "loader-private-runtime", target_env = "musl"))]
186pub use tool_host::prepare_tool_mapped_initial_image;
187#[cfg(all(feature = "loader-private-runtime", target_env = "musl"))]
188pub use tool_host::prepare_tool_mapped_initial_image_validated;
189#[cfg(all(feature = "loader-private-runtime", target_env = "musl"))]
190pub use tool_host::prepare_tool_mapped_successor_image_validated;
191#[cfg(feature = "exec-native-injection")]
192pub use tool_host::prepare_tool_successor_image;
193#[cfg(feature = "exec-native-injection")]
194pub use tool_host::prepare_tool_successor_image_validated;
195#[cfg(feature = "exec-private-init")]
196pub use tool_host::validate_straddler_selector;
197
198// AUTONOMOUS-BOT-IMPLEMENTED
199// TODO-HUMAN-REVIEW(PR-87): Review the inherited compatibility event channel.
200/// Environment variable selecting an inherited descriptor for compatibility events.
201///
202/// When unset, compatibility events retain their standalone behavior and use
203/// standard error.
204pub const COMPAT_EVENT_FD_ENV: &str = "REVERIE_LITEINST_EVENT_FD";
205
206/// Environment variable selecting a per-launch compatibility-event cookie.
207///
208/// A controller that sets [`COMPAT_EVENT_FD_ENV`] must also set this to a
209/// nonzero decimal `u64`. The runtime removes both variables before guest code
210/// starts and includes the cookie in every dedicated-channel record.
211pub const COMPAT_EVENT_COOKIE_ENV: &str = "REVERIE_LITEINST_EVENT_COOKIE";
212
213/// Built-in synchronous tool executed by the preload runtime.
214#[derive(Clone, Copy, Debug, Eq, PartialEq)]
215pub enum PreloadTool {
216    /// Emit one detailed line for every trapped syscall.
217    Strace,
218    /// Emit stable syscall-number markers for external comparison.
219    Compatibility,
220}
221
222impl PreloadTool {
223    const fn as_str(self) -> &'static str {
224        match self {
225            Self::Strace => "strace",
226            Self::Compatibility => "compat",
227        }
228    }
229}
230
231/// Locates the preload runtime produced beside the current executable.
232pub fn preload_library_path() -> io::Result<PathBuf> {
233    if let Some(path) = env::var_os("REVERIE_LITEINST_PRELOAD") {
234        let path = PathBuf::from(path);
235        return path.is_file().then_some(path).ok_or_else(|| {
236            io::Error::new(
237                io::ErrorKind::NotFound,
238                "REVERIE_LITEINST_PRELOAD does not name a file",
239            )
240        });
241    }
242
243    preload_library_beside(&env::current_exe()?)
244}
245
246fn preload_library_beside(executable: &std::path::Path) -> io::Result<PathBuf> {
247    let parent = executable.parent().ok_or_else(|| {
248        io::Error::new(io::ErrorKind::NotFound, "current executable has no parent")
249    })?;
250    [
251        parent.join("libreverie_liteinst_preload.so"),
252        parent.join("deps/libreverie_liteinst_preload.so"),
253        parent
254            .parent()
255            .unwrap_or(parent)
256            .join("libreverie_liteinst_preload.so"),
257        // A warm pre-split Cargo tree may retain the old core cdylib under this
258        // canonical installed name. Prefer every new leaf before that fallback.
259        parent.join("libreverie_liteinst.so"),
260    ]
261    .into_iter()
262    .find(|path| path.is_file())
263    .ok_or_else(|| {
264        io::Error::new(
265            io::ErrorKind::NotFound,
266            format!(
267                "cannot find libreverie_liteinst.so beside {}",
268                executable.display()
269            ),
270        )
271    })
272}
273
274/// Configures a guest command to load the runtime and select a built-in tool.
275pub fn configure_command(command: &mut Command, tool: PreloadTool) -> io::Result<()> {
276    let mut preload = preload_library_path()?.into_os_string();
277    if let Some(existing) = env::var_os("LD_PRELOAD").filter(|value| !value.is_empty()) {
278        preload.push(OsStr::new(":"));
279        preload.push(existing);
280    }
281    command
282        .env("LD_PRELOAD", preload)
283        .env("REVERIE_LITEINST_TOOL", tool.as_str());
284    Ok(())
285}
286
287// AUTONOMOUS-BOT-IMPLEMENTED
288// TODO-HUMAN-REVIEW(PR-252): Review shared built-in command configuration.
289/// Maps a shared [`BuiltinTool`] to its `REVERIE_LITEINST_TOOL` selector value.
290fn builtin_tool_env_value(tool: BuiltinTool) -> &'static str {
291    match tool {
292        BuiltinTool::Passthrough => TOOL_PASSTHROUGH,
293        BuiltinTool::SpoofGetpid => TOOL_SPOOF_GETPID,
294    }
295}
296
297/// Configures a guest command to load the runtime and select a shared built-in.
298///
299/// This is the built-in analog of [`configure_command`]: it sets `LD_PRELOAD`
300/// and `REVERIE_LITEINST_TOOL` to a shared `reverie-inguest` [`BuiltinTool`]
301/// selector, so the runtime installs the built-in verbatim through
302/// `reverie_inguest::install_builtin` (no LiteInst patching). It mirrors
303/// e9patch's launcher-side built-in configuration.
304pub fn configure_command_builtin(command: &mut Command, tool: BuiltinTool) -> io::Result<()> {
305    let mut preload = preload_library_path()?.into_os_string();
306    if let Some(existing) = env::var_os("LD_PRELOAD").filter(|value| !value.is_empty()) {
307        preload.push(OsStr::new(":"));
308        preload.push(existing);
309    }
310    command
311        .env("LD_PRELOAD", preload)
312        .env("REVERIE_LITEINST_TOOL", builtin_tool_env_value(tool));
313    Ok(())
314}
315
316// AUTONOMOUS-BOT-IMPLEMENTED
317// TODO-HUMAN-REVIEW(PR-254): Review launcher-side shared RuntimeConfig alt-stack selector.
318/// Selects the shared `reverie-inguest` `RuntimeConfig` alt-stack knob for a guest.
319///
320/// Sets [`ALT_STACK_ENV`] so the in-guest runtime installs its `SIGSYS` handler
321/// with or without an alternate signal stack (`RuntimeConfig::use_alt_stack`).
322/// The `RuntimeConfig` and the controller honoring it are shared with e9patch in
323/// `reverie-inguest`; only the env-var spelling is LiteInst's. Leaving this
324/// unset preserves the shared default (alt stack on). It composes with
325/// [`configure_command`] and [`configure_command_builtin`]; the written value
326/// round-trips through [`alt_stack_from_env_value`].
327pub fn set_guest_alt_stack(command: &mut Command, use_alt_stack: bool) {
328    command.env(ALT_STACK_ENV, if use_alt_stack { "1" } else { "0" });
329}
330
331/// Select whether the direct runtime may forward process-creation syscalls.
332///
333/// This does not add support for thread-style clone. It lets a consumer retain
334/// the existing fail-closed boundary until its Tool lifecycle has a positive
335/// fork bracket.
336pub fn set_guest_process_forks(command: &mut Command, allowed: bool) {
337    command.env(PROCESS_FORK_ENV, if allowed { "1" } else { "0" });
338}
339
340/// Select whether an in-guest Reverie Tool patches trapping syscall sites.
341///
342/// With `enabled == false` every trapping syscall runs the Tool through the
343/// in-guest `SIGSYS` fallback and no syscall site is patched; subscribed
344/// `cpuid`, `rdtsc`, and `rdtscp` instruction sites still are. See
345/// [`SITE_PATCHING_ENV`].
346/// The written value round-trips through [`site_patching_from_env_value`].
347pub fn set_guest_site_patching(command: &mut Command, enabled: bool) {
348    command.env(SITE_PATCHING_ENV, if enabled { "1" } else { "0" });
349}
350
351// TODO-HUMAN-REVIEW(#61): this constructor installs process-wide signal and seccomp state.
352/// Initializes the preload runtime when selected by the launcher environment.
353///
354/// The actual preload leaf owns the constructor and uses
355/// [`declare_fixed_tool_allocator!`]. An embedded legacy root uses
356/// [`declare_legacy_scoped_tool_allocator!`] or
357/// [`declare_legacy_private_tool_allocator!`] for its existing policy. Each
358/// declaration couples the compiler allocator with its immutable backing
359/// contract; a missing or duplicate declaration is a link error. The core
360/// installs neither a default allocator nor its own
361/// LiteInst constructor. The independent legacy `reverie-inguest` constructor
362/// can still be enabled by that dependency's `preload-constructor` feature.
363/// A caller whose allocator does not own the dispatch preflight allocation is
364/// refused before runtime activation. This explicit call first reserves a fixed
365/// guarded scalar stack, even when its environment getter selects no Tool. Such
366/// a call returns with that reservation retained and without runtime activation.
367/// aarch64 contract change (L0): the aarch64 body reserves nothing — with no
368/// Tool selected it returns without any reservation, and with a Tool selected
369/// it refuses (see `refuse_aarch64_c_entry_if_selected`); the scalar stack is
370/// an x86-64-only contract until the aarch64 native bootstrap exists.
371/// A repeated call, or an already-owned/colliding region, refuses before a
372/// second getter/body invocation. The selector-absent standalone constructor
373/// remains a separate inert path and does not call this entry.
374///
375/// # Safety
376///
377/// Call once during trusted single-threaded startup, with clear DF and no
378/// active runtime filter. Repeated calls refuse before reading the selector
379/// or installing another runtime.
380#[cfg(target_arch = "x86_64")]
381#[unsafe(naked)]
382#[unsafe(no_mangle)]
383pub unsafe extern "C" fn reverie_liteinst_initialize() {
384    core::arch::naked_asm!(
385        "endbr64",
386        "lea rdi, [rip + {body}]",
387        "jmp {entry}",
388        body = sym reverie_liteinst_generic_body,
389        entry = sym reverie_inguest::guest::tool_region::generic_entry,
390    );
391}
392
393/// Allocation-free aarch64 refusal for the C constructor entries.
394///
395/// Runs before `enter_dispatch` and `preflight_allocator`: the fixed tool
396/// allocator returns null before its arenas are published, and publication
397/// happens only in the native bootstrap, which has no aarch64 body, so any
398/// allocation on this path (including `io::Error` construction and
399/// `eprintln!`) would abort instead of refusing. Reads the selector with
400/// inguest's allocation-free environment scan, writes one fixed line naming
401/// aarch64 to stderr, and exits 127. With no Tool selected it returns and the
402/// entries stay inert.
403///
404/// # Safety
405///
406/// Same startup contract as the entries that call it: trusted
407/// single-threaded startup before application threads and filters.
408#[cfg(target_arch = "aarch64")]
409unsafe fn refuse_aarch64_c_entry_if_selected() {
410    if reverie_inguest::guest::support::environment_value(b"REVERIE_LITEINST_TOOL").is_some() {
411        const MESSAGE: &[u8] =
412            b"reverie-liteinst initialization failed: in-guest LiteInst runtime is not supported on aarch64\n";
413        // SAFETY: fd 2 write of a fixed byte string, then process exit; no
414        // allocation and no other state is touched on this path.
415        unsafe {
416            let _ = libc::write(2, MESSAGE.as_ptr() as *const libc::c_void, MESSAGE.len());
417            libc::_exit(127);
418        }
419    }
420}
421
422/// aarch64 body of [`reverie_liteinst_initialize`]: inert with no Tool
423/// selected, allocation-free named refusal (exit 127) with one selected.
424///
425/// # Safety
426///
427/// Same contract as the x86-64 entry: call once during trusted
428/// single-threaded startup, with clear DF and no active runtime filter.
429#[cfg(target_arch = "aarch64")]
430#[unsafe(no_mangle)]
431pub unsafe extern "C" fn reverie_liteinst_initialize() {
432    // SAFETY: same trusted single-threaded startup contract as the x86-64
433    // entry; the helper only scans the environment and, when a Tool is
434    // selected, writes one fixed line and exits.
435    unsafe { refuse_aarch64_c_entry_if_selected() }
436}
437
438// Distinct local Rust body: the existing dispatch/preflight/getter order stays
439// intact, and only the native entry may supply this body to its fresh bootstrap.
440#[cfg(target_arch = "x86_64")]
441#[unsafe(no_mangle)]
442#[inline(never)]
443unsafe extern "C" fn reverie_liteinst_generic_body() {
444    let _scope = reverie_inguest::guest::alloc::enter_dispatch();
445    initialization_or_exit(
446        patch_alloc::preflight_allocator().and_then(|()| runtime::initialize_from_environment()),
447    );
448}
449
450#[cfg(target_arch = "x86_64")]
451core::arch::global_asm!(".hidden reverie_liteinst_generic_body");
452
453/// Establish an ordinary region owner for the explicit-entry refusal control.
454/// This setup operation is separate from all read-only placement queries.
455#[cfg(feature = "allocator-fixture")]
456#[doc(hidden)]
457#[unsafe(no_mangle)]
458pub extern "C" fn m4_generic_ordinary_owner_setup() -> i32 {
459    match reverie_inguest::guest::tool_region::ToolRegion::reserve() {
460        Ok(_) => 0,
461        Err(error) => -error.raw_os_error().unwrap_or(libc::EIO),
462    }
463}
464
465/// Initialize the actual standalone leaf after native fixed-stack adoption.
466///
467/// This private leaf control reads the first exact selector from the current
468/// `environ` vector. It deliberately does not consult an interposed `getenv`;
469/// [`reverie_liteinst_initialize`] retains that generic embedding behavior.
470/// The owned value is copied before initialization calls other providers.
471///
472/// # Safety
473///
474/// Call once from the actual leaf's authenticated constructor body, before
475/// application threads start. The environment must remain valid and stable
476/// from the native selector scan through this copy. No active runtime may
477/// precede this initialization. The caller invokes its compatibility resolver
478/// only after this function returns and its dispatch scope has been dropped.
479#[doc(hidden)]
480#[inline(never)]
481#[unsafe(export_name = "reverie_liteinst_standalone_initialize")]
482pub unsafe extern "C" fn initialize_standalone() {
483    // aarch64: refuse before enter_dispatch/preflight (allocation would
484    // abort pre-publication); with no selector the entry stays inert.
485    #[cfg(target_arch = "aarch64")]
486    {
487        // SAFETY: same authenticated constructor-body contract as below; the
488        // helper only scans the environment and exits when a Tool is selected.
489        unsafe { refuse_aarch64_c_entry_if_selected() }
490    }
491    #[cfg(not(target_arch = "aarch64"))]
492    {
493        let _scope = reverie_inguest::guest::alloc::enter_dispatch();
494        let result = patch_alloc::preflight_allocator().and_then(|()| {
495            let selected =
496                reverie_inguest::guest::support::environment_value(b"REVERIE_LITEINST_TOOL")
497                    .ok_or_else(|| {
498                        io::Error::new(
499                            io::ErrorKind::InvalidInput,
500                            "REVERIE_LITEINST_TOOL disappeared during standalone initialization",
501                        )
502                    })?;
503            let selected = OsString::from_vec(selected.to_vec());
504            runtime::initialize_from_selected_value(Some(&selected))
505        });
506        initialization_or_exit(result);
507    }
508}
509
510// The actual leaf cannot be redirected through another object's initializer.
511// This does not change the separately exported generic initializer.
512core::arch::global_asm!(".hidden reverie_liteinst_standalone_initialize");
513
514#[cfg(target_arch = "x86_64")]
515fn initialization_or_exit(result: io::Result<()>) {
516    if let Err(error) = result {
517        eprintln!("reverie-liteinst initialization failed: {error}");
518        // libc's _exit, not a raw exit_group from this library: an exit_group
519        // issued from the runtime's own code bypasses the runtime's exit path,
520        // so an installed runtime would not report the process's statistics
521        // to the coordinator. The process ends here, so an interposed _exit
522        // can change only a heap that is about to disappear.
523        unsafe { libc::_exit(127) };
524    }
525}
526
527// TODO-HUMAN-REVIEW(PR-127): Review public per-site instrumentation counters.
528/// Returns the number of SIGSYS deliveries observed at one syscall instruction.
529#[unsafe(no_mangle)]
530pub extern "C" fn reverie_liteinst_site_trap_count(address: u64) -> u64 {
531    runtime::site_counts(address).0
532}
533
534/// Returns the number of installed-hook callbacks observed at one syscall instruction.
535#[unsafe(no_mangle)]
536pub extern "C" fn reverie_liteinst_site_hook_count(address: u64) -> u64 {
537    runtime::site_counts(address).1
538}
539
540// TODO-HUMAN-REVIEW(PR-249): Review public fallback-surface observability counters.
541/// Total syscalls that reached LiteInst's fallback dispatch path.
542///
543/// These sites have no installed hook. Typed Tool mode can dispatch them after
544/// signal return, so the count includes successful Tool calls and is not a
545/// syscall-failure count. The per-syscall-number breakdown uses the same keys
546/// as `reverie_e9patch_fallback_dispatch_count`.
547#[unsafe(no_mangle)]
548pub extern "C" fn reverie_liteinst_fallback_dispatch_count() -> u64 {
549    runtime::fallback_dispatch_count()
550}
551
552// TODO-HUMAN-REVIEW(PR-249): Review public fallback-surface observability counters.
553/// Number of times syscall `number` reached LiteInst's fallback dispatch path.
554///
555/// The per-syscall-number analog of the per-site counters, keyed by syscall
556/// number to match `reverie_e9patch_fallback_syscall_count`. Returns `0` for a
557/// negative number or one outside the tracked table; those are only reflected in
558/// [`reverie_liteinst_fallback_dispatch_count`].
559#[unsafe(no_mangle)]
560pub extern "C" fn reverie_liteinst_fallback_syscall_count(number: i64) -> u64 {
561    runtime::fallback_syscall_count(number)
562}
563
564/// Fallback attempts refused by the runtime before ordinary Tool dispatch.
565///
566/// This is a subset of [`reverie_liteinst_fallback_dispatch_count`]. Errors
567/// returned by a successfully invoked Tool are not runtime refusals.
568#[unsafe(no_mangle)]
569pub extern "C" fn reverie_liteinst_fallback_refusal_count() -> u64 {
570    runtime::fallback_refusal_count()
571}
572
573/// Per-syscall breakdown of [`reverie_liteinst_fallback_refusal_count`].
574/// Numbers outside the tracked table contribute only to the total.
575#[unsafe(no_mangle)]
576pub extern "C" fn reverie_liteinst_fallback_syscall_refusal_count(number: i64) -> u64 {
577    runtime::fallback_syscall_refusal_count(number)
578}
579
580#[cfg(test)]
581mod tests {
582    use std::ffi::OsStr;
583    use std::process::Command;
584
585    use super::ALT_STACK_ENV;
586    use super::SITE_PATCHING_ENV;
587    use super::alt_stack_from_env_value;
588    use super::set_guest_alt_stack;
589    use super::set_guest_site_patching;
590    use super::site_patching_from_env_value;
591
592    #[test]
593    fn generated_preload_leaves_precede_a_stale_canonical_artifact() {
594        let root = tempfile::tempdir().unwrap();
595        let debug = root.path().join("debug");
596        let deps = debug.join("deps");
597        std::fs::create_dir_all(&deps).unwrap();
598        let executable = debug.join("reverie-liteinst-strace");
599        let installed = debug.join("libreverie_liteinst.so");
600        std::fs::write(&installed, b"old core artifact or installed runtime").unwrap();
601        // Canonical installation still works when there is no generated leaf.
602        assert_eq!(
603            super::preload_library_beside(&executable).unwrap(),
604            installed
605        );
606        // Reproduce a warm Cargo tree after the package split: the old core
607        // artifact must not hide the newly produced private-allocator leaf.
608        let generated = deps.join("libreverie_liteinst_preload.so");
609        std::fs::write(&generated, b"fresh preload leaf").unwrap();
610        assert_eq!(
611            super::preload_library_beside(&executable).unwrap(),
612            generated
613        );
614        std::fs::remove_file(&generated).unwrap();
615        // A test executable under deps must also prefer the new parent leaf
616        // over a legacy artifact beside that executable.
617        let test_executable = deps.join("strace-test");
618        std::fs::write(deps.join("libreverie_liteinst.so"), b"stale core").unwrap();
619        let parent_leaf = debug.join("libreverie_liteinst_preload.so");
620        std::fs::write(&parent_leaf, b"fresh preload leaf").unwrap();
621        assert_eq!(
622            super::preload_library_beside(&test_executable).unwrap(),
623            parent_leaf
624        );
625    }
626
627    /// The value the launcher writes must parse back to the same boolean it
628    /// selected, for both polarities. This closes the loop between the setter
629    /// (`set_guest_alt_stack`) and the runtime-side parser
630    /// (`alt_stack_from_env_value`).
631    #[test]
632    fn alt_stack_setter_round_trips_through_the_parser() {
633        for use_alt_stack in [true, false] {
634            let mut command = Command::new("/bin/true");
635            set_guest_alt_stack(&mut command, use_alt_stack);
636            let written = command
637                .get_envs()
638                .find(|(key, _)| *key == OsStr::new(ALT_STACK_ENV))
639                .and_then(|(_, value)| value)
640                .expect("set_guest_alt_stack must set ALT_STACK_ENV")
641                .to_owned();
642            assert_eq!(
643                alt_stack_from_env_value(Some(written.as_os_str())).unwrap(),
644                use_alt_stack,
645                "written value must parse back to the selected boolean"
646            );
647        }
648    }
649
650    #[cfg(all(feature = "liteinst", target_arch = "x86_64"))]
651    #[test]
652    fn site_patching_setter_round_trips_through_the_parser() {
653        for enabled in [true, false] {
654            let mut command = Command::new("/bin/true");
655            set_guest_site_patching(&mut command, enabled);
656            let written = command
657                .get_envs()
658                .find(|(key, _)| *key == OsStr::new(SITE_PATCHING_ENV))
659                .and_then(|(_, value)| value)
660                .expect("set_guest_site_patching must set SITE_PATCHING_ENV")
661                .to_owned();
662            assert_eq!(
663                site_patching_from_env_value(Some(written.as_os_str())).unwrap(),
664                enabled,
665                "written value must parse back to the selected boolean"
666            );
667        }
668    }
669
670    #[cfg(all(feature = "liteinst", target_arch = "x86_64"))]
671    #[test]
672    fn site_patching_parser_defaults_on_and_rejects_other_values() {
673        assert!(site_patching_from_env_value(None).unwrap());
674        for rejected in ["", " 0", "0 ", "off", "false", "2", "yes"] {
675            let error = site_patching_from_env_value(Some(OsStr::new(rejected)))
676                .expect_err("only unset, 1, and 0 are accepted");
677            assert_eq!(
678                error.kind(),
679                std::io::ErrorKind::InvalidInput,
680                "{rejected:?}"
681            );
682        }
683    }
684    #[cfg(not(all(feature = "liteinst", target_arch = "x86_64")))]
685    #[test]
686    fn trap_only_build_defaults_off_and_refuses_explicit_patching() {
687        assert!(!site_patching_from_env_value(None).unwrap());
688        assert!(!site_patching_from_env_value(Some(OsStr::new("0"))).unwrap());
689        let mut command = Command::new("/bin/true");
690        set_guest_site_patching(&mut command, true);
691        let requested = command
692            .get_envs()
693            .find(|(key, _)| *key == OsStr::new(SITE_PATCHING_ENV))
694            .and_then(|(_, value)| value)
695            .unwrap();
696        let error = site_patching_from_env_value(Some(requested)).unwrap_err();
697        assert_eq!(error.kind(), std::io::ErrorKind::Unsupported);
698        #[cfg(target_arch = "aarch64")]
699        assert!(error.to_string().contains("not supported on aarch64"));
700        #[cfg(not(target_arch = "aarch64"))]
701        assert!(error.to_string().contains("built without LiteInst"));
702        for rejected in ["", " 0", "0 ", "off", "false", "2", "yes"] {
703            let error = site_patching_from_env_value(Some(OsStr::new(rejected)))
704                .expect_err("invalid selectors must still be rejected");
705            assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
706        }
707    }
708
709    // L0 refusal surface (Decision F(2)): every aarch64 install/selector
710    // entry refuses by name before touching process-global state. Runs
711    // under qemu-aarch64 (G6) and on metal; never compiled on x86-64.
712    #[cfg(target_arch = "aarch64")]
713    #[test]
714    fn aarch64_install_surfaces_refuse_by_name() {
715        fn assert_refusal(surface: &str, error: std::io::Error) {
716            assert_eq!(error.kind(), std::io::ErrorKind::Unsupported, "{surface}");
717            assert!(
718                error.to_string().contains("not supported on aarch64"),
719                "{surface}: {error}"
720            );
721            assert!(error.to_string().contains(surface), "{surface}: {error}");
722        }
723        // SAFETY: on aarch64 every surface refuses before installing any
724        // process-global state (that is exactly what is asserted here).
725        assert_refusal(
726            "install_tool",
727            unsafe { crate::install_tool::<()>("/nonexistent-coordinator") }.unwrap_err(),
728        );
729        assert_refusal(
730            "install_tool_quiescent",
731            unsafe { crate::install_tool_quiescent::<()>("/nonexistent-coordinator") }.unwrap_err(),
732        );
733        assert_refusal(
734            "install_tool_from_bootstrap",
735            unsafe { crate::install_tool_from_bootstrap::<()>("/nonexistent-coordinator") }
736                .unwrap_err(),
737        );
738        assert_refusal(
739            "install_tool_from_bootstrap_with_runtime",
740            unsafe {
741                crate::install_tool_from_bootstrap_with_runtime::<(), _>(
742                    "/nonexistent-coordinator",
743                    |_services| {
744                        crate::tool_host::LiteinstRuntime::new(
745                            crate::stats::GuestStatsHooks::DISABLED,
746                        )
747                    },
748                )
749            }
750            .unwrap_err(),
751        );
752        // The selector path: selected refuses naming aarch64, unselected is Ok.
753        let error =
754            crate::runtime::initialize_from_selected_value(Some(OsStr::new("strace"))).unwrap_err();
755        assert_eq!(error.kind(), std::io::ErrorKind::Unsupported);
756        assert!(error.to_string().contains("not supported on aarch64"));
757        crate::runtime::initialize_from_selected_value(None).unwrap();
758    }
759
760    #[cfg(target_arch = "aarch64")]
761    #[test]
762    fn aarch64_c_entry_refuses_selected_tool_as_subprocess() {
763        const CHILD: &str = "REVERIE_LITEINST_AARCH64_C_ENTRY_CHILD";
764        if std::env::var_os(CHILD).is_some() {
765            // Child: SIGSYS disposition and patching state must be untouched
766            // by an inert (unselected) call; a selected call never returns.
767            let mut action: libc::sigaction = unsafe { std::mem::zeroed() };
768            assert_eq!(
769                unsafe { libc::sigaction(libc::SIGSYS, std::ptr::null(), &mut action) },
770                0
771            );
772            let handler_before = action.sa_sigaction;
773            // SAFETY: isolated child process; the aarch64 body only scans
774            // the environment and exits when a Tool is selected.
775            unsafe { crate::reverie_liteinst_initialize() }
776            let mut after: libc::sigaction = unsafe { std::mem::zeroed() };
777            assert_eq!(
778                unsafe { libc::sigaction(libc::SIGSYS, std::ptr::null(), &mut after) },
779                0
780            );
781            assert_eq!(after.sa_sigaction, handler_before);
782            return;
783        }
784        let exe = std::env::current_exe().unwrap();
785        let args = [
786            "--exact",
787            "tests::aarch64_c_entry_refuses_selected_tool_as_subprocess",
788            "--nocapture",
789            "--test-threads=1",
790        ];
791        let selected = Command::new(&exe)
792            .args(args)
793            .env(CHILD, "1")
794            .env("REVERIE_LITEINST_TOOL", "strace")
795            .output()
796            .unwrap();
797        assert_eq!(selected.status.code(), Some(127), "{selected:?}");
798        assert!(
799            String::from_utf8_lossy(&selected.stderr).contains("aarch64"),
800            "{selected:?}"
801        );
802        let unselected = Command::new(&exe)
803            .args(args)
804            .env(CHILD, "1")
805            .env_remove("REVERIE_LITEINST_TOOL")
806            .output()
807            .unwrap();
808        assert!(unselected.status.success(), "{unselected:?}");
809        assert!(
810            String::from_utf8(unselected.stdout)
811                .unwrap()
812                .contains("1 passed"),
813            "the exact C-entry child must execute"
814        );
815    }
816}
817
818/// Bounded spare-lease diagnostics for the separate mapping integrity fixture.
819#[cfg(feature = "allocator-fixture")]
820#[doc(hidden)]
821pub mod mapping_integrity_fixture;