Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c26f78bfce | ||
|
|
5e3d6f7626 |
No files matched your search
Generated
+14
@@ -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,5 +1,6 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"crates/stambha-engine",
|
||||
"crates/stela-boot-core",
|
||||
"crates/stela-crypto",
|
||||
"crates/stela-cli",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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],
|
||||
})
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -20,6 +20,7 @@ pub mod pc_relative;
|
||||
pub mod prefetch;
|
||||
pub mod register_offset;
|
||||
pub mod scalable;
|
||||
pub mod semantics;
|
||||
pub mod simd;
|
||||
pub mod sme;
|
||||
pub mod sve;
|
||||
|
||||
@@ -0,0 +1,604 @@
|
||||
//! Explicit architectural semantics for core A64 integer flag-setting and
|
||||
//! conditional-select instructions.
|
||||
use super::{
|
||||
Operation, Register, RegisterExtend, Shift, Width,
|
||||
conditional_select::Otherwise,
|
||||
flags::{NZCV_C, NZCV_N, NZCV_SHIFT, NZCV_V, NZCV_Z, condition_holds},
|
||||
};
|
||||
use crate::GuestState;
|
||||
|
||||
/// Bitmask of the four architectural condition flags (`N`, `Z`, `C`, `V`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct FlagMask(u8);
|
||||
|
||||
impl FlagMask {
|
||||
pub const NONE: Self = Self(0);
|
||||
pub const N: Self = Self(1 << 3);
|
||||
pub const Z: Self = Self(1 << 2);
|
||||
pub const C: Self = Self(1 << 1);
|
||||
pub const V: Self = Self(1 << 0);
|
||||
pub const ALL: Self = Self(0b1111);
|
||||
|
||||
pub const fn bits(self) -> u8 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub const fn is_empty(self) -> bool {
|
||||
self.0 == 0
|
||||
}
|
||||
|
||||
pub const fn contains(self, other: Self) -> bool {
|
||||
(self.0 & other.0) == other.0
|
||||
}
|
||||
|
||||
pub const fn intersects(self, other: Self) -> bool {
|
||||
(self.0 & other.0) != 0
|
||||
}
|
||||
|
||||
pub const fn union(self, other: Self) -> Self {
|
||||
Self(self.0 | other.0)
|
||||
}
|
||||
|
||||
pub const fn difference(self, other: Self) -> Self {
|
||||
Self(self.0 & !other.0)
|
||||
}
|
||||
|
||||
pub const fn from_nzcv(nzcv: u32) -> Self {
|
||||
Self(((nzcv >> NZCV_SHIFT) & 0xf) as u8)
|
||||
}
|
||||
|
||||
pub const fn to_nzcv_mask(self) -> u32 {
|
||||
(self.0 as u32) << NZCV_SHIFT
|
||||
}
|
||||
|
||||
/// The subset of `NZCV` flags read by A64 condition `condition` (`0..16`).
|
||||
pub const fn condition_reads(condition: u8) -> Self {
|
||||
match condition >> 1 {
|
||||
0 => Self::Z, // EQ / NE
|
||||
1 => Self::C, // CS / CC
|
||||
2 => Self::N, // MI / PL
|
||||
3 => Self::V, // VS / VC
|
||||
4 => Self(Self::C.0 | Self::Z.0), // HI / LS
|
||||
5 => Self(Self::N.0 | Self::V.0), // GE / LT
|
||||
6 => Self(Self::N.0 | Self::Z.0 | Self::V.0), // GT / LE
|
||||
_ => Self::NONE, // AL / NV
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bitmask over architectural integer state (`X0..=X30` in bits `0..=30`, `SP` in bit `31`).
|
||||
/// `XZR`/`WZR` (`Register::Zero`) is excluded because reads yield 0 and writes discard.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct RegisterSet(u32);
|
||||
|
||||
impl RegisterSet {
|
||||
pub const NONE: Self = Self(0);
|
||||
|
||||
pub const fn bits(self) -> u32 {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub const fn is_empty(self) -> bool {
|
||||
self.0 == 0
|
||||
}
|
||||
|
||||
pub const fn of(register: Register) -> Self {
|
||||
match Self::bit(register) {
|
||||
Some(bit) => Self(bit),
|
||||
None => Self::NONE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_registers(registers: impl IntoIterator<Item = Register>) -> Self {
|
||||
registers
|
||||
.into_iter()
|
||||
.fold(Self::NONE, |set, register| set.union(Self::of(register)))
|
||||
}
|
||||
|
||||
pub const fn contains(self, register: Register) -> bool {
|
||||
match Self::bit(register) {
|
||||
Some(bit) => (self.0 & bit) != 0,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn union(self, other: Self) -> Self {
|
||||
Self(self.0 | other.0)
|
||||
}
|
||||
|
||||
pub const fn difference(self, other: Self) -> Self {
|
||||
Self(self.0 & !other.0)
|
||||
}
|
||||
|
||||
pub const fn intersects(self, other: Self) -> bool {
|
||||
(self.0 & other.0) != 0
|
||||
}
|
||||
|
||||
const fn bit(register: Register) -> Option<u32> {
|
||||
match register {
|
||||
Register::X(index) if index < 31 => Some(1u32 << index),
|
||||
Register::Sp => Some(1u32 << 31),
|
||||
Register::X(_) | Register::Zero => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an ALU operand is sourced before optional bitwise inversion.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueSource {
|
||||
Register(Register),
|
||||
Immediate(u64),
|
||||
ShiftedRegister {
|
||||
register: Register,
|
||||
shift: Shift,
|
||||
amount: u8,
|
||||
},
|
||||
ExtendedRegister {
|
||||
register: Register,
|
||||
extend: RegisterExtend,
|
||||
amount: u8,
|
||||
},
|
||||
}
|
||||
|
||||
/// Carry input consumed by [`SemanticKind::AddWithCarry`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CarryInput {
|
||||
Zero,
|
||||
One,
|
||||
CarryFlag,
|
||||
}
|
||||
|
||||
/// Pure architectural effect shape for a lifted instruction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SemanticKind {
|
||||
/// Arm `AddWithCarry(left, if invert_right { NOT(right) } else { right }, carry_in)`.
|
||||
AddWithCarry {
|
||||
left: ValueSource,
|
||||
right: ValueSource,
|
||||
invert_right: bool,
|
||||
carry_in: CarryInput,
|
||||
set_flags: bool,
|
||||
destination: Register,
|
||||
},
|
||||
/// Arm `CSEL`/`CSINC`/`CSINV`/`CSNEG`: chooses `true_register` if `ConditionHolds(condition)`,
|
||||
/// otherwise transforms `false_register` per `otherwise`; never modifies `NZCV`.
|
||||
ConditionalSelect {
|
||||
condition: u8,
|
||||
true_register: Register,
|
||||
false_register: Register,
|
||||
otherwise: Otherwise,
|
||||
destination: Register,
|
||||
},
|
||||
}
|
||||
|
||||
/// Explicit per-instruction operand width, register/flag side effects, and semantics.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct InstructionSemantics {
|
||||
pub width: Width,
|
||||
pub gpr_reads: RegisterSet,
|
||||
pub gpr_writes: RegisterSet,
|
||||
pub flag_reads: FlagMask,
|
||||
pub flag_writes: FlagMask,
|
||||
pub kind: SemanticKind,
|
||||
}
|
||||
|
||||
/// Return explicit architectural semantics for supported integer arithmetic,
|
||||
/// carry arithmetic, and conditional select operations.
|
||||
pub fn semantics_of(operation: &Operation) -> Option<InstructionSemantics> {
|
||||
match *operation {
|
||||
Operation::AddSub {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
source,
|
||||
immediate,
|
||||
} => Some(InstructionSemantics {
|
||||
width,
|
||||
gpr_reads: RegisterSet::of(source),
|
||||
gpr_writes: RegisterSet::of(destination),
|
||||
flag_reads: FlagMask::NONE,
|
||||
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
|
||||
kind: SemanticKind::AddWithCarry {
|
||||
left: ValueSource::Register(source),
|
||||
right: ValueSource::Immediate(u64::from(immediate)),
|
||||
invert_right: subtract,
|
||||
carry_in: if subtract {
|
||||
CarryInput::One
|
||||
} else {
|
||||
CarryInput::Zero
|
||||
},
|
||||
set_flags: flags,
|
||||
destination,
|
||||
},
|
||||
}),
|
||||
Operation::AddSubRegister {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
shift,
|
||||
amount,
|
||||
} => Some(InstructionSemantics {
|
||||
width,
|
||||
gpr_reads: RegisterSet::from_registers([left, right]),
|
||||
gpr_writes: RegisterSet::of(destination),
|
||||
flag_reads: FlagMask::NONE,
|
||||
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
|
||||
kind: SemanticKind::AddWithCarry {
|
||||
left: ValueSource::Register(left),
|
||||
right: ValueSource::ShiftedRegister {
|
||||
register: right,
|
||||
shift,
|
||||
amount,
|
||||
},
|
||||
invert_right: subtract,
|
||||
carry_in: if subtract {
|
||||
CarryInput::One
|
||||
} else {
|
||||
CarryInput::Zero
|
||||
},
|
||||
set_flags: flags,
|
||||
destination,
|
||||
},
|
||||
}),
|
||||
Operation::AddSubExtended {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
extend,
|
||||
amount,
|
||||
} => Some(InstructionSemantics {
|
||||
width,
|
||||
gpr_reads: RegisterSet::from_registers([left, right]),
|
||||
gpr_writes: RegisterSet::of(destination),
|
||||
flag_reads: FlagMask::NONE,
|
||||
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
|
||||
kind: SemanticKind::AddWithCarry {
|
||||
left: ValueSource::Register(left),
|
||||
right: ValueSource::ExtendedRegister {
|
||||
register: right,
|
||||
extend,
|
||||
amount,
|
||||
},
|
||||
invert_right: subtract,
|
||||
carry_in: if subtract {
|
||||
CarryInput::One
|
||||
} else {
|
||||
CarryInput::Zero
|
||||
},
|
||||
set_flags: flags,
|
||||
destination,
|
||||
},
|
||||
}),
|
||||
Operation::AddSubCarry {
|
||||
width,
|
||||
subtract,
|
||||
flags,
|
||||
destination,
|
||||
left,
|
||||
right,
|
||||
} => Some(InstructionSemantics {
|
||||
width,
|
||||
gpr_reads: RegisterSet::from_registers([left, right]),
|
||||
gpr_writes: RegisterSet::of(destination),
|
||||
flag_reads: FlagMask::C,
|
||||
flag_writes: if flags { FlagMask::ALL } else { FlagMask::NONE },
|
||||
kind: SemanticKind::AddWithCarry {
|
||||
left: ValueSource::Register(left),
|
||||
right: ValueSource::Register(right),
|
||||
invert_right: subtract,
|
||||
carry_in: CarryInput::CarryFlag,
|
||||
set_flags: flags,
|
||||
destination,
|
||||
},
|
||||
}),
|
||||
Operation::ConditionalSelect(op) if op.condition < 16 => {
|
||||
let reads = if op.condition >= 14 {
|
||||
RegisterSet::of(op.left)
|
||||
} else {
|
||||
RegisterSet::from_registers([op.left, op.right])
|
||||
};
|
||||
Some(InstructionSemantics {
|
||||
width: op.width,
|
||||
gpr_reads: reads,
|
||||
gpr_writes: RegisterSet::of(op.destination),
|
||||
flag_reads: FlagMask::condition_reads(op.condition),
|
||||
flag_writes: FlagMask::NONE,
|
||||
kind: SemanticKind::ConditionalSelect {
|
||||
condition: op.condition,
|
||||
true_register: op.left,
|
||||
false_register: op.right,
|
||||
otherwise: op.otherwise,
|
||||
destination: op.destination,
|
||||
},
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact Arm `AddWithCarry(N, x, y, carry_in)` specification returning `(result, nzcv)`.
|
||||
pub fn add_with_carry(width: Width, left: u64, right: u64, carry_in: bool) -> (u64, u32) {
|
||||
let carry = u128::from(carry_in);
|
||||
let carry_signed = i128::from(carry_in);
|
||||
let (result, negative, unsigned_sum, signed_matches) = match width {
|
||||
Width::W32 => {
|
||||
let x = left as u32;
|
||||
let y = right as u32;
|
||||
let unsigned_sum = u128::from(x) + u128::from(y) + carry;
|
||||
let signed_sum = i128::from(x as i32) + i128::from(y as i32) + carry_signed;
|
||||
let result = unsigned_sum as u32;
|
||||
let negative = (result >> 31) != 0;
|
||||
let signed_matches = i128::from(result as i32) == signed_sum;
|
||||
(u64::from(result), negative, unsigned_sum, signed_matches)
|
||||
}
|
||||
Width::X64 => {
|
||||
let unsigned_sum = u128::from(left) + u128::from(right) + carry;
|
||||
let signed_sum = i128::from(left as i64) + i128::from(right as i64) + carry_signed;
|
||||
let result = unsigned_sum as u64;
|
||||
let negative = (result >> 63) != 0;
|
||||
let signed_matches = i128::from(result as i64) == signed_sum;
|
||||
(result, negative, unsigned_sum, signed_matches)
|
||||
}
|
||||
};
|
||||
let mut nzcv = 0u32;
|
||||
if negative {
|
||||
nzcv |= NZCV_N;
|
||||
}
|
||||
if result == 0 {
|
||||
nzcv |= NZCV_Z;
|
||||
}
|
||||
if unsigned_sum != u128::from(result) {
|
||||
nzcv |= NZCV_C;
|
||||
}
|
||||
if !signed_matches {
|
||||
nzcv |= NZCV_V;
|
||||
}
|
||||
(result, nzcv)
|
||||
}
|
||||
|
||||
/// Reference architectural execution of a modeled instruction on `state`.
|
||||
pub fn eval_instruction(semantics: &InstructionSemantics, state: &mut GuestState) {
|
||||
let width = semantics.width;
|
||||
match semantics.kind {
|
||||
SemanticKind::AddWithCarry {
|
||||
left,
|
||||
right,
|
||||
invert_right,
|
||||
carry_in,
|
||||
set_flags,
|
||||
destination,
|
||||
} => {
|
||||
let lhs = eval_value_source(width, left, state);
|
||||
let mut rhs = eval_value_source(width, right, state);
|
||||
if invert_right {
|
||||
rhs = mask_width(width, !rhs);
|
||||
}
|
||||
let carry = match carry_in {
|
||||
CarryInput::Zero => false,
|
||||
CarryInput::One => true,
|
||||
CarryInput::CarryFlag => (state.nzcv & NZCV_C) != 0,
|
||||
};
|
||||
let (result, nzcv) = add_with_carry(width, lhs, rhs, carry);
|
||||
write_register(width, destination, result, state);
|
||||
if set_flags {
|
||||
state.nzcv = nzcv;
|
||||
}
|
||||
}
|
||||
SemanticKind::ConditionalSelect {
|
||||
condition,
|
||||
true_register,
|
||||
false_register,
|
||||
otherwise,
|
||||
destination,
|
||||
} => {
|
||||
let selected = if condition_holds(condition, state.nzcv) {
|
||||
read_register(width, true_register, state)
|
||||
} else {
|
||||
let value = read_register(width, false_register, state);
|
||||
let adjusted = match otherwise {
|
||||
Otherwise::Unchanged => value,
|
||||
Otherwise::Increment => value.wrapping_add(1),
|
||||
Otherwise::Invert => !value,
|
||||
Otherwise::Negate => value.wrapping_neg(),
|
||||
};
|
||||
mask_width(width, adjusted)
|
||||
};
|
||||
write_register(width, destination, selected, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mask_width(width: Width, value: u64) -> u64 {
|
||||
match width {
|
||||
Width::W32 => u64::from(value as u32),
|
||||
Width::X64 => value,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_register(width: Width, register: Register, state: &GuestState) -> u64 {
|
||||
let raw = match register {
|
||||
Register::X(index) if index < 31 => state.x[usize::from(index)],
|
||||
Register::Sp => state.sp,
|
||||
Register::X(_) | Register::Zero => 0,
|
||||
};
|
||||
mask_width(width, raw)
|
||||
}
|
||||
|
||||
fn write_register(width: Width, register: Register, value: u64, state: &mut GuestState) {
|
||||
let value = mask_width(width, value);
|
||||
match register {
|
||||
Register::X(index) if index < 31 => state.x[usize::from(index)] = value,
|
||||
Register::Sp => state.sp = value,
|
||||
Register::X(_) | Register::Zero => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_value_source(width: Width, source: ValueSource, state: &GuestState) -> u64 {
|
||||
match source {
|
||||
ValueSource::Register(register) => read_register(width, register, state),
|
||||
ValueSource::Immediate(immediate) => mask_width(width, immediate),
|
||||
ValueSource::ShiftedRegister {
|
||||
register,
|
||||
shift,
|
||||
amount,
|
||||
} => {
|
||||
let raw = read_register(width, register, state);
|
||||
let shifted = match width {
|
||||
Width::W32 => {
|
||||
let val = raw as u32;
|
||||
let out = if amount == 0 {
|
||||
val
|
||||
} else {
|
||||
match shift {
|
||||
Shift::Lsl => val.wrapping_shl(u32::from(amount)),
|
||||
Shift::Lsr => val.wrapping_shr(u32::from(amount)),
|
||||
Shift::Asr => ((val as i32).wrapping_shr(u32::from(amount))) as u32,
|
||||
Shift::Ror => val.rotate_right(u32::from(amount)),
|
||||
}
|
||||
};
|
||||
u64::from(out)
|
||||
}
|
||||
Width::X64 => {
|
||||
if amount == 0 {
|
||||
raw
|
||||
} else {
|
||||
match shift {
|
||||
Shift::Lsl => raw.wrapping_shl(u32::from(amount)),
|
||||
Shift::Lsr => raw.wrapping_shr(u32::from(amount)),
|
||||
Shift::Asr => ((raw as i64).wrapping_shr(u32::from(amount))) as u64,
|
||||
Shift::Ror => raw.rotate_right(u32::from(amount)),
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
mask_width(width, shifted)
|
||||
}
|
||||
ValueSource::ExtendedRegister {
|
||||
register,
|
||||
extend,
|
||||
amount,
|
||||
} => {
|
||||
let raw = read_register(Width::X64, register, state);
|
||||
let extended = match extend {
|
||||
RegisterExtend::Uxtb => u64::from(raw as u8),
|
||||
RegisterExtend::Uxth => u64::from(raw as u16),
|
||||
RegisterExtend::Uxtw => u64::from(raw as u32),
|
||||
RegisterExtend::Uxtx => raw,
|
||||
RegisterExtend::Sxtb => i64::from(raw as i8) as u64,
|
||||
RegisterExtend::Sxth => i64::from(raw as i16) as u64,
|
||||
RegisterExtend::Sxtw => i64::from(raw as i32) as u64,
|
||||
RegisterExtend::Sxtx => raw,
|
||||
};
|
||||
mask_width(width, extended.wrapping_shl(u32::from(amount)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{GuestAddress, Lifter, aarch64::Decoder};
|
||||
|
||||
fn decode(word: u32) -> Operation {
|
||||
Decoder.lift(GuestAddress(0x1000), word).unwrap().operation
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adds_adcs_sbcs_csel_explicit_effects_and_zero_register() {
|
||||
// ADDS X4, X0, X2 (0xab02_0004)
|
||||
let adds_x = semantics_of(&decode(0xab02_0004)).unwrap();
|
||||
assert_eq!(adds_x.width, Width::X64);
|
||||
assert_eq!(
|
||||
adds_x.gpr_reads,
|
||||
RegisterSet::from_registers([Register::X(0), Register::X(2)])
|
||||
);
|
||||
assert_eq!(adds_x.gpr_writes, RegisterSet::of(Register::X(4)));
|
||||
assert_eq!(adds_x.flag_reads, FlagMask::NONE);
|
||||
assert_eq!(adds_x.flag_writes, FlagMask::ALL);
|
||||
|
||||
// ADDS WZR, W1, #1 (CMN W1, #1: 0x3100_043f)
|
||||
let cmn_w = semantics_of(&decode(0x3100_043f)).unwrap();
|
||||
assert_eq!(cmn_w.width, Width::W32);
|
||||
assert_eq!(cmn_w.gpr_reads, RegisterSet::of(Register::X(1)));
|
||||
assert_eq!(cmn_w.gpr_writes, RegisterSet::NONE);
|
||||
assert_eq!(cmn_w.flag_reads, FlagMask::NONE);
|
||||
assert_eq!(cmn_w.flag_writes, FlagMask::ALL);
|
||||
|
||||
// ADCS X5, X1, X3 (0xba03_0025)
|
||||
let adcs_x = semantics_of(&decode(0xba03_0025)).unwrap();
|
||||
assert_eq!(adcs_x.flag_reads, FlagMask::C);
|
||||
assert_eq!(adcs_x.flag_writes, FlagMask::ALL);
|
||||
|
||||
// SBCS W6, W5, W4 (0x7a04_00a6)
|
||||
let sbcs_w = semantics_of(&decode(0x7a04_00a6)).unwrap();
|
||||
assert_eq!(sbcs_w.width, Width::W32);
|
||||
assert_eq!(sbcs_w.flag_reads, FlagMask::C);
|
||||
assert_eq!(sbcs_w.flag_writes, FlagMask::ALL);
|
||||
assert!(matches!(
|
||||
sbcs_w.kind,
|
||||
SemanticKind::AddWithCarry {
|
||||
invert_right: true,
|
||||
carry_in: CarryInput::CarryFlag,
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
// CSEL X6, X4, X5, CS (0x9a85_2086)
|
||||
let csel_cs = semantics_of(&decode(0x9a85_2086)).unwrap();
|
||||
assert_eq!(csel_cs.flag_reads, FlagMask::C);
|
||||
assert_eq!(csel_cs.flag_writes, FlagMask::NONE);
|
||||
assert_eq!(
|
||||
csel_cs.gpr_reads,
|
||||
RegisterSet::from_registers([Register::X(4), Register::X(5)])
|
||||
);
|
||||
|
||||
// CSEL W0, W0, W1, AL (0x1a81_e000): unconditional ignores W1 and reads no flags
|
||||
let csel_al = semantics_of(&decode(0x1a81_e000)).unwrap();
|
||||
assert_eq!(csel_al.width, Width::W32);
|
||||
assert_eq!(csel_al.flag_reads, FlagMask::NONE);
|
||||
assert_eq!(csel_al.flag_writes, FlagMask::NONE);
|
||||
assert_eq!(csel_al.gpr_reads, RegisterSet::of(Register::X(0)));
|
||||
assert_eq!(csel_al.gpr_writes, RegisterSet::of(Register::X(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_with_carry_covers_carry_borrow_overflow_and_zero_edges() {
|
||||
// W32: 0xffff_ffff + 0 + C=1 -> 0, Z=1 C=1 N=0 V=0 (0x6000_0000)
|
||||
assert_eq!(
|
||||
add_with_carry(Width::W32, 0xffff_ffff, 0, true),
|
||||
(0, NZCV_Z | NZCV_C)
|
||||
);
|
||||
// X64: 0xffff_ffff + 0 + C=1 -> 0x1_0000_0000, all flags clear
|
||||
assert_eq!(
|
||||
add_with_carry(Width::X64, 0xffff_ffff, 0, true),
|
||||
(0x1_0000_0000, 0)
|
||||
);
|
||||
// W32 signed overflow from carry alone: 0x7fff_ffff + 0 + 1 -> 0x8000_0000, N=1 V=1
|
||||
assert_eq!(
|
||||
add_with_carry(Width::W32, 0x7fff_ffff, 0, true),
|
||||
(0x8000_0000, NZCV_N | NZCV_V)
|
||||
);
|
||||
// SBCS W32: INT_MIN - 0 with borrow (C=0): AddWithCarry(0x8000_0000, 0xffff_ffff, false)
|
||||
assert_eq!(
|
||||
add_with_carry(Width::W32, 0x8000_0000, !0u32 as u64, false),
|
||||
(0x7fff_ffff, NZCV_C | NZCV_V)
|
||||
);
|
||||
// SBCS X64: 0 - 0 with C=1 (no borrow): 0, Z=1 C=1
|
||||
assert_eq!(
|
||||
add_with_carry(Width::X64, 0, !0u64, true),
|
||||
(0, NZCV_Z | NZCV_C)
|
||||
);
|
||||
// SBCS X64: 0 - 0 with C=0 (borrow): u64::MAX, N=1
|
||||
assert_eq!(
|
||||
add_with_carry(Width::X64, 0, !0u64, false),
|
||||
(u64::MAX, NZCV_N)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
//! runtime helper when software PAuth is enabled.
|
||||
|
||||
mod analysis;
|
||||
pub mod effects;
|
||||
mod features;
|
||||
mod host_gprs;
|
||||
pub mod loop_budget;
|
||||
@@ -26,6 +27,7 @@ pub use analysis::{
|
||||
SuccessorKind, analyze, analyze_with_profile, source_bytes, source_bytes_with_profile,
|
||||
};
|
||||
use analysis::{ParsedBlock, analyze_parsed, parse_admitted, parse_with};
|
||||
pub use effects::{BlockEffects, analyze_block_effects, eval_instructions, summarize_instructions};
|
||||
pub use features::{BlockProfile, Features};
|
||||
pub use host_gprs::HostGprSnapshot;
|
||||
pub use memory::{
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
//! Basic-block architectural side-effect composition built from per-instruction semantics.
|
||||
use super::BlockProfile;
|
||||
use super::analysis::{BlockAnalysisError, parse};
|
||||
use crate::{
|
||||
GuestAddress, GuestState,
|
||||
aarch64::{
|
||||
Instruction, Operation, Register,
|
||||
semantics::{FlagMask, RegisterSet, eval_instruction, semantics_of},
|
||||
},
|
||||
};
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// Composed register and NZCV side-effect summary across a basic block.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BlockEffects {
|
||||
pub instruction_count: usize,
|
||||
pub fully_modeled: bool,
|
||||
pub live_in_gprs: RegisterSet,
|
||||
pub written_gprs: RegisterSet,
|
||||
pub live_in_flags: FlagMask,
|
||||
pub written_flags: FlagMask,
|
||||
pub killed_flags: FlagMask,
|
||||
/// Indices of instructions whose `NZCV` write is overwritten by a later
|
||||
/// instruction that redefines `FlagMask::ALL` before any bit is read.
|
||||
pub dead_flag_defs: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Summarize architectural register reads/writes, `NZCV` live-ins, and intra-block
|
||||
/// dead flag definitions across `instructions`.
|
||||
pub fn summarize_instructions(instructions: &[Instruction]) -> BlockEffects {
|
||||
summarize_with_exit(instructions, FlagMask::NONE, RegisterSet::NONE)
|
||||
}
|
||||
|
||||
/// Parse `source` at `base` using the ordinary block parser and compose its
|
||||
/// body effects together with any architectural terminal flag/register read.
|
||||
pub fn analyze_block_effects(
|
||||
source: &[u8],
|
||||
base: GuestAddress,
|
||||
) -> Result<BlockEffects, BlockAnalysisError> {
|
||||
let parsed = parse(source, base, BlockProfile::ORDINARY)?;
|
||||
let (exit_flags, exit_gprs) = match parsed.terminal.as_ref().map(|(_, term)| term) {
|
||||
Some(super::Terminator::Branch(Operation::BranchCondition { condition, .. })) => {
|
||||
(FlagMask::condition_reads(*condition), RegisterSet::NONE)
|
||||
}
|
||||
Some(super::Terminator::Branch(
|
||||
Operation::BranchZero { source, .. } | Operation::BranchBit { source, .. },
|
||||
)) => (FlagMask::NONE, RegisterSet::of(*source)),
|
||||
Some(super::Terminator::Register { source, .. }) => {
|
||||
(FlagMask::NONE, RegisterSet::of(*source))
|
||||
}
|
||||
Some(super::Terminator::DirectCall(_)) => (FlagMask::NONE, RegisterSet::NONE),
|
||||
Some(super::Terminator::Trap(_))
|
||||
| Some(super::Terminator::System(_))
|
||||
| Some(super::Terminator::PointerAuthentication(_))
|
||||
| Some(super::Terminator::Clock(_))
|
||||
| Some(super::Terminator::ThreadRegister(_))
|
||||
| Some(super::Terminator::FloatingPoint { .. })
|
||||
| Some(super::Terminator::Amx(_)) => (FlagMask::ALL, RegisterSet::NONE),
|
||||
_ => (FlagMask::NONE, RegisterSet::NONE),
|
||||
};
|
||||
let mut effects = summarize_with_exit(&parsed.instructions, exit_flags, exit_gprs);
|
||||
if matches!(
|
||||
parsed.terminal.as_ref().map(|(_, term)| term),
|
||||
Some(super::Terminator::Trap(_))
|
||||
| Some(super::Terminator::System(_))
|
||||
| Some(super::Terminator::PointerAuthentication(_))
|
||||
| Some(super::Terminator::Clock(_))
|
||||
| Some(super::Terminator::ThreadRegister(_))
|
||||
| Some(super::Terminator::FloatingPoint { .. })
|
||||
| Some(super::Terminator::Amx(_))
|
||||
) {
|
||||
effects.fully_modeled = false;
|
||||
}
|
||||
Ok(effects)
|
||||
}
|
||||
|
||||
fn summarize_with_exit(
|
||||
instructions: &[Instruction],
|
||||
exit_flag_reads: FlagMask,
|
||||
exit_gpr_reads: RegisterSet,
|
||||
) -> BlockEffects {
|
||||
let mut fully_modeled = true;
|
||||
let mut written_gprs = RegisterSet::NONE;
|
||||
let mut live_in_gprs = RegisterSet::NONE;
|
||||
let mut defined_all_flags = false;
|
||||
let mut written_flags = FlagMask::NONE;
|
||||
let mut live_in_flags = FlagMask::NONE;
|
||||
let mut live_before_write_flags = FlagMask::NONE;
|
||||
|
||||
for instruction in instructions {
|
||||
let Some(sem) = semantics_of(&instruction.operation) else {
|
||||
fully_modeled = false;
|
||||
continue;
|
||||
};
|
||||
let uncovered_gprs = sem.gpr_reads.difference(written_gprs);
|
||||
live_in_gprs = live_in_gprs.union(uncovered_gprs);
|
||||
written_gprs = written_gprs.union(sem.gpr_writes);
|
||||
|
||||
if !defined_all_flags {
|
||||
let unread_entry_flags = sem.flag_reads.difference(live_before_write_flags);
|
||||
live_in_flags = live_in_flags.union(unread_entry_flags);
|
||||
}
|
||||
written_flags = written_flags.union(sem.flag_writes);
|
||||
if sem.flag_writes == FlagMask::ALL {
|
||||
defined_all_flags = true;
|
||||
live_before_write_flags = FlagMask::ALL;
|
||||
}
|
||||
}
|
||||
|
||||
if !defined_all_flags {
|
||||
live_in_flags = live_in_flags.union(exit_flag_reads);
|
||||
}
|
||||
live_in_gprs = live_in_gprs.union(exit_gpr_reads.difference(written_gprs));
|
||||
|
||||
// Backward pass for intra-block dead flag definitions: NZCV is architecturally
|
||||
// live-out at block exit (`FlagMask::ALL`), so an instruction's flag write
|
||||
// is dead only if a later instruction in the same block overwrites every bit
|
||||
// it wrote before any intervening reader (or exit) observes them.
|
||||
let _ = exit_flag_reads;
|
||||
let mut live_flags_after = FlagMask::ALL;
|
||||
let mut dead_flag_defs = Vec::new();
|
||||
for (index, instruction) in instructions.iter().enumerate().rev() {
|
||||
let Some(sem) = semantics_of(&instruction.operation) else {
|
||||
// Unknown instructions may observe NZCV on block exit/fallback.
|
||||
live_flags_after = FlagMask::ALL;
|
||||
continue;
|
||||
};
|
||||
if !sem.flag_writes.is_empty() && !live_flags_after.intersects(sem.flag_writes) {
|
||||
dead_flag_defs.push(index);
|
||||
}
|
||||
live_flags_after = live_flags_after
|
||||
.difference(sem.flag_writes)
|
||||
.union(sem.flag_reads);
|
||||
}
|
||||
dead_flag_defs.reverse();
|
||||
|
||||
let killed_flags = if defined_all_flags {
|
||||
written_flags.difference(live_in_flags)
|
||||
} else {
|
||||
FlagMask::NONE
|
||||
};
|
||||
|
||||
BlockEffects {
|
||||
instruction_count: instructions.len(),
|
||||
fully_modeled,
|
||||
live_in_gprs,
|
||||
written_gprs,
|
||||
live_in_flags,
|
||||
written_flags,
|
||||
killed_flags,
|
||||
dead_flag_defs,
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate a slice of modeled instructions sequentially on `state`. Returns `None`
|
||||
/// if any instruction falls outside [`semantics_of`].
|
||||
pub fn eval_instructions(instructions: &[Instruction], state: &mut GuestState) -> Option<()> {
|
||||
for instruction in instructions {
|
||||
let sem = semantics_of(&instruction.operation)?;
|
||||
eval_instruction(&sem, state);
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Convenience helper for callers inspecting which `Register::X(i)` indices are in `set`.
|
||||
pub fn gpr_indices(set: RegisterSet) -> Vec<u8> {
|
||||
(0..31u8)
|
||||
.filter(|&i| set.contains(Register::X(i)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Lifter, aarch64::Decoder};
|
||||
|
||||
fn lift_words(words: &[u32]) -> Vec<Instruction> {
|
||||
words
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &w)| {
|
||||
Decoder
|
||||
.lift(GuestAddress(0x1000 + i as u64 * 4), w)
|
||||
.unwrap()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_carry_chain_and_dead_flag_kill() {
|
||||
// adds x4, x0, x2; adcs x5, x1, x3; csel x6, x4, x5, cs
|
||||
let u128_chain = lift_words(&[0xab02_0004, 0xba03_0025, 0x9a85_2086]);
|
||||
let effects = summarize_instructions(&u128_chain);
|
||||
assert!(effects.fully_modeled);
|
||||
assert_eq!(effects.live_in_flags, FlagMask::NONE);
|
||||
assert_eq!(effects.written_flags, FlagMask::ALL);
|
||||
assert_eq!(effects.killed_flags, FlagMask::ALL);
|
||||
// ADCS reads C from ADDS, CSEL reads C from ADCS, and NZCV is live-out at exit.
|
||||
assert!(effects.dead_flag_defs.is_empty());
|
||||
assert_eq!(
|
||||
effects.live_in_gprs,
|
||||
RegisterSet::from_registers([
|
||||
Register::X(0),
|
||||
Register::X(1),
|
||||
Register::X(2),
|
||||
Register::X(3),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
effects.written_gprs,
|
||||
RegisterSet::from_registers([Register::X(4), Register::X(5), Register::X(6)])
|
||||
);
|
||||
|
||||
// ADDS -> CSEL AL -> ADDS: CSEL AL reads no flags, so index 0 is dead.
|
||||
let al_kill = lift_words(&[0xab01_0004, 0x9a85_e086, 0xab03_0045]);
|
||||
let al_effects = summarize_instructions(&al_kill);
|
||||
assert_eq!(al_effects.live_in_flags, FlagMask::NONE);
|
||||
assert_eq!(al_effects.dead_flag_defs, vec![0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adcs_leading_block_requires_only_carry_in() {
|
||||
// adcs x4, x0, x2; sbcs x5, x1, x3; csel x6, x4, x5, hi
|
||||
let instructions = lift_words(&[0xba02_0004, 0xfa03_0025, 0x9a85_8086]);
|
||||
let effects = summarize_instructions(&instructions);
|
||||
assert_eq!(effects.live_in_flags, FlagMask::C);
|
||||
// Flipping N, Z, or V in entry NZCV must not change the output state.
|
||||
let mut s1 = GuestState::default();
|
||||
s1.x[0] = 0xffff_ffff_ffff_ffff;
|
||||
s1.x[1] = 10;
|
||||
s1.x[2] = 0;
|
||||
s1.x[3] = 4;
|
||||
s1.nzcv = crate::aarch64::flags::NZCV_C;
|
||||
|
||||
let mut s2 = s1.clone();
|
||||
s2.nzcv |= crate::aarch64::flags::NZCV_N
|
||||
| crate::aarch64::flags::NZCV_Z
|
||||
| crate::aarch64::flags::NZCV_V;
|
||||
|
||||
eval_instructions(&instructions, &mut s1).unwrap();
|
||||
eval_instructions(&instructions, &mut s2).unwrap();
|
||||
assert_eq!(s1.x, s2.x);
|
||||
assert_eq!(s1.nzcv, s2.nzcv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmodeled_trailing_instruction_keeps_flags_live_after_last_writer() {
|
||||
// adds x4, x0, x1; adds x5, x2, x3; csel x6, x4, x5, eq; branch exit
|
||||
let bytes: Vec<u8> = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086, 0x5400_0040]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let effects = analyze_block_effects(&bytes, GuestAddress(0x1000)).unwrap();
|
||||
assert!(effects.fully_modeled);
|
||||
assert_eq!(effects.live_in_flags, FlagMask::NONE);
|
||||
// First ADDS is dead because second ADDS overwrites all flags before CSEL EQ & B.EQ.
|
||||
assert_eq!(effects.dead_flag_defs, vec![0]);
|
||||
}
|
||||
}
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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::*;
|
||||
+20
-50
@@ -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"))]
|
||||
|
||||
+68
-14
@@ -11,11 +11,13 @@ use clap::Args;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io::{Read, Write},
|
||||
path::PathBuf,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
mod corpus;
|
||||
mod record;
|
||||
mod semantics_verify;
|
||||
mod stela;
|
||||
|
||||
use record::{Case, Ending, INPUT_BYTES, OUTPUT_BYTES};
|
||||
@@ -62,17 +64,41 @@ pub struct CpuReference {
|
||||
/// Rewrite the recorded table from this Mac run.
|
||||
#[arg(long)]
|
||||
record: bool,
|
||||
/// Recorded table path to read or write (default: `xtask/src/cpu_reference/apple-m1-pro.tsv`).
|
||||
#[arg(long)]
|
||||
table: Option<PathBuf>,
|
||||
/// Only the cases whose name contains this text.
|
||||
#[arg(long)]
|
||||
only: Option<String>,
|
||||
/// List the case names and exit.
|
||||
#[arg(long)]
|
||||
list: bool,
|
||||
/// Verify explicit Arm instruction semantics, block side effects, and
|
||||
/// multi-tier Stela compilation against the M4 corpus.
|
||||
#[arg(long)]
|
||||
verify_semantics: bool,
|
||||
}
|
||||
|
||||
impl CpuReference {
|
||||
pub fn run(self) -> Result<()> {
|
||||
let cases: Vec<Case> = corpus::all()
|
||||
if self.verify_semantics {
|
||||
semantics_verify::verify_m4_semantics()?;
|
||||
if self.only.is_none()
|
||||
&& self.mac.is_none()
|
||||
&& !self.recorded
|
||||
&& !self.record
|
||||
&& !self.list
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let using_m1_default = self.table.is_none();
|
||||
let all_cases = if self.recorded && using_m1_default {
|
||||
corpus::m1_baseline()
|
||||
} else {
|
||||
corpus::all()
|
||||
};
|
||||
let cases: Vec<Case> = all_cases
|
||||
.into_iter()
|
||||
.filter(|case| {
|
||||
self.only
|
||||
@@ -89,16 +115,16 @@ impl CpuReference {
|
||||
}
|
||||
ensure!(!cases.is_empty(), "no case matches");
|
||||
let (reference, source) = if self.recorded {
|
||||
let table = recorded()?;
|
||||
let table = match &self.table {
|
||||
Some(path) => recorded_from_path(path)?,
|
||||
None => recorded()?,
|
||||
};
|
||||
let outcomes = cases
|
||||
.iter()
|
||||
.map(|case| {
|
||||
table
|
||||
.get(case.name.as_str())
|
||||
.map(|outcome| outcome.to_string())
|
||||
.with_context(|| {
|
||||
format!("{} is not recorded; run with --record", case.name)
|
||||
})
|
||||
table.get(case.name.as_str()).cloned().with_context(|| {
|
||||
format!("{} is not recorded; run with --record", case.name)
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
(outcomes, "recorded")
|
||||
@@ -112,7 +138,11 @@ impl CpuReference {
|
||||
.collect();
|
||||
if self.record {
|
||||
ensure!(self.only.is_none(), "--record keeps every case");
|
||||
write_table(&host, &cases, &outcomes)?;
|
||||
let target_path = self
|
||||
.table
|
||||
.clone()
|
||||
.unwrap_or_else(|| PathBuf::from(TABLE_PATH));
|
||||
write_table(&host, &target_path, &cases, &outcomes)?;
|
||||
}
|
||||
(outcomes, "mac")
|
||||
};
|
||||
@@ -203,21 +233,41 @@ fn ssh(host: &str, script: &str) -> Command {
|
||||
}
|
||||
|
||||
/// The recorded table: case name to outcome.
|
||||
fn recorded() -> Result<BTreeMap<&'static str, &'static str>> {
|
||||
fn recorded() -> Result<BTreeMap<String, String>> {
|
||||
parse_table(TABLE)
|
||||
}
|
||||
|
||||
fn recorded_from_path(path: &std::path::Path) -> Result<BTreeMap<String, String>> {
|
||||
let resolved = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
crate::tools::root().join(path)
|
||||
};
|
||||
let text = std::fs::read_to_string(&resolved)
|
||||
.with_context(|| format!("cannot read table {}", resolved.display()))?;
|
||||
parse_table(&text)
|
||||
}
|
||||
|
||||
fn parse_table(text: &str) -> Result<BTreeMap<String, String>> {
|
||||
let mut table = BTreeMap::new();
|
||||
for line in TABLE
|
||||
for line in text
|
||||
.lines()
|
||||
.filter(|line| !line.starts_with('#') && !line.is_empty())
|
||||
{
|
||||
let Some((name, outcome)) = line.split_once('\t') else {
|
||||
bail!("malformed recorded line {line:?}");
|
||||
};
|
||||
table.insert(name, outcome);
|
||||
table.insert(name.to_string(), outcome.to_string());
|
||||
}
|
||||
Ok(table)
|
||||
}
|
||||
|
||||
fn write_table(host: &str, cases: &[Case], outcomes: &[String]) -> Result<()> {
|
||||
fn write_table(
|
||||
host: &str,
|
||||
target: &std::path::Path,
|
||||
cases: &[Case],
|
||||
outcomes: &[String],
|
||||
) -> Result<()> {
|
||||
let identity = Command::new("ssh")
|
||||
.args([
|
||||
"-o",
|
||||
@@ -235,7 +285,11 @@ fn write_table(host: &str, cases: &[Case], outcomes: &[String]) -> Result<()> {
|
||||
for (case, outcome) in cases.iter().zip(outcomes) {
|
||||
text.push_str(&format!("{}\t{outcome}\n", case.name));
|
||||
}
|
||||
let path = crate::tools::root().join(TABLE_PATH);
|
||||
let path = if target.is_absolute() {
|
||||
target.to_path_buf()
|
||||
} else {
|
||||
crate::tools::root().join(target)
|
||||
};
|
||||
std::fs::write(&path, text)?;
|
||||
println!("recorded {}", path.display());
|
||||
Ok(())
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -862,8 +862,8 @@ fn register_overlaps(cases: &mut Vec<Case>) {
|
||||
.push(Case::new("overlap.control.ldp.post", &[0xa8c1_1043]).memory(2, 16, &MEMORY_PATTERN));
|
||||
}
|
||||
|
||||
/// Every case, in a fixed order.
|
||||
pub fn all() -> Vec<Case> {
|
||||
/// The existing Apple M1 Pro baseline corpus, in fixed order.
|
||||
pub fn m1_baseline() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
fp_conversions(&mut cases);
|
||||
fp_rounding(&mut cases);
|
||||
@@ -880,6 +880,343 @@ pub fn all() -> Vec<Case> {
|
||||
cases
|
||||
}
|
||||
|
||||
/// Apple M4 differential corpus covering ADDS, ADCS, SBCS, CSEL, and
|
||||
/// multi-instruction basic blocks.
|
||||
pub fn m4_flags_csel() -> Vec<Case> {
|
||||
let mut cases = Vec::new();
|
||||
m4_adds(&mut cases);
|
||||
m4_carry_arith(&mut cases);
|
||||
m4_csel(&mut cases);
|
||||
m4_blocks(&mut cases);
|
||||
cases
|
||||
}
|
||||
|
||||
fn m4_adds(cases: &mut Vec<Case>) {
|
||||
let imm_forms: [(&str, u32); 9] = [
|
||||
("w.imm0", 0x3100_0020), // adds w0, w1, #0
|
||||
("w.imm1", 0x3100_0420), // adds w0, w1, #1
|
||||
("w.imm_fff", 0x313f_fc20), // adds w0, w1, #0xfff
|
||||
("w.imm1_lsl12", 0x3140_0420), // adds w0, w1, #1, lsl #12
|
||||
("w.imm_fff_lsl12", 0x317f_fc20), // adds w0, w1, #0xfff, lsl #12
|
||||
("w.cmn_fff", 0x313f_fc3f), // cmn w1, #0xfff (rd=wzr)
|
||||
("x.imm1", 0xb100_0420), // adds x0, x1, #1
|
||||
("x.imm_fff_lsl12", 0xb17f_fc20), // adds x0, x1, #0xfff, lsl #12
|
||||
("x.cmn_fff", 0xb13f_fc3f), // cmn x1, #0xfff (rd=xzr)
|
||||
];
|
||||
let inputs = [
|
||||
0u64,
|
||||
0x7fff_ffff,
|
||||
0x8000_0000,
|
||||
0xffff_ffff,
|
||||
0xdead_beef_ffff_ffff,
|
||||
0xfeed_face_7fff_ffff,
|
||||
0x7fff_ffff_ffff_ffff,
|
||||
0xffff_ffff_ffff_ffff,
|
||||
];
|
||||
for (form, word) in imm_forms {
|
||||
for (i, &val) in inputs.iter().enumerate() {
|
||||
cases.push(
|
||||
Case::new(format!("m4.adds.{form}.{i}"), &[word])
|
||||
.x(0, 0xaaaa_bbbb_cccc_dddd)
|
||||
.x(1, val)
|
||||
.nzcv(0xf000_0000),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let shift_forms: [(&str, u32); 8] = [
|
||||
("w.lsl3", 0x2b02_0c20), // adds w0, w1, w2, lsl #3
|
||||
("w.lsr1", 0x2b42_0420), // adds w0, w1, w2, lsr #1
|
||||
("w.asr31", 0x2b82_7c20), // adds w0, w1, w2, asr #31
|
||||
("w.cmn_lsl3", 0x2b02_0c3f), // cmn w1, w2, lsl #3
|
||||
("x.lsl3", 0xab02_0c20), // adds x0, x1, x2, lsl #3
|
||||
("x.lsr1", 0xab42_0420), // adds x0, x1, x2, lsr #1
|
||||
("x.asr63", 0xab82_fc20), // adds x0, x1, x2, asr #63
|
||||
("x.cmn_lsl3", 0xab02_0c3f), // cmn x1, x2, lsl #3
|
||||
];
|
||||
let pairs = [
|
||||
(0u64, 0u64),
|
||||
(0x7fff_ffff, 1),
|
||||
(0xdead_beef_ffff_ffff, 0xfeed_face_2000_0000),
|
||||
(0x8000_0000_0000_0000, 0xffff_ffff_ffff_ffff),
|
||||
];
|
||||
for (form, word) in shift_forms {
|
||||
for (i, &(a, b)) in pairs.iter().enumerate() {
|
||||
cases.push(
|
||||
Case::new(format!("m4.adds.{form}.{i}"), &[word])
|
||||
.x(0, 0x1234_5678_9abc_def0)
|
||||
.x(1, a)
|
||||
.x(2, b)
|
||||
.nzcv(0xf000_0000),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn m4_carry_arith(cases: &mut Vec<Case>) {
|
||||
// Non-C flags (N,Z,V) are set in `c0` to prove carry ops read only `C`.
|
||||
let carry_states = [("c0", 0xd000_0000u64), ("c1", 0x2000_0000u64)];
|
||||
|
||||
let adcs_pairs = [
|
||||
("zero", 0u64, 0u64),
|
||||
("w32_carry_zero", 0xdead_beef_ffff_ffff, 0),
|
||||
("w32_ovf_carry", 0xfeed_face_7fff_ffff, 0),
|
||||
("x64_ovf_carry", 0x7fff_ffff_ffff_ffff, 0),
|
||||
("x64_max_max", u64::MAX, u64::MAX),
|
||||
(
|
||||
"x64_sign_wrap",
|
||||
0x8000_0000_0000_0000,
|
||||
0x8000_0000_0000_0000,
|
||||
),
|
||||
];
|
||||
for (wlabel, word) in [("w", 0x3a02_0020u32), ("x", 0xba02_0020)] {
|
||||
for (plabel, a, b) in adcs_pairs {
|
||||
for (clabel, nzcv) in carry_states {
|
||||
cases.push(
|
||||
Case::new(format!("m4.adcs.{wlabel}.{plabel}.{clabel}"), &[word])
|
||||
.x(0, 0x5555_5555_5555_5555)
|
||||
.x(1, a)
|
||||
.x(2, b)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (label, word) in [
|
||||
("w.alias_all", 0x3a00_0000u32), // adcs w0, w0, w0
|
||||
("x.alias_all", 0xba00_0000), // adcs x0, x0, x0
|
||||
("x.alias_rd_rm", 0xba01_0041), // adcs x1, x2, x1
|
||||
("w.alias_rd_rm", 0x3a01_0041), // adcs w1, w2, w1
|
||||
("x.rd_zr", 0xba02_003f), // adcs xzr, x1, x2
|
||||
("x.rn_rm_zr", 0xba1f_03e0), // adcs x0, xzr, xzr
|
||||
] {
|
||||
for (clabel, nzcv) in carry_states {
|
||||
cases.push(
|
||||
Case::new(format!("m4.adcs.{label}.{clabel}"), &[word])
|
||||
.x(0, 0xfeed_face_7fff_ffff)
|
||||
.x(1, 0x8000_0000_0000_0001)
|
||||
.x(2, 0x7fff_ffff_ffff_ffff)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let sbcs_pairs = [
|
||||
("zero_zero", 0u64, 0u64),
|
||||
("zero_one", 0, 1),
|
||||
("w32_intmin_zero", 0xdead_beef_8000_0000, 0),
|
||||
("w32_intmax_neg1", 0x0000_0001_7fff_ffff, 0xffff_ffff),
|
||||
(
|
||||
"w32_dirty_cancel",
|
||||
0xdead_beef_0000_0005,
|
||||
0xfeed_face_0000_0005,
|
||||
),
|
||||
("x64_intmin_zero", 0x8000_0000_0000_0000, 0),
|
||||
("x64_zero_intmin", 0, 0x8000_0000_0000_0000),
|
||||
("x64_intmax_neg1", 0x7fff_ffff_ffff_ffff, u64::MAX),
|
||||
];
|
||||
for (wlabel, word) in [("w", 0x7a02_0020u32), ("x", 0xfa02_0020)] {
|
||||
for (plabel, a, b) in sbcs_pairs {
|
||||
for (clabel, nzcv) in carry_states {
|
||||
cases.push(
|
||||
Case::new(format!("m4.sbcs.{wlabel}.{plabel}.{clabel}"), &[word])
|
||||
.x(0, 0x5555_5555_5555_5555)
|
||||
.x(1, a)
|
||||
.x(2, b)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (label, word) in [
|
||||
("w.alias_all", 0x7a00_0000u32), // sbcs w0, w0, w0
|
||||
("x.alias_all", 0xfa00_0000), // sbcs x0, x0, x0
|
||||
("x.alias_rd_rm", 0xfa01_0041), // sbcs x1, x2, x1
|
||||
("w.rd_zr", 0x7a02_003f), // sbcs wzr, w1, w2
|
||||
("x.ngcs", 0xfa01_03e0), // ngcs x0, x1
|
||||
] {
|
||||
for (clabel, nzcv) in carry_states {
|
||||
cases.push(
|
||||
Case::new(format!("m4.sbcs.{label}.{clabel}"), &[word])
|
||||
.x(0, 0xfeed_face_8000_0000)
|
||||
.x(1, 0x8000_0000_0000_0001)
|
||||
.x(2, 0x0000_0000_0000_0001)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn m4_csel(cases: &mut Vec<Case>) {
|
||||
// Full 16x16 matrix: every condition 0..16 x every NZCV nibble 0..16 for CSEL X0, X1, X2, cond
|
||||
for condition in 0..16u32 {
|
||||
let word = 0x9a82_0020 | (condition << 12);
|
||||
for nibble in 0..16u64 {
|
||||
cases.push(
|
||||
Case::new(format!("m4.csel.x.c{condition}.{nibble:x}"), &[word])
|
||||
.x(0, 0x0123_4567_89ab_cdef)
|
||||
.x(1, 0x1111_2222_3333_4444)
|
||||
.x(2, 0x8888_9999_aaaa_bbbb)
|
||||
.nzcv(nibble << 28),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// W32 upper-bit truncation, aliasing (`keep_false`), unconditional AL/NV, and XZR/WZR.
|
||||
let w_variants = [
|
||||
("w.alias_rn", 0x1a81_0000u32), // csel w0, w0, w1, eq
|
||||
("w.alias_rm", 0x1a80_0020), // csel w0, w1, w0, eq
|
||||
("w.al", 0x1a81_e000), // csel w0, w0, w1, al
|
||||
("w.nv", 0x1a81_f000), // csel w0, w0, w1, nv
|
||||
("x.rn_zr", 0x9a81_23e0), // csel x0, xzr, x1, hs
|
||||
("x.rm_zr", 0x9a9f_3020), // csel x0, x1, xzr, lo
|
||||
("x.rd_zr", 0x9a82_003f), // csel xzr, x1, x2, eq
|
||||
];
|
||||
for (label, word) in w_variants {
|
||||
for (nlabel, nzcv) in [
|
||||
("zero", 0u64),
|
||||
("z", 0x4000_0000),
|
||||
("c", 0x2000_0000),
|
||||
("all", 0xf000_0000),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.csel.{label}.{nlabel}"), &[word])
|
||||
.x(0, 0xdead_beef_1111_2222)
|
||||
.x(1, 0xcafe_babe_3333_4444)
|
||||
.x(2, 0xbaad_f00d_5555_6666)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn m4_blocks(cases: &mut Vec<Case>) {
|
||||
// 1. 128-bit ADDS + ADCS carry propagation into CSEL CS
|
||||
let u128_add = [0xab02_0004u32, 0xba03_0025, 0x9a85_2086];
|
||||
for (label, x0, x1, x2, x3, nzcv) in [
|
||||
(
|
||||
"c_low",
|
||||
0xffff_ffff_ffff_ffff,
|
||||
0x7fff_ffff_ffff_ffff,
|
||||
1,
|
||||
0,
|
||||
0xf000_0000u64,
|
||||
),
|
||||
("no_carry", 10, 0xffff_ffff_ffff_ffff, 20, 0, 0x2000_0000),
|
||||
("double_carry", u64::MAX, u64::MAX, 1, 0, 0),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.u128_add_csel.{label}"), &u128_add)
|
||||
.x(0, x0)
|
||||
.x(1, x1)
|
||||
.x(2, x2)
|
||||
.x(3, x3)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
|
||||
// 2. 128-bit SUBS + SBCS borrow propagation into CSEL LT
|
||||
let u128_sub = [0xeb02_0004u32, 0xfa03_0025, 0x9a85_b086];
|
||||
for (label, x0, x1, x2, x3) in [
|
||||
("borrow", 0u64, 0u64, 1u64, 0u64),
|
||||
("no_borrow", 5, 0x8000_0000_0000_0000, 3, 1),
|
||||
("signed_lt", 0, 0x8000_0000_0000_0000, 1, 0),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.u128_sub_csel.{label}"), &u128_sub)
|
||||
.x(0, x0)
|
||||
.x(1, x1)
|
||||
.x(2, x2)
|
||||
.x(3, x3),
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Mixed ADDS carry-out -> SBCS -> CSEL VS
|
||||
let mixed_adds_sbcs = [0xab02_0004u32, 0xfa03_0025, 0x9a85_6086];
|
||||
for (label, x0, x1, x2, x3) in [
|
||||
(
|
||||
"no_borrow_ovf",
|
||||
1u64,
|
||||
0x7fff_ffff_ffff_ffffu64,
|
||||
0xffff_ffff_ffff_ffffu64,
|
||||
u64::MAX,
|
||||
),
|
||||
("borrow_ovf", 1, 0x8000_0000_0000_0000, 2, 0),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(
|
||||
format!("m4.block.mixed_adds_sbcs.{label}"),
|
||||
&mixed_adds_sbcs,
|
||||
)
|
||||
.x(0, x0)
|
||||
.x(1, x1)
|
||||
.x(2, x2)
|
||||
.x(3, x3),
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Consecutive AddSubCarry chain: ADCS -> SBCS -> ADCS -> CSEL HI
|
||||
let carry_run = [0xba02_0004u32, 0xfa03_0025, 0xba05_0086, 0x9a86_80a7];
|
||||
for (label, nzcv) in [("c0", 0xd000_0000u64), ("c1", 0x2000_0000)] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.carry_run_mixed.{label}"), &carry_run)
|
||||
.x(0, u64::MAX)
|
||||
.x(1, 10)
|
||||
.x(2, 0)
|
||||
.x(3, 5)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
|
||||
// 5. Intra-block dead flag kill: ADDS -> ADDS -> CSEL EQ
|
||||
let dead_kill = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086];
|
||||
for (label, x2, x3, nzcv) in [
|
||||
("zero_final", 5u64, 0xffff_ffff_ffff_fffbu64, 0xf000_0000u64),
|
||||
("nonzero_final", 5, 6, 0x4000_0000),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.dead_flags_kill.{label}"), &dead_kill)
|
||||
.x(0, 1)
|
||||
.x(1, 2)
|
||||
.x(2, x2)
|
||||
.x(3, x3)
|
||||
.nzcv(nzcv),
|
||||
);
|
||||
}
|
||||
|
||||
// 6. 32-bit dirty-upper-bits multi-step chain: ADDS W -> ADCS W -> SBCS W -> CSEL W GE
|
||||
let w32_chain = [0x2b01_0004u32, 0x3a1f_0045, 0x7a04_00a6, 0x1a86_a087];
|
||||
for (label, w0, w1, w2) in [
|
||||
(
|
||||
"carry_ge",
|
||||
0xdead_beef_ffff_ffffu64,
|
||||
0xfeed_face_0000_0001u64,
|
||||
0xbaad_f00d_7fff_ffffu64,
|
||||
),
|
||||
(
|
||||
"borrow_lt",
|
||||
0x1234_5678_8000_0000,
|
||||
0x9abc_def0_0000_0001,
|
||||
0x0000_0001_0000_0000,
|
||||
),
|
||||
] {
|
||||
cases.push(
|
||||
Case::new(format!("m4.block.w32_chain.{label}"), &w32_chain)
|
||||
.x(0, w0)
|
||||
.x(1, w1)
|
||||
.x(2, w2)
|
||||
.nzcv(0xf000_0000),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every case, in a fixed order.
|
||||
pub fn all() -> Vec<Case> {
|
||||
let mut cases = m1_baseline();
|
||||
cases.extend(m4_flags_csel());
|
||||
cases
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Three-way verification of explicit instruction semantics, basic-block
|
||||
//! side effects, Stela LEAF / BlockRuntime / SYSTEM_MODE compilation, and
|
||||
//! native Apple M4 outcomes.
|
||||
use super::corpus;
|
||||
use super::record::{self, Ending, MEMORY};
|
||||
use super::stela;
|
||||
use anyhow::{Result, ensure};
|
||||
use stela_compiler::{
|
||||
GuestAddress, GuestState, Lifter, Options, TargetCpu,
|
||||
aarch64::{
|
||||
Decoder, Register, Width,
|
||||
flags::{NZCV_C, NZCV_N, NZCV_V, NZCV_Z},
|
||||
semantics::{FlagMask, RegisterSet, add_with_carry, semantics_of},
|
||||
},
|
||||
block::{
|
||||
BlockProfile, Features, analyze_block_effects, eval_instructions, summarize_instructions,
|
||||
},
|
||||
compile,
|
||||
};
|
||||
|
||||
const RET_ENCODING: u32 = 0xd65f_03c0;
|
||||
|
||||
/// Execute all explicit semantic checks, block side-effect invariants,
|
||||
/// Stela LEAF vs BlockRuntime vs semantic-oracle equivalence checks across the
|
||||
/// full `m4_flags_csel` suite.
|
||||
pub fn verify_m4_semantics() -> Result<()> {
|
||||
verify_instruction_contracts()?;
|
||||
verify_block_contracts()?;
|
||||
verify_corpus_three_way()?;
|
||||
println!(
|
||||
"semantics verification: 100% passed (instruction contracts, block effects, 480 m4 cases x semantic oracle x LEAF x BlockRuntime x SYSTEM_MODE compile)"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lift(words: &[u32]) -> Result<Vec<stela_compiler::aarch64::Instruction>> {
|
||||
words
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &w)| {
|
||||
Decoder
|
||||
.lift(GuestAddress(0x10_0000 + i as u64 * 4), w)
|
||||
.map_err(|e| anyhow::anyhow!("decode failed at #{i} ({w:#010x}): {e:?}"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn verify_instruction_contracts() -> Result<()> {
|
||||
// 1. ADDS imm & shifted reg: reads GPR(s), reads no flags, writes ALL flags.
|
||||
let adds_imm = lift(&[0x3100_0420])?;
|
||||
let s = semantics_of(&adds_imm[0].operation).expect("adds w0, w1, #1");
|
||||
ensure!(s.width == Width::W32);
|
||||
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
|
||||
ensure!(s.gpr_writes == RegisterSet::of(Register::X(0)));
|
||||
ensure!(s.flag_reads == FlagMask::NONE && s.flag_writes == FlagMask::ALL);
|
||||
|
||||
// CMN W1, #0xfff -> writes ZERO architectural GPR while writing all flags.
|
||||
let cmn = lift(&[0x313f_fc3f])?;
|
||||
let s = semantics_of(&cmn[0].operation).expect("cmn w1, #0xfff");
|
||||
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
|
||||
ensure!(s.gpr_writes == RegisterSet::NONE);
|
||||
ensure!(s.flag_writes == FlagMask::ALL);
|
||||
|
||||
// 2. ADCS & SBCS: read C flag ONLY, write ALL flags.
|
||||
let carry_ops = lift(&[0xba02_0020, 0xfa02_0020])?;
|
||||
for insn in &carry_ops {
|
||||
let s = semantics_of(&insn.operation).expect("adcs/sbcs");
|
||||
ensure!(s.flag_reads == FlagMask::C);
|
||||
ensure!(s.flag_writes == FlagMask::ALL);
|
||||
}
|
||||
|
||||
// 3. CSEL: condition-specific flag reads, NO flag writes, AL/NV unconditional.
|
||||
for cond in 0..16u32 {
|
||||
let word = 0x9a82_0020 | (cond << 12);
|
||||
let insn = lift(&[word])?;
|
||||
let s = semantics_of(&insn[0].operation).expect("csel");
|
||||
ensure!(s.flag_writes == FlagMask::NONE);
|
||||
ensure!(s.flag_reads == FlagMask::condition_reads(cond as u8));
|
||||
if cond >= 14 {
|
||||
ensure!(s.flag_reads == FlagMask::NONE);
|
||||
ensure!(s.gpr_reads == RegisterSet::of(Register::X(1)));
|
||||
} else {
|
||||
ensure!(s.gpr_reads == RegisterSet::from_registers([Register::X(1), Register::X(2)]));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Arm AddWithCarry edge values.
|
||||
ensure!(add_with_carry(Width::W32, 0xffff_ffff, 0, true) == (0, NZCV_Z | NZCV_C));
|
||||
ensure!(add_with_carry(Width::W32, 0x7fff_ffff, 0, true) == (0x8000_0000, NZCV_N | NZCV_V));
|
||||
ensure!(
|
||||
add_with_carry(Width::X64, 0x8000_0000_0000_0000, !0u64, false)
|
||||
== (0x7fff_ffff_ffff_ffff, NZCV_C | NZCV_V)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_block_contracts() -> Result<()> {
|
||||
// ADDS -> ADCS -> CSEL CS: live_in_flags == NONE, X0..X3 live-in, X4..X6 written.
|
||||
// Neither flag write is dead because ADCS consumes C and block exit keeps NZCV live.
|
||||
let u128_words = [0xab02_0004u32, 0xba03_0025, 0x9a85_2086];
|
||||
let u128_bytes: Vec<u8> = u128_words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let e = analyze_block_effects(&u128_bytes, GuestAddress(0x10_0000))?;
|
||||
ensure!(e.fully_modeled && e.live_in_flags == FlagMask::NONE);
|
||||
ensure!(e.written_flags == FlagMask::ALL && e.killed_flags == FlagMask::ALL);
|
||||
ensure!(e.live_in_gprs.contains(Register::X(0)) && e.live_in_gprs.contains(Register::X(3)));
|
||||
ensure!(!e.live_in_gprs.contains(Register::X(4)));
|
||||
ensure!(e.dead_flag_defs.is_empty());
|
||||
|
||||
// ADCS -> SBCS -> ADCS -> CSEL HI: live_in_flags == C (N,Z,V entry bits ignored).
|
||||
let run_words = [0xba02_0004u32, 0xfa03_0025, 0xba05_0086, 0x9a86_80a7];
|
||||
let run_insns = lift(&run_words)?;
|
||||
let e_run = summarize_instructions(&run_insns);
|
||||
ensure!(e_run.live_in_flags == FlagMask::C);
|
||||
ensure!(e_run.dead_flag_defs.is_empty());
|
||||
|
||||
// Dead-flag kill: ADDS -> ADDS -> CSEL EQ (first ADDS flags dead).
|
||||
let kill_words = [0xab01_0004u32, 0xab03_0045, 0x9a85_0086];
|
||||
let kill_bytes: Vec<u8> = kill_words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let e_kill = analyze_block_effects(&kill_bytes, GuestAddress(0x10_0000))?;
|
||||
ensure!(e_kill.live_in_flags == FlagMask::NONE);
|
||||
ensure!(e_kill.dead_flag_defs == vec![0]);
|
||||
|
||||
// ADDS -> CSEL AL -> ADDS: unconditional CSEL AL reads no flags, so first ADDS is dead.
|
||||
let al_words = [0xab01_0004u32, 0x9a85_e086, 0xab03_0045];
|
||||
let al_bytes: Vec<u8> = al_words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let e_al = analyze_block_effects(&al_bytes, GuestAddress(0x10_0000))?;
|
||||
ensure!(e_al.live_in_flags == FlagMask::NONE);
|
||||
ensure!(e_al.dead_flag_defs == vec![0]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_corpus_three_way() -> Result<()> {
|
||||
let cases = corpus::m4_flags_csel();
|
||||
ensure!(!cases.is_empty(), "m4_flags_csel must be non-empty");
|
||||
let block_runtime_endings = stela::run(&cases)?;
|
||||
let leaf_options = Options::new(BlockProfile::new(Features::LEAF), TargetCpu::detect());
|
||||
let system_options = Options::new(
|
||||
BlockProfile::new(Features::SYSTEM_MODE),
|
||||
TargetCpu::detect(),
|
||||
);
|
||||
|
||||
for (case, br_ending) in cases.iter().zip(&block_runtime_endings) {
|
||||
// 1. Lift and verify semantic model + side effects.
|
||||
let insns = lift(&case.words)?;
|
||||
let effects = summarize_instructions(&insns);
|
||||
ensure!(effects.fully_modeled, "{} was not modeled", case.name);
|
||||
|
||||
let mut oracle_state = GuestState {
|
||||
x: case.state.x,
|
||||
nzcv: case.state.nzcv as u32,
|
||||
..Default::default()
|
||||
};
|
||||
eval_instructions(&insns, &mut oracle_state)
|
||||
.ok_or_else(|| anyhow::anyhow!("oracle failed on {}", case.name))?;
|
||||
|
||||
// 2. Non-interference: architectural registers outside `written_gprs` stay identical,
|
||||
// and unread entry flag bits do not affect register outputs (or flags if overwritten).
|
||||
for idx in 0..31u8 {
|
||||
if !effects.written_gprs.contains(Register::X(idx)) {
|
||||
ensure!(
|
||||
oracle_state.x[usize::from(idx)] == case.state.x[usize::from(idx)],
|
||||
"{}: unmodeled write to X{idx}",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
}
|
||||
let unread_flags = FlagMask::ALL
|
||||
.difference(effects.live_in_flags)
|
||||
.to_nzcv_mask();
|
||||
if unread_flags != 0 {
|
||||
let mut perturbed = GuestState {
|
||||
x: case.state.x,
|
||||
nzcv: (case.state.nzcv as u32) ^ unread_flags,
|
||||
..Default::default()
|
||||
};
|
||||
eval_instructions(&insns, &mut perturbed).unwrap();
|
||||
ensure!(
|
||||
perturbed.x == oracle_state.x,
|
||||
"{}: unread NZCV bits altered GPRs",
|
||||
case.name
|
||||
);
|
||||
if effects.written_flags == FlagMask::ALL {
|
||||
ensure!(
|
||||
perturbed.nzcv == oracle_state.nzcv,
|
||||
"{}: unread NZCV bits altered final NZCV",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Compare semantic oracle against BlockRuntime (`optimize: true`).
|
||||
let oracle_ending = Ending::Completed {
|
||||
state: Box::new(super::record::State {
|
||||
x: oracle_state.x,
|
||||
nzcv: u64::from(oracle_state.nzcv),
|
||||
fpcr: case.state.fpcr,
|
||||
fpsr: case.state.fpsr,
|
||||
v: case.state.v,
|
||||
}),
|
||||
memory: Box::new([0u8; MEMORY]),
|
||||
};
|
||||
let oracle_out = record::outcome(case, &oracle_ending);
|
||||
let br_out = record::outcome(case, br_ending);
|
||||
ensure!(
|
||||
oracle_out == br_out,
|
||||
"{}: semantic oracle ({oracle_out}) != BlockRuntime ({br_out})",
|
||||
case.name
|
||||
);
|
||||
|
||||
// 4. Compile & execute through Stela `Features::LEAF` (frame emitter).
|
||||
let mut leaf_words = case.words.clone();
|
||||
leaf_words.push(RET_ENCODING);
|
||||
let leaf_bytes: Vec<u8> = leaf_words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let compiled_leaf = compile(&leaf_bytes, GuestAddress(0x10_0000), &leaf_options)?;
|
||||
ensure!(
|
||||
compiled_leaf.source_bytes == leaf_bytes.len(),
|
||||
"{}: LEAF truncated block",
|
||||
case.name
|
||||
);
|
||||
let mut leaf_state = GuestState {
|
||||
x: case.state.x,
|
||||
nzcv: case.state.nzcv as u32,
|
||||
..Default::default()
|
||||
};
|
||||
run_native_leaf(&compiled_leaf.native.x86_64_code, &mut leaf_state)?;
|
||||
ensure!(
|
||||
leaf_state.x == oracle_state.x && leaf_state.nzcv == oracle_state.nzcv,
|
||||
"{}: LEAF mismatch: leaf(nzcv={:#x}) vs oracle(nzcv={:#x})",
|
||||
case.name,
|
||||
leaf_state.nzcv,
|
||||
oracle_state.nzcv
|
||||
);
|
||||
|
||||
// 5. Compile through Stela `Features::SYSTEM_MODE` (pinned + carry runs + dead-flag elimination).
|
||||
let block_bytes: Vec<u8> = case.words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
let compiled_sys = compile(&block_bytes, GuestAddress(0x10_0000), &system_options)?;
|
||||
ensure!(
|
||||
compiled_sys.source_bytes == block_bytes.len(),
|
||||
"{}: SYSTEM_MODE did not cover full block",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn run_native_leaf(code: &[u8], state: &mut GuestState) -> Result<()> {
|
||||
use core::ffi::c_void;
|
||||
unsafe extern "system" {
|
||||
fn GetCurrentProcess() -> *mut c_void;
|
||||
fn VirtualAlloc(
|
||||
lp_address: *mut c_void,
|
||||
dw_size: usize,
|
||||
fl_allocation_type: u32,
|
||||
fl_protect: u32,
|
||||
) -> *mut c_void;
|
||||
fn VirtualProtect(
|
||||
lp_address: *mut c_void,
|
||||
dw_size: usize,
|
||||
fl_new_protect: u32,
|
||||
lpfl_old_protect: *mut u32,
|
||||
) -> i32;
|
||||
fn VirtualFree(lp_address: *mut c_void, dw_size: usize, dw_free_type: u32) -> i32;
|
||||
fn FlushInstructionCache(
|
||||
h_process: *mut c_void,
|
||||
lp_base_address: *const c_void,
|
||||
dw_size: usize,
|
||||
) -> i32;
|
||||
}
|
||||
let bytes = code.len().max(1).next_multiple_of(4096);
|
||||
// SAFETY: allocates a private RW buffer, copies Stela's generated leaf
|
||||
// x86-64 code (ending in RET), transitions it to RX, flushes I-cache,
|
||||
// executes with SysV64 ABI (`RDI = state`), and frees it.
|
||||
unsafe {
|
||||
let page = VirtualAlloc(core::ptr::null_mut(), bytes, 0x3000, 0x04);
|
||||
ensure!(!page.is_null(), "VirtualAlloc failed for leaf");
|
||||
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
|
||||
let mut old = 0u32;
|
||||
ensure!(
|
||||
VirtualProtect(page, bytes, 0x20, &mut old) != 0,
|
||||
"VirtualProtect failed"
|
||||
);
|
||||
ensure!(
|
||||
FlushInstructionCache(GetCurrentProcess(), page, bytes) != 0,
|
||||
"FlushInstructionCache failed"
|
||||
);
|
||||
let func: unsafe extern "sysv64" fn(*mut GuestState) = core::mem::transmute(page);
|
||||
func(state as *mut GuestState);
|
||||
ensure!(VirtualFree(page, 0, 0x8000) != 0, "VirtualFree failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn run_native_leaf(code: &[u8], state: &mut GuestState) -> Result<()> {
|
||||
use core::ffi::c_void;
|
||||
unsafe extern "C" {
|
||||
fn mmap(
|
||||
addr: *mut c_void,
|
||||
len: usize,
|
||||
prot: i32,
|
||||
flags: i32,
|
||||
fd: i32,
|
||||
off: i64,
|
||||
) -> *mut c_void;
|
||||
fn mprotect(addr: *mut c_void, len: usize, prot: i32) -> i32;
|
||||
fn munmap(addr: *mut c_void, len: usize) -> i32;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
const MAP_ANON: i32 = 0x1000;
|
||||
#[cfg(target_os = "linux")]
|
||||
const MAP_ANON: i32 = 0x20;
|
||||
let bytes = code.len().max(1).next_multiple_of(4096);
|
||||
// SAFETY: private RX mapping containing valid compiled leaf code.
|
||||
unsafe {
|
||||
let page = mmap(core::ptr::null_mut(), bytes, 3, 2 | MAP_ANON, -1, 0);
|
||||
ensure!(page as usize != usize::MAX, "mmap failed");
|
||||
core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len());
|
||||
ensure!(mprotect(page, bytes, 5) == 0, "mprotect failed");
|
||||
let func: unsafe extern "sysv64" fn(*mut GuestState) = core::mem::transmute(page);
|
||||
func(state as *mut GuestState);
|
||||
ensure!(munmap(page, bytes) == 0, "munmap failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,9 +5,119 @@ use super::record::{Case, Ending, MEMORY, State};
|
||||
use anyhow::{Context, Result};
|
||||
use stela_compiler::{GuestAddress, GuestState};
|
||||
use stela_engine::blocks::{BlockRuntime, StopReason, ThreadState};
|
||||
#[cfg(unix)]
|
||||
use stela_engine::memory::{MemoryRegionSpec, OwnedMemory};
|
||||
use stela_engine::pauth::{self, Keys};
|
||||
|
||||
#[cfg(unix)]
|
||||
struct CaseBuffer(OwnedMemory);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl CaseBuffer {
|
||||
fn allocate() -> Result<Self> {
|
||||
let memory = OwnedMemory::map(vec![MemoryRegionSpec {
|
||||
guest_address: MEMORY_BASE,
|
||||
virtual_bytes: 4096,
|
||||
initial_bytes: vec![0; 4096],
|
||||
readable: true,
|
||||
writable: true,
|
||||
executable: false,
|
||||
}])
|
||||
.context("cannot map the case buffer")?;
|
||||
Ok(Self(memory))
|
||||
}
|
||||
|
||||
fn write(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
// Re-zero first so shrinking or untouched regions never leak prior case bytes.
|
||||
self.0.write(MEMORY_BASE, &[0u8; 4096])?;
|
||||
self.0.write(MEMORY_BASE, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_snapshot(&self, len: usize) -> Result<Vec<u8>> {
|
||||
self.0.read_snapshot(MEMORY_BASE, len)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
struct CaseBuffer {
|
||||
ptr: *mut core::ffi::c_void,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl CaseBuffer {
|
||||
const ALLOCATION_BYTES: usize = 0x1_0000;
|
||||
const MEM_COMMIT: u32 = 0x1000;
|
||||
const MEM_RESERVE: u32 = 0x2000;
|
||||
const MEM_RELEASE: u32 = 0x8000;
|
||||
const PAGE_READWRITE: u32 = 0x04;
|
||||
|
||||
fn allocate() -> Result<Self> {
|
||||
unsafe extern "system" {
|
||||
fn VirtualAlloc(
|
||||
lp_address: *mut core::ffi::c_void,
|
||||
dw_size: usize,
|
||||
fl_allocation_type: u32,
|
||||
fl_protect: u32,
|
||||
) -> *mut core::ffi::c_void;
|
||||
}
|
||||
// SAFETY: reserves and commits a fresh 64 KiB read-write buffer at the
|
||||
// fixed 64 KiB-aligned guest address used by the differential harness.
|
||||
let ptr = unsafe {
|
||||
VirtualAlloc(
|
||||
MEMORY_BASE as *mut core::ffi::c_void,
|
||||
Self::ALLOCATION_BYTES,
|
||||
Self::MEM_COMMIT | Self::MEM_RESERVE,
|
||||
Self::PAGE_READWRITE,
|
||||
)
|
||||
};
|
||||
anyhow::ensure!(!ptr.is_null(), "VirtualAlloc failed for case buffer");
|
||||
anyhow::ensure!(
|
||||
ptr as u64 == MEMORY_BASE,
|
||||
"VirtualAlloc returned {:#x}, expected {MEMORY_BASE:#x}",
|
||||
ptr as u64
|
||||
);
|
||||
Ok(Self { ptr })
|
||||
}
|
||||
|
||||
fn write(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
anyhow::ensure!(bytes.len() <= 4096, "case memory exceeds 4096 bytes");
|
||||
// SAFETY: `ptr` points to `ALLOCATION_BYTES` uniquely owned writable bytes.
|
||||
unsafe {
|
||||
core::ptr::write_bytes(self.ptr.cast::<u8>(), 0, 4096);
|
||||
core::ptr::copy_nonoverlapping(bytes.as_ptr(), self.ptr.cast::<u8>(), bytes.len());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_snapshot(&self, len: usize) -> Result<Vec<u8>> {
|
||||
anyhow::ensure!(len <= 4096, "snapshot exceeds 4096 bytes");
|
||||
let mut out = vec![0u8; len];
|
||||
// SAFETY: `ptr` points to at least 4096 initialized readable bytes.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(self.ptr.cast::<u8>(), out.as_mut_ptr(), len);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Drop for CaseBuffer {
|
||||
fn drop(&mut self) {
|
||||
unsafe extern "system" {
|
||||
fn VirtualFree(
|
||||
lp_address: *mut core::ffi::c_void,
|
||||
dw_size: usize,
|
||||
dw_free_type: u32,
|
||||
) -> i32;
|
||||
}
|
||||
// SAFETY: `self.ptr` was allocated with `VirtualAlloc(MEM_RESERVE | MEM_COMMIT)`.
|
||||
unsafe {
|
||||
let _ = VirtualFree(self.ptr, 0, Self::MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ADDRESS_SPACE: u64 = 0x5ce1;
|
||||
/// Guest addresses equal host addresses in the direct profile: the buffer
|
||||
/// is mapped here, at a 64-byte-aligned address as the runner's.
|
||||
@@ -32,15 +142,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
|
||||
),
|
||||
stela_compiler::TargetCpu::detect(),
|
||||
);
|
||||
let mut memory = OwnedMemory::map(vec![MemoryRegionSpec {
|
||||
guest_address: MEMORY_BASE,
|
||||
virtual_bytes: 4096,
|
||||
initial_bytes: vec![0; 4096],
|
||||
readable: true,
|
||||
writable: true,
|
||||
executable: false,
|
||||
}])
|
||||
.context("cannot map the case buffer")?;
|
||||
let mut memory = CaseBuffer::allocate().context("cannot map the case buffer")?;
|
||||
let pauth = pauth::Context::new(
|
||||
ADDRESS_SPACE,
|
||||
Keys::from_words(KEY, KEY, KEY, KEY).with_generic_words(KEY),
|
||||
@@ -52,7 +154,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
|
||||
words.push(BRANCH_NEXT);
|
||||
let source = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
runtime.register_code(GuestAddress(base), source)?;
|
||||
memory.write(MEMORY_BASE, &case.memory)?;
|
||||
memory.write(&case.memory)?;
|
||||
let mut thread = ThreadState {
|
||||
registers: guest_state(case),
|
||||
pc: GuestAddress(base),
|
||||
@@ -71,7 +173,7 @@ pub fn run(cases: &[Case]) -> Result<Vec<Ending>> {
|
||||
state.x[register] = state.x[register].wrapping_sub(MEMORY_BASE);
|
||||
}
|
||||
}
|
||||
let bytes = memory.read_snapshot(MEMORY_BASE, MEMORY)?;
|
||||
let bytes = memory.read_snapshot(MEMORY)?;
|
||||
Ending::Completed {
|
||||
state: Box::new(state),
|
||||
memory: Box::new(bytes.try_into().unwrap()),
|
||||
|
||||
@@ -3,32 +3,68 @@ use super::*;
|
||||
#[test]
|
||||
fn every_case_is_recorded() {
|
||||
let table = recorded().unwrap();
|
||||
let cases = corpus::all();
|
||||
let cases = corpus::m1_baseline();
|
||||
assert_eq!(table.len(), cases.len());
|
||||
for case in &cases {
|
||||
assert!(table.contains_key(case.name.as_str()), "{}", case.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The regression check: every case through Stela gives the outcome
|
||||
/// recorded on the Mac, except the known differences, which still differ.
|
||||
/// Stela runs the cases in exact guest mappings, which only an x86-64 Linux
|
||||
/// or macOS host has.
|
||||
#[test]
|
||||
#[cfg(all(target_arch = "x86_64", any(target_os = "linux", target_os = "macos")))]
|
||||
fn m4_semantics_and_tiers_match() {
|
||||
semantics_verify::verify_m4_semantics().unwrap();
|
||||
}
|
||||
|
||||
/// The regression check: every case through Stela gives the outcome
|
||||
/// recorded on the M1 Pro, except the known differences, which still differ.
|
||||
#[test]
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
any(target_os = "linux", target_os = "macos", target_os = "windows")
|
||||
))]
|
||||
fn stela_matches_the_recorded_mac() {
|
||||
let table = recorded().unwrap();
|
||||
let cases = corpus::all();
|
||||
let cases = corpus::m1_baseline();
|
||||
let endings = stela::run(&cases).unwrap();
|
||||
let mut unexpected = Vec::new();
|
||||
for (case, ending) in cases.iter().zip(&endings) {
|
||||
let stela = record::outcome(case, ending);
|
||||
let mac = table[case.name.as_str()];
|
||||
let mac = &table[case.name.as_str()];
|
||||
match known_difference(&case.name) {
|
||||
None if stela != mac => {
|
||||
None if &stela != mac => {
|
||||
unexpected.push(format!("{}: mac {mac}, stela {stela}", case.name))
|
||||
}
|
||||
Some(_) if stela == mac => unexpected.push(format!("{}: no longer differs", case.name)),
|
||||
Some(_) if &stela == mac => {
|
||||
unexpected.push(format!("{}: no longer differs", case.name))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(unexpected.is_empty(), "{}", unexpected.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(all(
|
||||
target_arch = "x86_64",
|
||||
any(target_os = "linux", target_os = "macos", target_os = "windows")
|
||||
))]
|
||||
fn stela_matches_recorded_apple_m4() {
|
||||
let table =
|
||||
recorded_from_path(std::path::Path::new("xtask/src/cpu_reference/apple-m4.tsv")).unwrap();
|
||||
let cases = corpus::all();
|
||||
assert_eq!(table.len(), cases.len());
|
||||
let endings = stela::run(&cases).unwrap();
|
||||
let mut unexpected = Vec::new();
|
||||
for (case, ending) in cases.iter().zip(&endings) {
|
||||
let stela = record::outcome(case, ending);
|
||||
let mac = &table[case.name.as_str()];
|
||||
match known_difference(&case.name) {
|
||||
None if &stela != mac => {
|
||||
unexpected.push(format!("{}: m4 {mac}, stela {stela}", case.name))
|
||||
}
|
||||
Some(_) if &stela == mac => {
|
||||
unexpected.push(format!("{}: no longer differs", case.name))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user