1 Commits
Author SHA1 Message Date
YXC0915 5e3d6f7626 Add a hosted Stambha engine for VM launchers 2026-11-30 10:51:14 +08:00
15 changed files with 711 additions and 60 deletions

No files matched your search

Generated
+14
View File
@@ -2103,6 +2103,19 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "stambha-engine"
version = "0.1.0"
dependencies = [
"anyhow",
"clap",
"serde",
"serde_json",
"stela-compiler",
"stela-engine",
"tempfile",
]
[[package]]
name = "stela-boot-core"
version = "0.5.0"
@@ -2329,6 +2342,7 @@ dependencies = [
"stela-fingerprint",
"stela-formats",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
+1
View File
@@ -1,5 +1,6 @@
[workspace]
members = [
"crates/stambha-engine",
"crates/stela-boot-core",
"crates/stela-crypto",
"crates/stela-cli",
+1
View File
@@ -16,6 +16,7 @@ without it that links Apache-2.0 code is distributed under GPL-3.0-or-later
stela.efi GPL-2.0-only (contains Linux code)
stela (CLI) GPL-3.0-or-later (links Apache-2.0 crates and no
GPL-2.0-only code)
stambha-engine GPL-3.0-or-later (hosted engine process)
stela-gpu-maintenance GPL-2.0-or-later
Stela.app GPL-2.0-or-later
StelaGPU.kext GPL-2.0-or-later
+30
View File
@@ -67,6 +67,36 @@ build fetches and compiles Linux, Mesa and LLVM sources and takes a long time. I
command keeps its original name until the rename to `stambha` lands.
</details>
### Hosted engine for VM managers
Build the standalone Windows x86-64 process with `cargo build --locked --release -p stambha-engine`.
```powershell
.\target\release\stambha-engine.exe info
.\target\release\stambha-engine.exe self-test
```
Each command writes one JSON object to standard output and exits with a nonzero code on error.
`info` reports the runtime kind `stambha-hosted`, the protocol version and the available capabilities.
`self-test` translates and executes two blocks from a built-in ARM64 program and reports the register
result. The check uses no installation media or guest disk.
`boot-plan` prepares a per-VM EDK2 variable store and returns `exe_path`, `args`, `work_dir` and
`serial_log`. Reims-Go can pass the command fields to its L3 Guest Driver's `host/vm.spawn` API
and track the QEMU PID directly.
```powershell
.\target\release\stambha-engine.exe boot-plan --qemu $qemuExe --firmware-code $uefiCode `
--firmware-vars $uefiTemplate --vm-dir $vmDir --boot-volume $bootVolume
```
Use `--usb-image` for a raw Stambha USB image. It uses a temporary overlay by default.
An explicitly supplied raw NVMe disk via `--disk` keeps guest writes.
The QEMU path runs the existing Stambha EFI engine inside a virtual PC. The native Windows
self-test exercises the optional direct translation path. Full macOS boot has yet to be
validated on the hosted runtime, so `info` reports `macos_boot: false`.
## What's next
- **0.6.2:** Intel graphics, safer installs over flaky networks, many fixes from your logs
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "stambha-engine"
version = "0.1.0"
edition.workspace = true
license = "GPL-3.0-or-later"
description = "Hosted Stambha engine for VM launchers"
rust-version.workspace = true
publish = false
[dependencies]
anyhow.workspace = true
clap.workspace = true
serde = { workspace = true, features = ["std"] }
serde_json.workspace = true
stela-compiler.workspace = true
stela-engine.workspace = true
tempfile.workspace = true
[lints]
workspace = true
+131
View File
@@ -0,0 +1,131 @@
use anyhow::{Context, Result, ensure};
use clap::{Parser, Subcommand};
use serde::Serialize;
use std::io::{self, Write};
use stela_compiler::{GuestAddress, GuestState, TargetCpu, block::BlockProfile};
use stela_engine::blocks::{BlockRuntime, StopReason, ThreadState};
mod qemu;
const RUNTIME_KIND: &str = "stambha-hosted";
const RUNTIME_API: &str = "0.1.0";
#[derive(Parser)]
#[command(version, about)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Report the runtime protocol and available capabilities as JSON.
Info,
/// Translate and execute the built-in ARM64 program.
SelfTest,
/// Prepare a launch command for the Stambha UEFI engine under QEMU.
BootPlan(Box<qemu::BootOptions>),
}
#[derive(Serialize)]
struct RuntimeInfo {
runtime_kind: &'static str,
runtime_api: &'static str,
engine_version: &'static str,
host_os: &'static str,
host_arch: &'static str,
capabilities: Capabilities,
}
#[derive(Serialize)]
struct Capabilities {
native_arm64_self_test: bool,
qemu_uefi_boot_plan: bool,
macos_boot: bool,
}
#[derive(Serialize)]
struct SelfTestReport {
runtime_api: &'static str,
guest_arch: &'static str,
blocks_executed: usize,
blocks_compiled: usize,
result: u64,
}
fn main() -> Result<()> {
match Cli::parse().command {
Command::Info => write_json(&RuntimeInfo {
runtime_kind: RUNTIME_KIND,
runtime_api: RUNTIME_API,
engine_version: env!("CARGO_PKG_VERSION"),
host_os: std::env::consts::OS,
host_arch: std::env::consts::ARCH,
capabilities: Capabilities {
native_arm64_self_test: stela_engine::execution::platform::ensure_supported()
.is_ok(),
qemu_uefi_boot_plan: true,
macos_boot: false,
},
}),
Command::SelfTest => write_json(&self_test()?),
Command::BootPlan(options) => write_json(&options.prepare()?),
}
}
fn write_json(value: &impl Serialize) -> Result<()> {
let mut stdout = io::stdout().lock();
serde_json::to_writer(&mut stdout, value)?;
writeln!(stdout)?;
Ok(())
}
fn self_test() -> Result<SelfTestReport> {
stela_engine::execution::platform::ensure_supported()?;
const ENTRY: GuestAddress = GuestAddress(0x1000);
const RETURN: GuestAddress = GuestAddress(0x2000);
const PROGRAM: [u32; 5] = [
0xd2800500, // MOV X0, #40
0x14000002, // B past the next instruction
0xd2800c60, // MOV X0, #99 (skipped)
0x91000800, // ADD X0, X0, #2
0xd65f03c0, // RET
];
let cache = tempfile::tempdir().context("create temporary self-test cache")?;
let mut engine = BlockRuntime::new_for_target(
1,
cache.path().to_path_buf(),
BlockProfile::ORDINARY,
TargetCpu::Baseline,
);
engine.register_code(
ENTRY,
PROGRAM.into_iter().flat_map(u32::to_le_bytes).collect(),
)?;
let mut thread = ThreadState {
pc: ENTRY,
registers: GuestState::default(),
};
thread.registers.x[30] = RETURN.0;
// SAFETY: the built-in instructions have no memory accesses and the only
// dynamic branch goes to the explicit stop address.
let outcome = unsafe { engine.run(&mut thread, Some(RETURN), 8)? };
ensure!(
outcome.reason == StopReason::StopAddress && thread.pc == RETURN,
"ARM64 self-test stopped at {:#x} with {:?}",
thread.pc.0,
outcome.reason
);
ensure!(
thread.registers.x[0] == 42 && outcome.blocks_executed == 2 && outcome.compiled_blocks == 2,
"unexpected ARM64 translation result or block counts"
);
Ok(SelfTestReport {
runtime_api: RUNTIME_API,
guest_arch: "arm64",
blocks_executed: outcome.blocks_executed,
blocks_compiled: outcome.compiled_blocks,
result: thread.registers.x[0],
})
}
+267
View File
@@ -0,0 +1,267 @@
use anyhow::{Context, Result, ensure};
use clap::Args;
use serde::Serialize;
use std::{
fs::{self, File},
io,
path::{Path, PathBuf},
};
use crate::RUNTIME_API;
#[derive(Args)]
pub(crate) struct BootOptions {
/// QEMU x86-64 executable.
#[arg(long)]
qemu: PathBuf,
/// Read-only EDK2 code image.
#[arg(long)]
firmware_code: PathBuf,
/// EDK2 variables template, copied on first launch.
#[arg(long)]
firmware_vars: PathBuf,
/// Directory that holds persistent firmware variables and the serial log.
#[arg(long)]
vm_dir: PathBuf,
/// Directory containing EFI/BOOT/BOOTX64.EFI and EFI/stela/stela.cfg.
#[arg(
long,
conflicts_with = "usb_image",
required_unless_present = "usb_image"
)]
boot_volume: Option<PathBuf>,
/// Raw Stambha USB disk image. Writes go to a temporary overlay by default.
#[arg(long)]
usb_image: Option<PathBuf>,
/// USB serial used by the boot medium's Stambha configuration.
#[arg(long, default_value = "STELAUSBIMAGE", value_parser = usb_serial)]
usb_serial: String,
/// Persist changes to the USB image.
#[arg(long, requires = "usb_image")]
write_usb: bool,
/// Optional writable raw file attached as an NVMe disk with serial STELAANS.
#[arg(long)]
disk: Option<PathBuf>,
#[arg(long, default_value_t = 8192, value_parser = clap::value_parser!(u32).range(1024..))]
memory_mib: u32,
#[arg(long, default_value_t = 1, value_parser = clap::value_parser!(u8).range(1..=64))]
cpus: u8,
/// Open an SDL display with a virtual keyboard and tablet.
#[arg(long)]
display: bool,
}
#[derive(Serialize)]
pub(crate) struct BootPlan {
runtime_api: &'static str,
exe_path: PathBuf,
args: Vec<String>,
work_dir: PathBuf,
serial_log: PathBuf,
}
impl BootOptions {
pub(crate) fn prepare(self) -> Result<BootPlan> {
let qemu = file(&self.qemu)?;
let firmware_code = file(&self.firmware_code)?;
let firmware_vars = file(&self.firmware_vars)?;
let vm_dir = absolute(&self.vm_dir)?;
let serial_log = vm_dir.join("serial.log");
let vars = vm_dir.join("uefi-vars.fd");
let mut args: Vec<String> = [
"-accel",
"tcg,thread=multi",
"-cpu",
"max,vendor=GenuineIntel",
"-nodefaults",
"-no-reboot",
"-monitor",
"none",
"-nic",
"none",
"-device",
"isa-debug-exit,iobase=0xf4,iosize=4",
"-serial",
"chardev:uart",
]
.into_iter()
.map(String::from)
.collect();
let i8042 = if self.usb_image.is_some() {
"on"
} else {
"off"
};
option(
&mut args,
"-machine",
format!("q35,smm=off,sata=off,usb=off,smbus=off,hpet=off,i8042={i8042},vmport=off",),
);
option(&mut args, "-m", format!("{}M", self.memory_mib));
option(
&mut args,
"-smp",
format!("cpus={},sockets=1,cores={},threads=1", self.cpus, self.cpus),
);
option(
&mut args,
"-display",
if self.display { "sdl" } else { "none" },
);
if self.display {
for device in ["VGA", "virtio-keyboard-pci", "virtio-tablet-pci"] {
option(&mut args, "-device", device);
}
}
option(
&mut args,
"-chardev",
format!("file,id=uart,path={},append=on", qemu_path(&serial_log)?),
);
option(
&mut args,
"-drive",
format!(
"if=pflash,format=raw,readonly=on,file={}",
qemu_path(&firmware_code)?
),
);
option(
&mut args,
"-drive",
format!("if=pflash,format=raw,file={}", qemu_path(&vars)?),
);
match (self.boot_volume, self.usb_image) {
(Some(volume), None) => {
let volume = absolute(&volume)?;
file(&volume.join("EFI/BOOT/BOOTX64.EFI"))?;
file(&volume.join("EFI/stela/stela.cfg"))?;
option(
&mut args,
"-drive",
format!(
"if=none,id=volume,format=raw,readonly=on,file=fat:{}",
qemu_path(&volume)?
),
);
option(&mut args, "-device", "virtio-blk-pci,drive=volume");
}
(None, Some(image)) => {
let image = file(&image)?;
let snapshot = if self.write_usb { "off" } else { "on" };
option(
&mut args,
"-drive",
format!(
"if=none,id=volume,format=raw,snapshot={snapshot},file={}",
qemu_path(&image)?
),
);
option(&mut args, "-device", "qemu-xhci,id=host-usb,p2=8,p3=0");
option(
&mut args,
"-device",
format!(
"usb-storage,drive=volume,serial={},bus=host-usb.0,bootindex=0",
self.usb_serial
),
);
}
_ => anyhow::bail!("provide exactly one boot medium"),
}
if let Some(disk) = self.disk {
option(
&mut args,
"-drive",
format!(
"if=none,id=guest,format=raw,file={}",
qemu_path(&file(&disk)?)?
),
);
option(&mut args, "-device", "nvme,drive=guest,serial=STELAANS");
}
fs::create_dir_all(&vm_dir).with_context(|| format!("create {}", vm_dir.display()))?;
prepare_vars(&firmware_vars, &vars)?;
Ok(BootPlan {
runtime_api: RUNTIME_API,
exe_path: qemu,
args,
work_dir: vm_dir,
serial_log,
})
}
}
fn option(args: &mut Vec<String>, flag: &str, value: impl Into<String>) {
args.extend([flag.to_owned(), value.into()]);
}
fn usb_serial(value: &str) -> Result<String, &'static str> {
if !value.is_empty()
&& value.len() <= 32
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"-_".contains(&byte))
{
Ok(value.to_owned())
} else {
Err("use 1 to 32 letters, digits, dashes or underscores for the USB serial")
}
}
fn absolute(path: &Path) -> Result<PathBuf> {
let path = std::path::absolute(path)?;
#[cfg(windows)]
{
use std::path::{Component, Prefix};
ensure!(
matches!(path.components().next(), Some(Component::Prefix(prefix))
if matches!(prefix.kind(), Prefix::Disk(_) | Prefix::UNC(_, _))),
"expected a filesystem path: {}",
path.display()
);
}
Ok(path)
}
fn file(path: &Path) -> Result<PathBuf> {
let path = absolute(path)?;
let metadata = fs::metadata(&path).with_context(|| format!("open {}", path.display()))?;
ensure!(
metadata.is_file() && metadata.len() != 0,
"expected a nonempty file: {}",
path.display()
);
Ok(path)
}
fn qemu_path(path: &Path) -> Result<String> {
Ok(path
.to_str()
.context("QEMU paths must be valid Unicode")?
.replace(',', ",,"))
}
fn prepare_vars(template: &Path, destination: &Path) -> Result<()> {
if !destination.try_exists()? {
let parent = destination.parent().context("missing NVRAM directory")?;
let mut staging = tempfile::NamedTempFile::new_in(parent)?;
io::copy(&mut File::open(template)?, &mut staging)?;
staging.as_file().sync_all()?;
match staging.persist_noclobber(destination) {
Ok(_) => {}
Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error.error.into()),
}
}
let actual = fs::symlink_metadata(destination)?;
ensure!(
actual.is_file() && actual.len() == fs::metadata(template)?.len(),
"UEFI variable store differs in size from its template: {}",
destination.display()
);
Ok(())
}
+87
View File
@@ -0,0 +1,87 @@
use std::{ffi::OsStr, fs, process::Command};
fn json_output(argument: &str) -> serde_json::Value {
run_json([OsStr::new(argument)])
}
fn run_json(arguments: impl IntoIterator<Item = impl AsRef<OsStr>>) -> serde_json::Value {
let output = Command::new(env!("CARGO_BIN_EXE_stambha-engine"))
.args(arguments)
.output()
.expect("start hosted engine");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("one JSON reply")
}
#[test]
fn reports_host_capabilities() {
let info = json_output("info");
assert_eq!(info["runtime_kind"], "stambha-hosted");
assert_eq!(info["runtime_api"], "0.1.0");
assert_eq!(info["host_os"], std::env::consts::OS);
assert_eq!(info["host_arch"], std::env::consts::ARCH);
assert_eq!(info["capabilities"]["macos_boot"], false);
}
#[cfg(all(
target_arch = "x86_64",
any(windows, target_os = "linux", target_os = "macos")
))]
#[test]
fn executes_two_translated_arm64_blocks() {
assert_eq!(
json_output("info")["capabilities"]["native_arm64_self_test"],
true
);
let report = json_output("self-test");
assert_eq!(report["runtime_api"], "0.1.0");
assert_eq!(report["guest_arch"], "arm64");
assert_eq!(report["blocks_compiled"], 2);
assert_eq!(report["blocks_executed"], 2);
assert_eq!(report["result"], 42);
}
#[test]
fn boot_plan_uses_file_media_and_keeps_existing_firmware_variables() {
let temp = tempfile::tempdir().unwrap();
let qemu = temp.path().join("qemu");
let code = temp.path().join("code.fd");
let template = temp.path().join("vars.fd");
let image = temp.path().join("test, disk.img");
let vm = temp.path().join("test vm");
for path in [&qemu, &code, &template, &image] {
fs::write(path, b"template").unwrap();
}
let plan = || {
run_json([
OsStr::new("boot-plan"),
OsStr::new("--qemu"),
qemu.as_os_str(),
OsStr::new("--firmware-code"),
code.as_os_str(),
OsStr::new("--firmware-vars"),
template.as_os_str(),
OsStr::new("--vm-dir"),
vm.as_os_str(),
OsStr::new("--usb-image"),
image.as_os_str(),
])
};
let reply = plan();
let args = reply["args"].as_array().unwrap();
assert!(args.iter().any(|argument| {
argument.as_str().is_some_and(|argument| {
argument.contains("format=raw,snapshot=on,file=")
&& argument.ends_with("test,, disk.img")
})
}));
let variables = vm.join("uefi-vars.fd");
assert_eq!(fs::read(&variables).unwrap(), b"template");
fs::write(&variables, b"memorize").unwrap();
plan();
assert_eq!(fs::read(&variables).unwrap(), b"memorize");
}
+8 -1
View File
@@ -15,7 +15,7 @@ workspace = true
default = ["std"]
test-support = []
native-profile = ["stela-contracts/native-profile"]
std = ["serde/std", "serde_json/std", "stela-compiler/std", "stela-contracts/std", "stela-formats/std", "dep:tempfile", "dep:libc"]
std = ["serde/std", "serde_json/std", "stela-compiler/std", "stela-contracts/std", "stela-formats/std", "dep:tempfile", "dep:libc", "dep:windows-sys"]
[dependencies]
serde.workspace = true
@@ -32,6 +32,13 @@ stela-formats = { path = "../stela-formats", default-features = false }
[build-dependencies]
stela-fingerprint = { path = "../stela-fingerprint" }
[target.'cfg(all(windows, target_arch = "x86_64"))'.dependencies]
windows-sys = { version = "0.61", optional = true, features = [
"Win32_System_Diagnostics_Debug",
"Win32_System_Memory",
"Win32_System_Threading",
] }
[dev-dependencies]
anyhow.workspace = true
stela-compiler = { path = "../stela-compiler", features = ["test-support"] }
+8 -2
View File
@@ -7,9 +7,15 @@ pub mod checked_memory;
pub(crate) mod context;
#[cfg(feature = "std")]
pub(crate) mod floating_environment;
#[cfg(all(host_memory, target_arch = "x86_64"))]
#[cfg(all(
target_arch = "x86_64",
any(host_memory, all(windows, feature = "std"))
))]
mod native_image;
#[cfg(all(host_memory, target_arch = "x86_64"))]
#[cfg(all(
target_arch = "x86_64",
any(host_memory, all(windows, feature = "std"))
))]
pub(crate) use native_image::ReachedCall as ObservedNativeCall;
#[cfg(feature = "std")]
+22 -6
View File
@@ -2,20 +2,36 @@
#[cfg(all(target_arch = "x86_64", target_os = "uefi", not(feature = "std")))]
mod freestanding;
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
mod posix;
#[cfg(all(
target_arch = "x86_64",
feature = "std",
any(windows, target_os = "macos", target_os = "linux")
))]
mod hosted;
#[cfg(not(any(
all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")),
all(
target_arch = "x86_64",
feature = "std",
any(windows, target_os = "macos", target_os = "linux")
),
all(target_arch = "x86_64", target_os = "uefi", not(feature = "std"))
)))]
mod unsupported;
#[cfg(all(target_arch = "x86_64", target_os = "uefi", not(feature = "std")))]
pub use freestanding::*;
#[cfg(all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")))]
pub use posix::*;
#[cfg(all(
target_arch = "x86_64",
feature = "std",
any(windows, target_os = "macos", target_os = "linux")
))]
pub use hosted::*;
#[cfg(not(any(
all(target_arch = "x86_64", any(target_os = "macos", target_os = "linux")),
all(
target_arch = "x86_64",
feature = "std",
any(windows, target_os = "macos", target_os = "linux")
),
all(target_arch = "x86_64", target_os = "uefi", not(feature = "std"))
)))]
pub use unsupported::*;
@@ -1,13 +1,17 @@
//! Native code mappings on x86-64 macOS and Linux.
//! Native code mappings in x86-64 host processes.
#[cfg_attr(windows, path = "hosted/windows.rs")]
#[cfg_attr(not(windows), path = "hosted/posix.rs")]
mod memory;
use crate::Result;
use crate::execution::native_image::{ExecutableStorage, NativeImage};
use crate::{Result, error::Io};
use core::{convert::Infallible, ptr::NonNull};
use stela_compiler::GuestState;
use stela_contracts::{refuse, require};
use stela_contracts::require;
pub fn ensure_supported() -> Result<()> {
// Every x86-64 CPU implements Stela's integer and SSE2 baseline.
// Mac x86-64 and Linux x86-64 both use the required System V C ABI.
// Native calls explicitly use the compiler's System V ABI on every host.
Ok(())
}
@@ -20,50 +24,18 @@ pub struct Mapping {
impl Mapping {
pub fn new(bytes: &[u8]) -> Result<Self> {
require!(!bytes.is_empty(), "cannot map empty native code");
// SAFETY: Request fresh anonymous private RW storage. MAP_FAILED is
// checked before the pointer is used. Never request executable RW.
let pointer = unsafe {
libc::mmap(
core::ptr::null_mut(),
bytes.len(),
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANON,
-1,
0,
)
};
if pointer == libc::MAP_FAILED {
return Err(std::io::Error::last_os_error()).io("allocate RW native code");
}
let Some(pointer) = NonNull::new(pointer.cast::<u8>()) else {
// SAFETY: Address zero cannot back a Rust NonNull mapping, even if an OS
// were to honor it. Release the successful OS allocation first.
unsafe { libc::munmap(pointer, bytes.len()) };
return Err(refuse!("OS returned an unusable null native mapping").into());
};
let mapping = Self {
pointer,
pointer: memory::allocate(bytes.len())?,
length: bytes.len(),
};
// SAFETY: mmap returned at least length fresh RW bytes, disjoint from
// SAFETY: allocate returned at least length fresh RW bytes, disjoint from
// the input Vec, and this mapping has not escaped.
unsafe {
core::ptr::copy_nonoverlapping(bytes.as_ptr(), mapping.pointer.as_ptr(), bytes.len());
}
// SAFETY: the whole mapping is initialized. The OS switches it from
// RW to RX atomically, and x86 instruction and data caches are
// coherent.
let result = unsafe {
libc::mprotect(
mapping.pointer.as_ptr().cast(),
mapping.length,
libc::PROT_READ | libc::PROT_EXEC,
)
};
if result != 0 {
// mapping's Drop releases memory on this error path too.
return Err(std::io::Error::last_os_error()).io("protect native code RX");
}
// SAFETY: this is the full, initialized allocation, still uniquely
// owned by mapping. Drop releases it if publication fails.
unsafe { memory::protect_executable(mapping.pointer, mapping.length)? };
Ok(mapping)
}
@@ -136,7 +108,7 @@ impl Mapping {
}
/// Keep the native result alongside the storage check. Err is a refusal
/// before the call; POSIX storage cannot fail.
/// before the call; the borrowed RX allocation stays live across it.
///
/// # Safety
/// The source, native code, ABI, map, requirements and context must be
@@ -240,17 +212,15 @@ impl Mapping {
Ok(())
}
#[cfg(test)]
#[cfg(all(test, not(windows)))]
pub fn address(&self) -> usize {
self.pointer.as_ptr() as usize
}
}
// SAFETY: Mapping::new exclusively owns fresh initialized mmap storage,
// atomically transitioned to RX. Escaped addresses require the unsafe caller to keep this owner. Calls borrow
// self; no unmap or writable alias can coexist through safe runtime APIs.
// Host ownership is infallible to keep, so no fallible frame postcheck is
// invented for this implementation. Guest ABI/PE admission stays at callsite.
// SAFETY: Mapping::new exclusively owns fresh, initialized OS pages
// transitioned to RX. Calls borrow self, keeping those pages live and
// immutable until return. Raw entry users must uphold the same ownership.
unsafe impl ExecutableStorage for Mapping {
type Error = Infallible;
fn entry(&self) -> NonNull<u8> {
@@ -263,7 +233,7 @@ unsafe impl ExecutableStorage for Mapping {
impl Drop for Mapping {
fn drop(&mut self) {
// SAFETY: the mapping is uniquely owned and safe calls borrow `self`; external raw entry users must keep this owner.
unsafe { libc::munmap(self.pointer.as_ptr().cast(), self.length) };
// SAFETY: this mapping uniquely owns the original allocation.
unsafe { memory::release(self.pointer, self.length) };
}
}
@@ -0,0 +1,47 @@
use crate::{Result, error::Io};
use core::ptr::NonNull;
use stela_contracts::refuse;
pub(super) fn allocate(length: usize) -> Result<NonNull<u8>> {
// SAFETY: request a new private mapping, checking the result before use.
let pointer = unsafe {
libc::mmap(
core::ptr::null_mut(),
length,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANON,
-1,
0,
)
};
if pointer == libc::MAP_FAILED {
return Err(std::io::Error::last_os_error()).io("allocate RW native code");
}
let Some(mapping) = NonNull::new(pointer.cast()) else {
// SAFETY: address zero was returned by a successful mmap above.
unsafe { libc::munmap(pointer, length) };
return Err(refuse!("OS returned an unusable null native mapping").into());
};
Ok(mapping)
}
pub(super) unsafe fn protect_executable(pointer: NonNull<u8>, length: usize) -> Result<()> {
// SAFETY: the caller uniquely owns this initialized allocation. On x86-64
// instruction and data caches are coherent for the published mapping.
let result = unsafe {
libc::mprotect(
pointer.as_ptr().cast(),
length,
libc::PROT_READ | libc::PROT_EXEC,
)
};
if result != 0 {
return Err(std::io::Error::last_os_error()).io("protect native code RX");
}
Ok(())
}
pub(super) unsafe fn release(pointer: NonNull<u8>, length: usize) {
// SAFETY: the caller exclusively owns the original allocation.
unsafe { libc::munmap(pointer.as_ptr().cast(), length) };
}
@@ -0,0 +1,54 @@
use crate::{Result, error::Io};
use core::ptr::NonNull;
use windows_sys::Win32::System::{
Diagnostics::Debug::FlushInstructionCache,
Memory::{
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc,
VirtualFree, VirtualProtect,
},
Threading::GetCurrentProcess,
};
pub(super) fn allocate(length: usize) -> Result<NonNull<u8>> {
// SAFETY: request dedicated private RW pages, with no address preference.
let pointer = unsafe {
VirtualAlloc(
core::ptr::null(),
length,
MEM_COMMIT | MEM_RESERVE,
PAGE_READWRITE,
)
};
NonNull::new(pointer.cast())
.ok_or_else(std::io::Error::last_os_error)
.io("allocate RW native code")
}
pub(super) unsafe fn protect_executable(pointer: NonNull<u8>, length: usize) -> Result<()> {
let mut previous = 0;
// SAFETY: the caller uniquely owns these initialized, committed pages.
let protected = unsafe {
VirtualProtect(
pointer.as_ptr().cast(),
length,
PAGE_EXECUTE_READ,
&mut previous,
)
};
if protected == 0 {
return Err(std::io::Error::last_os_error()).io("protect native code RX");
}
// SAFETY: the pages are still live in this process and are not yet published.
let flushed =
unsafe { FlushInstructionCache(GetCurrentProcess(), pointer.as_ptr().cast(), length) };
if flushed == 0 {
return Err(std::io::Error::last_os_error()).io("flush native instruction cache");
}
Ok(())
}
pub(super) unsafe fn release(pointer: NonNull<u8>, _length: usize) {
// SAFETY: the caller owns the original VirtualAlloc base. MEM_RELEASE
// requires a size of zero and releases its entire reservation.
unsafe { VirtualFree(pointer.as_ptr().cast(), 0, MEM_RELEASE) };
}
@@ -6,7 +6,7 @@ use stela_contracts::refuse;
pub fn ensure_supported() -> Result<()> {
#[cfg(feature = "std")]
return Err(refuse!(
"native leaf execution requires x86-64 macOS or Linux with the System V ABI"
"native leaf execution requires x86-64 Windows, macOS or Linux"
)
.into());
#[cfg(not(feature = "std"))]