Compare commits

...
Author SHA1 Message Date
atharvranjan acb3839351 Integrate PR #280 process termination and exit callbacks
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:00:19 -06:00
atharvranjan f9d5838091 Integrate PR #277 with the combined typed runtime services
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:59:43 -06:00
zachdoxsee ab73969135 Merge upstream main into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:27:10 +01:00
zachdoxsee e57386950b Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 0aeb2b69a9 Merge task/329-gate-a1 into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee 34e99b3745 Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:01 +01:00
zachdoxsee a91c7fa39d Merge task/329-gate-a1 (with upstream main) into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:52 +01:00
zachdoxsee 22425287e2 Merge upstream main into task/392-program-arguments
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 48d22f533b Merge task/329-gate-a1 (with upstream main) into task/395-crt-exit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:57:12 +01:00
zachdoxsee aae04a2956 Merge upstream main into task/392-program-arguments
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
zachdoxsee d326e929a9 loader: add exit, _exit and abort for a hosted C program (#395)
A C program ends through the C runtime's exit, not ExitProcess, and a
program built with the mingw-w64 runtime imports exit, _exit and abort.
None resolved, so the loader refused the program before its entry point.

exit calls the functions registered with atexit and _crt_atexit, most
recently registered first, then ends the guest with ProcessExit(status).
_exit ends it with its status and abort with exit code 3; neither calls a
registered function. All three use the cleanup behind ExitProcess.

Built on the process exit from #329. Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 00:47:33 +01:00
zachdoxsee 32251af4c8 loader: add program arguments for a hosted C program (#392)
A program built with the mingw-w64 runtime gets argc, argv and envp for
main from __p___argc, __p___argv, __p__environ, _configure_narrow_argv
and _initialize_narrow_environment. None resolved, so the loader refused
the program before its entry point, and a host could not say what the
program's arguments are.

The five services are added to the typed registry, and
ServicesState::set_program_arguments lets a host supply argv. The
environment table is empty.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:40:27 +01:00
12 changed files with 1145 additions and 16 deletions

No files matched your search

+4
View File
@@ -137,10 +137,14 @@ remains unsupported.
- Added non-alertable extended event waits through both Win64 wait APIs.
- Added the C runtime's `exit`, `_exit` and `abort` (#395, part of Gate A2), on top of the process exit from #329. A C program ends through `exit`, not `ExitProcess`, and a program built with the mingw-w64 runtime imports all three; the loader refused it before its entry point because they did not resolve. `exit` calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, and then ends the guest with `ExitReason::ProcessExit(status)`; `_exit` ends it with its status and `abort` with exit code 3, and neither calls a registered function. All three go through the same cleanup as `ExitProcess` and never end the host. A function registered while `exit` runs is called next, as ISO C requires; `exit` called again from a registered function, which ISO C leaves undefined, runs the remaining functions once and ends with the later status. All three are partial: no stream is flushed because there are none, `abort` prints no message and calls no `SIGABRT` handler, and thread-local destructors are not run. Nine tests in `crt_exit.rs` call them from guest code. `docs/testing/gate-a.md` now describes A2 as in progress and not passing. Not compared with Windows; awaiting independent review.
- Added immediate wait-any and wait-all for guest event handles.
- 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};
@@ -201,6 +203,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>,
@@ -230,6 +233,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(),
@@ -246,6 +250,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
@@ -905,6 +924,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)
}
}
@@ -400,6 +400,57 @@ impl CallbackTask for ExitFunctions {
}
}
/// `exit`: calls the functions registered with `atexit` and `_crt_atexit`,
/// most recently registered first, and then ends the guest process.
///
/// It takes one function at a time from the shared list. A function that is
/// registered while `exit` runs is therefore called next, before the older
/// ones that have not run yet, as ISO C requires (7.22.4.2, 7.22.4.4). A
/// registered function that calls `exit` again, which ISO C leaves undefined,
/// starts a second task on the same list: the remaining functions run once
/// each and the process ends with the later status.
struct Exit {
state: Arc<ServicesState>,
status: u32,
}
impl Exit {
fn next(&mut self) -> Result<CallbackStep, ExitReason> {
let function = self
.state
.atexit
.lock()
.expect("guest atexit functions")
.pop();
match function {
Some(entry) => Ok(CallbackStep::Call {
entry,
args: [0; 4],
}),
None => Err(ExitReason::ProcessExit(
self.state.exit_process(self.status),
)),
}
}
fn start(mut self) -> Result<CallbackStart, ExitReason> {
match self.next()? {
CallbackStep::Call { entry, args } => Ok(CallbackStart::Call {
task: Box::new(self),
entry,
args,
}),
CallbackStep::Return(value) => Ok(CallbackStart::Return(value)),
}
}
}
impl CallbackTask for Exit {
fn resume(&mut self, _: u64, _: u64, _: &mut GuestMemory) -> Result<CallbackStep, ExitReason> {
self.next()
}
}
fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
registry.register(UCRT, "_initialize_onexit_table", |args, _, mem| {
let table = args.rcx;
@@ -473,6 +524,24 @@ fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState
Ok(ExitFunctions { pending }.start())
});
// exit does not return. It is partial: no stream is flushed, because
// there are none, and thread-local destructors are not run.
let s = Arc::clone(state);
registry.register_callback_task(
UCRT,
"exit",
ServiceStatus::Partial,
move |args, _, _, _| {
// The status is an int, the low half of the first argument.
Exit {
state: Arc::clone(&s),
status: args.rcx as u32,
}
.start()
},
);
registry.alias(CRT_RUNTIME_API, UCRT, "exit");
for symbol in [
"_initialize_onexit_table",
"_register_onexit_function",
+26
View File
@@ -8,6 +8,10 @@ use crate::imports::{ImportRegistry, ServiceStatus};
use std::sync::Arc;
const PROCESS_THREADS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
const UCRT: &str = "ucrtbase.dll";
const CRT_RUNTIME_API: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
/// The exit code `abort` ends the process with (Microsoft Learn, "abort").
const ABORT_STATUS: u32 = 3;
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
// ExitProcess does not return (processthreadsapi.h). It stops the guest
@@ -20,4 +24,26 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
});
registry.alias(PROCESS_THREADS_API, KERNEL32, "ExitProcess");
registry.set_status(KERNEL32, "ExitProcess", ServiceStatus::Partial);
// _exit ends the process without calling the functions registered with
// atexit (Microsoft Learn, "exit, _Exit, _exit"). `exit`, which does call
// them, is beside `_cexit` in crt_callbacks.rs.
let s = Arc::clone(state);
registry.register(UCRT, "_exit", move |args, _, _| {
// The status is an int, the low half of the first argument.
Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32)))
});
// abort ends the process with exit code 3 and calls no registered
// function. It is partial: it prints no message, and it does not call a
// SIGABRT handler, which the documentation says it does when one is set.
let s = Arc::clone(state);
registry.register(UCRT, "abort", move |_, _, _| {
Err(ExitReason::ProcessExit(s.exit_process(ABORT_STATUS)))
});
for symbol in ["_exit", "abort"] {
registry.alias(CRT_RUNTIME_API, UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
+332
View File
@@ -0,0 +1,332 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The C runtime's `exit`, `_exit` and `abort` (issue #395), called from
//! translated guest code through a bound import table.
//!
//! Expected behaviour is from the Microsoft Learn pages "exit, _Exit, _exit"
//! (`exit` calls the functions registered by `atexit` "in last-in-first-out
//! (LIFO) order"; `_exit` terminates "without ... processing atexit or _onexit
//! functions") and "abort" ("calls _exit to terminate the process with exit
//! code 3"), and from ISO C 7.22.4.2 and 7.22.4.4 for a function registered
//! while `exit` runs. Calling `exit` again from a registered function is
//! undefined in ISO C; the test for it states Xenora's rule. The order each
//! test expects is the order in which it registered its functions. The guest
//! code is original.
mod support;
use support::*;
use xenora_loader::cpu::ExitReason;
use xenora_loader::import_table::ImportName;
use xenora_loader::imports::{ImportRegistry, ServiceStatus};
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
const KERNEL32: &str = "kernel32.dll";
const UCRT: &str = "ucrtbase.dll";
const RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
const EXIT: usize = 0;
const ATEXIT: usize = 3;
const IMPORTS: &[(&str, &str)] = &[
(UCRT, "exit"),
(UCRT, "_exit"),
(UCRT, "abort"),
(UCRT, "atexit"),
(RUNTIME, "_crt_atexit"),
(RUNTIME, "_cexit"),
(KERNEL32, "CreateEventW"),
(KERNEL32, "SetLastError"),
];
/// The same imports as a program built with mingw-w64 names the three: by the
/// runtime API set.
const BY_API_SET: &[(&str, &str)] = &[
(RUNTIME, "exit"),
(RUNTIME, "_exit"),
(RUNTIME, "abort"),
(UCRT, "atexit"),
(RUNTIME, "_crt_atexit"),
(RUNTIME, "_cexit"),
(KERNEL32, "CreateEventW"),
(KERNEL32, "SetLastError"),
];
/// A decimal log of the registered functions that ran, oldest digit first.
const LOG: u64 = SCRATCH;
/// Set to one by code placed after a call that must not return.
const RETURNED: u64 = SCRATCH + 0x100;
/// Guest address of the stub `call [slot]; hlt` for import `index`.
fn stub(index: usize) -> u64 {
BASE + u64::from(CODE_RVA) + 16 * index as u64
}
/// Guest address of the import address table slot of import `index`, read
/// from the displacement of its stub.
fn slot(guest: &Guest, index: usize) -> u64 {
let displacement = guest.u32_at(stub(index) + 2) as i32;
(stub(index) + 6).wrapping_add_signed(i64::from(displacement))
}
// Routine indices. Routines are 32 bytes apart.
const APPEND_1: usize = 0;
const APPEND_2: usize = 1;
const APPEND_3: usize = 2;
const APPEND_4: usize = 3;
const APPEND_5: usize = 4;
const REGISTER_4_THEN_APPEND_5: usize = 5;
const EXIT_AGAIN: usize = 6;
/// The status the `EXIT_AGAIN` routine exits with.
const SECOND_STATUS: u32 = 77;
/// `log = log * 10 + digit; return 0`
fn append(digit: u8) -> Vec<u8> {
let mut code = vec![0x48, 0xB8]; // mov rax, LOG
code.extend(LOG.to_le_bytes());
code.extend([
0x48, 0x8B, 0x08, // mov rcx, [rax]
0x48, 0x6B, 0xC9, 0x0A, // imul rcx, rcx, 10
0x48, 0x83, 0xC1, digit, // add rcx, digit
0x48, 0x89, 0x08, // mov [rax], rcx
0x31, 0xC0, // xor eax, eax
0xC3, // ret
]);
code
}
fn rel32(from_end: u64, to: u64) -> [u8; 4] {
(to.wrapping_sub(from_end) as u32).to_le_bytes()
}
/// A registered function that registers `APPEND_4` with `atexit`, through the
/// import address table as compiled code would, and then appends 5.
fn register_4_then_append_5(atexit_slot: u64) -> Vec<u8> {
let at = routine(REGISTER_4_THEN_APPEND_5);
let mut code = vec![0x48, 0x83, 0xEC, 0x28]; // sub rsp, 0x28
code.extend([0x48, 0x8D, 0x0D]); // lea rcx, [rip + APPEND_4]
code.extend(rel32(at + 11, routine(APPEND_4)));
code.extend([0xFF, 0x15]); // call [rip + atexit slot]
code.extend(rel32(at + 17, atexit_slot));
code.extend([0x48, 0x83, 0xC4, 0x28]); // add rsp, 0x28
code.push(0xE9); // jmp APPEND_5
code.extend(rel32(at + 26, routine(APPEND_5)));
code
}
/// A registered function that calls `exit(SECOND_STATUS)`. The code after the
/// call would record that `exit` returned.
fn exit_again() -> Vec<u8> {
let at = routine(EXIT_AGAIN);
let mut code = vec![0x48, 0x83, 0xEC, 0x28]; // sub rsp, 0x28
code.push(0xB9); // mov ecx, SECOND_STATUS
code.extend(SECOND_STATUS.to_le_bytes());
code.push(0xE8); // call <exit stub>
code.extend(rel32(at + 14, stub(EXIT)));
code.extend([0x48, 0xB8]); // mov rax, RETURNED
code.extend(RETURNED.to_le_bytes());
code.extend([
0xC6, 0x00, 0x01, // mov byte ptr [rax], 1
0x48, 0x83, 0xC4, 0x28, // add rsp, 0x28
0xC3, // ret
]);
code
}
fn guest_with(imports: &'static [(&'static str, &'static str)]) -> Guest {
// The slot of `atexit` depends only on the import list, so a guest built
// without routines tells where it is.
let atexit_slot = slot(&Guest::new(imports, &[]), ATEXIT);
let routines = [
append(1),
append(2),
append(3),
append(4),
append(5),
register_4_then_append_5(atexit_slot),
exit_again(),
];
let guest = Guest::new(imports, &routines);
assert_eq!(slot(&guest, ATEXIT), atexit_slot);
guest
}
fn guest() -> Guest {
guest_with(IMPORTS)
}
fn register(guest: &mut Guest, symbol: &str, index: usize) {
assert_eq!(guest.call(symbol, &[routine(index)]) as u32, 0, "{symbol}");
}
#[test]
fn exit_runs_registered_functions_most_recent_first_then_ends_the_process() {
for imports in [IMPORTS, BY_API_SET] {
let mut guest = guest_with(imports);
// atexit and _crt_atexit feed one list.
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "_crt_atexit", APPEND_2);
register(&mut guest, "atexit", APPEND_3);
assert_eq!(guest.u64_at(LOG), 0);
assert_eq!(guest.state.exit_status(), None);
// The status is an int: the upper half of RCX is not part of it.
let (_, exit) = guest.run("exit", &[0xAAAA_BBBB_1234_5678]);
assert_eq!(exit, ExitReason::ProcessExit(0x1234_5678));
assert_eq!(guest.u64_at(LOG), 321, "last registered runs first");
assert_eq!(guest.state.exit_status(), Some(0x1234_5678));
}
}
#[test]
fn exit_with_nothing_registered_ends_the_process_with_its_status() {
for (argument, status) in [
(0, 0),
(1, 1),
(300, 300),
(0xFFFF_FFFF, 0xFFFF_FFFF),
(0x1_0000_0000, 0),
] {
let mut guest = guest();
// The stub is `call [exit]; hlt`: a service that returned would reach
// the HLT and report Halt.
let (_, exit) = guest.run("exit", &[argument]);
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
assert_eq!(guest.u64_at(LOG), 0);
assert_eq!(guest.state.exit_status(), Some(status));
}
}
/// ISO C 7.22.4.4: registered functions are called in reverse order of
/// registration, "except that a function is called after any previously
/// registered functions that had already been called at the time it was
/// registered". A function registered by the second function to run is
/// therefore the third to run, ahead of the one registered first.
#[test]
fn a_function_registered_while_exit_runs_is_called_next() {
let mut guest = guest();
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "atexit", REGISTER_4_THEN_APPEND_5);
register(&mut guest, "atexit", APPEND_3);
let (_, exit) = guest.run("exit", &[6]);
assert_eq!(exit, ExitReason::ProcessExit(6));
// 3 ran first; then the function that registered 4 and logged 5; then 4,
// registered during exit; then 1, the oldest.
assert_eq!(guest.u64_at(LOG), 3541);
}
/// Calling `exit` from a registered function is undefined in ISO C. Xenora's
/// rule: the functions that have not run yet run once each, and the process
/// ends with the status of the later call. Nothing runs twice and the inner
/// call does not return.
#[test]
fn exit_called_again_from_a_registered_function_finishes_with_the_later_status() {
let mut guest = guest();
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "atexit", EXIT_AGAIN);
register(&mut guest, "atexit", APPEND_3);
let (_, exit) = guest.run("exit", &[5]);
assert_eq!(exit, ExitReason::ProcessExit(SECOND_STATUS));
// 3, then the function that called exit again, then 1 from inside that
// second call. A status of 5 would mean the function never ran.
assert_eq!(guest.u64_at(LOG), 31);
assert_eq!(guest.memory.read_u8(RETURNED).unwrap(), 0);
assert_eq!(guest.state.exit_status(), Some(SECOND_STATUS));
}
#[test]
fn underscore_exit_and_abort_run_no_registered_function() {
for imports in [IMPORTS, BY_API_SET] {
// _exit ends the process with its status, an int.
for (argument, status) in [(9, 9), (0xAAAA_BBBB_0000_0102, 0x102), (0, 0)] {
let mut guest = guest_with(imports);
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "_crt_atexit", APPEND_2);
let (_, exit) = guest.run("_exit", &[argument]);
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
assert_eq!(guest.u64_at(LOG), 0);
assert_eq!(guest.state.exit_status(), Some(status));
}
// abort takes no argument and ends the process with exit code 3,
// whatever the argument registers hold.
for junk in [0, 0x1234] {
let mut guest = guest_with(imports);
register(&mut guest, "atexit", APPEND_1);
let (_, exit) = guest.run("abort", &[junk, junk, junk, junk]);
assert_eq!(exit, ExitReason::ProcessExit(3));
assert_eq!(guest.u64_at(LOG), 0);
assert_eq!(guest.state.exit_status(), Some(3));
}
}
}
#[test]
fn each_way_out_closes_the_guest_handles() {
for symbol in ["exit", "_exit", "abort"] {
let mut guest = guest();
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
assert_ne!(guest.call("CreateEventW", &[0, 0, 1, 0]), 0);
assert_eq!(guest.state.open_handle_count(), 2);
let (_, exit) = guest.run(symbol, &[4]);
assert!(matches!(exit, ExitReason::ProcessExit(_)), "{symbol}");
assert_eq!(guest.state.open_handle_count(), 0, "{symbol}");
}
// With registered functions: they run while the handles are still open,
// and the handles are closed once the last one has returned.
let mut guest = guest();
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
register(&mut guest, "atexit", APPEND_1);
assert_eq!(guest.run("exit", &[0]).1, ExitReason::ProcessExit(0));
assert_eq!(guest.u64_at(LOG), 1);
assert_eq!(guest.state.open_handle_count(), 0);
}
#[test]
fn an_exited_guest_runs_nothing_further() {
for symbol in ["exit", "_exit", "abort"] {
let mut guest = guest();
let first = guest.run(symbol, &[8]).1;
assert!(matches!(first, ExitReason::ProcessExit(_)), "{symbol}");
// Neither another service nor a second exit takes effect.
for (later, argument) in [("SetLastError", 5), ("exit", 9), ("_exit", 9), ("abort", 0)] {
assert_eq!(guest.run(later, &[argument]).1, first, "{symbol}, {later}");
}
assert_eq!(guest.state.last_error(THREAD_A), 0, "{symbol}");
}
}
#[test]
fn functions_already_run_by_cexit_are_not_run_again_by_exit() {
let mut guest = guest();
register(&mut guest, "atexit", APPEND_1);
register(&mut guest, "atexit", APPEND_2);
// _cexit runs the registered functions and returns to the caller.
assert_eq!(guest.call("_cexit", &[]), 0);
assert_eq!(guest.u64_at(LOG), 21);
// One registered afterwards is the only one exit has left to run.
register(&mut guest, "atexit", APPEND_3);
assert_eq!(guest.run("exit", &[2]).1, ExitReason::ProcessExit(2));
assert_eq!(guest.u64_at(LOG), 213);
}
#[test]
fn the_three_resolve_under_the_library_and_the_runtime_api_set() {
let state = std::sync::Arc::new(ServicesState::new(std::sync::Arc::new(MockClock::new(0))));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, state);
let named = |name: &str| ImportName::Name(name.to_owned());
for symbol in ["exit", "_exit", "abort"] {
let service = registry
.resolve(UCRT, &named(symbol))
.unwrap_or_else(|| panic!("{symbol}"));
let aliased = registry.resolve(RUNTIME, &named(symbol)).unwrap();
assert!(std::ptr::eq(service, aliased), "{symbol}");
assert_eq!(service.status, ServiceStatus::Partial, "{symbol}");
// Not exported by kernel32, and not through an unrelated API set.
assert!(registry.resolve(KERNEL32, &named(symbol)).is_none());
assert!(
registry
.resolve("api-ms-win-crt-heap-l1-1-0.dll", &named(symbol))
.is_none()
);
}
// The spelling is exact: _Exit is another function and is not provided.
assert!(registry.resolve(UCRT, &named("_Exit")).is_none());
}
+249 -1
View File
@@ -20,7 +20,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;
@@ -240,6 +243,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;
@@ -635,6 +641,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();
+64 -3
View File
@@ -78,11 +78,35 @@ Windows while the process has one thread. The exit closes every guest handle:
kernel objects, Winsock sockets and task-queue handles, which
`ServicesState::open_handle_count` counts together. Files stay on the synthetic `C:` drive, guest memory stays mapped so the host
can inspect it, and `atexit` functions are not run: that belongs to the C
runtime's `exit`, which is not implemented. `ServicesState::exit_status`
runtime's `exit`, described below. `ServicesState::exit_status`
reports the status. After an exit the `DbtEngine` that ran the guest executes
no further guest instruction and answers every later `run` with the same
`ProcessExit`. A service callback that was in progress is never resumed.
A C program ends through the C runtime instead. `ucrtbase.dll` and
`api-ms-win-crt-runtime-l1-1-0.dll` provide three ways out, each ending the
guest with the same `ProcessExit` and the same cleanup as `ExitProcess`:
| Service | Behaviour |
| --- | --- |
| `exit(status)` | Calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, then ends the process with `status` |
| `_exit(status)` | Ends the process with `status` and calls no registered function |
| `abort()` | Ends the process with exit code 3 and calls no registered function |
`exit` takes one function at a time from the registered list. A function
registered while `exit` runs is therefore called next, before the older ones
that have not run yet, which is ISO C's rule. A registered function that calls
`exit` again is undefined in ISO C; here the functions that have not run yet
run once each and the process ends with the status of the later call.
Functions that `_cexit` has already run are not run again.
All three are partial. `exit` flushes no stream, because there are none, and
runs no thread-local destructor. It does not walk a module's own `_onexit`
table; that module's startup code runs it through `_execute_onexit_table`.
`abort` prints no message and does not call a `SIGABRT` handler, which the
documentation says it does when one is set. `_Exit`, `quick_exit` and
`_c_exit` are not provided. None of this has been compared with Windows.
A TLS callback may end the process too. Startup then reports the exit as its
outcome, with the status, and runs neither the remaining callbacks nor the
entry point; `StartupResult::tls_callbacks` counts the callbacks that finished.
@@ -259,6 +283,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
@@ -468,8 +529,8 @@ The CRT uses this for:
on the default guest heap, and they hold at most 65,536 entries. Execution
resets the table first, then calls the functions in reverse order of
registration. `atexit` and `_crt_atexit` record process exit functions,
which `_cexit` runs in reverse order. Process termination through `exit` is
not modeled.
which `_cexit` runs in reverse order and returns. `exit` runs them and
then ends the process; see "PE32+ fixture startup" above.
Null comparators, null arrays with a nonzero count, and reversed or
misaligned tables would reach the CRT invalid-parameter handler. That
+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 |
+20 -5
View File
@@ -8,7 +8,7 @@ when both pass.
| Milestone | What it is | Status |
| --- | --- | --- |
| A1 | An original C program with no C library linked, importing documented `kernel32.dll` and `ucrtbase.dll` functions, run through the loader and the ARM64 DBT with proper process exit | Passes locally; awaiting independent review |
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | Not started |
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | In progress; does not pass |
## A1
@@ -47,7 +47,22 @@ whose entry point returns its status gives the same result as `ExitProcess`.
## A2
Not started. It needs at least the C standard I/O functions, `exit` with
`atexit` handlers, command-line and environment access, and a decision on
which C runtime startup code may be linked and under what licence. None of
those are registered today.
In progress. It does not pass, and there is no A2 test in the repository yet.
The target is an original C program built with the mingw-w64 runtime (UCRT),
whose own startup code runs before `main`. Such a program needs pieces that
are being added one issue at a time. This page records only what is in the
tree it is part of:
| Piece | State here |
| --- | --- |
| Normal exit: `exit` with its `atexit` functions, `_exit` and `abort` | Present (#395), on top of the process exit A1 added |
| The PE headers mapped at the image base, which the startup code reads | Separate change (#333) |
| `FNINIT`, the one instruction the startup code needs that was refused | Separate change (#378) |
| The C runtime startup calls, and the functions a program imports but does not call | Separate changes (#382, #388) |
| `argc`, `argv` and the environment table | Separate change (#392) |
| Standard streams, files and formatted output | Not started |
| The A2 program itself, its build and its test | Not started |
Until the last two rows exist nothing here shows a hosted C program running,
and A2 must not be reported as passing.