Merge task/392-program-arguments into task/419-gate-a2

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
This commit is contained in:
zachdoxsee committed 2026-11-25 02:16:20 +01:00
commit a9abc36eef
8 files changed
+669 -8

No files matched your search

+2
View File
@@ -122,6 +122,8 @@ remains unsupported.
- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings.
- Added command-line arguments for a hosted C program (#392, part of Gate A2): the C runtime services `__p___argc`, `__p___argv`, `__p__environ`, `_configure_narrow_argv` and `_initialize_narrow_environment`, and a host method, `ServicesState::set_program_arguments`, that supplies the program's `argv`. A program built with the mingw-w64 runtime gets `argc`, `argv` and `envp` for `main` through these five, and the loader refused it before its entry point because they did not resolve. After configuration the guest finds the host's arguments in `__argc` and `__argv`, each NUL-terminated, with a null pointer after the last; with no host input it gets one empty argument, as ISO C specifies. The host method refuses a NUL byte, more than 32,767 bytes in all, and a call after the guest has built its table. The three variables are documented and the two initialization functions are not, so their behaviour is Xenora's: no code page, no wildcard expansion, and an empty environment table. All five are `partial`. Four tests in `runtime_services.rs` call the services from guest code and compare what the guest sees with what the test supplied. Not compared with Windows; awaiting independent review.
- Added bounded guest CRT long-integer parsing for byte and wide strings.
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
+45
View File
@@ -132,6 +132,51 @@ service kernel32.dll SetLastError(code: u32) -> void
ref errhandlingapi.h SetLastError
test last_error_is_set_by_failures_and_by_the_guest
# What a hosted C program's startup code hands to `main`. The three pointer
# functions and the two initialization functions are listed by Microsoft only
# by name; crates/loader/src/services/crt_arguments.rs says what is documented,
# inferred and Xenora's choice.
service ucrtbase.dll __p___argc() -> ptr
handler argc_pointer
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails stops the guest when the variable cannot be allocated
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
test program_arguments_reach_the_guest_as_argc_and_argv
service ucrtbase.dll __p___argv() -> ptr
handler argv_pointer
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails stops the guest when the variable cannot be allocated
ref Microsoft Learn, C runtime library reference, __argc, __argv, __wargv
test program_arguments_reach_the_guest_as_argc_and_argv
service ucrtbase.dll __p__environ() -> ptr
handler environ_pointer
status partial
alias api-ms-win-crt-environment-l1-1-0.dll
fails stops the guest when the variable cannot be allocated
ref Microsoft Learn, C runtime library reference, _environ, _wenviron
test the_environment_table_is_empty_and_ends_with_a_null_pointer
service ucrtbase.dll _configure_narrow_argv(mode: i32) -> i32
handler configure_narrow_argv
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated
ref corecrt_startup.h _configure_narrow_argv
test program_arguments_reach_the_guest_as_argc_and_argv
service ucrtbase.dll _initialize_narrow_environment() -> i32
handler initialize_narrow_environment
status partial
alias api-ms-win-crt-runtime-l1-1-0.dll
fails stops the guest when the table cannot be allocated
ref corecrt_startup.h _initialize_narrow_environment
test the_environment_table_is_empty_and_ends_with_a_null_pointer
service kernel32.dll VirtualAlloc(address: ptr, size: u64, kind: u32, protect: u32) -> ptr
handler virtual_alloc
status partial
+92 -1
View File
@@ -8,7 +8,7 @@ use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};
use crate::services::{ServicesState, handlers};
use std::sync::Arc;
pub static SERVICES: [ServiceMetadata; 32] = [
pub static SERVICES: [ServiceMetadata; 37] = [
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetProcessPriorityBoost",
@@ -163,6 +163,61 @@ pub static SERVICES: [ServiceMetadata; 32] = [
reference: "errhandlingapi.h SetLastError",
tests: &["last_error_is_set_by_failures_and_by_the_guest"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__p___argc",
parameters: &[],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "stops the guest when the variable cannot be allocated",
reference: "Microsoft Learn, C runtime library reference, __argc, __argv, __wargv",
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__p___argv",
parameters: &[],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "stops the guest when the variable cannot be allocated",
reference: "Microsoft Learn, C runtime library reference, __argc, __argv, __wargv",
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "__p__environ",
parameters: &[],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-environment-l1-1-0.dll"],
failure: "stops the guest when the variable cannot be allocated",
reference: "Microsoft Learn, C runtime library reference, _environ, _wenviron",
tests: &["the_environment_table_is_empty_and_ends_with_a_null_pointer"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "_configure_narrow_argv",
parameters: &[Parameter { name: "mode", kind: "i32" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated",
reference: "corecrt_startup.h _configure_narrow_argv",
tests: &["program_arguments_reach_the_guest_as_argc_and_argv"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "_initialize_narrow_environment",
parameters: &[],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"],
failure: "stops the guest when the table cannot be allocated",
reference: "corecrt_startup.h _initialize_narrow_environment",
tests: &["the_environment_table_is_empty_and_ends_with_a_null_pointer"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "VirtualAlloc",
@@ -478,6 +533,42 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
Ok(0)
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__p___argc", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::argc_pointer(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__p___argv", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::argv_pointer(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "__p__environ", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: u64 = handlers::environ_pointer(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "_configure_narrow_argv", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.i32(0)?;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::configure_narrow_argv(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "_initialize_narrow_environment", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
let result: i32 = handlers::initialize_narrow_environment(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "VirtualAlloc", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
+51
View File
@@ -10,6 +10,7 @@
//! - Xbox physical memory: `XMemAlloc`, `XMemFree`
mod crt;
mod crt_arguments;
mod crt_callbacks;
mod crt_startup;
mod events;
@@ -26,6 +27,7 @@ pub(crate) mod threads;
mod winsock;
use crate::runtime::HResult;
pub use crt_arguments::{MAX_PROGRAM_ARGUMENT_BYTES, ProgramArgumentsError};
use crate::cpu::ExitReason;
use crate::imports::{ImportRegistry, ServiceStatus};
@@ -195,6 +197,7 @@ pub struct ServicesState {
pub guest_profile: sysinfo::GuestSystemProfile,
objects: Mutex<ObjectState>,
last_errors: Mutex<BTreeMap<u64, u32>>,
crt_arguments: Mutex<crt_arguments::CrtArguments>,
synch: Mutex<synch::Synch>,
pub(crate) threads: Mutex<threads::ThreadTable>,
pub(crate) hooks: Arc<threads::SchedulerHooks>,
@@ -224,6 +227,7 @@ impl ServicesState {
guest_profile: sysinfo::GuestSystemProfile::default(),
objects: Mutex::new(ObjectState::default()),
last_errors: Mutex::default(),
crt_arguments: Mutex::default(),
synch: Mutex::default(),
threads: Mutex::default(),
hooks: Arc::default(),
@@ -240,6 +244,21 @@ impl ServicesState {
graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())),
}
}
/// Give a hosted C program the arguments its `main` receives in `argv`,
/// program name first. Call it before running the guest: the C runtime's
/// startup code builds `argv` once, and a call after that is refused.
///
/// The strings reach the guest as their bytes; no code page is applied.
/// A host that never calls this gives the program one argument, the empty
/// string. An empty slice gives it none.
pub fn set_program_arguments(&self, arguments: &[&str]) -> Result<(), ProgramArgumentsError> {
self.crt_arguments().supply(arguments)
}
fn crt_arguments(&self) -> std::sync::MutexGuard<'_, crt_arguments::CrtArguments> {
self.crt_arguments.lock().expect("program arguments")
}
fn uptime_millis(&self) -> u64 {
let ticks = self
.clock
@@ -899,6 +918,38 @@ pub(crate) mod handlers {
Ok(())
}
// What a hosted C program's startup code hands to `main` (#392).
// `crt_arguments.rs` says what is documented, inferred and Xenora's choice.
pub fn argc_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
let mut arguments = context.state.crt_arguments();
arguments.address(context.memory, crt_arguments::Variable::Argc)
}
pub fn argv_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
let mut arguments = context.state.crt_arguments();
arguments.address(context.memory, crt_arguments::Variable::Argv)
}
pub fn environ_pointer(context: &mut ServiceContext<'_>) -> Outcome<u64> {
let mut arguments = context.state.crt_arguments();
arguments.address(context.memory, crt_arguments::Variable::Environ)
}
pub fn configure_narrow_argv(context: &mut ServiceContext<'_>, mode: i32) -> Outcome<i32> {
context
.state
.crt_arguments()
.configure(context.memory, mode)
}
pub fn initialize_narrow_environment(context: &mut ServiceContext<'_>) -> Outcome<i32> {
context
.state
.crt_arguments()
.initialize_environment(context.memory)
}
pub fn virtual_alloc(
context: &mut ServiceContext<'_>,
requested: u64,
+182
View File
@@ -0,0 +1,182 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The arguments and environment a hosted C program's startup code hands to
//! `main`.
//!
//! Documented: the global variables `__argc` (the argument count), `__argv` (a
//! pointer to the array of argument strings) and `_environ` (a pointer to the
//! array of environment strings), and ISO C's rule that a null pointer follows
//! the last argument.
//!
//! Inferred: that `__p___argc`, `__p___argv` and `__p__environ` return the
//! address of those variables, as the documented `__p__fmode` does for
//! `_fmode`. Microsoft lists all five functions here only by name.
//!
//! Xenora's choice, because nothing public describes it: what
//! `_configure_narrow_argv` and `_initialize_narrow_environment` do. The
//! arguments come from the host, as bytes with no code page; wildcards are not
//! expanded; and the environment table is empty.
use crate::cpu::ExitReason;
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
use std::fmt;
const EINVAL: i32 = 22;
/// `_crt_argv_no_arguments`, `_crt_argv_unexpanded_arguments` and
/// `_crt_argv_expanded_arguments` (corecrt_startup.h).
const NO_ARGUMENTS: i32 = 0;
const UNEXPANDED_ARGUMENTS: i32 = 1;
const EXPANDED_ARGUMENTS: i32 = 2;
/// Windows limits a command line to 32,767 characters including its
/// terminator (`CreateProcess`). The same bound is applied here to the
/// arguments with their terminators.
pub const MAX_PROGRAM_ARGUMENT_BYTES: usize = 32_767;
/// Why [`super::ServicesState::set_program_arguments`] refused its input.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProgramArgumentsError {
/// An argument holds a NUL byte, which would end it early in the guest.
ContainsNul,
/// The arguments and their terminators exceed
/// [`MAX_PROGRAM_ARGUMENT_BYTES`].
TooLong,
/// The guest has already built `__argv`; it would not see a change.
AlreadyConfigured,
}
impl fmt::Display for ProgramArgumentsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::ContainsNul => "a program argument contains a NUL byte",
Self::TooLong => "the program arguments exceed 32,767 bytes",
Self::AlreadyConfigured => "the guest has already configured its arguments",
})
}
}
impl std::error::Error for ProgramArgumentsError {}
/// Which of the three guest variables a `__p_` function points at. The value
/// is the variable's offset in their shared block.
#[derive(Clone, Copy)]
pub(super) enum Variable {
Argc = 0,
Argv = 8,
Environ = 16,
}
#[derive(Default)]
pub(super) struct CrtArguments {
/// What the host supplied, program name first.
supplied: Option<Vec<Vec<u8>>>,
/// Guest address of the block holding `__argc`, `__argv` and `_environ`.
variables: Option<u64>,
configured: bool,
environment_initialized: bool,
}
fn fault(error: MemoryError) -> ExitReason {
ExitReason::MemoryFault(error)
}
impl CrtArguments {
pub(super) fn supply(&mut self, arguments: &[&str]) -> Result<(), ProgramArgumentsError> {
if self.configured {
return Err(ProgramArgumentsError::AlreadyConfigured);
}
if arguments.iter().any(|argument| argument.contains('\0')) {
return Err(ProgramArgumentsError::ContainsNul);
}
let bytes: usize = arguments.iter().map(|argument| argument.len() + 1).sum();
if bytes > MAX_PROGRAM_ARGUMENT_BYTES {
return Err(ProgramArgumentsError::TooLong);
}
self.supplied = Some(
arguments
.iter()
.map(|argument| argument.as_bytes().to_vec())
.collect(),
);
Ok(())
}
/// Guest address of one of the three variables. They are allocated
/// together from the process heap on first use, as zeros: no arguments,
/// and null `__argv` and `_environ`.
pub(super) fn address(
&mut self,
memory: &mut GuestMemory,
variable: Variable,
) -> Result<u64, ExitReason> {
let base = match self.variables {
Some(base) => base,
None => {
let base = memory
.map_heap_allocation(PROCESS_HEAP, 24)
.map_err(fault)?;
self.variables = Some(base);
base
}
};
Ok(base + variable as u64)
}
/// `_configure_narrow_argv`. Modes 1 and 2 build `__argc` and `__argv`
/// once; a later call changes nothing. Mode 0 builds nothing. Any other
/// mode is refused with `EINVAL`.
pub(super) fn configure(
&mut self,
memory: &mut GuestMemory,
mode: i32,
) -> Result<i32, ExitReason> {
match mode {
NO_ARGUMENTS => return Ok(0),
UNEXPANDED_ARGUMENTS | EXPANDED_ARGUMENTS => {}
_ => return Ok(EINVAL),
}
if self.configured {
return Ok(0);
}
// With no host input the program name is not available, and ISO C
// then makes argv[0] the empty string.
let default = [Vec::new()];
let arguments = self.supplied.as_deref().unwrap_or(&default);
let table_bytes = 8 * (arguments.len() + 1);
let string_bytes: usize = arguments.iter().map(|argument| argument.len() + 1).sum();
let table = memory
.map_heap_allocation(PROCESS_HEAP, table_bytes + string_bytes)
.map_err(fault)?;
// The pointers first, then the strings. The block starts as zeros, so
// the pointer after the last argument and every terminator are in place.
let mut string = table + table_bytes as u64;
for (index, argument) in arguments.iter().enumerate() {
memory
.write_u64(table + 8 * index as u64, string)
.map_err(fault)?;
memory.write_bytes(string, argument).map_err(fault)?;
string += argument.len() as u64 + 1;
}
let count = arguments.len() as u32;
let argc = self.address(memory, Variable::Argc)?;
let argv = self.address(memory, Variable::Argv)?;
memory.write_u32(argc, count).map_err(fault)?;
memory.write_u64(argv, table).map_err(fault)?;
self.configured = true;
Ok(0)
}
/// `_initialize_narrow_environment`. Points `_environ` at an empty table,
/// one null pointer, once.
pub(super) fn initialize_environment(
&mut self,
memory: &mut GuestMemory,
) -> Result<i32, ExitReason> {
if !self.environment_initialized {
let table = memory.map_heap_allocation(PROCESS_HEAP, 8).map_err(fault)?;
let environ = self.address(memory, Variable::Environ)?;
memory.write_u64(environ, table).map_err(fault)?;
self.environment_initialized = true;
}
Ok(0)
}
}
+249 -1
View File
@@ -19,7 +19,10 @@ use xenora_loader::pe::ParsedPe;
use xenora_loader::probe::{ProbeConfig, ProbeReport, probe_pe_bytes};
use xenora_loader::runtime::{Call, Float32, Float64};
use xenora_loader::runtime_table::SERVICES;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
use xenora_loader::services::{
MAX_PROGRAM_ARGUMENT_BYTES, MockClock, ProgramArgumentsError, ServicesState,
register_standard_services,
};
const BASE: u64 = 0x1_4000_0000;
const CODE_RVA: u32 = 0x1000;
@@ -239,6 +242,9 @@ impl Guest {
}
}
/// Bits above an `int` argument are not part of it.
const JUNK_HIGH: u64 = 0xFFFF_FFFF_0000_0000;
const PROCESS: u64 = u64::MAX;
const THREAD: u64 = u64::MAX - 1;
@@ -634,6 +640,248 @@ fn last_error_is_set_by_failures_and_by_the_guest() {
assert_eq!(guest.last_error(), 6);
}
/// What a guest sees in `__argc` and `__argv`: the count, each argument's
/// bytes up to its terminator, and the pointer after the last argument.
fn guest_arguments(guest: &mut Guest) -> (u32, Vec<Vec<u8>>, u64) {
let argc = guest.call("__p___argc", &[]);
let argv = guest.call("__p___argv", &[]);
let count = guest.memory.read_u32(argc).unwrap();
let table = guest.memory.read_u64(argv).unwrap();
let mut arguments = Vec::new();
for index in 0..u64::from(count) {
let mut at = guest.memory.read_u64(table + 8 * index).unwrap();
let mut bytes = Vec::new();
loop {
match guest.memory.read_u8(at).unwrap() {
0 => break,
byte => bytes.push(byte),
}
at += 1;
}
arguments.push(bytes);
}
let after = guest.memory.read_u64(table + 8 * u64::from(count)).unwrap();
(count, arguments, after)
}
/// The arguments a host supplies are what the guest finds in `__argc` and
/// `__argv` after `_configure_narrow_argv`, the way the mingw-w64 startup code
/// reads them before `main`. `__argc` and `__argv` are documented globals; ISO
/// C (5.1.2.2.1) puts a null pointer after the last argument, lets the program
/// modify the strings, and makes `argv[0]` the empty string when no program
/// name is available. Expected values are the strings this test supplied.
#[test]
fn program_arguments_reach_the_guest_as_argc_and_argv() {
let mut guest = Guest::new();
let supplied = ["gate-a2.exe", "one", "two words", "", "caf\u{e9} \u{2713}"];
guest.state.set_program_arguments(&supplied).unwrap();
// Before the runtime configures them there are no arguments.
let argc = guest.call("__p___argc", &[]);
let argv = guest.call("__p___argv", &[]);
assert!(argc != 0 && argv != 0 && argc.abs_diff(argv) >= 8);
assert_eq!(guest.memory.read_u32(argc).unwrap(), 0);
assert_eq!(guest.memory.read_u64(argv).unwrap(), 0);
// A mode other than 0, 1 or 2 is refused with EINVAL; mode 0 asks for no
// arguments. Neither builds anything. The mode is an int.
for (mode, result) in [(3, 22), (0xFFFF_FFFF, 22), (0x8000_0001, 22), (0, 0)] {
let returned = guest.call("_configure_narrow_argv", &[JUNK_HIGH | mode]);
assert_eq!(returned & 0xFFFF_FFFF, result, "mode {mode:#x}");
assert_eq!(guest.memory.read_u32(argc).unwrap(), 0, "mode {mode:#x}");
assert_eq!(guest.memory.read_u64(argv).unwrap(), 0, "mode {mode:#x}");
}
// _crt_argv_unexpanded_arguments is 1.
assert_eq!(
guest.call("_configure_narrow_argv", &[JUNK_HIGH | 1]) & 0xFFFF_FFFF,
0
);
let (count, arguments, after) = guest_arguments(&mut guest);
assert_eq!(count, 5);
let wanted: Vec<Vec<u8>> = supplied
.iter()
.map(|text| text.as_bytes().to_vec())
.collect();
assert_eq!(arguments, wanted);
assert_eq!(after, 0, "argv[argc] is a null pointer");
// The variables did not move, and each argument has its own storage.
assert_eq!(guest.call("__p___argc", &[]), argc);
assert_eq!(guest.call("__p___argv", &[]), argv);
let table = guest.memory.read_u64(argv).unwrap();
let mut starts: Vec<u64> = (0..5)
.map(|index| guest.memory.read_u64(table + 8 * index).unwrap())
.collect();
for (start, argument) in starts.iter().zip(&wanted) {
assert!(*start >= table + 8 * 6, "a string inside the pointer table");
// The terminator is the byte after the argument.
assert_eq!(
guest.memory.read_u8(start + argument.len() as u64).unwrap(),
0
);
}
starts.sort_unstable();
for (pair, argument) in starts.windows(2).zip(&wanted) {
assert!(pair[1] - pair[0] > argument.len() as u64, "strings overlap");
}
// The program may modify its arguments; a second configuration, in either
// mode, does not rebuild them.
let first = guest.memory.read_u64(table).unwrap();
guest.memory.write_u8(first, b'G').unwrap();
for mode in [1, 2, 0, 3] {
guest.call("_configure_narrow_argv", &[mode]);
assert_eq!(guest.memory.read_u64(argv).unwrap(), table, "mode {mode}");
assert_eq!(guest.memory.read_u8(first).unwrap(), b'G', "mode {mode}");
assert_eq!(guest.memory.read_u32(argc).unwrap(), 5, "mode {mode}");
}
// Once built, the host can no longer change them.
assert_eq!(
guest.state.set_program_arguments(&["late"]),
Err(ProgramArgumentsError::AlreadyConfigured)
);
assert_eq!(guest_arguments(&mut guest).0, 5);
}
/// What a guest gets when the host supplies nothing, supplies no arguments at
/// all, or uses `_crt_argv_expanded_arguments` (2), and what a host may not
/// supply.
#[test]
fn program_arguments_have_defaults_and_limits() {
// No host input: the program name is not available, so ISO C makes
// argv[0] the empty string.
let mut guest = Guest::new();
assert_eq!(guest.call("_configure_narrow_argv", &[1]), 0);
assert_eq!(guest_arguments(&mut guest), (1, vec![Vec::new()], 0));
// An empty list is zero arguments: argv is one null pointer.
let mut guest = Guest::new();
guest.state.set_program_arguments(&[]).unwrap();
assert_eq!(guest.call("_configure_narrow_argv", &[1]), 0);
assert_eq!(guest_arguments(&mut guest), (0, Vec::new(), 0));
let argv = guest.call("__p___argv", &[]);
assert_ne!(guest.memory.read_u64(argv).unwrap(), 0);
// Mode 2 asks for wildcard expansion, which is not performed: a pattern
// arrives as it was supplied. The last list supplied before configuration
// is the one used, and configuring first and asking for the pointers
// afterwards works too.
let mut guest = Guest::new();
guest.state.set_program_arguments(&["first"]).unwrap();
guest
.state
.set_program_arguments(&["prog", "*.txt", "a?c"])
.unwrap();
assert_eq!(guest.call("_configure_narrow_argv", &[2]), 0);
let wanted = vec![b"prog".to_vec(), b"*.txt".to_vec(), b"a?c".to_vec()];
assert_eq!(guest_arguments(&mut guest), (3, wanted, 0));
// A NUL byte would end the argument early in the guest.
let guest = Guest::new();
let state = &guest.state;
assert_eq!(
state.set_program_arguments(&["ok", "a\0b"]),
Err(ProgramArgumentsError::ContainsNul)
);
// The bound counts each argument with its terminator, and is inclusive.
assert_eq!(MAX_PROGRAM_ARGUMENT_BYTES, 32_767);
let longest = "x".repeat(MAX_PROGRAM_ARGUMENT_BYTES - 1);
assert_eq!(state.set_program_arguments(&[&longest]), Ok(()));
let too_long = "x".repeat(MAX_PROGRAM_ARGUMENT_BYTES);
assert_eq!(
state.set_program_arguments(&[&too_long]),
Err(ProgramArgumentsError::TooLong)
);
// Two arguments of 16,383 and 16,382 bytes take 32,767 with their
// terminators; one more empty argument is one byte too many.
let (half, rest) = ("y".repeat(16_383), "z".repeat(16_382));
assert_eq!(state.set_program_arguments(&[&half, &rest]), Ok(()));
assert_eq!(
state.set_program_arguments(&[&half, &rest, ""]),
Err(ProgramArgumentsError::TooLong)
);
// A refused list replaces nothing: the last accepted one is still used.
let mut guest = guest;
assert_eq!(guest.call("_configure_narrow_argv", &[1]), 0);
let (count, arguments, after) = guest_arguments(&mut guest);
assert_eq!((count, after), (2, 0));
assert_eq!(arguments, [half.as_bytes(), rest.as_bytes()]);
}
/// `_environ` is a documented global: a pointer to the array of environment
/// strings. Xenora's environment is empty, so after
/// `_initialize_narrow_environment` the table is one null pointer, the usual
/// end of such a table. Before that call `_environ` is null.
#[test]
fn the_environment_table_is_empty_and_ends_with_a_null_pointer() {
let mut guest = Guest::new();
let environ = guest.call("__p__environ", &[]);
assert_ne!(environ, 0);
assert_eq!(guest.memory.read_u64(environ).unwrap(), 0);
assert_eq!(guest.call("_initialize_narrow_environment", &[]), 0);
let table = guest.memory.read_u64(environ).unwrap();
assert_ne!(table, 0);
assert_eq!(guest.memory.read_u64(table).unwrap(), 0);
// A second call keeps the table, and the pointer does not move.
assert_eq!(guest.call("_initialize_narrow_environment", &[]), 0);
assert_eq!(guest.call("__p__environ", &[]), environ);
assert_eq!(guest.memory.read_u64(environ).unwrap(), table);
// The three variables are separate, and neither initialization touches
// the other's: the order the mingw-w64 startup uses is environment first.
let argc = guest.call("__p___argc", &[]);
let argv = guest.call("__p___argv", &[]);
let mut cells = [argc, argv, environ];
cells.sort_unstable();
assert!(cells[1] - cells[0] >= 8 && cells[2] - cells[1] >= 8);
assert_eq!(guest.memory.read_u32(argc).unwrap(), 0);
assert_eq!(guest.memory.read_u64(argv).unwrap(), 0);
assert_eq!(guest.call("_configure_narrow_argv", &[1]), 0);
assert_eq!(guest.memory.read_u64(environ).unwrap(), table);
assert_eq!(guest.memory.read_u64(table).unwrap(), 0);
assert_eq!(guest_arguments(&mut guest).0, 1);
// Arguments first, environment second, on a fresh guest.
let mut other = Guest::new();
assert_eq!(other.call("_configure_narrow_argv", &[1]), 0);
let environ = other.call("__p__environ", &[]);
assert_eq!(other.memory.read_u64(environ).unwrap(), 0);
assert_eq!(other.call("_initialize_narrow_environment", &[]), 0);
let table = other.memory.read_u64(environ).unwrap();
assert_eq!(other.memory.read_u64(table).unwrap(), 0);
assert_eq!(guest_arguments(&mut other), (1, vec![Vec::new()], 0));
}
/// The module and symbol pairs a program built with mingw-w64 14.0.0 (UCRT)
/// imports these five services by, read from such a program's import table.
#[test]
fn program_argument_services_resolve_as_mingw_w64_imports_them() {
let (registry, _) = standard(0);
let named = |name: &str| ImportName::Name(name.to_owned());
const RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
const ENVIRONMENT: &str = "api-ms-win-crt-environment-l1-1-0.dll";
for (module, symbol) in [
(RUNTIME, "__p___argc"),
(RUNTIME, "__p___argv"),
(ENVIRONMENT, "__p__environ"),
(RUNTIME, "_configure_narrow_argv"),
(RUNTIME, "_initialize_narrow_environment"),
] {
let service = registry
.resolve(module, &named(symbol))
.unwrap_or_else(|| panic!("{module}!{symbol}"));
let target = registry.resolve("ucrtbase.dll", &named(symbol)).unwrap();
assert!(std::ptr::eq(service, target), "{module}!{symbol}");
assert_eq!(service.status, ServiceStatus::Partial, "{symbol}");
}
// An API set forwards only the symbols listed for it.
assert!(
registry
.resolve(ENVIRONMENT, &named("__p___argc"))
.is_none()
);
assert!(registry.resolve(RUNTIME, &named("__p__environ")).is_none());
}
#[test]
fn virtual_memory_is_mapped_released_and_bounded() {
let mut guest = Guest::new();
+37
View File
@@ -259,6 +259,43 @@ up to 1 MiB. Each nonempty span must be fully mapped with the required permissio
A span may cross adjacent guest regions. Writes validate the full destination before changing
bytes, and moves preserve the original source bytes when ranges overlap.
### Program arguments and environment
A hosted C program's startup code gets `argc`, `argv` and `envp` for `main`
from five C runtime services. A host supplies the arguments with
`ServicesState::set_program_arguments(&["program", "first", ...])`, program
name first, before it runs the guest.
| Service | Behaviour |
| --- | --- |
| `__p___argc()`, `__p___argv()`, `__p__environ()` | The address of the guest variable `__argc`, `__argv` or `_environ`. All three start as zero or null |
| `_configure_narrow_argv(mode)` | For mode 1 or 2, sets `__argc` to the number of arguments and `__argv` to a table of pointers to their NUL-terminated strings, with a null pointer after the last, and returns 0. It builds the table once; later calls return 0 and change nothing. Mode 0 returns 0 and builds nothing. Any other mode returns `EINVAL` |
| `_initialize_narrow_environment()` | Points `_environ` at a table holding one null pointer, once, and returns 0 |
`set_program_arguments` refuses an argument containing a NUL byte, arguments
whose bytes and terminators exceed 32,767 (`MAX_PROGRAM_ARGUMENT_BYTES`, the
documented Windows command-line limit), and a call after the guest has built
its table. A host that never calls it gives the program one argument, the
empty string, which is what ISO C specifies when no program name is
available. An empty list gives it none.
What is documented, inferred and chosen:
- **Documented:** the three global variables and what they hold, and ISO C's
rules for `argv` (a null pointer after the last argument, strings the
program may modify).
- **Inferred:** that each `__p_` function returns the address of its
variable, as the documented `__p__fmode` does. Microsoft lists these five
functions only by name.
- **Xenora's choice:** what the two initialization functions do. Arguments
reach the guest as the bytes of the host's strings, with no code page.
Mode 2 asks for wildcard expansion and none is performed. The environment
is empty. The variables and tables are blocks from the process heap.
The wide-character counterparts, `GetCommandLineA` and `GetCommandLineW`, and
environment variables do not exist. All five services are `partial`. None of
this has been compared with Windows.
### Guest heaps
`GetProcessHeap`, `HeapAlloc`, `HeapSize`, and `HeapFree` expose the
+11 -6
View File
@@ -6,14 +6,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
| Measure | Count |
| --- | ---: |
| Services with a declared ABI | 32 |
| Generated adapters | 32 |
| Unique handler implementations | 32 |
| Services with a declared ABI | 37 |
| Generated adapters | 37 |
| Unique handler implementations | 37 |
| Implemented | 7 |
| Partial | 22 |
| Partial | 27 |
| Stub | 3 |
| Conformance-tested through guest dispatch | 32 |
| API-set aliases (not services) | 32 |
| Conformance-tested through guest dispatch | 37 |
| API-set aliases (not services) | 37 |
| Independently accepted | 0 |
| Service | Signature | Status | Failure |
@@ -32,6 +32,11 @@ A declared service is not a claim of compatibility. `implemented` and `partial`
| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer |
| `kernel32.dll!GetLastError` | `() -> u32` | partial | never |
| `kernel32.dll!SetLastError` | `(code: u32) -> void` | partial | never |
| `ucrtbase.dll!__p___argc` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
| `ucrtbase.dll!__p___argv` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
| `ucrtbase.dll!__p__environ` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated |
| `ucrtbase.dll!_configure_narrow_argv` | `(mode: i32) -> i32` | partial | EINVAL for a mode other than 0, 1 or 2; stops the guest when the table cannot be allocated |
| `ucrtbase.dll!_initialize_narrow_environment` | `() -> i32` | partial | stops the guest when the table cannot be allocated |
| `kernel32.dll!VirtualAlloc` | `(address: ptr, size: u64, kind: u32, protect: u32) -> ptr` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY |
| `kernel32.dll!VirtualFree` | `(address: ptr, size: u64, kind: u32) -> bool32` | partial | 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS |
| `kernel32.dll!VirtualProtect` | `(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32` | stub | always: stops the guest with the runtime-limit fault; no protection changes |