mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 14:50:43 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
061c28b405 |
No files matched your search
+1
-2
@@ -25,6 +25,7 @@ remains unsupported.
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
|
||||
### Added
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
@@ -203,8 +204,6 @@ remains unsupported.
|
||||
### Fixed
|
||||
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
|
||||
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
|
||||
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
//! Synthetic interpreter and DBT timings.
|
||||
//!
|
||||
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
|
||||
//! document (format version 1). The text output does not change. Values the
|
||||
//! benchmark cannot determine, such as the git revision outside a checkout,
|
||||
//! are written as `null`.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
|
||||
@@ -10,7 +15,7 @@
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::dbt::{DbtEngine, DbtMetrics};
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
@@ -103,19 +108,215 @@ fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
|
||||
lower + (upper - lower).mul_f64(rank.fract())
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
/// Order statistics of one timing series, shared by the text and JSON reports.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Summary {
|
||||
samples: usize,
|
||||
median: Duration,
|
||||
min: Duration,
|
||||
max: Duration,
|
||||
p95: Duration,
|
||||
p99: Duration,
|
||||
iqr: Duration,
|
||||
mips: f64,
|
||||
}
|
||||
|
||||
fn summarize(samples: &mut [Duration]) -> Summary {
|
||||
samples.sort_unstable();
|
||||
let median = percentile(samples, 0.50);
|
||||
let p95 = percentile(samples, 0.95);
|
||||
let p99 = percentile(samples, 0.99);
|
||||
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
|
||||
let min = samples[0];
|
||||
let max = samples[samples.len() - 1];
|
||||
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
|
||||
println!(
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
Summary {
|
||||
samples: samples.len(),
|
||||
median,
|
||||
min: samples[0],
|
||||
max: samples[samples.len() - 1],
|
||||
p95: percentile(samples, 0.95),
|
||||
p99: percentile(samples, 0.99),
|
||||
iqr: percentile(samples, 0.75) - percentile(samples, 0.25),
|
||||
mips: INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn report_line(label: &str, s: &Summary) -> String {
|
||||
format!(
|
||||
"{label}: {} samples, median {:?}, min {:?}, max {:?}, p95 {:?}, p99 {:?}, IQR {:?}, median {:.2} MIPS",
|
||||
s.samples, s.median, s.min, s.max, s.p95, s.p99, s.iqr, s.mips
|
||||
)
|
||||
}
|
||||
|
||||
/// Facts about the run that are not timings. `None` means the benchmark could not
|
||||
/// determine the value.
|
||||
struct RunInfo {
|
||||
unix_time: Option<u64>,
|
||||
cpu: Option<String>,
|
||||
os: &'static str,
|
||||
os_version: Option<String>,
|
||||
arch: &'static str,
|
||||
revision: Option<String>,
|
||||
dirty: Option<bool>,
|
||||
debug_assertions: bool,
|
||||
guest_code_bytes: usize,
|
||||
warmup: usize,
|
||||
}
|
||||
|
||||
fn command_output(program: &str, args: &[&str]) -> Option<String> {
|
||||
let output = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(String::from_utf8(output.stdout).ok()?.trim().to_owned())
|
||||
}
|
||||
|
||||
fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
|
||||
let non_empty = |value: Option<String>| value.filter(|v| !v.is_empty());
|
||||
RunInfo {
|
||||
unix_time: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.ok()
|
||||
.map(|d| d.as_secs()),
|
||||
cpu: non_empty(command_output(
|
||||
"sysctl",
|
||||
&["-n", "machdep.cpu.brand_string"],
|
||||
)),
|
||||
os: std::env::consts::OS,
|
||||
os_version: non_empty(command_output("sw_vers", &["-productVersion"])),
|
||||
arch: std::env::consts::ARCH,
|
||||
revision: non_empty(command_output("git", &["rev-parse", "HEAD"])),
|
||||
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
|
||||
.map(|status| !status.is_empty()),
|
||||
debug_assertions: cfg!(debug_assertions),
|
||||
guest_code_bytes,
|
||||
warmup,
|
||||
}
|
||||
}
|
||||
|
||||
fn json_string(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len() + 2);
|
||||
out.push('"');
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
fn json_option<T>(value: Option<T>, render: impl FnOnce(T) -> String) -> String {
|
||||
value.map_or_else(|| "null".to_owned(), render)
|
||||
}
|
||||
|
||||
/// JSON has no infinity or NaN, so a non-finite rate (a zero median) is `null`.
|
||||
fn json_f64(value: f64) -> String {
|
||||
if value.is_finite() {
|
||||
format!("{value}")
|
||||
} else {
|
||||
"null".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn json_object(fields: &[(&str, String)]) -> String {
|
||||
let body: Vec<String> = fields
|
||||
.iter()
|
||||
.map(|(key, value)| format!("{}:{value}", json_string(key)))
|
||||
.collect();
|
||||
format!("{{{}}}", body.join(","))
|
||||
}
|
||||
|
||||
fn json_summary(s: &Summary) -> String {
|
||||
json_object(&[
|
||||
("samples", s.samples.to_string()),
|
||||
("median_ns", s.median.as_nanos().to_string()),
|
||||
("min_ns", s.min.as_nanos().to_string()),
|
||||
("max_ns", s.max.as_nanos().to_string()),
|
||||
("p95_ns", s.p95.as_nanos().to_string()),
|
||||
("p99_ns", s.p99.as_nanos().to_string()),
|
||||
("iqr_ns", s.iqr.as_nanos().to_string()),
|
||||
("median_mips", json_f64(s.mips)),
|
||||
])
|
||||
}
|
||||
|
||||
fn json_document(
|
||||
info: &RunInfo,
|
||||
interpreter: &Summary,
|
||||
cold: &Summary,
|
||||
warm: &Summary,
|
||||
metrics: &DbtMetrics,
|
||||
) -> String {
|
||||
let string = |value: &String| json_string(value);
|
||||
json_object(&[
|
||||
("format_version", "1".to_owned()),
|
||||
("benchmark", json_string("dbt_bench")),
|
||||
("unix_time", json_option(info.unix_time, |t| t.to_string())),
|
||||
(
|
||||
"host",
|
||||
json_object(&[
|
||||
("cpu", json_option(info.cpu.as_ref(), string)),
|
||||
("os", json_string(info.os)),
|
||||
("os_version", json_option(info.os_version.as_ref(), string)),
|
||||
("arch", json_string(info.arch)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"source",
|
||||
json_object(&[
|
||||
("revision", json_option(info.revision.as_ref(), string)),
|
||||
("dirty", json_option(info.dirty, |d| d.to_string())),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"build",
|
||||
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
|
||||
),
|
||||
(
|
||||
"workload",
|
||||
json_object(&[
|
||||
("name", json_string("add_rax_chain")),
|
||||
("guest_instructions", INSTRUCTIONS.to_string()),
|
||||
("guest_code_bytes", info.guest_code_bytes.to_string()),
|
||||
("instruction_budget", BUDGET.to_string()),
|
||||
("warmup_rounds", info.warmup.to_string()),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"timings",
|
||||
json_object(&[
|
||||
("interpreter", json_summary(interpreter)),
|
||||
("cold_dbt", json_summary(cold)),
|
||||
("warm_dbt", json_summary(warm)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"cold_dbt_metrics",
|
||||
json_object(&[
|
||||
("blocks_compiled", metrics.blocks_compiled.to_string()),
|
||||
("cache_hits", metrics.cache_hits.to_string()),
|
||||
("cache_misses", metrics.cache_misses.to_string()),
|
||||
(
|
||||
"native_bytes_emitted",
|
||||
metrics.native_bytes_emitted.to_string(),
|
||||
),
|
||||
("dbt_dispatches", metrics.dbt_dispatches.to_string()),
|
||||
(
|
||||
"instructions_executed",
|
||||
metrics.instructions_executed.to_string(),
|
||||
),
|
||||
(
|
||||
"interpreter_fallbacks",
|
||||
metrics.interpreter_fallbacks.to_string(),
|
||||
),
|
||||
("service_calls", metrics.service_calls.to_string()),
|
||||
]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -190,14 +391,24 @@ fn main() {
|
||||
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
|
||||
);
|
||||
println!("Even sample counts use the midpoint of the two middle values for the median.");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
let interpreter = summarize(&mut interpreter);
|
||||
let cold = summarize(&mut cold);
|
||||
let warm = summarize(&mut warm);
|
||||
println!("{}", report_line("Interpreter", &interpreter));
|
||||
println!("{}", report_line("Cold DBT", &cold));
|
||||
println!("{}", report_line("Warm DBT", &warm));
|
||||
let metrics = cold_metrics.unwrap();
|
||||
println!(
|
||||
"Cold DBT compiled {} blocks and emitted {} native bytes in {} dispatches",
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
|
||||
if let Some(path) = std::env::var_os("XENORA_DBT_BENCH_JSON") {
|
||||
let info = run_info(code.len(), warmup_count);
|
||||
let document = json_document(&info, &interpreter, &cold, &warm, &metrics);
|
||||
std::fs::write(&path, document + "\n").expect("write XENORA_DBT_BENCH_JSON");
|
||||
println!("JSON results written to {}", path.to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -233,4 +444,140 @@ mod tests {
|
||||
let samples = [10, 20, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_strings_escape_quotes_backslashes_and_controls() {
|
||||
use super::json_string;
|
||||
|
||||
assert_eq!(json_string("plain"), r#""plain""#);
|
||||
assert_eq!(json_string(r#"a"b\c"#), r#""a\"b\\c""#);
|
||||
assert_eq!(json_string("l1\nl2\r\t"), r#""l1\nl2\r\t""#);
|
||||
assert_eq!(json_string("\u{1}\u{1f}"), r#""\u0001\u001f""#);
|
||||
// Non-ASCII text needs no escape in UTF-8 JSON.
|
||||
assert_eq!(json_string("Zażółć"), "\"Zażółć\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_values_and_non_finite_rates_are_null() {
|
||||
use super::{json_f64, json_option};
|
||||
|
||||
assert_eq!(json_option(None::<u64>, |v| v.to_string()), "null");
|
||||
assert_eq!(json_option(Some(7_u64), |v| v.to_string()), "7");
|
||||
assert_eq!(json_f64(f64::INFINITY), "null");
|
||||
assert_eq!(json_f64(f64::NAN), "null");
|
||||
assert_eq!(json_f64(12.5), "12.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_has_every_field_with_the_summary_values() {
|
||||
fn fixed_summary(median_us: u64) -> super::Summary {
|
||||
use super::Duration;
|
||||
super::Summary {
|
||||
samples: 3,
|
||||
median: Duration::from_micros(median_us),
|
||||
min: Duration::from_micros(10),
|
||||
max: Duration::from_micros(100),
|
||||
p95: Duration::from_nanos(92_000),
|
||||
p99: Duration::from_nanos(98_400),
|
||||
iqr: Duration::from_micros(45),
|
||||
mips: 500.25,
|
||||
}
|
||||
}
|
||||
|
||||
fn fixed_info() -> super::RunInfo {
|
||||
super::RunInfo {
|
||||
unix_time: Some(1_700_000_000),
|
||||
cpu: Some("Test \"CPU\"\\1".to_owned()),
|
||||
os: "macos",
|
||||
os_version: None,
|
||||
arch: "aarch64",
|
||||
revision: Some("0123abcd".to_owned()),
|
||||
dirty: Some(false),
|
||||
debug_assertions: false,
|
||||
guest_code_bytes: 40_011,
|
||||
warmup: 10,
|
||||
}
|
||||
}
|
||||
|
||||
use super::{DbtMetrics, INSTRUCTIONS, json_document};
|
||||
|
||||
let metrics = DbtMetrics {
|
||||
blocks_compiled: 626,
|
||||
cache_hits: 0,
|
||||
cache_misses: 626,
|
||||
native_bytes_emitted: 245_168,
|
||||
dbt_dispatches: 626,
|
||||
instructions_executed: 10_002,
|
||||
interpreter_fallbacks: 1,
|
||||
service_calls: 0,
|
||||
};
|
||||
let document = json_document(
|
||||
&fixed_info(),
|
||||
&fixed_summary(20),
|
||||
&fixed_summary(30),
|
||||
&fixed_summary(40),
|
||||
&metrics,
|
||||
);
|
||||
let summary = |median: &str| {
|
||||
format!(
|
||||
r#"{{"samples":3,"median_ns":{median},"min_ns":10000,"max_ns":100000,"p95_ns":92000,"p99_ns":98400,"iqr_ns":45000,"median_mips":500.25}}"#
|
||||
)
|
||||
};
|
||||
let expected = format!(
|
||||
concat!(
|
||||
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
|
||||
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
|
||||
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
|
||||
r#""build":{{"debug_assertions":false}},"#,
|
||||
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
|
||||
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
|
||||
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
|
||||
),
|
||||
INSTRUCTIONS,
|
||||
summary("20000"),
|
||||
summary("30000"),
|
||||
summary("40000"),
|
||||
);
|
||||
assert_eq!(document, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_report_keeps_its_format() {
|
||||
fn fixed_summary(median_us: u64) -> super::Summary {
|
||||
use super::Duration;
|
||||
super::Summary {
|
||||
samples: 3,
|
||||
median: Duration::from_micros(median_us),
|
||||
min: Duration::from_micros(10),
|
||||
max: Duration::from_micros(100),
|
||||
p95: Duration::from_nanos(92_000),
|
||||
p99: Duration::from_nanos(98_400),
|
||||
iqr: Duration::from_micros(45),
|
||||
mips: 500.25,
|
||||
}
|
||||
}
|
||||
|
||||
use super::report_line;
|
||||
|
||||
assert_eq!(
|
||||
report_line("Cold DBT", &fixed_summary(20)),
|
||||
"Cold DBT: 3 samples, median 20µs, min 10µs, max 100µs, p95 92µs, p99 98.4µs, IQR 45µs, median 500.25 MIPS"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_matches_the_percentile_helper() {
|
||||
use super::{Duration, INSTRUCTIONS, summarize};
|
||||
|
||||
let mut samples = [100, 10, 30, 20].map(Duration::from_micros);
|
||||
let s = summarize(&mut samples);
|
||||
assert_eq!(s.samples, 4);
|
||||
assert_eq!(s.median, Duration::from_micros(25));
|
||||
assert_eq!(s.min, Duration::from_micros(10));
|
||||
assert_eq!(s.max, Duration::from_micros(100));
|
||||
assert_eq!(s.p95, Duration::from_nanos(89_500));
|
||||
assert_eq!(s.p99, Duration::from_nanos(97_900));
|
||||
assert_eq!(s.iqr, Duration::from_micros(30));
|
||||
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
|
||||
}
|
||||
}
|
||||
+26
-446
@@ -11,39 +11,11 @@ use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::fmt;
|
||||
|
||||
/// Most callbacks one TLS directory may list.
|
||||
pub const MAX_TLS_CALLBACKS: usize = 64;
|
||||
|
||||
/// Bytes below the stack top that a callback is entered with: the return
|
||||
/// address and the 32-byte home space the Win64 convention gives every callee.
|
||||
const CALLBACK_FRAME: u64 = 40;
|
||||
|
||||
/// Errors arising during TLS setup or callback invocation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum TlsError {
|
||||
DirectoryOutOfBounds {
|
||||
rva: u32,
|
||||
},
|
||||
InvalidTemplateRange {
|
||||
start: u64,
|
||||
end: u64,
|
||||
},
|
||||
/// `AddressOfCallbacks` is not zero and not inside a section of the image.
|
||||
CallbackArrayOutOfBounds {
|
||||
address: u64,
|
||||
},
|
||||
/// The callback array leaves its section before a null entry.
|
||||
CallbackArrayUnterminated {
|
||||
address: u64,
|
||||
},
|
||||
/// The callback array lists more than [`MAX_TLS_CALLBACKS`] entries.
|
||||
TooManyCallbacks {
|
||||
limit: usize,
|
||||
},
|
||||
/// The stack cannot hold a callback's entry frame or is not 16-byte aligned.
|
||||
InvalidCallbackStack {
|
||||
stack_top: u64,
|
||||
},
|
||||
DirectoryOutOfBounds { rva: u32 },
|
||||
InvalidTemplateRange { start: u64, end: u64 },
|
||||
CallbackExecutionFault(ExitReason),
|
||||
Memory(MemoryError),
|
||||
}
|
||||
@@ -60,27 +32,6 @@ impl fmt::Display for TlsError {
|
||||
"invalid TLS template range: 0x{start:016x}..0x{end:016x}"
|
||||
)
|
||||
}
|
||||
Self::CallbackArrayOutOfBounds { address } => {
|
||||
write!(
|
||||
f,
|
||||
"TLS callback array at 0x{address:016x} is outside the image"
|
||||
)
|
||||
}
|
||||
Self::CallbackArrayUnterminated { address } => {
|
||||
write!(
|
||||
f,
|
||||
"TLS callback array at 0x{address:016x} has no null entry in its section"
|
||||
)
|
||||
}
|
||||
Self::TooManyCallbacks { limit } => {
|
||||
write!(f, "TLS callback array lists more than {limit} callbacks")
|
||||
}
|
||||
Self::InvalidCallbackStack { stack_top } => {
|
||||
write!(
|
||||
f,
|
||||
"stack top 0x{stack_top:016x} cannot hold an aligned TLS callback frame"
|
||||
)
|
||||
}
|
||||
Self::CallbackExecutionFault(e) => {
|
||||
write!(f, "fault during TLS callback execution: {e}")
|
||||
}
|
||||
@@ -127,7 +78,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
) as usize;
|
||||
|
||||
// TLS directory is directory index 9 (offset 112 + 9 * 8 = 184 in Optional Header)
|
||||
if size_of_opt < 192 || bytes.len() < opt_offset + 192 {
|
||||
if size_of_opt < 192 || bytes.len() < opt_offset + 188 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -163,7 +114,24 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
u32::from_le_bytes(bytes[tls_off + 32..tls_off + 36].try_into().unwrap());
|
||||
let characteristics = u32::from_le_bytes(bytes[tls_off + 36..tls_off + 40].try_into().unwrap());
|
||||
|
||||
let callbacks = read_callbacks(bytes, pe, callbacks_address)?;
|
||||
let mut callbacks = Vec::new();
|
||||
if callbacks_address >= pe.image_base {
|
||||
let cb_rva = (callbacks_address - pe.image_base) as u32;
|
||||
if let Some(cb_off) = pe.rva_to_file_offset(cb_rva) {
|
||||
let mut curr = cb_off;
|
||||
while curr + 8 <= bytes.len() {
|
||||
let target = u64::from_le_bytes(bytes[curr..curr + 8].try_into().unwrap());
|
||||
if target == 0 {
|
||||
break;
|
||||
}
|
||||
callbacks.push(target);
|
||||
curr += 8;
|
||||
if callbacks.len() >= 64 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(TlsDirectory {
|
||||
raw_data_start_va,
|
||||
@@ -176,74 +144,9 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
}))
|
||||
}
|
||||
|
||||
/// Read the null-terminated callback array that `address` names.
|
||||
///
|
||||
/// A null `address` means the image has no callbacks. Any other value must be a
|
||||
/// virtual address inside one section, and the array must reach its null entry
|
||||
/// inside that section. Bytes past the section's file data, up to its virtual
|
||||
/// size, are zero in the loaded image and are read as zero here.
|
||||
fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>, TlsError> {
|
||||
if address == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (section, start) = address
|
||||
.checked_sub(pe.image_base)
|
||||
.and_then(|rva| u32::try_from(rva).ok())
|
||||
.and_then(|rva| {
|
||||
pe.sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
let extent = section.virtual_size.max(section.raw_data_size);
|
||||
(offset < extent).then_some((section, u64::from(offset)))
|
||||
})
|
||||
})
|
||||
.ok_or(TlsError::CallbackArrayOutOfBounds { address })?;
|
||||
let extent = u64::from(section.virtual_size.max(section.raw_data_size));
|
||||
let byte_at = |offset: u64| -> Option<u8> {
|
||||
if offset >= extent {
|
||||
None
|
||||
} else if offset >= u64::from(section.raw_data_size) {
|
||||
Some(0)
|
||||
} else {
|
||||
let file = u64::from(section.raw_data_ptr) + offset;
|
||||
bytes.get(usize::try_from(file).ok()?).copied()
|
||||
}
|
||||
};
|
||||
|
||||
let mut callbacks = Vec::new();
|
||||
let mut offset = start;
|
||||
loop {
|
||||
let mut entry = [0u8; 8];
|
||||
for byte in &mut entry {
|
||||
*byte = byte_at(offset).ok_or(TlsError::CallbackArrayUnterminated { address })?;
|
||||
offset += 1;
|
||||
}
|
||||
let target = u64::from_le_bytes(entry);
|
||||
if target == 0 {
|
||||
return Ok(callbacks);
|
||||
}
|
||||
if callbacks.len() == MAX_TLS_CALLBACKS {
|
||||
return Err(TlsError::TooManyCallbacks {
|
||||
limit: MAX_TLS_CALLBACKS,
|
||||
});
|
||||
}
|
||||
callbacks.push(target);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
|
||||
const TLS_ARRAY_SIZE: usize = 0x1000;
|
||||
|
||||
/// Set up TLS runtime state in guest memory:
|
||||
/// 1. Assign TLS index 0 at `index_address`.
|
||||
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
|
||||
/// 3. Map the thread's data block one page above it, initialized from the
|
||||
/// template and zero fill, and store its address in the array slot of the
|
||||
/// index.
|
||||
///
|
||||
/// `thread_tls_base` is the value the thread environment block holds as its
|
||||
/// TLS pointer. Compiled code loads that pointer, indexes it by the module's
|
||||
/// TLS index to find the data block, and then adds a variable's offset, so the
|
||||
/// array and the data are separate regions.
|
||||
/// 1. Assign TLS index (e.g. 0) at `index_address`.
|
||||
/// 2. Allocate and initialize per-thread TLS storage from the template.
|
||||
pub fn setup_tls(
|
||||
tls: &TlsDirectory,
|
||||
loaded_base: u64,
|
||||
@@ -284,25 +187,15 @@ pub fn setup_tls(
|
||||
memory.read_bytes(actual_start, &mut template_data)?;
|
||||
}
|
||||
|
||||
// Allocate the pointer array and the per-thread TLS block.
|
||||
let block_base = thread_tls_base
|
||||
.checked_add(TLS_ARRAY_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
// Allocate per-thread TLS block
|
||||
let page_size = 4096;
|
||||
let map_size = (total_size + page_size - 1) & !(page_size - 1);
|
||||
memory.map_region(
|
||||
thread_tls_base,
|
||||
TLS_ARRAY_SIZE,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
)?;
|
||||
memory.map_region_with_data(
|
||||
block_base,
|
||||
thread_tls_base,
|
||||
map_size,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&template_data,
|
||||
)?;
|
||||
// Slot 0 belongs to the index assigned above.
|
||||
memory.write_u64(thread_tls_base, block_base)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -313,11 +206,6 @@ pub fn setup_tls(
|
||||
/// - RCX = DllHandle (loaded_base)
|
||||
/// - RDX = Reason (DLL_PROCESS_ATTACH = 1)
|
||||
/// - R8 = Reserved (0)
|
||||
///
|
||||
/// Each callback is entered as after a CALL from a 16-byte aligned stack: RSP
|
||||
/// is `stack_top - 40`, holding the return address below 32 bytes of home
|
||||
/// space. A `stack_top` that is not 16-byte aligned or cannot hold that frame
|
||||
/// is rejected before any callback runs.
|
||||
pub fn execute_tls_callbacks(
|
||||
callbacks: &[u64],
|
||||
loaded_base: u64,
|
||||
@@ -327,12 +215,6 @@ pub fn execute_tls_callbacks(
|
||||
memory: &mut GuestMemory,
|
||||
dbt: &mut DbtEngine,
|
||||
) -> Result<usize, TlsError> {
|
||||
if callbacks.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
if stack_top < CALLBACK_FRAME || !stack_top.is_multiple_of(16) {
|
||||
return Err(TlsError::InvalidCallbackStack { stack_top });
|
||||
}
|
||||
let delta = (loaded_base as i128) - (preferred_base as i128);
|
||||
let mut executed_count = 0;
|
||||
|
||||
@@ -342,7 +224,7 @@ pub fn execute_tls_callbacks(
|
||||
// Reset CPU state for callback execution adhering to Win64 ABI
|
||||
cpu.rip = actual_cb_va;
|
||||
// Stack pointer aligned with 32-byte shadow space + return address
|
||||
let rsp = stack_top - CALLBACK_FRAME;
|
||||
let rsp = stack_top - 40;
|
||||
cpu.set(Register::Rsp, rsp);
|
||||
// Write synthetic magic return address (0xFFFF_FFFF_FFFF_0000) into [RSP]
|
||||
let magic_ret = 0xFFFF_FFFF_FFFF_0000u64;
|
||||
@@ -379,305 +261,3 @@ pub fn execute_tls_callbacks(
|
||||
|
||||
Ok(executed_count)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! Expectations come from Microsoft's public PE Format page (the TLS
|
||||
//! directory: `AddressOfCallbacks` is a virtual address of a null-terminated
|
||||
//! array, and a callback is `void cb(PVOID DllHandle, DWORD Reason, PVOID
|
||||
//! Reserved)`) and its x64 calling convention page (the stack is 16-byte
|
||||
//! aligned before a call, the caller provides 32 bytes of home space, and
|
||||
//! the first three integer arguments are in RCX, RDX and R8). The headers
|
||||
//! and code bytes below are original. Nothing here ran on Windows.
|
||||
|
||||
use super::*;
|
||||
use crate::pe::PeSection;
|
||||
|
||||
const IMAGE_BASE: u64 = 0x1_4000_0000;
|
||||
const SECTION_RVA: u32 = 0x1000;
|
||||
const SECTION_FILE: usize = 0x400;
|
||||
const SECTION_SIZE: u32 = 0x400;
|
||||
/// Offset of the optional header: `e_lfanew` (0x80), signature, COFF header.
|
||||
const OPTIONAL_HEADER: usize = 0x80 + 24;
|
||||
|
||||
fn parsed(virtual_size: u32) -> ParsedPe {
|
||||
ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: IMAGE_BASE,
|
||||
section_alignment: 0x1000,
|
||||
file_alignment: 0x200,
|
||||
size_of_image: 0x3000,
|
||||
size_of_headers: 0x400,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".rdata".into(),
|
||||
virtual_address: SECTION_RVA,
|
||||
virtual_size,
|
||||
raw_data_ptr: SECTION_FILE as u32,
|
||||
raw_data_size: SECTION_SIZE,
|
||||
characteristics: crate::pe::IMAGE_SCN_MEM_READ,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// A file with one section holding a TLS directory at its start and the
|
||||
/// callback `entries` at `array_rva`. The directory names `callbacks_address`.
|
||||
/// Every byte after the section's file data is 0xCC.
|
||||
fn file(callbacks_address: u64, array_rva: u32, entries: &[u64]) -> Vec<u8> {
|
||||
let section_end = SECTION_FILE + SECTION_SIZE as usize;
|
||||
let mut bytes = vec![0u8; section_end];
|
||||
bytes.resize(section_end + 0x200, 0xCC);
|
||||
bytes[0x3C..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
// SizeOfOptionalHeader: a PE32+ optional header with 16 data directories.
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
// Data directory 9 (TLS): RVA and size.
|
||||
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
|
||||
bytes[entry..entry + 4].copy_from_slice(&SECTION_RVA.to_le_bytes());
|
||||
bytes[entry + 4..entry + 8].copy_from_slice(&40u32.to_le_bytes());
|
||||
// IMAGE_TLS_DIRECTORY64.AddressOfCallBacks is its fourth 8-byte field.
|
||||
bytes[SECTION_FILE + 24..SECTION_FILE + 32]
|
||||
.copy_from_slice(&callbacks_address.to_le_bytes());
|
||||
let mut at = SECTION_FILE + (array_rva - SECTION_RVA) as usize;
|
||||
for entry in entries {
|
||||
bytes[at..at + 8].copy_from_slice(&entry.to_le_bytes());
|
||||
at += 8;
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
fn callbacks_of(bytes: &[u8], pe: &ParsedPe) -> Result<Vec<u64>, TlsError> {
|
||||
parse_tls_directory(bytes, pe).map(|tls| tls.expect("a TLS directory").callbacks)
|
||||
}
|
||||
|
||||
const ARRAY_RVA: u32 = 0x1100;
|
||||
const ARRAY: u64 = IMAGE_BASE + ARRAY_RVA as u64;
|
||||
const FIRST: u64 = IMAGE_BASE + 0x2000;
|
||||
const SECOND: u64 = IMAGE_BASE + 0x2010;
|
||||
|
||||
#[test]
|
||||
fn callbacks_are_read_in_order_up_to_the_null_entry() {
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, SECOND, 0, IMAGE_BASE + 0x2020]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Ok(vec![FIRST, SECOND])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_callbacks_address_means_no_callbacks() {
|
||||
let bytes = file(0, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(callbacks_of(&bytes, &parsed(SECTION_SIZE)), Ok(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_outside_the_image_is_rejected() {
|
||||
for address in [8, IMAGE_BASE - 8, IMAGE_BASE + 0x800, IMAGE_BASE + 0x5000] {
|
||||
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayOutOfBounds { address }),
|
||||
"{address:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_address_is_not_truncated_to_32_bits() {
|
||||
// The low 32 bits of the offset name the real array.
|
||||
let address = ARRAY + (1 << 32);
|
||||
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayOutOfBounds { address })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_must_end_inside_its_section() {
|
||||
// Two entries fill the last 16 bytes of the section; the file goes on.
|
||||
let rva = SECTION_RVA + SECTION_SIZE - 16;
|
||||
let address = IMAGE_BASE + u64::from(rva);
|
||||
let bytes = file(address, rva, &[FIRST, SECOND]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayUnterminated { address })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_fill_after_the_section_file_data_ends_the_array() {
|
||||
// The section is larger in memory than in the file, so the bytes after
|
||||
// its file data are zero when loaded, whatever follows in the file.
|
||||
let rva = SECTION_RVA + SECTION_SIZE - 16;
|
||||
let address = IMAGE_BASE + u64::from(rva);
|
||||
let bytes = file(address, rva, &[FIRST, SECOND]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE + 0x100)),
|
||||
Ok(vec![FIRST, SECOND])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_over_the_limit_is_rejected() {
|
||||
let entries: Vec<u64> = (0..65).map(|index| FIRST + index * 16).collect();
|
||||
let mut at_limit = entries[..MAX_TLS_CALLBACKS].to_vec();
|
||||
at_limit.push(0);
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &at_limit);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Ok(entries[..64].to_vec())
|
||||
);
|
||||
|
||||
let mut over = entries.clone();
|
||||
over.push(0);
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &over);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::TooManyCallbacks { limit: 64 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_cut_inside_the_tls_data_directory_has_no_tls_directory() {
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, 0]);
|
||||
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
|
||||
for length in entry..entry + 8 {
|
||||
let directory = parse_tls_directory(&bytes[..length], &parsed(SECTION_SIZE));
|
||||
assert!(matches!(directory, Ok(None)), "length {length:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
const CODE: u64 = 0x40_0000;
|
||||
const STACK_TOP: u64 = 0x80_0000;
|
||||
const SENTINEL: u64 = 0xFFFF_FFFF_FFFF_0000;
|
||||
|
||||
/// Code at `CODE`, a 4 KiB stack below `STACK_TOP` and a fresh translator.
|
||||
fn guest(code: &[u8]) -> (CpuState, GuestMemory, DbtEngine) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(CODE, 0x1000, MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK_TOP - 0x1000, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
(
|
||||
CpuState::new(0, 0),
|
||||
memory,
|
||||
DbtEngine::new(64 * 1024).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Two callbacks 16 bytes apart. Each shifts RAX left by four bits and sets
|
||||
/// its own number in the low bits, so RAX records the order they ran in.
|
||||
const TAGGING: [u8; 25] = [
|
||||
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
|
||||
0x48, 0x83, 0xC8, 0x01, // or rax, 1
|
||||
0xC3, // ret
|
||||
0, 0, 0, 0, 0, 0, 0, // padding
|
||||
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
|
||||
0x48, 0x83, 0xC8, 0x02, // or rax, 2
|
||||
0xC3, // ret
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn a_callback_is_entered_with_the_win64_arguments_and_frame() {
|
||||
let code = [0x48, 0x89, 0xE0, 0xC3]; // mov rax, rsp; ret
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&code);
|
||||
// Loaded 64 KiB above the preferred base: the listed address is rebased.
|
||||
let loaded = IMAGE_BASE + 0x1_0000;
|
||||
let listed = [CODE - 0x1_0000];
|
||||
let ran = execute_tls_callbacks(
|
||||
&listed,
|
||||
loaded,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(ran, Ok(1));
|
||||
let entry_rsp = cpu.get(Register::Rax);
|
||||
assert_eq!(entry_rsp, STACK_TOP - 40);
|
||||
// A callee is entered 8 bytes off 16-byte alignment, as after a CALL.
|
||||
assert_eq!(entry_rsp % 16, 8);
|
||||
assert_eq!(memory.read_u64(entry_rsp), Ok(SENTINEL));
|
||||
assert_eq!(cpu.get(Register::Rcx), loaded);
|
||||
assert_eq!(cpu.get(Register::Rdx), 1); // DLL_PROCESS_ATTACH
|
||||
assert_eq!(cpu.get(Register::R8), 0);
|
||||
// RET popped the return address and nothing else.
|
||||
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
|
||||
assert_eq!(cpu.rip, SENTINEL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callbacks_run_in_array_order() {
|
||||
for (order, recorded) in [([CODE, CODE + 16], 0x12), ([CODE + 16, CODE], 0x21)] {
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
|
||||
let ran = execute_tls_callbacks(
|
||||
&order,
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(ran, Ok(2));
|
||||
assert_eq!(cpu.get(Register::Rax), recorded);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_over_the_instruction_budget_stops_the_sequence() {
|
||||
let mut code = TAGGING.to_vec();
|
||||
code.resize(32, 0);
|
||||
code.extend([0xEB, 0xFE]); // jmp to itself
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&code);
|
||||
let ran = execute_tls_callbacks(
|
||||
&[CODE, CODE + 32, CODE + 16],
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(
|
||||
ran,
|
||||
Err(TlsError::CallbackExecutionFault(
|
||||
ExitReason::StepLimitExceeded
|
||||
))
|
||||
);
|
||||
// The first callback ran; the one after the endless one did not.
|
||||
assert_eq!(cpu.get(Register::Rax), 0x1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_callback_stack_is_rejected_before_anything_runs() {
|
||||
for stack_top in [0, 32, STACK_TOP - 8, STACK_TOP - 1] {
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
|
||||
let ran = execute_tls_callbacks(
|
||||
&[CODE],
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
stack_top,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(
|
||||
ran,
|
||||
Err(TlsError::InvalidCallbackStack { stack_top }),
|
||||
"{stack_top:#x}"
|
||||
);
|
||||
assert_eq!(cpu, CpuState::new(0, 0));
|
||||
assert_eq!(memory.read_u64(STACK_TOP - 48), Ok(0));
|
||||
// No callback, no frame: the stack is not looked at.
|
||||
let none = execute_tls_callbacks(&[], 0, 0, stack_top, &mut cpu, &mut memory, &mut dbt);
|
||||
assert_eq!(none, Ok(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Thread-local storage layout as compiled code reads it (#76).
|
||||
//!
|
||||
//! Microsoft's public PE Format page ("The .tls Section") describes the
|
||||
//! access: load the address of the thread's TLS array from the thread
|
||||
//! environment block, load the module's TLS index from the address the TLS
|
||||
//! directory names, use the index times the pointer size as an offset into
|
||||
//! the array to get the address of the module's data block, then add the
|
||||
//! variable's offset in the template. The block starts as a copy of the
|
||||
//! template followed by `SizeOfZeroFill` zero bytes.
|
||||
//!
|
||||
//! The startup harness stores the `thread_tls_base` it passes to `setup_tls`
|
||||
//! in the TEB's TLS pointer field, so these tests start from that value and
|
||||
//! follow the same steps through guest memory. The directory and template are
|
||||
//! original. Nothing here ran on Windows.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P, TlsDirectory, setup_tls};
|
||||
|
||||
const IMAGE: u64 = 0x1_4000_0000;
|
||||
const TEMPLATE: u64 = IMAGE + 0x3000;
|
||||
const INDEX: u64 = IMAGE + 0x4000;
|
||||
const THREAD_TLS: u64 = 0x3_0000_0000;
|
||||
/// Read as a pointer, the first eight bytes are the template's own address, so
|
||||
/// a layout that takes the data for the array still finds readable memory.
|
||||
const TEMPLATE_BYTES: [u8; 20] = [
|
||||
0x00, 0x30, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
|
||||
0xA1, 0xB2, 0xC3, 0xD4,
|
||||
];
|
||||
|
||||
fn directory(template_len: u64, zero_fill: u32) -> TlsDirectory {
|
||||
TlsDirectory {
|
||||
raw_data_start_va: TEMPLATE,
|
||||
raw_data_end_va: TEMPLATE + template_len,
|
||||
index_address: INDEX,
|
||||
size_of_zero_fill: zero_fill,
|
||||
..TlsDirectory::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// An image with the template in read-only data and a writable index that
|
||||
/// does not start at zero.
|
||||
fn image(base: u64) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
TEMPLATE - IMAGE + base,
|
||||
0x1000,
|
||||
P::READ_ONLY,
|
||||
&TEMPLATE_BYTES,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(INDEX - IMAGE + base, 0x1000, P::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
/// The address of the module's data block, found the way compiled code does.
|
||||
fn block_address(memory: &GuestMemory, teb_tls_pointer: u64, index_address: u64) -> u64 {
|
||||
let index = u64::from(memory.read_u32(index_address).unwrap());
|
||||
memory.read_u64(teb_tls_pointer + index * 8).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tls_array_slot_leads_to_a_copy_of_the_template() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
|
||||
assert_eq!(memory.read_u32(INDEX), Ok(0));
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
assert_ne!(block, THREAD_TLS, "the array is not the data block");
|
||||
assert_ne!(block, TEMPLATE, "the block is the thread's own copy");
|
||||
let mut data = [0xEEu8; 32];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data[..20], TEMPLATE_BYTES);
|
||||
assert_eq!(data[20..], [0u8; 12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_thread_block_is_writable_and_separate_from_the_template() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
|
||||
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(memory.read_u64(block + 8), Ok(0x0102_0304_0506_0708));
|
||||
// The image's template is the initial value for later threads.
|
||||
let mut template = [0u8; 20];
|
||||
memory.read_bytes(TEMPLATE, &mut template).unwrap();
|
||||
assert_eq!(template, TEMPLATE_BYTES);
|
||||
// The array slot still names the block after the block is written.
|
||||
assert_eq!(block_address(&memory, THREAD_TLS, INDEX), block);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rebased_image_uses_its_loaded_addresses() {
|
||||
let loaded = IMAGE + 0x20_0000;
|
||||
let mut memory = image(loaded);
|
||||
setup_tls(&directory(20, 0), loaded, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
|
||||
let index_address = INDEX - IMAGE + loaded;
|
||||
assert_eq!(memory.read_u32(index_address), Ok(0));
|
||||
let block = block_address(&memory, THREAD_TLS, index_address);
|
||||
let mut data = [0u8; 20];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data, TEMPLATE_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_fill_only_directory_gets_a_zeroed_block() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(0, 24), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
let mut data = [0xEEu8; 24];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data, [0u8; 24]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inverted_template_range_is_rejected_before_anything_is_mapped() {
|
||||
let mut memory = image(IMAGE);
|
||||
let mut inverted = directory(20, 0);
|
||||
inverted.raw_data_end_va = TEMPLATE - 1;
|
||||
assert!(setup_tls(&inverted, IMAGE, IMAGE, &mut memory, THREAD_TLS).is_err());
|
||||
assert_eq!(
|
||||
memory.read_u64(THREAD_TLS),
|
||||
Err(MemoryError::UnmappedAddress(THREAD_TLS))
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user